{"input": "import java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Random;\nimport routing.util.EnergyModel;\nimport routing.util.MessageTransferAcceptPolicy;\nimport routing.util.RoutingInfo;\nimport util.Tuple;\nimport core.Connection;\nimport core.DTNHost;\nimport core.Message;\nimport core.MessageListener;\nimport core.NetworkInterface;\nimport core.Settings;\nimport core.SimClock;", "context": "src/routing/ActiveRouter.java\n/*\n * Copyright 2010 Aalto University, ComNet\n * Released under GPLv3. See LICENSE.txt for details.\n */\npackage routing;\n\n\n\n\n/**\n * Superclass of active routers. Contains convenience methods (e.g.\n * {@link #getNextMessageToRemove(boolean)}) and watching of sending connections (see\n * {@link #update()}).\n */\npublic abstract class ActiveRouter extends MessageRouter {\n\t/** Delete delivered messages -setting id ({@value}). Boolean valued.\n\t * If set to true and final recipient of a message rejects it because it\n\t * already has it, the message is deleted from buffer. Default=false. */\n\tpublic static final String DELETE_DELIVERED_S = \"deleteDelivered\";\n\t/** should messages that final recipient marks as delivered be deleted\n\t * from message buffer */\n\tprotected boolean deleteDelivered;\n\n\t/** prefix of all response message IDs */\n\tpublic static final String RESPONSE_PREFIX = \"R_\";\n\t/** how often TTL check (discarding old messages) is performed */\n\tpublic static int TTL_CHECK_INTERVAL = 60;\n\t/** connection(s) that are currently used for sending */\n\tprotected ArrayList sendingConnections;\n\t/** sim time when the last TTL check was done */\n\tprivate double lastTtlCheck;\n\n\tprivate MessageTransferAcceptPolicy policy;\n\tprivate EnergyModel energy;\n\n\t/**\n\t * Constructor. Creates a new message router based on the settings in\n\t * the given Settings object.\n\t * @param s The settings object\n\t */\n\tpublic ActiveRouter(Settings s) {\n\t\tsuper(s);\n\n\t\tthis.policy = new MessageTransferAcceptPolicy(s);\n\n\t\tthis.deleteDelivered = s.getBoolean(DELETE_DELIVERED_S, false);\n\n\t\tif (s.contains(EnergyModel.INIT_ENERGY_S)) {\n\t\t\tthis.energy = new EnergyModel(s);\n\t\t} else {\n\t\t\tthis.energy = null; /* no energy model */\n\t\t}\n\t}\n\n\t/**\n\t * Copy constructor.\n\t * @param r The router prototype where setting values are copied from\n\t */\n\tprotected ActiveRouter(ActiveRouter r) {\n\t\tsuper(r);\n\t\tthis.deleteDelivered = r.deleteDelivered;\n\t\tthis.policy = r.policy;\n\t\tthis.energy = (r.energy != null ? r.energy.replicate() : null);\n\t}\n\n\t@Override\n\tpublic void init(DTNHost host, List mListeners) {\n\t\tsuper.init(host, mListeners);\n\t\tthis.sendingConnections = new ArrayList(1);\n\t\tthis.lastTtlCheck = 0;\n\t}\n\n\t/**\n\t * Called when a connection's state changes. If energy modeling is enabled,\n\t * and a new connection is created to this node, reduces the energy for the\n\t * device discovery (scan response) amount\n\t * @param con The connection whose state changed\n\t */\n\t@Override\n\tpublic void changedConnection(Connection con) {\n\t\tif (this.energy != null && con.isUp() && !con.isInitiator(getHost())) {\n\t\t\tthis.energy.reduceDiscoveryEnergy();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean requestDeliverableMessages(Connection con) {\n\t\tif (isTransferring()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tDTNHost other = con.getOtherNode(getHost());\n\t\t/* do a copy to avoid concurrent modification exceptions\n\t\t * (startTransfer may remove messages) */\n\t\tArrayList temp =\n\t\t\tnew ArrayList(this.getMessageCollection());\n\t\tfor (Message m : temp) {\n\t\t\tif (other == m.getTo()) {\n\t\t\t\tif (startTransfer(m, con) == RCV_OK) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean createNewMessage(Message m) {\n\t\tmakeRoomForNewMessage(m.getSize());\n\t\treturn super.createNewMessage(m);\n\t}\n\n\t@Override\n\tpublic int receiveMessage(Message m, DTNHost from) {\n\t\tint recvCheck = checkReceiving(m, from);\n\t\tif (recvCheck != RCV_OK) {\n\t\t\treturn recvCheck;\n\t\t}\n\n\t\t// seems OK, start receiving the message\n\t\treturn super.receiveMessage(m, from);\n\t}\n\n\t@Override\n\tpublic Message messageTransferred(String id, DTNHost from) {\n\t\tMessage m = super.messageTransferred(id, from);\n\n\t\t/**\n\t\t * N.B. With application support the following if-block\n\t\t * becomes obsolete, and the response size should be configured\n\t\t * to zero.\n\t\t */\n\t\t// check if msg was for this host and a response was requested\n\nsrc/core/NetworkInterface.java\nabstract public class NetworkInterface implements ModuleCommunicationListener, Comparable {\n\t/** transmit range -setting id ({@value})*/\n\tpublic static final String TRANSMIT_RANGE_S = \"transmitRange\";\n\t/** transmit speed -setting id ({@value})*/\n\tpublic static final String TRANSMIT_SPEED_S = \"transmitSpeed\";\n\t/** scanning interval -setting id ({@value})*/\n\tpublic static final String SCAN_INTERVAL_S = \"scanInterval\";\n\n\t/**\n\t * Sub-namespace for the network related settings in the Group namespace\n\t * ({@value})\n\t */\n\tpublic static final String NET_SUB_NS = \"net\";\n\n\t/** Activeness offset jitter -setting id ({@value})\n\t * The maximum amount of random offset for the offset */\n\tpublic static final String ACT_JITTER_S = \"activenessOffsetJitter\";\n\n\t/** {@link ModuleCommunicationBus} identifier for the \"scanning interval\"\n variable. */\n\tpublic static final String SCAN_INTERVAL_ID = \"Network.scanInterval\";\n\t/** {@link ModuleCommunicationBus} identifier for the \"radio range\"\n\tvariable. Value type: double */\n\tpublic static final String RANGE_ID = \"Network.radioRange\";\n\t/** {@link ModuleCommunicationBus} identifier for the \"transmission speed\"\n variable. Value type: integer */\n\tpublic static final String SPEED_ID = \"Network.speed\";\n\n\tprivate static final int CON_UP = 1;\n\tprivate static final int CON_DOWN = 2;\n\n\tprivate static Random rng;\n\tprotected DTNHost host = null;\n\n\tprotected String interfacetype;\n\tprotected List connections; // connected hosts\n\tprivate List cListeners = null; // list of listeners\n\tprivate int address; // network interface address\n\tprotected double transmitRange;\n\tprotected double oldTransmitRange;\n\tprotected int transmitSpeed;\n\t/** scanning interval, or 0.0 if n/a */\n\tprivate double scanInterval;\n\tprivate double lastScanTime;\n\n\t/** activeness handler for the node group */\n\tprivate ActivenessHandler ah;\n\t/** maximum activeness jitter value for the node group */\n\tprivate int activenessJitterMax;\n\t/** this interface's activeness jitter value */\n\tprivate int activenessJitterValue;\n\n\tstatic {\n\t\tDTNSim.registerForReset(NetworkInterface.class.getCanonicalName());\n\t\treset();\n\t}\n\n\t/**\n\t * Resets the static fields of the class\n\t */\n\tpublic static void reset() {\n\t\trng = new Random(0);\n\t}\n\n\t/**\n\t * For creating an empty class of a specific type\n\t */\n\tpublic NetworkInterface(Settings s) {\n\t\tthis.interfacetype = s.getNameSpace();\n\t\tthis.connections = new ArrayList();\n\n\t\tthis.transmitRange = s.getDouble(TRANSMIT_RANGE_S);\n\t\tthis.transmitSpeed = s.getInt(TRANSMIT_SPEED_S);\n\t\tensurePositiveValue(transmitRange, TRANSMIT_RANGE_S);\n\t\tensurePositiveValue(transmitSpeed, TRANSMIT_SPEED_S);\n\t}\n\n\t/**\n\t * For creating an empty class of a specific type\n\t */\n\tpublic NetworkInterface() {\n\t\tthis.interfacetype = \"Default\";\n\t\tthis.connections = new ArrayList();\n\t}\n\n\t/**\n\t * copy constructor\n\t */\n\tpublic NetworkInterface(NetworkInterface ni) {\n\t\tthis.connections = new ArrayList();\n\t\tthis.host = ni.host;\n\t\tthis.cListeners = ni.cListeners;\n\t\tthis.interfacetype = ni.interfacetype;\n\t\tthis.transmitRange = ni.transmitRange;\n\t\tthis.transmitSpeed = ni.transmitSpeed;\n\t\tthis.scanInterval = ni.scanInterval;\n\t\tthis.ah = ni.ah;\n\n\t\tif (ni.activenessJitterMax > 0) {\n\t\t\tthis.activenessJitterValue = rng.nextInt(ni.activenessJitterMax);\n\t\t} else {\n\t\t\tthis.activenessJitterValue = 0;\n\t\t}\n\n\t\tthis.scanInterval = ni.scanInterval;\n\t\t/* draw lastScanTime of [0 -- scanInterval] */\n\t\tthis.lastScanTime = rng.nextDouble() * this.scanInterval;\n\t}\n\n\t/**\n\t * Replication function\n\t */\n\tabstract public NetworkInterface replicate();\n\n\t/**\n\t * For setting the host - needed when a prototype is copied for several\n\t * hosts\n\t * @param host The host where the network interface is\n\t */\n\tpublic void setHost(DTNHost host) {\n\t\tthis.host = host;\n\t\tModuleCommunicationBus comBus = host.getComBus();\n\n\t\tif (!comBus.containsProperty(SCAN_INTERVAL_ID) &&\n\t\t !comBus.containsProperty(RANGE_ID)) {\n\t\t\t/* add properties and subscriptions only for the 1st interface */\n\t\t\t/* TODO: support for multiple interfaces */\n\t\t\tcomBus.addProperty(SCAN_INTERVAL_ID, this.scanInterval);\n\t\t\tcomBus.addProperty(RANGE_ID, this.transmitRange);\n\t\t\tcomBus.addProperty(SPEED_ID, this.transmitSpeed);\n\t\t\tcomBus.subscribe(SCAN_INTERVAL_ID, this);\n\t\t\tcomBus.subscribe(RANGE_ID, this);\n\t\t\tcomBus.subscribe(SPEED_ID, this);\n\t\t}\n\t}\n\n\t/**\n\t * Sets group-based settings for the network interface\n\t * @param s The settings object using the right group namespace\n\t */\n\tpublic void setGroupSettings(Settings s) {\n\t\ts.setSubNameSpace(NET_SUB_NS);\n\t\tah = new ActivenessHandler(s);\n\n\t\tif (s.contains(SCAN_INTERVAL_S)) {\n\t\t\tthis.scanInterval = s.getDouble(SCAN_INTERVAL_S);\n\t\t} else {\n\t\t\tthis.scanInterval = 0;\n\t\t}\n\t\tif (s.contains(ACT_JITTER_S)) {\n\t\t\tthis.activenessJitterMax = s.getInt(ACT_JITTER_S);\n\t\t}\n\n\t\ts.restoreSubNameSpace();\n\t}\n\n\t/**\n\t * For checking what interface type this interface is\n\t */\n\tpublic String getInterfaceType() {\n\t\treturn interfacetype;\n\t}\n\n\t/**\n\t * For setting the connectionListeners\n\t * @param cListeners List of connection listeners\n\t */\n\tpublic void setClisteners(List cListeners) {\n\t\tthis.cListeners = cListeners;\n\t}\n\n\t/**\n\t * Returns the transmit range of this network layer\n\t * @return the transmit range\n\t */\n\tpublic double getTransmitRange() {\n\t\treturn this.transmitRange;\n\t}\n\n\t/**\n\t * Returns the transmit speed of this network layer with respect to the\n\t * another network interface\n\t * @param ni The other network interface\n\t * @return the transmit speed\n\t */\n\tpublic int getTransmitSpeed(NetworkInterface ni) {\n\t\treturn this.transmitSpeed;\n\t}\n\n\t/**\n\t * Returns a list of currently connected connections\n\t * @return a list of currently connected connections\n\t */\n\tpublic List getConnections() {\n\t\treturn this.connections;\n\t}\n\n\t/**\n\t * Returns true if the interface is on at the moment (false if not)\n\t * @return true if the interface is on at the moment (false if not)\n\t */\n\tpublic boolean isActive() {\n\t\tboolean active;\n\n\t\tif (ah == null) {\n\t\t\treturn true; /* no handler: always active */\n\t\t}\n\n\t\tactive = ah.isActive(this.activenessJitterValue);\n\n\t\tif (active && host.getComBus().getDouble(EnergyModel.ENERGY_VALUE_ID,\n\t\t\t\t\t1) <= 0) {\n\t\t\t/* TODO: better way to check battery level */\n\t\t\t/* no battery -> inactive */\n\t\t\tactive = false;\n\t\t}\n\n\t\tif (active == false && this.transmitRange > 0) {\n\t\t\t/* not active -> make range 0 */\n\t\t\tthis.oldTransmitRange = this.transmitRange;\n\t\t\thost.getComBus().updateProperty(RANGE_ID, 0.0);\n\t\t} else if (active == true && this.transmitRange == 0.0) {\n\t\t\t/* active, but range == 0 -> restore range */\n\t\t\thost.getComBus().updateProperty(RANGE_ID,\n\t\t\t\t\tthis.oldTransmitRange);\n\t\t}\n\t\treturn active;\n\t}\n\n\t/**\n\t * Checks if this interface is currently in the scanning mode\n\t * @return True if the interface is scanning; false if not\n\t */\n\tpublic boolean isScanning() {\n\t\tdouble simTime = SimClock.getTime();\n\n\t\tif (!isActive()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (scanInterval > 0.0) {\n\t\t\tif (simTime < lastScanTime) {\n\t\t\t\treturn false; /* not time for the first scan */\n\t\t\t}\n\t\t\telse if (simTime > lastScanTime + scanInterval) {\n\t\t\t\tlastScanTime = simTime; /* time to start the next scan round */\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (simTime != lastScanTime ){\n\t\t\t\treturn false; /* not in the scan round */\n\t\t\t}\n\t\t}\n\t\t/* interval == 0 or still in the same scan round as when\n\t\t last time asked */\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns true if one of the connections of this interface is transferring\n\t * data\n\t * @return true if the interface transferring\n\t */\n\tpublic boolean isTransferring() {\n\t\tfor (Connection c : this.connections) {\n\t\t\tif (c.isTransferring()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Connects the interface to another interface.\n\t *\n\t * Overload this in a derived class. Check the requirements for\n\t * the connection to work in the derived class, then call\n\t * connect(Connection, NetworkInterface) for the actual connection.\n\t * @param anotherInterface The interface to connect to\n\t */\n\tpublic abstract void connect(NetworkInterface anotherInterface);\n\n\t/**\n\t * Connects this host to another host. The derived class should check\n\t * that all pre-requisites for making a connection are satisfied before\n\t * actually connecting.\n\t * @param con The new connection object\n\t * @param anotherInterface The interface to connect to\n\t */\n\tprotected void connect(Connection con, NetworkInterface anotherInterface) {\n\t\tthis.connections.add(con);\n\t\tnotifyConnectionListeners(CON_UP, anotherInterface.getHost());\n\n\t\t// set up bidirectional connection\n\t\tanotherInterface.getConnections().add(con);\n\n\t\t// inform routers about the connection\n\t\tthis.host.connectionUp(con);\n\t\tanotherInterface.getHost().connectionUp(con);\n\t}\n\n\t/**\n\t * Disconnect a connection between this and another host.\n\t * @param other The other host's network interface to disconnect\n\t * from this host\n\t */\n\tpublic void disconnect(NetworkInterface other) {\n\t\tfor (int i = 0; i < this.connections.size(); i++) {\n\t\t\tConnection con = this.connections.get(i);\n\n\t\t\tif (con.getOtherInterface(this) == other) {\n\t\t\t\tdisconnect(con, other);\n\t\t\t\tconnections.remove(i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// the connection didn't exist, do nothing\n\t}\n\n\t/**\n\t * Disconnects this host from another host. The derived class should\n\t * make the decision whether to disconnect or not\n\t * @param con The connection to tear down\n\t */\n\tprotected void disconnect(Connection con, NetworkInterface other) {\n\t\t// all connections should be up at this stage\n\t\tassert con.isUp() : \"Connection \" + con + \" was down!\";\n\n\t\tcon.setUpState(false);\n\t\tnotifyConnectionListeners(CON_DOWN, other.getHost());\n\n\t\t// tear down bidirectional connection\n\t\tif (!other.getConnections().remove(con)) {\n\t\t\tthrow new SimError(\"No connection \" + con + \" found in \" +\n\t\t\t\t\tother);\n\t\t}\n\n\t\tthis.host.connectionDown(con);\n\t\tother.getHost().connectionDown(con);\n\t}\n\n\t/**\n\t * Returns true if the given NetworkInterface is connected to this interface.\n\t * @param other The other NetworkInterface to check\n\t * @return True if the two hosts are connected\n\t */\n\tpublic boolean isConnected(NetworkInterface other) {\n\t\tfor (int i = 0; i < this.connections.size(); i++) {\n\t\t\tif (this.connections.get(i).getOtherInterface(this) == other) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Makes sure that a value is positive\n\t * @param value Value to check\n\t * @param settingName Name of the setting (for error's message)\n\t * @throws SettingsError if the value was not positive\n\t */\n\tprotected void ensurePositiveValue(double value, String settingName) {\n\t\tif (value < 0) {\n\t\t\tthrow new SettingsError(\"Negative value (\" + value +\n\t\t\t\t\t\") not accepted for setting \" + settingName);\n\t\t}\n\t}\n\n\t/**\n\t * Called when interface enters the transmission range\n\t * May be called only once even if connection is not immediately established\n\t * Callee is responsible to keep track of available connections\n\t * Caller guarantees that:\n\t * - =/= \n\t * - There is no connection yet\n\t * @param other The other interface\n\t */\n\tpublic void linkUp(NetworkInterface other) {\n\t\tconnect(other);\n\t}\n\n\t/**\n\t * Called when interface leaves the transmission range\n\t * Caller guarantees that:\n\t * - =/= \n\t * - There was a connection\n\t * @param other The other interface\n\t */\n\tpublic void linkDown(NetworkInterface other) {\n\t\tdisconnect(other);\n\t}\n\n\t/**\n\t * Updates the state of current connections(ie recalculate transmission speeds etc.).\n\t */\n\tpublic abstract void update();\n\n\t/**\n\t * Notifies all the connection listeners about a change in connections.\n\t * @param type Type of the change (e.g. {@link #CON_DOWN} )\n\t * @param otherHost The other host on the other end of the connection.\n\t */\n\tprivate void notifyConnectionListeners(int type, DTNHost otherHost) {\n\t\tif (this.cListeners == null) {\n\t\t\treturn;\n\t\t}\n\t\tfor (ConnectionListener cl : this.cListeners) {\n\t\t\tswitch (type) {\n\t\t\tcase CON_UP:\n\t\t\t\tcl.hostsConnected(this.host, otherHost);\n\t\t\t\tbreak;\n\t\t\tcase CON_DOWN:\n\t\t\t\tcl.hostsDisconnected(this.host, otherHost);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert false : type;\t// invalid type code\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * This method is called by the {@link ModuleCommunicationBus} when/if\n\t * someone changes the scanning interval, transmit speed, or range\n\t * @param key Identifier of the changed value\n\t * @param newValue New value for the variable\n\t */\n\tpublic void moduleValueChanged(String key, Object newValue) {\n\t\tif (key.equals(SCAN_INTERVAL_ID)) {\n\t\t\tthis.scanInterval = (Double)newValue;\n\t\t}\n\t\telse if (key.equals(SPEED_ID)) {\n\t\t\tthis.transmitSpeed = (Integer)newValue;\n\t\t}\n\t\telse if (key.equals(RANGE_ID)) {\n\t\t\tthis.transmitRange = (Double)newValue;\n\t\t}\n\t\telse {\n\t\t\tthrow new SimError(\"Unexpected combus ID \" + key);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a connection to another host. This method does not do any checks\n\t * on whether the other node is in range or active\n\t * (cf. {@link #connect(NetworkInterface)}).\n\t * @param anotherInterface The interface to create the connection to\n\t */\n\tpublic abstract void createConnection(NetworkInterface anotherInterface);\n\n\t/**\n\t * Returns the DTNHost of this interface\n\t */\n\tpublic DTNHost getHost() {\n\t\treturn host;\n\t}\n\n\t/**\n\t * Returns the current location of the host of this interface.\n\t * @return The location\n\t */\n\tpublic Coord getLocation() {\n\t\treturn host.getLocation();\n\t}\n\n\t/**\n\t * Returns a string representation of the object.\n\t * @return a string representation of the object.\n\t */\n\tpublic String toString() {\n\t\treturn this.address + \" of \" + this.host +\n\t\t\t\". Connections: \" +\tthis.connections;\n\t}\n\n\t@Override\n\tpublic int compareTo(NetworkInterface b) {\n\t\treturn this.getHost().getID() - b.getHost().getID();\n\t}\n\n}\n\nsrc/core/SimClock.java\npublic class SimClock {\n\tprivate static double clockTime = 0.0;\n\tprivate static SimClock clock = null;\n\n\tprivate SimClock() {}\n\n\tstatic {\n\t\tDTNSim.registerForReset(SimClock.class.getCanonicalName());\n\t\treset();\n\t}\n\n\t/**\n\t * Get the instance of the class that can also change the time.\n\t * @return The instance of this clock\n\t */\n\tpublic static SimClock getInstance() {\n\t\tif (clock == null) {\n\t\t\tclock = new SimClock();\n\t\t}\n\t\treturn clock;\n\t}\n\n\t/**\n\t * Returns the current time (seconds since start)\n\t * @return Time as a double\n\t */\n\tpublic static double getTime() {\n\t\treturn clockTime;\n\t}\n\n\t/**\n\t * Returns the current time rounded to the nearest integer\n\t * @return Time as integer\n\t */\n\tpublic static int getIntTime() {\n\t\treturn (int)Math.round(clockTime);\n\t}\n\n\t/**\n\t * Returns a string presentation of the sim time shown with the given amount\n\t * of decimals\n\t * @param decimals The number of decimals to show\n\t * @return The sim time\n\t */\n\tpublic static String getFormattedTime(int decimals) {\n\t\treturn String.format(\"%.\" + decimals + \"f\", clockTime);\n\t}\n\n\t/**\n\t * Advances the time by n seconds\n\t * @param time Nrof seconds to increase the time\n\t */\n\tpublic void advance(double time) {\n\t\tclockTime += time;\n\t}\n\n\t/**\n\t * Sets the time of the clock.\n\t * @param time the time to set\n\t */\n\tpublic void setTime(double time) {\n\t\tclockTime = time;\n\t}\n\n\t/**\n\t * Returns the current simulation time in a string\n\t * @return the current simulation time in a string\n\t */\n\tpublic String toString() {\n\t\treturn \"SimTime: \" + clockTime;\n\t}\n\n\t/**\n\t * Resets the static fields of the class\n\t */\n\tpublic static void reset() {\n\t\tclockTime = 0;\n\t}\n}\n\nsrc/core/MessageListener.java\npublic interface MessageListener {\n\n\t/**\n\t * Method is called when a new message is created\n\t * @param m Message that was created\n\t */\n\tpublic void newMessage(Message m);\n\n\t/**\n\t * Method is called when a message's transfer is started\n\t * @param m The message that is going to be transferred\n\t * @param from Node where the message is transferred from\n\t * @param to Node where the message is transferred to\n\t */\n\tpublic void messageTransferStarted(Message m, DTNHost from, DTNHost to);\n\n\t/**\n\t * Method is called when a message is deleted\n\t * @param m The message that was deleted\n\t * @param where The host where the message was deleted\n\t * @param dropped True if the message was dropped, false if removed\n\t */\n\tpublic void messageDeleted(Message m, DTNHost where, boolean dropped);\n\n\t/**\n\t * Method is called when a message's transfer was aborted before\n\t * it finished\n\t * @param m The message that was being transferred\n\t * @param from Node where the message was being transferred from\n\t * @param to Node where the message was being transferred to\n\t */\n\tpublic void messageTransferAborted(Message m, DTNHost from, DTNHost to);\n\n\t/**\n\t * Method is called when a message is successfully transferred from\n\t * a node to another.\n\t * @param m The message that was transferred\n\t * @param from Node where the message was transferred from\n\t * @param to Node where the message was transferred to\n\t * @param firstDelivery Was the target node final destination of the message\n\t * and received this message for the first time.\n\t */\n\tpublic void messageTransferred(Message m, DTNHost from, DTNHost to,\n\t\t\tboolean firstDelivery);\n}\n\nsrc/core/Connection.java\npublic abstract class Connection {\n\tprotected DTNHost toNode;\n\tprotected NetworkInterface toInterface;\n\tprotected DTNHost fromNode;\n\tprotected NetworkInterface fromInterface;\n\tprotected DTNHost msgFromNode;\n\n\tprivate boolean isUp;\n\tprotected Message msgOnFly;\n\t/** how many bytes this connection has transferred */\n\tprotected int bytesTransferred;\n\n\t/**\n\t * Creates a new connection between nodes and sets the connection\n\t * state to \"up\".\n\t * @param fromNode The node that initiated the connection\n\t * @param fromInterface The interface that initiated the connection\n\t * @param toNode The node in the other side of the connection\n\t * @param toInterface The interface in the other side of the connection\n\t */\n\tpublic Connection(DTNHost fromNode, NetworkInterface fromInterface,\n\t\t\tDTNHost toNode, NetworkInterface toInterface) {\n\t\tthis.fromNode = fromNode;\n\t\tthis.fromInterface = fromInterface;\n\t\tthis.toNode = toNode;\n\t\tthis.toInterface = toInterface;\n\t\tthis.isUp = true;\n\t\tthis.bytesTransferred = 0;\n\t}\n\n\n\t/**\n\t * Returns true if the connection is up\n\t * @return state of the connection\n\t */\n\tpublic boolean isUp() {\n\t\treturn this.isUp;\n\t}\n\n\t/**\n\t * Returns true if the connections is transferring a message\n\t * @return true if the connections is transferring a message\n\t */\n\tpublic boolean isTransferring() {\n\t\treturn this.msgOnFly != null;\n\t}\n\n\n\t/**\n\t * Returns true if the given node is the initiator of the connection, false\n\t * otherwise\n\t * @param node The node to check\n\t * @return true if the given node is the initiator of the connection\n\t */\n\tpublic boolean isInitiator(DTNHost node) {\n\t\treturn node == this.fromNode;\n\t}\n\n\t/**\n\t * Sets the state of the connection.\n\t * @param state True if the connection is up, false if not\n\t */\n\tpublic void setUpState(boolean state) {\n\t\tthis.isUp = state;\n\t}\n\n\t/**\n\t * Sets a message that this connection is currently transferring. If message\n\t * passing is controlled by external events, this method is not needed\n\t * (but then e.g. {@link #finalizeTransfer()} and\n\t * {@link #isMessageTransferred()} will not work either). Only a one message\n\t * at a time can be transferred using one connection.\n\t * @param m The message\n\t * @return The value returned by\n\t * {@link MessageRouter#receiveMessage(Message, DTNHost)}\n\t */\n\tpublic abstract int startTransfer(DTNHost from, Message m);\n\n\t/**\n\t * Calculate the current transmission speed from the information\n\t * given by the interfaces, and calculate the missing data amount.\n\t */\n\tpublic void update() {};\n\n\t/**\n * Aborts the transfer of the currently transferred message.\n */\n\tpublic void abortTransfer() {\n\t\tassert msgOnFly != null : \"No message to abort at \" + msgFromNode;\n\t\tint bytesRemaining = getRemainingByteCount();\n\n\t\tthis.bytesTransferred += msgOnFly.getSize() - bytesRemaining;\n\n\t\tgetOtherNode(msgFromNode).messageAborted(this.msgOnFly.getId(),\n\t\t\t\tmsgFromNode, bytesRemaining);\n\t\tclearMsgOnFly();\n\t}\n\n\t/**\n\t * Returns the amount of bytes to be transferred before ongoing transfer\n\t * is ready or 0 if there's no ongoing transfer or it has finished\n\t * already\n\t * @return the amount of bytes to be transferred\n\t */\n\tpublic abstract int getRemainingByteCount();\n\n\t/**\n\t * Clears the message that is currently being transferred.\n\t * Calls to {@link #getMessage()} will return null after this.\n\t */\n\tprotected void clearMsgOnFly() {\n\t\tthis.msgOnFly = null;\n\t\tthis.msgFromNode = null;\n\t}\n\n\t/**\n\t * Finalizes the transfer of the currently transferred message.\n\t * The message that was being transferred can not be\n\t * retrieved from this connections after calling this method (using\n\t * {@link #getMessage()}).\n\t */\n\tpublic void finalizeTransfer() {\n\t\tassert this.msgOnFly != null : \"Nothing to finalize in \" + this;\n\t\tassert msgFromNode != null : \"msgFromNode is not set\";\n\n\t\tthis.bytesTransferred += msgOnFly.getSize();\n\n\t\tgetOtherNode(msgFromNode).messageTransferred(this.msgOnFly.getId(),\n\t\t\t\tmsgFromNode);\n\t\tclearMsgOnFly();\n\t}\n\n\t/**\n\t * Returns true if the current message transfer is done\n\t * @return True if the transfer is done, false if not\n\t */\n\tpublic abstract boolean isMessageTransferred();\n\n\t/**\n\t * Returns true if the connection is ready to transfer a message (connection\n\t * is up and there is no message being transferred).\n\t * @return true if the connection is ready to transfer a message\n\t */\n\tpublic boolean isReadyForTransfer() {\n\t\treturn this.isUp && this.msgOnFly == null;\n\t}\n\n\t/**\n\t * Gets the message that this connection is currently transferring.\n\t * @return The message or null if no message is being transferred\n\t */\n\tpublic Message getMessage() {\n\t\treturn this.msgOnFly;\n\t}\n\n\t/**\n\t * Gets the current connection speed\n\t */\n\tpublic abstract double getSpeed();\n\n\t/**\n\t * Returns the total amount of bytes this connection has transferred so far\n\t * (including all transfers).\n\t */\n\tpublic int getTotalBytesTransferred() {\n\t\tif (this.msgOnFly == null) {\n\t\t\treturn this.bytesTransferred;\n\t\t}\n\t\telse {\n\t\t\tif (isMessageTransferred()) {\n\t\t\t\treturn this.bytesTransferred + this.msgOnFly.getSize();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn this.bytesTransferred +\n\t\t\t\t(msgOnFly.getSize() - getRemainingByteCount());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the node in the other end of the connection\n\t * @param node The node in this end of the connection\n\t * @return The requested node\n\t */\n\tpublic DTNHost getOtherNode(DTNHost node) {\n\t\tif (node == this.fromNode) {\n\t\t\treturn this.toNode;\n\t\t}\n\t\telse {\n\t\t\treturn this.fromNode;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the interface in the other end of the connection\n\t * @param i The interface in this end of the connection\n\t * @return The requested interface\n\t */\n\tpublic NetworkInterface getOtherInterface(NetworkInterface i) {\n\t\tif (i == this.fromInterface) {\n\t\t\treturn this.toInterface;\n\t\t}\n\t\telse {\n\t\t\treturn this.fromInterface;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a String presentation of the connection.\n\t */\n\tpublic String toString() {\n\t\treturn fromNode + \"<->\" + toNode + \" (\" + getSpeed()/1000 + \" kBps) is \" +\n\t\t(isUp() ? \"up\":\"down\") +\n\t\t(isTransferring() ? \" transferring \" + this.msgOnFly +\n\t\t\t\t\" from \" + this.msgFromNode : \"\");\n\t}\n\n}\n\nsrc/routing/util/EnergyModel.java\npublic class EnergyModel implements ModuleCommunicationListener {\n\t/** Initial units of energy -setting id ({@value}). Can be either a\n\t * single value, or a range of two values. In the latter case, the used\n\t * value is a uniformly distributed random value between the two values. */\n\tpublic static final String INIT_ENERGY_S = \"initialEnergy\";\n\n\t/** Energy usage per scanning (device discovery) -setting id ({@value}). */\n\tpublic static final String SCAN_ENERGY_S = \"scanEnergy\";\n\n\t/** Energy usage per scanning (device discovery) response -setting id\n\t * ({@value}). */\n\tpublic static final String SCAN_RSP_ENERGY_S = \"scanResponseEnergy\";\n\n\t/** Energy usage per second when transferring data \n\t * -setting id ({@value}). */\n\tpublic static final String TRANSMIT_ENERGY_S = \"transmitEnergy\";\n\n\t/** Energy update warmup period -setting id ({@value}). Defines the\n\t * simulation time after which the energy level starts to decrease due to\n\t * scanning, transmissions, etc. Default value = 0. If value of \"-1\" is\n\t * defined, uses the value from the report warmup setting\n\t * {@link report.Report#WARMUP_S} from the namespace\n\t * {@value report.Report#REPORT_NS}. */\n\tpublic static final String WARMUP_S = \"energyWarmup\";\n\n\t/** {@link ModuleCommunicationBus} identifier for the \"current amount of\n\t * energy left\" variable. Value type: double */\n\tpublic static final String ENERGY_VALUE_ID = \"Energy.value\";\n\n\t/** Initial energy levels from the settings */\n\tprivate final double[] initEnergy;\n\tprivate double warmupTime;\n\t/** current energy level */\n\tprivate double currentEnergy;\n\t/** energy usage per scan */\n\tprivate double scanEnergy;\n\t/** energy usage per transmitted byte */\n\tprivate double transmitEnergy;\n\t/** energy usage per device discovery response */\n\tprivate double scanResponseEnergy;\n\t/** sim time of the last energy updated */\n\tprivate double lastUpdate;\n\tprivate ModuleCommunicationBus comBus;\n\tprivate static Random rng = null;\n\n\t/**\n\t * Constructor. Creates a new message router based on the settings in\n\t * the given Settings object.\n\t * @param s The settings object\n\t */\n\tpublic EnergyModel(Settings s) {\n\t\tthis.initEnergy = s.getCsvDoubles(INIT_ENERGY_S);\n\n\t\tif (this.initEnergy.length != 1 && this.initEnergy.length != 2) {\n\t\t\tthrow new SettingsError(INIT_ENERGY_S + \" setting must have \" +\n\t\t\t\t\t\"either a single value or two comma separated values\");\n\t\t}\n\n\t\tthis.scanEnergy = s.getDouble(SCAN_ENERGY_S);\n\t\tthis.transmitEnergy = s.getDouble(TRANSMIT_ENERGY_S);\n\t\tthis.scanResponseEnergy = s.getDouble(SCAN_RSP_ENERGY_S);\n\n\t\tif (s.contains(WARMUP_S)) {\n\t\t\tthis.warmupTime = s.getInt(WARMUP_S);\n\t\t\tif (this.warmupTime == -1) {\n\t\t\t\tthis.warmupTime = new Settings(report.Report.REPORT_NS).\n\t\t\t\t\tgetInt(report.Report.WARMUP_S);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthis.warmupTime = 0;\n\t\t}\n\t}\n\n\t/**\n\t * Copy constructor.\n\t * @param proto The model prototype where setting values are copied from\n\t */\n\tprotected EnergyModel(EnergyModel proto) {\n\t\tthis.initEnergy = proto.initEnergy;\n\t\tsetEnergy(this.initEnergy);\n\t\tthis.scanEnergy = proto.scanEnergy;\n\t\tthis.transmitEnergy = proto.transmitEnergy;\n\t\tthis.warmupTime = proto.warmupTime;\n\t\tthis.scanResponseEnergy = proto.scanResponseEnergy;\n\t\tthis.comBus = null;\n\t\tthis.lastUpdate = 0;\n\t}\n\n\tpublic EnergyModel replicate() {\n\t\treturn new EnergyModel(this);\n\t}\n\n\t/**\n\t * Sets the current energy level into the given range using uniform\n\t * random distribution.\n\t * @param range The min and max values of the range, or if only one value\n\t * is given, that is used as the energy level\n\t */\n\tprotected void setEnergy(double range[]) {\n\t\tif (range.length == 1) {\n\t\t\tthis.currentEnergy = range[0];\n\t\t}\n\t\telse {\n\t\t\tif (rng == null) {\n\t\t\t\trng = new Random((int)(range[0] + range[1]));\n\t\t\t}\n\t\t\tthis.currentEnergy = range[0] +\n\t\t\t\trng.nextDouble() * (range[1] - range[0]);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the current energy level\n\t * @return the current energy level\n\t */\n\tpublic double getEnergy() {\n\t\treturn this.currentEnergy;\n\t}\n\n\t/**\n\t * Updates the current energy so that the given amount is reduced from it.\n\t * If the energy level goes below zero, sets the level to zero.\n\t * Does nothing if the warmup time has not passed.\n\t * @param amount The amount of energy to reduce\n\t */\n\tprotected void reduceEnergy(double amount) {\n\t\tif (SimClock.getTime() < this.warmupTime) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (comBus == null) {\n\t\t\treturn; /* model not initialized (via update) yet */\n\t\t}\n\n\t\tif (amount >= this.currentEnergy) {\n\t\t\tcomBus.updateProperty(ENERGY_VALUE_ID, 0.0);\n\t\t} else {\n\t\t\tcomBus.updateDouble(ENERGY_VALUE_ID, -amount);\n\t\t}\n\n\t}\n\n\t/**\n\t * Reduces the energy reserve for the amount that is used when another\n\t * host connects (does device discovery)\n\t */\n\tpublic void reduceDiscoveryEnergy() {\n\t\treduceEnergy(this.scanResponseEnergy);\n\t}\n\n\t/**\n\t * Reduces the energy reserve for the amount that is used by sending data\n\t * and scanning for the other nodes.\n\t */\n\tpublic void update(NetworkInterface iface, ModuleCommunicationBus comBus) {\n\t\tdouble simTime = SimClock.getTime();\n\t\tdouble delta = simTime - this.lastUpdate;\n\n\t\tif (this.comBus == null) {\n\t\t\tthis.comBus = comBus;\n\t\t\tthis.comBus.addProperty(ENERGY_VALUE_ID, this.currentEnergy);\n\t\t\tthis.comBus.subscribe(ENERGY_VALUE_ID, this);\n\t\t}\n\n\t\tif (simTime > this.lastUpdate && iface.isTransferring()) {\n\t\t\t/* sending or receiving data */\n\t\t\treduceEnergy(delta * this.transmitEnergy);\n\t\t}\n\t\tthis.lastUpdate = simTime;\n\n\t\tif (iface.isScanning()) {\n\t\t\t/* scanning at this update round */\n\t\t\tif (iface.getTransmitRange() > 0) {\n\t\t\t\tif (delta < 1) {\n\t\t\t\t\treduceEnergy(this.scanEnergy * delta);\n\t\t\t\t} else {\n\t\t\t\t\treduceEnergy(this.scanEnergy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called by the combus if the energy value is changed\n\t * @param key The energy ID\n\t * @param newValue The new energy value\n\t */\n\tpublic void moduleValueChanged(String key, Object newValue) {\n\t\tthis.currentEnergy = (Double)newValue;\n\t}\n\n}\n\nsrc/core/DTNHost.java\npublic class DTNHost implements Comparable {\n\tprivate static int count = 0;\n\tprivate int ID;\n\n\tprivate Coord destination;\t// where is it going\n\n\tprivate MessageRouter router;\n\tprivate MovementEngine movementEngine;\n\tprivate MovementModel movementModel;\n\tprivate Path path;\n\tprivate double speed;\n\tpublic final String groupId;\n\tprivate String name;\n\tprivate List msgListeners;\n\tprivate List movListeners;\n\tprivate List net;\n\tprivate ModuleCommunicationBus comBus;\n\n\tstatic {\n\t\tDTNSim.registerForReset(DTNHost.class.getCanonicalName());\n\t\treset();\n\t}\n\t/**\n\t * Creates a new DTNHost.\n\t * @param msgLs Message listeners\n\t * @param movLs Movement listeners\n\t * @param groupId GroupID of this host\n\t * @param interf List of NetworkInterfaces for the class\n\t * @param comBus Module communication bus object\n\t * @param mmProto Prototype of the movement model of this host\n\t * @param mRouterProto Prototype of the message router of this host\n\t */\n\tpublic DTNHost(List msgLs,\n\t\t\tList movLs,\n\t\t\tString groupId, List interf,\n\t\t\tModuleCommunicationBus comBus,\n\t\t\tMovementEngine me, MovementModel mmProto, MessageRouter mRouterProto) {\n\t\tthis.comBus = comBus;\n\t\tthis.ID = getNextID();\n\t\tthis.groupId = groupId;\n\t\tthis.name = groupId+ ID;\n\t\tthis.net = new ArrayList();\n\n\t\tfor (NetworkInterface i : interf) {\n\t\t\tNetworkInterface ni = i.replicate();\n\t\t\tni.setHost(this);\n\t\t\tnet.add(ni);\n\t\t}\n\n\t\t// TODO - think about the names of the interfaces and the nodes\n\t\t//this.name = groupId + ((NetworkInterface)net.get(1)).getAddress();\n\n\t\tthis.msgListeners = msgLs;\n\t\tthis.movListeners = movLs;\n\n\t\tthis.movementEngine = me;\n\n\t\t// create instances by replicating the prototypes\n\t\tthis.movementModel = mmProto.replicate();\n\t\tthis.movementModel.setComBus(comBus);\n\t\tthis.movementModel.setHost(this);\n\t\tsetRouter(mRouterProto.replicate());\n\n\t\tthis.path = null;\n\t}\n\n\t/**\n\t * Returns a new unique ID and increment the host count.\n\t * @return The next ID.\n\t */\n\tprivate synchronized static int getNextID() {\n\t\treturn count++;\n\t}\n\n\t/**\n\t * Reset the host and its interfaces\n\t */\n\tpublic static void reset() {\n\t\tcount = 0;\n\t}\n\n\t/**\n\t * Returns true if this node is actively moving (false if not)\n\t * @return true if this node is actively moving (false if not)\n\t */\n\tpublic boolean isMovementActive() {\n\t\treturn this.movementModel.isActive();\n\t}\n\n\t/**\n\t * Returns true if this node's radio is active (false if not)\n\t * @return true if this node's radio is active (false if not)\n\t */\n\tpublic boolean isRadioActive() {\n\t\t// Radio is active if any of the network interfaces are active.\n\t\tfor (final NetworkInterface i : this.net) {\n\t\t\tif (i.isActive()) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Set a router for this host\n\t * @param router The router to set\n\t */\n\tprivate void setRouter(MessageRouter router) {\n\t\trouter.init(this, msgListeners);\n\t\tthis.router = router;\n\t}\n\n\t/**\n\t * Returns the router of this host\n\t * @return the router of this host\n\t */\n\tpublic MessageRouter getRouter() {\n\t\treturn this.router;\n\t}\n\n\t/**\n\t * Returns the ID of this host.\n\t */\n\tpublic int getID() {\n\t\treturn this.ID;\n\t}\n\n\t/**\n\t * Returns this hosts's ModuleCommunicationBus\n\t * @return this hosts's ModuleCommunicationBus\n\t */\n\tpublic ModuleCommunicationBus getComBus() {\n\t\treturn this.comBus;\n\t}\n\n /**\n\t * Informs the router of this host about state change in a connection\n\t * object.\n\t * @param con The connection object whose state changed\n\t */\n\tpublic void connectionUp(Connection con) {\n\t\tthis.router.changedConnection(con);\n\t}\n\n\tpublic void connectionDown(Connection con) {\n\t\tthis.router.changedConnection(con);\n\t}\n\n\t/**\n\t * Returns a copy of the list of connections this host has with other hosts\n\t * @return a copy of the list of connections this host has with other hosts\n\t */\n\tpublic List getConnections() {\n\t\tList lc = new ArrayList();\n\n\t\tfor (NetworkInterface i : net) {\n\t\t\tlc.addAll(i.getConnections());\n\t\t}\n\n\t\treturn lc;\n\t}\n\n\t/**\n\t * Sets the host's location\n\t * @param location The location to set\n\t */\n\tpublic void setLocation(Coord location) {\n\t\tmovementEngine.setLocation(ID, location);\n\t}\n\n\t/**\n\t * Returns the current location of this host.\n\t * @return The location\n\t */\n\tpublic Coord getLocation() {\n\t\treturn movementEngine.getLocation(ID);\n\t}\n\n\t/**\n\t * Sets the Node's next destination and speed\n\t * @param destination The destination to set\n\t */\n\tpublic void setDestination(Coord destination, double speed) {\n\t\tif (destination == null) {\n\t\t\tthis.destination = null;\n\t\t\treturn;\n\t\t}\n\t\tthis.destination = destination.clone();\n\t\tthis.speed = speed;\n\n\t\tif (this.movListeners != null) {\n\t\t\tfor (MovementListener l : this.movListeners) {\n\t\t\t\tl.newDestination(this, this.destination, this.speed);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the current destination of this host.\n\t * @return The destination\n\t */\n\tpublic Coord getDestination() {\n\t\treturn this.destination;\n\t}\n\n\t/**\n\t * Returns the current speed of this host.\n\t * @return The speed\n\t */\n\tpublic double getSpeed() {\n\t\treturn this.speed;\n\t}\n\n\t/**\n\t * Sets the Path this node is currently traveling or null if no\n\t * path is in use at the moment. (Node is waiting for new path or stationary)\n\t * @return The path this node is traveling\n\t */\n\tpublic void setPath(Path path) {\n\t\tthis.path = path;\n\t}\n\n\t/**\n\t * Returns the Path this node is currently traveling or null if no\n\t * path is in use at the moment.\n\t * @return The path this node is traveling\n\t */\n\tpublic Path getPath() {\n\t\treturn this.path;\n\t}\n\n\t/**\n\t * Returns the movement model of this node\n\t * @return The movement model of this node\n\t */\n\tpublic MovementModel getMovementModel() {\n\t\treturn this.movementModel;\n\t}\n\n\t/**\n\t * Sets the Node's name overriding the default name (groupId + netAddress)\n\t * @param name The name to set\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * Returns the messages in a collection.\n\t * @return Messages in a collection\n\t */\n\tpublic Collection getMessageCollection() {\n\t\treturn this.router.getMessageCollection();\n\t}\n\n\t/**\n\t * Returns the number of messages this node is carrying.\n\t * @return How many messages the node is carrying currently.\n\t */\n\tpublic int getNrofMessages() {\n\t\treturn this.router.getNrofMessages();\n\t}\n\n\t/**\n\t * Returns the buffer occupancy percentage. Occupancy is 0 for empty\n\t * buffer but can be over 100 if a created message is bigger than buffer\n\t * space that could be freed.\n\t * @return Buffer occupancy percentage\n\t */\n\tpublic double getBufferOccupancy() {\n\t\tlong bSize = router.getBufferSize();\n\t\tlong freeBuffer = router.getFreeBufferSize();\n\t\treturn 100*((bSize-freeBuffer)/(bSize * 1.0));\n\t}\n\n\t/**\n\t * Returns routing info of this host's router.\n\t * @return The routing info.\n\t */\n\tpublic RoutingInfo getRoutingInfo() {\n\t\treturn this.router.getRoutingInfo();\n\t}\n\n\t/**\n\t * Returns the interface objects of the node\n\t */\n\tpublic List getInterfaces() {\n\t\treturn net;\n\t}\n\n\t/**\n\t * Find the network interface based on the index\n\t */\n\tpublic NetworkInterface getInterface(int interfaceNo) {\n\t\tNetworkInterface ni = null;\n\t\ttry {\n\t\t\tni = net.get(interfaceNo-1);\n\t\t} catch (IndexOutOfBoundsException ex) {\n\t\t\tthrow new SimError(\"No such interface: \"+interfaceNo +\n\t\t\t\t\t\" at \" + this);\n\t\t}\n\t\treturn ni;\n\t}\n\n\t/**\n\t * Find the network interface based on the interfacetype\n\t */\n\tprotected NetworkInterface getInterface(String interfacetype) {\n\t\tfor (NetworkInterface ni : net) {\n\t\t\tif (ni.getInterfaceType().equals(interfacetype)) {\n\t\t\t\treturn ni;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Force a connection event\n\t */\n\tpublic void forceConnection(DTNHost anotherHost, String interfaceId,\n\t\t\tboolean up) {\n\t\tNetworkInterface ni;\n\t\tNetworkInterface no;\n\n\t\tif (interfaceId != null) {\n\t\t\tni = getInterface(interfaceId);\n\t\t\tno = anotherHost.getInterface(interfaceId);\n\n\t\t\tassert (ni != null) : \"Tried to use a nonexisting interfacetype \"+interfaceId;\n\t\t\tassert (no != null) : \"Tried to use a nonexisting interfacetype \"+interfaceId;\n\t\t} else {\n\t\t\tni = getInterface(1);\n\t\t\tno = anotherHost.getInterface(1);\n\n\t\t\tassert (ni.getInterfaceType().equals(no.getInterfaceType())) :\n\t\t\t\t\"Interface types do not match. Please specify interface type explicitly\";\n\t\t}\n\n\t\tif (up) {\n\t\t\tni.createConnection(no);\n\t\t} else {\n\t\t\tni.disconnect(no);\n\t\t}\n\t}\n\n\t/**\n\t * for tests only --- do not use!!!\n\t */\n\tpublic void connect(DTNHost h) {\n\t\tif (DEBUG) Debug.p(\"WARNING: using deprecated DTNHost.connect\" +\n\t\t\t\"(DTNHost) Use DTNHost.forceConnection(DTNHost,null,true) instead\");\n\t\tforceConnection(h,null,true);\n\t}\n\n\t/**\n\t * Updates node's network layer and router.\n\t * @param simulateConnections Should network layer be updated too\n\t */\n\tpublic void update(boolean simulateConnections) {\n\t\tif (!isRadioActive()) {\n\t\t\t// Make sure inactive nodes don't have connections\n\t\t\ttearDownAllConnections();\n\t\t\treturn;\n\t\t}\n\n\t\tif (simulateConnections) {\n\t\t\tfor (NetworkInterface i : net) {\n\t\t\t\ti.update();\n\t\t\t}\n\t\t}\n\t\tthis.router.update();\n\t}\n\n\t/**\n\t * Tears down all connections for this host.\n\t */\n\tprivate void tearDownAllConnections() {\n\t\tfor (NetworkInterface i : net) {\n\t\t\t// Get all connections for the interface\n\t\t\tList conns = i.getConnections();\n\t\t\tif (conns.size() == 0) continue;\n\n\t\t\t// Destroy all connections\n\t\t\tList removeList =\n\t\t\t\tnew ArrayList(conns.size());\n\t\t\tfor (Connection con : conns) {\n\t\t\t\tremoveList.add(con.getOtherInterface(i));\n\t\t\t}\n\t\t\tfor (NetworkInterface inf : removeList) {\n\t\t\t\ti.disconnect(inf);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sends a message from this host to another host\n\t * @param id Identifier of the message\n\t * @param to Host the message should be sent to\n\t */\n\tpublic void sendMessage(String id, DTNHost to) {\n\t\tthis.router.sendMessage(id, to);\n\t}\n\n\t/**\n\t * Start receiving a message from another host\n\t * @param m The message\n\t * @param from Who the message is from\n\t * @return The value returned by\n\t * {@link MessageRouter#receiveMessage(Message, DTNHost)}\n\t */\n\tpublic int receiveMessage(Message m, DTNHost from) {\n\t\tint retVal = this.router.receiveMessage(m, from);\n\n\t\tif (retVal == MessageRouter.RCV_OK) {\n\t\t\tm.addNodeOnPath(this);\t// add this node on the messages path\n\t\t}\n\n\t\treturn retVal;\n\t}\n\n\t/**\n\t * Requests for deliverable message from this host to be sent trough a\n\t * connection.\n\t * @param con The connection to send the messages trough\n\t * @return True if this host started a transfer, false if not\n\t */\n\tpublic boolean requestDeliverableMessages(Connection con) {\n\t\treturn this.router.requestDeliverableMessages(con);\n\t}\n\n\t/**\n\t * Informs the host that a message was successfully transferred.\n\t * @param id Identifier of the message\n\t * @param from From who the message was from\n\t */\n\tpublic void messageTransferred(String id, DTNHost from) {\n\t\tthis.router.messageTransferred(id, from);\n\t}\n\n\t/**\n\t * Informs the host that a message transfer was aborted.\n\t * @param id Identifier of the message\n\t * @param from From who the message was from\n\t * @param bytesRemaining Nrof bytes that were left before the transfer\n\t * would have been ready; or -1 if the number of bytes is not known\n\t */\n\tpublic void messageAborted(String id, DTNHost from, int bytesRemaining) {\n\t\tthis.router.messageAborted(id, from, bytesRemaining);\n\t}\n\n\t/**\n\t * Creates a new message to this host's router\n\t * @param m The message to create\n\t */\n\tpublic void createNewMessage(Message m) {\n\t\tthis.router.createNewMessage(m);\n\t}\n\n\t/**\n\t * Deletes a message from this host\n\t * @param id Identifier of the message\n\t * @param drop True if the message is deleted because of \"dropping\"\n\t * (e.g. buffer is full) or false if it was deleted for some other reason\n\t * (e.g. the message got delivered to final destination). This effects the\n\t * way the removing is reported to the message listeners.\n\t */\n\tpublic void deleteMessage(String id, boolean drop) {\n\t\tthis.router.deleteMessage(id, drop);\n\t}\n\n\t/**\n\t * Informs movement listeners about the initial location.\n\t * Called by movement engine after setting the initial location.\n\t */\n\tpublic void notifyInitialLocation() {\n\t\tif (movListeners != null) {\n\t\t\tfor (MovementListener l : movListeners) {\n\t\t\t\tl.initialLocation(this, getLocation());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns a string presentation of the host.\n\t * @return Host's name\n\t */\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * Checks if a host is the same as this host by comparing the object\n\t * reference\n\t * @param otherHost The other host\n\t * @return True if the hosts objects are the same object\n\t */\n\tpublic boolean equals(DTNHost otherHost) {\n\t\treturn this == otherHost;\n\t}\n\n\t/**\n\t * Compares two DTNHosts by their IDs.\n\t * @see Comparable#compareTo(Object)\n\t */\n\tpublic int compareTo(DTNHost h) {\n\t\treturn this.getID() - h.getID();\n\t}\n\n}\n\nsrc/core/Settings.java\npublic class Settings {\n\t/** properties object where the setting files are read into */\n\tprotected static Properties props;\n\t/** file name of the default settings file ({@value}) */\n\tpublic static final String DEF_SETTINGS_FILE =\"default_settings.txt\";\n\n\t/**\n\t * Setting to define the file name where all read settings are written\n\t * ({@value}. If set to an empty string, standard output is used.\n\t * By default setting are not written anywhere.\n\t */\n\tpublic static final String SETTING_OUTPUT_S = \"Settings.output\";\n\n\t/** delimiter for requested values in strings ({@value})\n\t * @see #valueFillString(String) */\n\tpublic static final String FILL_DELIMITER = \"%%\";\n\n\t/** Stream where all read settings are written to */\n\tprivate static PrintStream out = null;\n\tprivate static Set writtenSettings = new HashSet();\n\n\t/** run index for run-specific settings */\n\tprivate static int runIndex = 0;\n\tprivate String namespace = null; // namespace to look the settings from\n\tprivate String secondaryNamespace = null;\n\tprivate Stack oldNamespaces;\n\tprivate Stack secondaryNamespaces;\n\n\t/**\n\t * Creates a setting object with a namespace. Namespace is the prefix\n\t * of the all subsequent setting requests.\n\t * @param namespace Namespace to use\n\t */\n\tpublic Settings(String namespace) {\n\t\tthis.oldNamespaces = new Stack();\n\t\tthis.secondaryNamespaces = new Stack();\n\t\tsetNameSpace(namespace);\n\t}\n\n\t/**\n\t * Create a setting object without namespace. All setting requests must\n\t * be prefixed with a valid namespace (e.g. \"Report.nrofReports\").\n\t */\n\tpublic Settings() {\n\t\tthis(null);\n\t}\n\n\t/**\n\t * Sets the run index for the settings (only has effect on settings with\n\t * run array). A run array can be defined with syntax
\n\t * [settingFor1stRun ; settingFor2ndRun ; SettingFor3rdRun]\n\t *
I.e. settings are put in brackets and delimited with semicolon.\n\t * First run's setting is returned when index is 0, second when index is\n\t * 1 etc. If run index is bigger than run array's length, indexing wraps\n\t * around in run array (i.e. return value is the value at index\n\t * runIndex % arrayLength).\n\t * To disable whole run-index-thing, set index to value smaller than\n\t * zero (e.g. -1). When disabled, run-arrays are returned as normal values,\n\t * including the brackets.\n\t * @param index The run index to use for subsequent settings calls, or\n\t * -1 to disable run indexing\n\t */\n\tpublic static void setRunIndex(int index) {\n\t\trunIndex = index;\n\t\twrittenSettings.clear();\n\t}\n\n\t/**\n\t * Checks that the given integer array contains a valid range. I.e.,\n\t * the length of the array must be two and\n\t * first_value <= second_value.\n\t * @param range The range array\n\t * @param sname Name of the setting (for error messages)\n\t * @throws SettingsError If the given array didn't qualify as a range\n\t */\n\tpublic void assertValidRange(int range[], String sname)\n\t\tthrows SettingsError {\n\t\tif (range.length != 2) {\n\t\t\tthrow new SettingsError(\"Range setting \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" should contain only two comma separated integer values\");\n\t\t}\n\t\tif (range[0] > range[1]) {\n\t\t\tthrow new SettingsError(\"Range setting's \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" first value should be smaller or equal to second value\");\n\t\t}\n\t}\n\n\t/**\n\t * Makes sure that the given settings value is positive\n\t * @param value Value to check\n\t * @param settingName Name of the setting (for error's message)\n\t * @throws SettingsError if the value was not positive\n\t */\n\tpublic void ensurePositiveValue(double value, String settingName) {\n\t\tif (value < 0) {\n\t\t\tthrow new SettingsError(\"Negative value (\" + value +\n\t\t\t\t\t\") not accepted for setting \" + settingName);\n\t\t}\n\t}\n\n\t/**\n\t * Sets the namespace to something else than the current namespace.\n\t * This change can be reverted using {@link #restoreNameSpace()}\n\t * @param namespace The new namespace\n\t */\n\tpublic void setNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = namespace;\n\t}\n\n\t/**\n\t * Appends the given namespace to the the current namespace, \n\t * for both the primary and secondary namespace .\n\t * This change can be reverted using {@link #restoreNameSpace()} and\n\t * {@link #restoreSecondaryNamespace()}.\n\t * @param namespace The new namespace to append\n\t */\n\tpublic void setSubNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = this.namespace + \".\" + namespace;\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = this.secondaryNamespace + \".\" + namespace;\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for a setting.\n\t * @param setting The name of the setting\n\t * @return The setting name prefixed with fully qualified name of the\n\t * namespace where the requested setting would be retrieved from or null\n\t * if that setting is not found from any of the current namespace(s)\n\t */\n\tpublic String getFullPropertyName(String setting) {\n\t\tif (!contains(setting)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (props.getProperty(getFullPropertyName(setting, false)) != null) {\n\t\t\treturn getFullPropertyName(setting, false);\n\t\t}\n\n\t\t// not found from primary, but Settings contains -> must be from 2ndary\n\t\telse return getFullPropertyName(setting, true);\n\t}\n\n\t/**\n\t * Returns the namespace of the settings object\n\t * @return the namespace of the settings object\n\t */\n\tpublic String getNameSpace() {\n\t\treturn this.namespace;\n\t}\n\n\t/**\n\t * Returns the secondary namespace of the settings object\n\t * @return the secondary namespace of the settings object\n\t */\n\tpublic String getSecondaryNameSpace() {\n\t\treturn this.secondaryNamespace;\n\t}\n\n\t/**\n\t * Sets a secondary namespace where a setting is searched from if it\n\t * isn't found from the primary namespace. Secondary namespace can\n\t * be used e.g. as a \"default\" space where the settings are looked from\n\t * if no specific setting is set.\n\t * This change can be reverted using {@link #restoreSecondaryNamespace()}\n\t * @param namespace The new secondary namespace or null if secondary\n\t * namespace is not used (default behavior)\n\t */\n\tpublic void setSecondaryNamespace(String namespace) {\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = namespace;\n\t}\n\n\t/**\n\t * Restores the namespace that was in use before a call to setNameSpace\n\t * @see #setNameSpace(String)\n\t */\n\tpublic void restoreNameSpace() {\n\t\tthis.namespace = this.oldNamespaces.pop();\n\t}\n\n\t/**\n\t * Restores the secondary namespace that was in use before a call to\n\t * setSecondaryNameSpace\n\t * @see #setSecondaryNamespace(String)\n\t */\n\tpublic void restoreSecondaryNamespace() {\n\t\tthis.secondaryNamespace = this.secondaryNamespaces.pop();\n\t}\n\n\t/**\n\t * Reverts the change made with {@link #setSubNameSpace(String)}, i.e.,\n\t * restores both the primary and secondary namespace.\n\t */\n\tpublic void restoreSubNameSpace() {\n\t\trestoreNameSpace();\n\t\trestoreSecondaryNamespace();\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t * The file {@link #DEF_SETTINGS_FILE}, if exists, is always read.\n\t * @param propFile Path to the property file where additional settings\n\t * are read from or null if no additional settings files are needed.\n\t * @throws SettingsError If loading the settings file(s) didn't succeed\n\t */\n\tpublic static void init(String propFile) throws SettingsError {\n\t\tString outFile;\n\t\ttry {\n\t\t\tif (new File(DEF_SETTINGS_FILE).exists()) {\n\t\t\t\tProperties defProperties = new Properties();\n\t\t\t\tdefProperties.load(new FileInputStream(DEF_SETTINGS_FILE));\n\t\t\t\tprops = new Properties(defProperties);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprops = new Properties();\n\t\t\t}\n\t\t\tif (propFile != null) {\n\t\t\t\tprops.load(new FileInputStream(propFile));\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\toutFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t *\n\t * @param settingsStream\n\t * \t\tInputStream where the properties are read.\n\t * @throws SettingsError\n\t * \t\tIf loading the settings didn't succeed\n\t */\n\tpublic static void initFromStream(final InputStream settingsStream)\n\tthrows SettingsError {\n\t\tprops = new Properties();\n\t\ttry {\n\t\t\tprops.load(settingsStream);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\tString outFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reads another settings file and adds the key-value pairs to the current\n\t * settings overriding any values that already existed with the same keys.\n\t * @param propFile Path to the property file\n\t * @throws SettingsError If loading the settings file didn't succeed\n\t * @see #init(String)\n\t */\n\tpublic static void addSettings(String propFile) throws SettingsError {\n\t\ttry {\n\t\t\tprops.load(new FileInputStream(propFile));\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\t}\n\n\t/**\n\t * Writes the given setting string to the settings output (if any)\n\t * @param setting The string to write\n\t */\n\tprivate static void outputSetting(String setting) {\n\t\tif (out != null && !writtenSettings.contains(setting)) {\n\t\t\tif (writtenSettings.size() == 0) {\n\t\t\t\tout.println(\"# Settings for run \" + (runIndex + 1));\n\t\t\t}\n\t\t\tout.println(setting);\n\t\t\twrittenSettings.add(setting);\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if a setting with defined name (in the current namespace\n\t * or secondary namespace if such is set) exists and has some value\n\t * (not just white space)\n\t * @param name Name of the setting to check\n\t * @return True if the setting exists, false if not\n\t */\n\tpublic boolean contains(String name) {\n\t\ttry {\n\t\t\tString value = getSetting(name);\n\t\t\tif (value == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\telse return value.trim().length() > 0;\n\t\t}\n\t\tcatch (SettingsError e) {\n\t\t\treturn false; // didn't find the setting\n\t\t}\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for setting.\n\t * @param name Name of the settings\n\t * @param secondary If true, the secondary namespace is used.\n\t * @return full (prefixed with current namespace) property name for setting\n\t */\n\tprivate String getFullPropertyName(String name, boolean secondary) {\n\t\tString usedNamespace = (secondary ? secondaryNamespace : namespace);\n\n\t\tif (usedNamespace != null) {\n\t\t\treturn usedNamespace + \".\" + name;\n\t\t}\n\t\telse {\n\t\t\treturn name;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a String-valued setting. Setting is first looked from the\n\t * namespace that is set (if any) and then from the secondary namespace\n\t * (if any). All other getters use this method as their first step too\n\t * (so all getters may throw SettingsError and look from both namespaces).\n\t * @param name Name of the setting to get\n\t * @return The contents of the setting in a String\n\t * @throws SettingsError if the setting is not found from either one of\n\t * the namespaces\n\t */\n\tpublic String getSetting(String name) {\n\t\tString fullPropName;\n\t\tif (props == null) {\n\t\t\tinit(null);\n\t\t}\n\t\tfullPropName = getFullPropertyName(name, false);\n\t\tString value = props.getProperty(fullPropName);\n\n\t\tif (value != null) { // found value, check if run setting can be parsed\n\t\t\tvalue = parseRunSetting(value.trim());\n\t\t}\n\n\t\tif ((value == null || value.length() == 0) &&\n\t\t\t\tthis.secondaryNamespace != null) {\n\t\t\t// try secondary namespace if the value wasn't found from primary\n\t\t\tfullPropName = getFullPropertyName(name, true);\n\t\t\tvalue = props.getProperty(fullPropName);\n\n\t\t\tif (value != null) {\n\t\t\t\tvalue = parseRunSetting(value.trim());\n\t\t\t}\n\t\t}\n\n\t\tif (value == null || value.length() == 0) {\n\t\t\tthrow new SettingsError(\"Can't find setting \" +\n\t\t\t\t\tgetPropertyNamesString(name));\n\t\t}\n\n\t\toutputSetting(fullPropName + \" = \" + value);\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the given setting if it exists, or defaultValue if the setting\n\t * does not exist\n\t * @param name The name of the setting\n\t * @param defaultValue The value to return if the given setting didn't exist\n\t * @return The setting value or the default value if the setting didn't\n\t * exist\n\t */\n\tpublic String getSetting(String name, String defaultValue) {\n\t\tif (!contains(name)) {\n\t\t\treturn defaultValue;\n\t\t} else {\n\t\t\treturn getSetting(name);\n\t\t}\n\t}\n\n\t/**\n\t * Parses run-specific settings from a String value\n\t * @param value The String to parse\n\t * @return The runIndex % arrayLength'th value of the run array\n\t */\n\tprivate static String parseRunSetting(String value) {\n\t\tfinal String RUN_ARRAY_START = \"[\";\n\t\tfinal String RUN_ARRAY_END = \"]\";\n\t\tfinal String RUN_ARRAY_DELIM = \";\";\n\t\tfinal int MIN_LENGTH = 3; // minimum run is one value. e.g. \"[v]\"\n\n\t\tif (!value.startsWith(RUN_ARRAY_START) ||\n\t\t\t!value.endsWith(RUN_ARRAY_END) ||\n\t\t\trunIndex < 0 ||\n\t\t\tvalue.length() < MIN_LENGTH) {\n\t\t\treturn value; // standard format setting -> return\n\t\t}\n\n\t\tvalue = value.substring(1,value.length()-1); // remove brackets\n\t\tString[] valueArr = value.split(RUN_ARRAY_DELIM);\n\t\tint arrIndex = runIndex % valueArr.length;\n\t\tvalue = valueArr[arrIndex].trim();\n\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the setting name appended to namespace name(s) on a String\n\t * (for error messages)\n\t * @param name Name of the setting\n\t * @return the setting name appended to namespace name(s) on a String\n\t */\n\tprivate String getPropertyNamesString(String name) {\n\t\tif (this.secondaryNamespace != null) {\n\t\t\treturn \"'\"+ this.secondaryNamespace + \".\" + name + \"' nor '\" +\n\t\t\t\tthis.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse if (this.namespace != null){\n\t\t\treturn \"'\" + this.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse {\n\t\t\treturn \"'\" + name + \"'\";\n\t\t}\n\t}\n\n\t/**\n\t * Returns a double-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as a double\n\t */\n\tpublic double getDouble(String name) {\n\t\treturn parseDouble(getSetting(name), name);\n\t}\n\n\t/**\n\t * Returns a double-valued setting, or the default value if the given\n\t * setting does not exist\n\t * @param name Name of the setting to get\n\t * @param defaultValue The value to return if the setting doesn't exist\n\t * @return Value of the setting as a double (or the default value)\n\t */\n\tpublic double getDouble(String name, double defaultValue) {\n\t\treturn parseDouble(getSetting(name, \"\"+defaultValue), name);\n\t}\n\n\t/**\n\t * Parses a double value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a double\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate double parseDouble(String value, String setting) {\n\t\tdouble number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t\t//replaceAll removes everything which is not a digit or point\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Double.parseDouble(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses a long value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a long\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate long parseLong(String value, String setting) {\n\t\tlong number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Long.parseLong(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses the multiplier suffix from numeric setting\n\t * @param value The setting value\n\t * @return The muliplier as a number\n\t */\n\tprivate int getMultiplier(String value) {\n\t\tvalue = value.trim();\n\t\t\n\t\tif (value.endsWith(\"k\")) {\n\t\t\treturn 1000;\n\t\t}\n\t\telse if (value.endsWith(\"M\")) {\n\t\t\treturn 1000000;\n\t\t}\n\t\telse if (value.endsWith(\"G\")) {\n\t\t\treturn 1000000000;\n\t\t}\n\t\telse if (value.endsWith(\"kiB\")) {\n\t\t\t//2^10\n\t\t\treturn 1024;\n\t\t}\n\t\telse if (value.endsWith(\"MiB\")) {\n\t\t\t//2^20\n\t\t\treturn 1048576;\n\t\t}\n\t\telse if (value.endsWith(\"GiB\")) {\n\t\t\t//2^30\n\t\t\treturn 1073741824;\n\t\t} else {\n\t\t\t// no multiplier\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a CSV setting. Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading\n\t */\n\tpublic String[] getCsvSetting(String name) {\n\t\tArrayList values = new ArrayList();\n\t\tString csv = getSetting(name);\n\t\tScanner s = new Scanner(csv);\n\t\ts.useDelimiter(\",\");\n\n\t\twhile (s.hasNext()) {\n\t\t\tvalues.add(s.next().trim());\n\t\t}\n\n\t\treturn values.toArray(new String[0]);\n\t}\n\n\t/**\n\t * Returns a CSV setting containing expected amount of values.\n\t * Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading or didn't\n\t * read the expected amount of values.\n\t */\n\tpublic String[] getCsvSetting(String name, int expectedCount) {\n\t\tString[] values = getCsvSetting(name);\n\n\t\tif (values.length != expectedCount) {\n\t\t\tthrow new SettingsError(\"Read unexpected amount (\" + values.length +\n\t\t\t\t\t\") of comma separated values for setting '\"\n\t\t\t\t\t+ name + \"' (expected \" + expectedCount + \")\");\n\t\t}\n\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values containing expected\n\t * amount of values.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic double[] getCsvDoubles(String name, int expectedCount) {\n\t\treturn parseDoubles(getCsvSetting(name, expectedCount),name);\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String)\n\t */\n\tpublic double[] getCsvDoubles(String name) {\n\t\treturn parseDoubles(getCsvSetting(name), name);\n\t}\n\n\t/**\n\t * Parses a double array out of a String array\n\t * @param strings The array of strings containing double values\n\t * @param name Name of the setting\n\t * @return Array of double values parsed from the string values\n\t */\n\tprivate double[] parseDoubles(String[] strings, String name) {\n\t\tdouble[] values = new double[strings.length];\n\t\tfor (int i=0; i[] argsClass = {Settings.class};\n\t\tObject[] args = {this};\n\n\t\treturn loadObject(className, argsClass, args);\n\t}\n\n\t/**\n\t * Creates (and dynamically loads the class of) an object using the\n\t * constructor without any parameters.\n\t * @param className Name of the class of the object\n\t * @return Initialized object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tpublic Object createObject(String className) {\n\t\treturn loadObject(className, null, null);\n\t}\n\n\t/**\n\t * Dynamically loads and creates an object.\n\t * @param className Name of the class of the object\n\t * @param argsClass Class(es) of the argument(s) or null if no-argument\n\t * constructor should be called\n\t * @param args Argument(s)\n\t * @return The new object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tprivate Object loadObject(String className, Class[] argsClass,\n\t\t\tObject[] args) {\n\t\tObject o = null;\n\t\tClass objClass = getClass(className);\n\t\tConstructor constructor;\n\n\t\ttry {\n\t\t\tif (argsClass != null) { // use a specific constructor\n\t\t\t\tconstructor = objClass.getConstructor((Class[])argsClass);\n\t\t\t\to = constructor.newInstance(args);\n\t\t\t}\n\t\t\telse { // call empty constructor\n\t\t\t\to = objClass.newInstance();\n\t\t\t}\n\t\t} catch (SecurityException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (NoSuchMethodException e) {\n\t\t\tthrow new SettingsError(\"Class '\" + className +\n\t\t\t\t\t\"' doesn't have a suitable constructor\", e);\n\t\t} catch (InstantiationException e) {\n\t\t\tthrow new SettingsError(\"Can't create an instance of '\" +\n\t\t\t\t\tclassName + \"'\", e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (InvocationTargetException e) {\n\t\t\t// this exception occurs if initialization of the object fails\n\t\t\tif (e.getCause() instanceof SettingsError) {\n\t\t\t\tthrow (SettingsError)e.getCause();\n\t\t\t}\n\t\t\telse {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new SimError(\"Couldn't create settings-accepting object\"+\n\t\t\t\t\t\" for '\" + className + \"'\\n\" + \"cause: \" + e.getCause(), e);\n\t\t\t}\n\t\t}\n\n\t\treturn o;\n\t}\n\n\t/**\n\t * Returns a Class object for the name of class of throws SettingsError\n\t * if such class wasn't found.\n\t * @param name Full name of the class (including package name)\n\t * @return A Class object of that class\n\t * @throws SettingsError if such class wasn't found or couldn't be loaded\n\t */\n\tprivate Class getClass(String name) {\n\t\tString className = name;\n\t\tClass c;\n\n\t\ttry {\n\t\t\tc = Class.forName(className);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\tthrow new SettingsError(\"Couldn't find class '\" + className + \"'\"+\n\t\t\t\t\t\"\\n\" + e.getMessage(),e);\n\t\t}\n\n\t\treturn c;\n\t}\n\n\t/**\n\t * Fills a String formatted in a special way with values from Settings.\n\t * String can contain (fully qualified) setting names surrounded by\n\t * delimiters (see {@link #FILL_DELIMITER}). Values for those settings\n\t * are retrieved and filled in the place of place holders.\n\t * @param input The input string that may contain value requests\n\t * @return A string filled with requested values (or the original string\n\t * if no requests were found)\n\t * @throws SettingsError if such settings were not found\n\t */\n\tpublic String valueFillString(String input) {\n\t\tif (!input.contains(FILL_DELIMITER)) {\n\t\t\treturn input;\t// nothing to fill\n\t\t}\n\n\t\tSettings s = new Settings(); // don't use any namespace\n\t\tString result = \"\";\n\t\tScanner scan = new Scanner(input);\n\t\tscan.useDelimiter(FILL_DELIMITER);\n\n\t\tif (input.startsWith(FILL_DELIMITER)) {\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\n\t\twhile(scan.hasNext()) {\n\t\t\tresult += scan.next();\n\t\t\tif (!scan.hasNext()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns a String representation of the stored settings\n\t * @return a String representation of the stored settings\n\t */\n\tpublic String toString() {\n\t\treturn props.toString();\n\t}\n\n}\n\nsrc/routing/util/RoutingInfo.java\npublic class RoutingInfo {\n\tprivate String text;\n\tprivate List moreInfo = null;\n\n\t/**\n\t * Creates a routing info based on a text.\n\t * @param infoText The text of the info\n\t */\n\tpublic RoutingInfo(String infoText) {\n\t\tthis.text = infoText;\n\t}\n\n\t/**\n\t * Creates a routing info based on any object. Object's\n\t * toString() method's output is used as the info text.\n\t * @param o The object this info is based on\n\t */\n\tpublic RoutingInfo(Object o) {\n\t\tthis.text = o.toString();\n\t}\n\n\t/**\n\t * Adds child info object for this routing info.\n\t * @param info The info object to add.\n\t */\n\tpublic void addMoreInfo(RoutingInfo info) {\n\t\tif (this.moreInfo == null) { // lazy creation\n\t\t\tthis.moreInfo = new ArrayList();\n\t\t}\n\t\tthis.moreInfo.add(info);\n\t}\n\n\t/**\n\t * Returns the child routing infos of this info.\n\t * @return The children of this info or an empty list if this info\n\t * doesn't have any children.\n\t */\n\tpublic List getMoreInfo() {\n\t\tif (this.moreInfo == null) {\n\t\t\treturn new ArrayList(0);\n\t\t}\n\t\treturn this.moreInfo;\n\t}\n\n\t/**\n\t * Returns the info text of this routing info.\n\t * @return The info text\n\t */\n\tpublic String toString() {\n\t\treturn this.text;\n\t}\n\n}\n\nsrc/util/Tuple.java\npublic class Tuple {\n\tprivate K key;\n\tprivate V value;\n\n\t/**\n\t * Creates a new tuple.\n\t * @param key The key of the tuple\n\t * @param value The value of the tuple\n\t */\n\tpublic Tuple(K key, V value) {\n\t\tthis.key = key;\n\t\tthis.value = value;\n\t}\n\n\t/**\n\t * Returns the key\n\t * @return the key\n\t */\n\tpublic K getKey() {\n\t\treturn key;\n\t}\n\n\t/**\n\t * Returns the value\n\t * @return the value\n\t */\n\tpublic V getValue() {\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns a string representation of the tuple\n\t * @return a string representation of the tuple\n\t */\n\tpublic String toString() {\n\t\treturn key.toString() + \":\" + value.toString();\n\t}\n}\n\nsrc/routing/util/MessageTransferAcceptPolicy.java\npublic class MessageTransferAcceptPolicy {\n\n\t/** Namespace for all \"Message Transfer Accept policy\" settings ({@value})*/\n\tpublic static final String MTA_POLICY_NS = \"mtaPolicy\";\n\n\t/** Number of Module Communication Bus Conditions -setting id ({@value}).\n\t * Two comma separated values. Defines the number of receiving and number of\n\t * sending conditions to read from the settings. */\n\tpublic static final String NROF_MCBCS_S = \"nrofMCBACs\";\n\n\t/** Module Communication Bus Arithmetic Condition for Receiving -setting id\n\t * ({@value}). {@link ArithmeticCondition}. Defines one arithmetic condition\n\t * to use for receiving messages. */\n\tpublic static final String MCBACR_S = \"MCBRcondition\";\n\t/** Module Communication Bus Arithmetic Condition for Sending -setting id\n\t * ({@value}). {@link ArithmeticCondition}. */\n\tpublic static final String MCBACS_S = \"MCBScondition\";\n\n\t/** Module Communication Bus Condition Value for Receiving -setting id\n\t * ({@value}). String. Defines the ID to use with the receiving\n\t * condition. */\n\tpublic static final String MCBCVR_S = \"MCBRvalue\";\n\t/** Module Communication Bus Condition Value for Sending -setting id\n\t * ({@value}). String. Defines the ID to use with the sending\n\t * condition. */\n\tpublic static final String MCBCVS_S = \"MCBSvalue\";\n\n\t/** The valued used in to-policy to refer to this host ({@value}) */\n\tpublic static final int TO_ME_VALUE = -1;\n\n\t/** Simple-policy accept-to -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the destination of a\n\t * message when receiving messages. Special value {@link #TO_ME_VALUE}\n\t * refers to this host. */\n\tpublic static final String TO_RPOLICY_S = \"toReceivePolicy\";\n\n\t/** Simple-policy accept-from -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the source of a\n\t * message when receiving messages. Special value {@link #TO_ME_VALUE}\n\t * refers to this host. */\n\tpublic static final String FROM_RPOLICY_S = \"fromReceivePolicy\";\n\n\t/** Simple-policy accept-to -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the destination of a\n\t * message when sending messages. Special value {@link #TO_ME_VALUE} refers\n\t * to this host (but doesn't usually make much sense here). */\n\tpublic static final String TO_SPOLICY_S = \"toSendPolicy\";\n\n\t/**

Simple-policy accept-from -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the source of a\n\t * message when sending messages. Special value {@link #TO_ME_VALUE} refers\n\t * to this host.

\n\t *

Note: if this setting is defined and the {@link #TO_ME_VALUE}\n\t * is NOT listed, the hosts own messages are not sent anywhere.

*/\n\tpublic static final String FROM_SPOLICY_S = \"fromSendPolicy\";\n\n\t/** Hop count forwarding receive policy -setting id ({@value}).\n\t * {@link ArithmeticCondition}. Defines condition for the message hop\n\t * count; if the condition does not match, the message is rejected,\n\t * unless it is destined to this node. */\n\tpublic static final String HOPCOUNT_RPOLICY_S = \"hopCountReceivePolicy\";\n\t/** Hop count forwarding send policy -setting id ({@value}).\n\t * {@link ArithmeticCondition}. Defines condition for the message hop\n\t * count; if the condition does not match, the message is not offered\n\t * to other nodes, unless it would be delivered to the final destination. */\n\tpublic static final String HOPCOUNT_SPOLICY_S = \"hopCountSendPolicy\";\n\n\tprivate ArrayList> recvConditions = null;\n\tprivate ArrayList> sendConditions = null;\n\n\tprivate Range[] toSendPolicy = null;\n\tprivate Range[] fromSendPolicy = null;\n\tprivate Range[] toReceivePolicy = null;\n\tprivate Range[] fromReceivePolicy = null;\n\tprivate ArithmeticCondition hopCountSendPolicy = null;\n\tprivate ArithmeticCondition hopCountReceivePolicy = null;\n\n\tpublic MessageTransferAcceptPolicy(Settings nsSettings) {\n\t\tSettings s;\n\n\t\tif (! nsSettings.contains(MTA_POLICY_NS)) {\n\t\t\treturn; /* no (or \"default\") policy */\n\t\t}\n\n\t\ts = new Settings(nsSettings.getSetting(MTA_POLICY_NS));\n\t\taddMCBCs(s);\n\n\t\tif (s.contains(TO_SPOLICY_S)) {\n\t\t\tthis.toSendPolicy = s.getCsvRanges(TO_SPOLICY_S);\n\t\t}\n\t\tif (s.contains(FROM_SPOLICY_S)) {\n\t\t\tthis.fromSendPolicy = s.getCsvRanges(FROM_SPOLICY_S);\n\t\t}\n\t\tif (s.contains(TO_RPOLICY_S)) {\n\t\t\tthis.toReceivePolicy = s.getCsvRanges(TO_RPOLICY_S);\n\t\t}\n\t\tif (s.contains(FROM_RPOLICY_S)) {\n\t\t\tthis.fromReceivePolicy = s.getCsvRanges(FROM_RPOLICY_S);\n\t\t}\n\t\tif (s.contains(HOPCOUNT_SPOLICY_S)) {\n\t\t\thopCountSendPolicy = s.getCondition(HOPCOUNT_SPOLICY_S);\n\t\t}\n\t\tif (s.contains(HOPCOUNT_RPOLICY_S)) {\n\t\t\thopCountReceivePolicy = s.getCondition(HOPCOUNT_RPOLICY_S);\n\t\t}\n\t}\n\n\t/**\n\t * Adds MessageCommunicationBus Conditions\n\t * @param s Settings where the conditions are read from\n\t */\n\tprivate void addMCBCs(Settings s) {\n\t\tif (!s.contains(NROF_MCBCS_S)) {\n\t\t\treturn; /* no transfer policy defined */\n\t\t}\n\n\t\tint[] nrof = s.getCsvInts(NROF_MCBCS_S);\n\t\tif (nrof[0] > 0) { /* create lists only if needed */\n\t\t\tthis.recvConditions =\n\t\t\t\tnew ArrayList>();\n\t\t}\n\t\tif (nrof[1] > 0) {\n\t\t\tthis.sendConditions =\n\t\t\t\tnew ArrayList>();\n\t\t}\n\n\t\taddConditions(s, MCBACR_S, MCBCVR_S, this.recvConditions, nrof[0]);\n\t\taddConditions(s, MCBACS_S, MCBCVS_S, this.sendConditions, nrof[1]);\n\t}\n\n\t/**\n\t * Read conditions from the settings and add them to the given list\n\t * @param s The settings object\n\t * @param cPrefix Condition setting prefix\n\t * @param vPrefix Value setting prefix\n\t * @param list The list to add conditions\n\t * @param nrof The number of settings to read\n\t */\n\tprivate void addConditions(Settings s, String cPrefix, String vPrefix,\n\t\t\tArrayList> list,\n\t\t\tint nrof) {\n\t\tfor (int i=1; i<=nrof; i++) {\n\t\t\tArithmeticCondition ac = s.getCondition(cPrefix + i);\n\t\t\tString mcbValue = s.getSetting(vPrefix + i);\n\t\t\tlist.add(new Tuple(mcbValue, ac));\n\t\t}\n\t}\n\n\t/**\n\t * Checks all the Module Communication Bus conditions and returns false\n\t * if at least one of them failed.\n\t * @param mcb The module communication bus to use\n\t * @param receiving Should check using the receiving conditions list;\n\t * if false, the sending conditions list is used\n\t * @return true if all conditions evaluated to true\n\t */\n\tprivate boolean checkMcbConditions(ModuleCommunicationBus mcb,\n\t\t\tboolean receiving) {\n\t\tArrayList> list =\n\t\t\t(receiving ? this.recvConditions : this.sendConditions);\n\n\t\tif (list == null) {\n\t\t\treturn true;\n\t\t}\n\n\t\tfor (Tuple t : list) {\n\t\t\tif (!mcb.containsProperty(t.getKey())) {\n\t\t\t\tcontinue; /* no value in the bus; can't fail condition */\n\t\t\t}\n\t\t\tif (t.getValue().isTrueFor(mcb.getDouble(t.getKey(), 0))){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if the host's address is contained in the policy list\n\t * (or {@value #TO_ME_VALUE} is contained and the address matches to\n\t * thisHost parameter)\n\t * @param host The hosts whose address to check\n\t * @param policy The list of accepted addresses\n\t * @param thisHost The address of this host\n\t * @return True if the address was in the policy list, or the policy list\n\t * was null\n\t */\n\tprivate boolean checkSimplePolicy(DTNHost host, Range [] policy,\n\t\t\tint thisHost) {\n\t\tint address;\n\n\t\tif (policy == null) {\n\t\t\treturn true;\n\t\t}\n\n\t\taddress = host.getID();\n\n\t\tfor (Range r : policy) {\n\t\t\tif (r.isInRange(TO_ME_VALUE) && address == thisHost) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t else if (r.isInRange(address)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks the given messages hop count against the given policy arithmetic\n\t * condition\n\t * @param m The message whose hop count is checked\n\t * @param ac The policy arithmetic condition\n\t * @return True if the condition is null or the hop count matches to the\n\t * condition, false otherwise\n\t */\n\tprivate boolean checkHopCountPolicy(Message m, ArithmeticCondition ac) {\n\t\tif (ac == null) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn ac.isTrueFor(m.getHopCount());\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if the given message, using the given connection, is OK\n\t * to send from \"from\" to \"to\" host.\n\t * @param from The sending host\n\t * @param to The receiving host\n\t * @param con The connection used by the hosts\n\t * @param m The message to transfer\n\t * @return True if the message is OK to transfer, false is not\n\t */\n\tpublic boolean acceptSending(DTNHost from, DTNHost to, Connection con,\n\t\t\tMessage m) {\n\t\tif (!checkMcbConditions(from.getComBus(), false)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tint myAddr = from.getID();\n\t\tif (! (checkSimplePolicy(m.getTo(), this.toSendPolicy, myAddr) &&\n\t\t\tcheckSimplePolicy(m.getFrom(), this.fromSendPolicy,\tmyAddr)) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m.getTo() != to &&\n\t\t\t\t!checkHopCountPolicy(m, this.hopCountSendPolicy)){\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns true if the given message is OK to receive from \"from\" to\n\t * \"to\" host.\n\t * @param from The sending host\n\t * @param to The receiving host\n\t * @param m The message to transfer\n\t * @return True if the message is OK to transfer, false is not\n\t */\n\tpublic boolean acceptReceiving(DTNHost from, DTNHost to, Message m) {\n\t\tif (! checkMcbConditions(to.getComBus(), true)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tint myAddr = to.getID();\n\t\tif (! (checkSimplePolicy(m.getTo(), this.toReceivePolicy,myAddr) &&\n\t\t\tcheckSimplePolicy(m.getFrom(), this.fromReceivePolicy, myAddr)) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m.getTo() != to &&\n\t\t\t\t!checkHopCountPolicy(m, this.hopCountReceivePolicy)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n}\n\nsrc/core/Message.java\npublic class Message implements Comparable {\n\t/** Value for infinite TTL of message */\n\tpublic static final int INFINITE_TTL = -1;\n\tprivate DTNHost from;\n\tprivate DTNHost to;\n\t/** Identifier of the message */\n\tprivate String id;\n\t/** Size of the message (bytes) */\n\tprivate int size;\n\t/** List of nodes this message has passed */\n\tprivate List path;\n\t/** Next unique identifier to be given */\n\tprivate static int nextUniqueId;\n\t/** Unique ID of this message */\n\tprivate int uniqueId;\n\t/** The time this message was received */\n\tprivate double timeReceived;\n\t/** The time when this message was created */\n\tprivate double timeCreated;\n\t/** Initial TTL of the message */\n\tprivate int initTtl;\n\n\t/** if a response to this message is required, this is the size of the\n\t * response message (or 0 if no response is requested) */\n\tprivate int responseSize;\n\t/** if this message is a response message, this is set to the request msg*/\n\tprivate Message requestMsg;\n\n\t/** Container for generic message properties. Note that all values\n\t * stored in the properties should be immutable because only a shallow\n\t * copy of the properties is made when replicating messages */\n\tprivate Map properties;\n\n\t/** Application ID of the application that created the message */\n\tprivate String\tappID;\n\n\tstatic {\n\t\treset();\n\t\tDTNSim.registerForReset(Message.class.getCanonicalName());\n\t}\n\n\t/**\n\t * Creates a new Message.\n\t * @param from Who the message is (originally) from\n\t * @param to Who the message is (originally) to\n\t * @param id Message identifier (must be unique for message but\n\t * \twill be the same for all replicates of the message)\n\t * @param size Size of the message (in bytes)\n\t */\n\tpublic Message(DTNHost from, DTNHost to, String id, int size) {\n\t\tthis.from = from;\n\t\tthis.to = to;\n\t\tthis.id = id;\n\t\tthis.size = size;\n\t\tthis.path = new ArrayList();\n\t\tthis.uniqueId = nextUniqueId;\n\n\t\tthis.timeCreated = SimClock.getTime();\n\t\tthis.timeReceived = this.timeCreated;\n\t\tthis.initTtl = INFINITE_TTL;\n\t\tthis.responseSize = 0;\n\t\tthis.requestMsg = null;\n\t\tthis.properties = null;\n\t\tthis.appID = null;\n\n\t\tMessage.nextUniqueId++;\n\t\taddNodeOnPath(from);\n\t}\n\n\t/**\n\t * Returns the node this message is originally from\n\t * @return the node this message is originally from\n\t */\n\tpublic DTNHost getFrom() {\n\t\treturn this.from;\n\t}\n\n\t/**\n\t * Returns the node this message is originally to\n\t * @return the node this message is originally to\n\t */\n\tpublic DTNHost getTo() {\n\t\treturn this.to;\n\t}\n\n\t/**\n\t * Returns the ID of the message\n\t * @return The message id\n\t */\n\tpublic String getId() {\n\t\treturn this.id;\n\t}\n\n\t/**\n\t * Returns an ID that is unique per message instance\n\t * (different for replicates too)\n\t * @return The unique id\n\t */\n\tpublic int getUniqueId() {\n\t\treturn this.uniqueId;\n\t}\n\n\t/**\n\t * Returns the size of the message (in bytes)\n\t * @return the size of the message\n\t */\n\tpublic int getSize() {\n\t\treturn this.size;\n\t}\n\n\t/**\n\t * Adds a new node on the list of nodes this message has passed\n\t * @param node The node to add\n\t */\n\tpublic void addNodeOnPath(DTNHost node) {\n\t\tthis.path.add(node);\n\t}\n\n\t/**\n\t * Returns a list of nodes this message has passed so far\n\t * @return The list as vector\n\t */\n\tpublic List getHops() {\n\t\treturn this.path;\n\t}\n\n\t/**\n\t * Returns the amount of hops this message has passed\n\t * @return the amount of hops this message has passed\n\t */\n\tpublic int getHopCount() {\n\t\treturn this.path.size() -1;\n\t}\n\n\t/**\n\t * Returns the time to live (minutes) of the message or Integer.MAX_VALUE\n\t * if the TTL is infinite. Returned value can be negative if the TTL has\n\t * passed already.\n\t * @return The TTL (minutes)\n\t */\n\tpublic int getTtl() {\n\t\tif (this.initTtl == INFINITE_TTL) {\n\t\t\treturn Integer.MAX_VALUE;\n\t\t}\n\t\telse {\n\t\t\treturn (int)( ((this.initTtl * 60) -\n\t\t\t\t\t(SimClock.getTime()-this.timeCreated)) /60.0 );\n\t\t}\n\t}\n\n\n\t/**\n\t * Sets the initial TTL (time-to-live) for this message. The initial\n\t * TTL is the TTL when the original message was created. The current TTL\n\t * is calculated based on the time of\n\t * @param ttl The time-to-live to set\n\t */\n\tpublic void setTtl(int ttl) {\n\t\tthis.initTtl = ttl;\n\t}\n\n\t/**\n\t * Sets the time when this message was received.\n\t * @param time The time to set\n\t */\n\tpublic void setReceiveTime(double time) {\n\t\tthis.timeReceived = time;\n\t}\n\n\t/**\n\t * Returns the time when this message was received\n\t * @return The time\n\t */\n\tpublic double getReceiveTime() {\n\t\treturn this.timeReceived;\n\t}\n\n\t/**\n\t * Returns the time when this message was created\n\t * @return the time when this message was created\n\t */\n\tpublic double getCreationTime() {\n\t\treturn this.timeCreated;\n\t}\n\n\t/**\n\t * If this message is a response to a request, sets the request message\n\t * @param request The request message\n\t */\n\tpublic void setRequest(Message request) {\n\t\tthis.requestMsg = request;\n\t}\n\n\t/**\n\t * Returns the message this message is response to or null if this is not\n\t * a response message\n\t * @return the message this message is response to\n\t */\n\tpublic Message getRequest() {\n\t\treturn this.requestMsg;\n\t}\n\n\t/**\n\t * Returns true if this message is a response message\n\t * @return true if this message is a response message\n\t */\n\tpublic boolean isResponse() {\n\t\treturn this.requestMsg != null;\n\t}\n\n\t/**\n\t * Sets the requested response message's size. If size == 0, no response\n\t * is requested (default)\n\t * @param size Size of the response message\n\t */\n\tpublic void setResponseSize(int size) {\n\t\tthis.responseSize = size;\n\t}\n\n\t/**\n\t * Returns the size of the requested response message or 0 if no response\n\t * is requested.\n\t * @return the size of the requested response message\n\t */\n\tpublic int getResponseSize() {\n\t\treturn responseSize;\n\t}\n\n\t/**\n\t * Returns a string representation of the message\n\t * @return a string representation of the message\n\t */\n\tpublic String toString () {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Deep copies message data from other message. If new fields are\n\t * introduced to this class, most likely they should be copied here too\n\t * (unless done in constructor).\n\t * @param m The message where the data is copied\n\t */\n\tprotected void copyFrom(Message m) {\n\t\tthis.path = new ArrayList(m.path);\n\t\tthis.timeCreated = m.timeCreated;\n\t\tthis.responseSize = m.responseSize;\n\t\tthis.requestMsg = m.requestMsg;\n\t\tthis.initTtl = m.initTtl;\n\t\tthis.appID = m.appID;\n\n\t\tif (m.properties != null) {\n\t\t\tSet keys = m.properties.keySet();\n\t\t\tfor (String key : keys) {\n\t\t\t\tupdateProperty(key, m.getProperty(key));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Adds a generic property for this message. The key can be any string but\n\t * it should be such that no other class accidently uses the same value.\n\t * The value can be any object but it's good idea to store only immutable\n\t * objects because when message is replicated, only a shallow copy of the\n\t * properties is made.\n\t * @param key The key which is used to lookup the value\n\t * @param value The value to store\n\t * @throws SimError if the message already has a value for the given key\n\t */\n\tpublic void addProperty(String key, Object value) throws SimError {\n\t\tif (this.properties != null && this.properties.containsKey(key)) {\n\t\t\t/* check to prevent accidental name space collisions */\n\t\t\tthrow new SimError(\"Message \" + this + \" already contains value \" +\n\t\t\t\t\t\"for a key \" + key);\n\t\t}\n\n\t\tthis.updateProperty(key, value);\n\t}\n\n\t/**\n\t * Returns an object that was stored to this message using the given\n\t * key. If such object is not found, null is returned.\n\t * @param key The key used to lookup the object\n\t * @return The stored object or null if it isn't found\n\t */\n\tpublic Object getProperty(String key) {\n\t\tif (this.properties == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn this.properties.get(key);\n\t}\n\n\t/**\n\t * Updates a value for an existing property. For storing the value first\n\t * time, {@link #addProperty(String, Object)} should be used which\n\t * checks for name space clashes.\n\t * @param key The key which is used to lookup the value\n\t * @param value The new value to store\n\t */\n\tpublic void updateProperty(String key, Object value) throws SimError {\n\t\tif (this.properties == null) {\n\t\t\t/* lazy creation to prevent performance overhead for classes\n\t\t\t that don't use the property feature */\n\t\t\tthis.properties = new HashMap();\n\t\t}\n\n\t\tthis.properties.put(key, value);\n\t}\n\n\t/**\n\t * Returns a replicate of this message (identical except for the unique id)\n\t * @return A replicate of the message\n\t */\n\tpublic Message replicate() {\n\t\tMessage m = new Message(from, to, id, size);\n\t\tm.copyFrom(this);\n\t\treturn m;\n\t}\n\n\t/**\n\t * Compares two messages by their ID (alphabetically).\n\t * @see String#compareTo(String)\n\t */\n\tpublic int compareTo(Message m) {\n\t\treturn toString().compareTo(m.toString());\n\t}\n\n\t/**\n\t * Resets all static fields to default values\n\t */\n\tpublic static void reset() {\n\t\tnextUniqueId = 0;\n\t}\n\n\t/**\n\t * @return the appID\n\t */\n\tpublic String getAppID() {\n\t\treturn appID;\n\t}\n\n\t/**\n\t * @param appID the appID to set\n\t */\n\tpublic void setAppID(String appID) {\n\t\tthis.appID = appID;\n\t}\n\n}", "answers": ["\t\tif (m.getTo() == getHost() && m.getResponseSize() > 0) {"], "length": 13382, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "d9a925b9-f5c7-4884-a2b7-a3847a555abd", "reasoning": "In ActiveRouter.messageTransferred, after calling super.messageTransferred and the comment about checking if the message was for this host and a response was requested, the next logical line is the conditional that performs this check. The code checks whether the destination of the transferred message is the current host and whether a response size is set (>0). Hence the next line is the if statement that starts this check.", "reasoning_model_answer": "if (m.getTo() == getHost() && m.getResponseSize() > 0) {", "assistant_with_reasoning": "\nIn ActiveRouter.messageTransferred, after calling super.messageTransferred and the comment about checking if the message was for this host and a response was requested, the next logical line is the conditional that performs this check. The code checks whether the destination of the transferred message is the current host and whether a response size is set (>0). Hence the next line is the if statement that starts this check.\n\nif (m.getTo() == getHost() && m.getResponseSize() > 0) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.226, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36464, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "if (m.getTo() == getHost() && m.getResponseSize() > 0) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Component;\nimport com.netflix.conductor.common.metadata.tasks.TaskDef;\nimport com.netflix.conductor.common.metadata.tasks.TaskType;\nimport com.netflix.conductor.common.metadata.workflow.WorkflowDef;\nimport com.netflix.conductor.common.metadata.workflow.WorkflowTask;\nimport com.netflix.conductor.core.exception.TerminateWorkflowException;\nimport com.netflix.conductor.core.utils.ParametersUtils;\nimport com.netflix.conductor.model.TaskModel;\nimport com.netflix.conductor.model.WorkflowModel;", "context": "core/src/main/java/com/netflix/conductor/core/execution/mapper/SimpleTaskMapper.java\n/*\n * Copyright 2022 Conductor Authors.\n *

\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *

\n * http://www.apache.org/licenses/LICENSE-2.0\n *

\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\npackage com.netflix.conductor.core.execution.mapper;\n\n\n\n\n/**\n * An implementation of {@link TaskMapper} to map a {@link WorkflowTask} of type {@link\n * TaskType#SIMPLE} to a {@link TaskModel} with status {@link TaskModel.Status#SCHEDULED}.\n * NOTE: There is not type defined for simples task.\n */\n@Component\npublic class SimpleTaskMapper implements TaskMapper {\n\n public static final Logger LOGGER = LoggerFactory.getLogger(SimpleTaskMapper.class);\n private final ParametersUtils parametersUtils;\n\n public SimpleTaskMapper(ParametersUtils parametersUtils) {\n this.parametersUtils = parametersUtils;\n }\n\n @Override\n public String getTaskType() {\n\ncommon/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowDef.java\n@ProtoMessage\n@TaskReferenceNameUniqueConstraint\npublic class WorkflowDef extends BaseDef {\n\n @ProtoEnum\n public enum TimeoutPolicy {\n TIME_OUT_WF,\n ALERT_ONLY\n }\n\n @NotEmpty(message = \"WorkflowDef name cannot be null or empty\")\n @ProtoField(id = 1)\n @NoSemiColonConstraint(\n message = \"Workflow name cannot contain the following set of characters: ':'\")\n private String name;\n\n @ProtoField(id = 2)\n private String description;\n\n @ProtoField(id = 3)\n private int version = 1;\n\n @ProtoField(id = 4)\n @NotNull\n @NotEmpty(message = \"WorkflowTask list cannot be empty\")\n private List<@Valid WorkflowTask> tasks = new LinkedList<>();\n\n @ProtoField(id = 5)\n private List inputParameters = new LinkedList<>();\n\n @ProtoField(id = 6)\n private Map outputParameters = new HashMap<>();\n\n @ProtoField(id = 7)\n private String failureWorkflow;\n\n @ProtoField(id = 8)\n @Min(value = 2, message = \"workflowDef schemaVersion: {value} is only supported\")\n @Max(value = 2, message = \"workflowDef schemaVersion: {value} is only supported\")\n private int schemaVersion = 2;\n\n // By default, a workflow is restartable\n @ProtoField(id = 9)\n private boolean restartable = true;\n\n @ProtoField(id = 10)\n private boolean workflowStatusListenerEnabled = false;\n\n @ProtoField(id = 11)\n @OwnerEmailMandatoryConstraint\n @Email(message = \"ownerEmail should be valid email address\")\n private String ownerEmail;\n\n @ProtoField(id = 12)\n private TimeoutPolicy timeoutPolicy = TimeoutPolicy.ALERT_ONLY;\n\n @ProtoField(id = 13)\n @NotNull\n private long timeoutSeconds;\n\n @ProtoField(id = 14)\n private Map variables = new HashMap<>();\n\n @ProtoField(id = 15)\n private Map inputTemplate = new HashMap<>();\n\n /**\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name the name to set\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return the description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description the description to set\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return the tasks\n */\n public List getTasks() {\n return tasks;\n }\n\n /**\n * @param tasks the tasks to set\n */\n public void setTasks(List<@Valid WorkflowTask> tasks) {\n this.tasks = tasks;\n }\n\n /**\n * @return the inputParameters\n */\n public List getInputParameters() {\n return inputParameters;\n }\n\n /**\n * @param inputParameters the inputParameters to set\n */\n public void setInputParameters(List inputParameters) {\n this.inputParameters = inputParameters;\n }\n\n /**\n * @return the outputParameters\n */\n public Map getOutputParameters() {\n return outputParameters;\n }\n\n /**\n * @param outputParameters the outputParameters to set\n */\n public void setOutputParameters(Map outputParameters) {\n this.outputParameters = outputParameters;\n }\n\n /**\n * @return the version\n */\n public int getVersion() {\n return version;\n }\n\n /**\n * @return the failureWorkflow\n */\n public String getFailureWorkflow() {\n return failureWorkflow;\n }\n\n /**\n * @param failureWorkflow the failureWorkflow to set\n */\n public void setFailureWorkflow(String failureWorkflow) {\n this.failureWorkflow = failureWorkflow;\n }\n\n /**\n * @param version the version to set\n */\n public void setVersion(int version) {\n this.version = version;\n }\n\n /**\n * This method determines if the workflow is restartable or not\n *\n * @return true: if the workflow is restartable false: if the workflow is non restartable\n */\n public boolean isRestartable() {\n return restartable;\n }\n\n /**\n * This method is called only when the workflow definition is created\n *\n * @param restartable true: if the workflow is restartable false: if the workflow is non\n * restartable\n */\n public void setRestartable(boolean restartable) {\n this.restartable = restartable;\n }\n\n /**\n * @return the schemaVersion\n */\n public int getSchemaVersion() {\n return schemaVersion;\n }\n\n /**\n * @param schemaVersion the schemaVersion to set\n */\n public void setSchemaVersion(int schemaVersion) {\n this.schemaVersion = schemaVersion;\n }\n\n /**\n * @return true is workflow listener will be invoked when workflow gets into a terminal state\n */\n public boolean isWorkflowStatusListenerEnabled() {\n return workflowStatusListenerEnabled;\n }\n\n /**\n * Specify if workflow listener is enabled to invoke a callback for completed or terminated\n * workflows\n *\n * @param workflowStatusListenerEnabled\n */\n public void setWorkflowStatusListenerEnabled(boolean workflowStatusListenerEnabled) {\n this.workflowStatusListenerEnabled = workflowStatusListenerEnabled;\n }\n\n /**\n * @return the email of the owner of this workflow definition\n */\n public String getOwnerEmail() {\n return ownerEmail;\n }\n\n /**\n * @param ownerEmail the owner email to set\n */\n public void setOwnerEmail(String ownerEmail) {\n this.ownerEmail = ownerEmail;\n }\n\n /**\n * @return the timeoutPolicy\n */\n public TimeoutPolicy getTimeoutPolicy() {\n return timeoutPolicy;\n }\n\n /**\n * @param timeoutPolicy the timeoutPolicy to set\n */\n public void setTimeoutPolicy(TimeoutPolicy timeoutPolicy) {\n this.timeoutPolicy = timeoutPolicy;\n }\n\n /**\n * @return the time after which a workflow is deemed to have timed out\n */\n public long getTimeoutSeconds() {\n return timeoutSeconds;\n }\n\n /**\n * @param timeoutSeconds the timeout in seconds to set\n */\n public void setTimeoutSeconds(long timeoutSeconds) {\n this.timeoutSeconds = timeoutSeconds;\n }\n\n /**\n * @return the global workflow variables\n */\n public Map getVariables() {\n return variables;\n }\n\n /**\n * @param variables the set of global workflow variables to set\n */\n public void setVariables(Map variables) {\n this.variables = variables;\n }\n\n public Map getInputTemplate() {\n return inputTemplate;\n }\n\n public void setInputTemplate(Map inputTemplate) {\n this.inputTemplate = inputTemplate;\n }\n\n public String key() {\n return getKey(name, version);\n }\n\n public static String getKey(String name, int version) {\n return name + \".\" + version;\n }\n\n public boolean containsType(String taskType) {\n return collectTasks().stream().anyMatch(t -> t.getType().equals(taskType));\n }\n\n public WorkflowTask getNextTask(String taskReferenceName) {\n WorkflowTask workflowTask = getTaskByRefName(taskReferenceName);\n if (workflowTask != null && TaskType.TERMINATE.name().equals(workflowTask.getType())) {\n return null;\n }\n\n Iterator iterator = tasks.iterator();\n while (iterator.hasNext()) {\n WorkflowTask task = iterator.next();\n if (task.getTaskReferenceName().equals(taskReferenceName)) {\n // If taskReferenceName matches, break out\n break;\n }\n WorkflowTask nextTask = task.next(taskReferenceName, null);\n if (nextTask != null) {\n return nextTask;\n } else if (TaskType.DO_WHILE.name().equals(task.getType())\n && !task.getTaskReferenceName().equals(taskReferenceName)\n && task.has(taskReferenceName)) {\n // If the task is child of Loop Task and at last position, return null.\n return null;\n }\n\n if (task.has(taskReferenceName)) {\n break;\n }\n }\n if (iterator.hasNext()) {\n return iterator.next();\n }\n return null;\n }\n\n public WorkflowTask getTaskByRefName(String taskReferenceName) {\n return collectTasks().stream()\n .filter(\n workflowTask ->\n workflowTask.getTaskReferenceName().equals(taskReferenceName))\n .findFirst()\n .orElse(null);\n }\n\n public List collectTasks() {\n List tasks = new LinkedList<>();\n for (WorkflowTask workflowTask : this.tasks) {\n tasks.addAll(workflowTask.collectTasks());\n }\n return tasks;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n WorkflowDef that = (WorkflowDef) o;\n return getVersion() == that.getVersion()\n && getSchemaVersion() == that.getSchemaVersion()\n && Objects.equals(getName(), that.getName())\n && Objects.equals(getDescription(), that.getDescription())\n && Objects.equals(getTasks(), that.getTasks())\n && Objects.equals(getInputParameters(), that.getInputParameters())\n && Objects.equals(getOutputParameters(), that.getOutputParameters())\n && Objects.equals(getFailureWorkflow(), that.getFailureWorkflow())\n && Objects.equals(getOwnerEmail(), that.getOwnerEmail())\n && Objects.equals(getTimeoutSeconds(), that.getTimeoutSeconds());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n getName(),\n getDescription(),\n getVersion(),\n getTasks(),\n getInputParameters(),\n getOutputParameters(),\n getFailureWorkflow(),\n getSchemaVersion(),\n getOwnerEmail(),\n getTimeoutSeconds());\n }\n\n @Override\n public String toString() {\n return \"WorkflowDef{\"\n + \"name='\"\n + name\n + '\\''\n + \", description='\"\n + description\n + '\\''\n + \", version=\"\n + version\n + \", tasks=\"\n + tasks\n + \", inputParameters=\"\n + inputParameters\n + \", outputParameters=\"\n + outputParameters\n + \", failureWorkflow='\"\n + failureWorkflow\n + '\\''\n + \", schemaVersion=\"\n + schemaVersion\n + \", restartable=\"\n + restartable\n + \", workflowStatusListenerEnabled=\"\n + workflowStatusListenerEnabled\n + \", timeoutSeconds=\"\n + timeoutSeconds\n + '}';\n }\n}\n\ncore/src/main/java/com/netflix/conductor/core/exception/TerminateWorkflowException.java\npublic class TerminateWorkflowException extends RuntimeException {\n\n private final WorkflowModel.Status workflowStatus;\n private final TaskModel task;\n\n public TerminateWorkflowException(String reason) {\n this(reason, FAILED);\n }\n\n public TerminateWorkflowException(String reason, WorkflowModel.Status workflowStatus) {\n this(reason, workflowStatus, null);\n }\n\n public TerminateWorkflowException(\n String reason, WorkflowModel.Status workflowStatus, TaskModel task) {\n super(reason);\n this.workflowStatus = workflowStatus;\n this.task = task;\n }\n\n public WorkflowModel.Status getWorkflowStatus() {\n return workflowStatus;\n }\n\n public TaskModel getTask() {\n return task;\n }\n}\n\ncommon/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskDef.java\n@ProtoMessage\n@TaskTimeoutConstraint\n@Valid\npublic class TaskDef extends BaseDef {\n\n @ProtoEnum\n public enum TimeoutPolicy {\n RETRY,\n TIME_OUT_WF,\n ALERT_ONLY\n }\n\n @ProtoEnum\n public enum RetryLogic {\n FIXED,\n EXPONENTIAL_BACKOFF,\n LINEAR_BACKOFF\n }\n\n public static final int ONE_HOUR = 60 * 60;\n\n /** Unique name identifying the task. The name is unique across */\n @NotEmpty(message = \"TaskDef name cannot be null or empty\")\n @ProtoField(id = 1)\n private String name;\n\n @ProtoField(id = 2)\n private String description;\n\n @ProtoField(id = 3)\n @Min(value = 0, message = \"TaskDef retryCount: {value} must be >= 0\")\n private int retryCount = 3; // Default\n\n @ProtoField(id = 4)\n @NotNull\n private long timeoutSeconds;\n\n @ProtoField(id = 5)\n private List inputKeys = new ArrayList<>();\n\n @ProtoField(id = 6)\n private List outputKeys = new ArrayList<>();\n\n @ProtoField(id = 7)\n private TimeoutPolicy timeoutPolicy = TimeoutPolicy.TIME_OUT_WF;\n\n @ProtoField(id = 8)\n private RetryLogic retryLogic = RetryLogic.FIXED;\n\n @ProtoField(id = 9)\n private int retryDelaySeconds = 60;\n\n @ProtoField(id = 10)\n @Min(\n value = 1,\n message =\n \"TaskDef responseTimeoutSeconds: ${validatedValue} should be minimum {value} second\")\n private long responseTimeoutSeconds = ONE_HOUR;\n\n @ProtoField(id = 11)\n private Integer concurrentExecLimit;\n\n @ProtoField(id = 12)\n private Map inputTemplate = new HashMap<>();\n\n // This field is deprecated, do not use id 13.\n //\t@ProtoField(id = 13)\n //\tprivate Integer rateLimitPerSecond;\n\n @ProtoField(id = 14)\n private Integer rateLimitPerFrequency;\n\n @ProtoField(id = 15)\n private Integer rateLimitFrequencyInSeconds;\n\n @ProtoField(id = 16)\n private String isolationGroupId;\n\n @ProtoField(id = 17)\n private String executionNameSpace;\n\n @ProtoField(id = 18)\n @OwnerEmailMandatoryConstraint\n @Email(message = \"ownerEmail should be valid email address\")\n private String ownerEmail;\n\n @ProtoField(id = 19)\n @Min(value = 0, message = \"TaskDef pollTimeoutSeconds: {value} must be >= 0\")\n private Integer pollTimeoutSeconds;\n\n @ProtoField(id = 20)\n @Min(value = 1, message = \"Backoff scale factor. Applicable for LINEAR_BACKOFF\")\n private Integer backoffScaleFactor = 1;\n\n public TaskDef() {}\n\n public TaskDef(String name) {\n this.name = name;\n }\n\n public TaskDef(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n public TaskDef(String name, String description, int retryCount, long timeoutSeconds) {\n this.name = name;\n this.description = description;\n this.retryCount = retryCount;\n this.timeoutSeconds = timeoutSeconds;\n }\n\n public TaskDef(\n String name,\n String description,\n String ownerEmail,\n int retryCount,\n long timeoutSeconds,\n long responseTimeoutSeconds) {\n this.name = name;\n this.description = description;\n this.ownerEmail = ownerEmail;\n this.retryCount = retryCount;\n this.timeoutSeconds = timeoutSeconds;\n this.responseTimeoutSeconds = responseTimeoutSeconds;\n }\n\n /**\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name the name to set\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return the description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description the description to set\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return the retryCount\n */\n public int getRetryCount() {\n return retryCount;\n }\n\n /**\n * @param retryCount the retryCount to set\n */\n public void setRetryCount(int retryCount) {\n this.retryCount = retryCount;\n }\n\n /**\n * @return the timeoutSeconds\n */\n public long getTimeoutSeconds() {\n return timeoutSeconds;\n }\n\n /**\n * @param timeoutSeconds the timeoutSeconds to set\n */\n public void setTimeoutSeconds(long timeoutSeconds) {\n this.timeoutSeconds = timeoutSeconds;\n }\n\n /**\n * @return Returns the input keys\n */\n public List getInputKeys() {\n return inputKeys;\n }\n\n /**\n * @param inputKeys Set of keys that the task accepts in the input map\n */\n public void setInputKeys(List inputKeys) {\n this.inputKeys = inputKeys;\n }\n\n /**\n * @return Returns the output keys for the task when executed\n */\n public List getOutputKeys() {\n return outputKeys;\n }\n\n /**\n * @param outputKeys Sets the output keys\n */\n public void setOutputKeys(List outputKeys) {\n this.outputKeys = outputKeys;\n }\n\n /**\n * @return the timeoutPolicy\n */\n public TimeoutPolicy getTimeoutPolicy() {\n return timeoutPolicy;\n }\n\n /**\n * @param timeoutPolicy the timeoutPolicy to set\n */\n public void setTimeoutPolicy(TimeoutPolicy timeoutPolicy) {\n this.timeoutPolicy = timeoutPolicy;\n }\n\n /**\n * @return the retryLogic\n */\n public RetryLogic getRetryLogic() {\n return retryLogic;\n }\n\n /**\n * @param retryLogic the retryLogic to set\n */\n public void setRetryLogic(RetryLogic retryLogic) {\n this.retryLogic = retryLogic;\n }\n\n /**\n * @return the retryDelaySeconds\n */\n public int getRetryDelaySeconds() {\n return retryDelaySeconds;\n }\n\n /**\n * @return the timeout for task to send response. After this timeout, the task will be re-queued\n */\n public long getResponseTimeoutSeconds() {\n return responseTimeoutSeconds;\n }\n\n /**\n * @param responseTimeoutSeconds - timeout for task to send response. After this timeout, the\n * task will be re-queued\n */\n public void setResponseTimeoutSeconds(long responseTimeoutSeconds) {\n this.responseTimeoutSeconds = responseTimeoutSeconds;\n }\n\n /**\n * @param retryDelaySeconds the retryDelaySeconds to set\n */\n public void setRetryDelaySeconds(int retryDelaySeconds) {\n this.retryDelaySeconds = retryDelaySeconds;\n }\n\n /**\n * @return the inputTemplate\n */\n public Map getInputTemplate() {\n return inputTemplate;\n }\n\n /**\n * @return rateLimitPerFrequency The max number of tasks that will be allowed to be executed per\n * rateLimitFrequencyInSeconds.\n */\n public Integer getRateLimitPerFrequency() {\n return rateLimitPerFrequency == null ? 0 : rateLimitPerFrequency;\n }\n\n /**\n * @param rateLimitPerFrequency The max number of tasks that will be allowed to be executed per\n * rateLimitFrequencyInSeconds. Setting the value to 0 removes the rate limit\n */\n public void setRateLimitPerFrequency(Integer rateLimitPerFrequency) {\n this.rateLimitPerFrequency = rateLimitPerFrequency;\n }\n\n /**\n * @return rateLimitFrequencyInSeconds: The time bucket that is used to rate limit tasks based\n * on {@link #getRateLimitPerFrequency()} If null or not set, then defaults to 1 second\n */\n public Integer getRateLimitFrequencyInSeconds() {\n return rateLimitFrequencyInSeconds == null ? 1 : rateLimitFrequencyInSeconds;\n }\n\n /**\n * @param rateLimitFrequencyInSeconds: The time window/bucket for which the rate limit needs to\n * be applied. This will only have affect if {@link #getRateLimitPerFrequency()} is greater\n * than zero\n */\n public void setRateLimitFrequencyInSeconds(Integer rateLimitFrequencyInSeconds) {\n this.rateLimitFrequencyInSeconds = rateLimitFrequencyInSeconds;\n }\n\n /**\n * @param concurrentExecLimit Limit of number of concurrent task that can be IN_PROGRESS at a\n * given time. Seting the value to 0 removes the limit.\n */\n public void setConcurrentExecLimit(Integer concurrentExecLimit) {\n this.concurrentExecLimit = concurrentExecLimit;\n }\n\n /**\n * @return Limit of number of concurrent task that can be IN_PROGRESS at a given time\n */\n public Integer getConcurrentExecLimit() {\n return concurrentExecLimit;\n }\n\n /**\n * @return concurrency limit\n */\n public int concurrencyLimit() {\n return concurrentExecLimit == null ? 0 : concurrentExecLimit;\n }\n\n /**\n * @param inputTemplate the inputTemplate to set\n */\n public void setInputTemplate(Map inputTemplate) {\n this.inputTemplate = inputTemplate;\n }\n\n public String getIsolationGroupId() {\n return isolationGroupId;\n }\n\n public void setIsolationGroupId(String isolationGroupId) {\n this.isolationGroupId = isolationGroupId;\n }\n\n public String getExecutionNameSpace() {\n return executionNameSpace;\n }\n\n public void setExecutionNameSpace(String executionNameSpace) {\n this.executionNameSpace = executionNameSpace;\n }\n\n /**\n * @return the email of the owner of this task definition\n */\n public String getOwnerEmail() {\n return ownerEmail;\n }\n\n /**\n * @param ownerEmail the owner email to set\n */\n public void setOwnerEmail(String ownerEmail) {\n this.ownerEmail = ownerEmail;\n }\n\n /**\n * @param pollTimeoutSeconds the poll timeout to set\n */\n public void setPollTimeoutSeconds(Integer pollTimeoutSeconds) {\n this.pollTimeoutSeconds = pollTimeoutSeconds;\n }\n\n /**\n * @return the poll timeout of this task definition\n */\n public Integer getPollTimeoutSeconds() {\n return pollTimeoutSeconds;\n }\n\n /**\n * @param backoffScaleFactor the backoff rate to set\n */\n public void setBackoffScaleFactor(Integer backoffScaleFactor) {\n this.backoffScaleFactor = backoffScaleFactor;\n }\n\n /**\n * @return the backoff rate of this task definition\n */\n public Integer getBackoffScaleFactor() {\n return backoffScaleFactor;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n TaskDef taskDef = (TaskDef) o;\n return getRetryCount() == taskDef.getRetryCount()\n && getTimeoutSeconds() == taskDef.getTimeoutSeconds()\n && getRetryDelaySeconds() == taskDef.getRetryDelaySeconds()\n && getBackoffScaleFactor() == taskDef.getBackoffScaleFactor()\n && getResponseTimeoutSeconds() == taskDef.getResponseTimeoutSeconds()\n && Objects.equals(getName(), taskDef.getName())\n && Objects.equals(getDescription(), taskDef.getDescription())\n && Objects.equals(getInputKeys(), taskDef.getInputKeys())\n && Objects.equals(getOutputKeys(), taskDef.getOutputKeys())\n && getTimeoutPolicy() == taskDef.getTimeoutPolicy()\n && getRetryLogic() == taskDef.getRetryLogic()\n && Objects.equals(getConcurrentExecLimit(), taskDef.getConcurrentExecLimit())\n && Objects.equals(getRateLimitPerFrequency(), taskDef.getRateLimitPerFrequency())\n && Objects.equals(getInputTemplate(), taskDef.getInputTemplate())\n && Objects.equals(getIsolationGroupId(), taskDef.getIsolationGroupId())\n && Objects.equals(getExecutionNameSpace(), taskDef.getExecutionNameSpace())\n && Objects.equals(getOwnerEmail(), taskDef.getOwnerEmail());\n }\n\n @Override\n public int hashCode() {\n\n return Objects.hash(\n getName(),\n getDescription(),\n getRetryCount(),\n getTimeoutSeconds(),\n getInputKeys(),\n getOutputKeys(),\n getTimeoutPolicy(),\n getRetryLogic(),\n getRetryDelaySeconds(),\n getBackoffScaleFactor(),\n getResponseTimeoutSeconds(),\n getConcurrentExecLimit(),\n getRateLimitPerFrequency(),\n getInputTemplate(),\n getIsolationGroupId(),\n getExecutionNameSpace(),\n getOwnerEmail());\n }\n}\n\ncommon/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowTask.java\n@ProtoMessage\npublic class WorkflowTask {\n\n @ProtoField(id = 1)\n @NotEmpty(message = \"WorkflowTask name cannot be empty or null\")\n private String name;\n\n @ProtoField(id = 2)\n @NotEmpty(message = \"WorkflowTask taskReferenceName name cannot be empty or null\")\n private String taskReferenceName;\n\n @ProtoField(id = 3)\n private String description;\n\n @ProtoField(id = 4)\n private Map inputParameters = new HashMap<>();\n\n @ProtoField(id = 5)\n private String type = TaskType.SIMPLE.name();\n\n @ProtoField(id = 6)\n private String dynamicTaskNameParam;\n\n @Deprecated\n @ProtoField(id = 7)\n private String caseValueParam;\n\n @Deprecated\n @ProtoField(id = 8)\n private String caseExpression;\n\n @ProtoField(id = 22)\n private String scriptExpression;\n\n @ProtoMessage(wrapper = true)\n public static class WorkflowTaskList {\n\n public List getTasks() {\n return tasks;\n }\n\n public void setTasks(List tasks) {\n this.tasks = tasks;\n }\n\n @ProtoField(id = 1)\n private List tasks;\n }\n\n // Populates for the tasks of the decision type\n @ProtoField(id = 9)\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private Map> decisionCases = new LinkedHashMap<>();\n\n @Deprecated private String dynamicForkJoinTasksParam;\n\n @ProtoField(id = 10)\n private String dynamicForkTasksParam;\n\n @ProtoField(id = 11)\n private String dynamicForkTasksInputParamName;\n\n @ProtoField(id = 12)\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private List<@Valid WorkflowTask> defaultCase = new LinkedList<>();\n\n @ProtoField(id = 13)\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private List<@Valid List<@Valid WorkflowTask>> forkTasks = new LinkedList<>();\n\n @ProtoField(id = 14)\n @PositiveOrZero\n private int startDelay; // No. of seconds (at-least) to wait before starting a task.\n\n @ProtoField(id = 15)\n @Valid\n private SubWorkflowParams subWorkflowParam;\n\n @ProtoField(id = 16)\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private List joinOn = new LinkedList<>();\n\n @ProtoField(id = 17)\n private String sink;\n\n @ProtoField(id = 18)\n private boolean optional = false;\n\n @ProtoField(id = 19)\n private TaskDef taskDefinition;\n\n @ProtoField(id = 20)\n private Boolean rateLimited;\n\n @ProtoField(id = 21)\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private List defaultExclusiveJoinTask = new LinkedList<>();\n\n @ProtoField(id = 23)\n private Boolean asyncComplete = false;\n\n @ProtoField(id = 24)\n private String loopCondition;\n\n @ProtoField(id = 25)\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private List loopOver = new LinkedList<>();\n\n @ProtoField(id = 26)\n private Integer retryCount;\n\n @ProtoField(id = 27)\n private String evaluatorType;\n\n @ProtoField(id = 28)\n private String expression;\n\n @ProtoField(id = 29)\n private boolean permissive = false;\n\n /**\n * @return the name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @param name the name to set\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return the taskReferenceName\n */\n public String getTaskReferenceName() {\n return taskReferenceName;\n }\n\n /**\n * @param taskReferenceName the taskReferenceName to set\n */\n public void setTaskReferenceName(String taskReferenceName) {\n this.taskReferenceName = taskReferenceName;\n }\n\n /**\n * @return the description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description the description to set\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return the inputParameters\n */\n public Map getInputParameters() {\n return inputParameters;\n }\n\n /**\n * @param inputParameters the inputParameters to set\n */\n public void setInputParameters(Map inputParameters) {\n this.inputParameters = inputParameters;\n }\n\n /**\n * @return the type\n */\n public String getType() {\n return type;\n }\n\n public void setWorkflowTaskType(TaskType type) {\n this.type = type.name();\n }\n\n /**\n * @param type the type to set\n */\n public void setType(@NotEmpty(message = \"WorkTask type cannot be null or empty\") String type) {\n this.type = type;\n }\n\n /**\n * @return the decisionCases\n */\n public Map> getDecisionCases() {\n return decisionCases;\n }\n\n /**\n * @param decisionCases the decisionCases to set\n */\n public void setDecisionCases(Map> decisionCases) {\n this.decisionCases = decisionCases;\n }\n\n /**\n * @return the defaultCase\n */\n public List getDefaultCase() {\n return defaultCase;\n }\n\n /**\n * @param defaultCase the defaultCase to set\n */\n public void setDefaultCase(List defaultCase) {\n this.defaultCase = defaultCase;\n }\n\n /**\n * @return the forkTasks\n */\n public List> getForkTasks() {\n return forkTasks;\n }\n\n /**\n * @param forkTasks the forkTasks to set\n */\n public void setForkTasks(List> forkTasks) {\n this.forkTasks = forkTasks;\n }\n\n /**\n * @return the startDelay in seconds\n */\n public int getStartDelay() {\n return startDelay;\n }\n\n /**\n * @param startDelay the startDelay to set\n */\n public void setStartDelay(int startDelay) {\n this.startDelay = startDelay;\n }\n\n /**\n * @return the retryCount\n */\n public Integer getRetryCount() {\n return retryCount;\n }\n\n /**\n * @param retryCount the retryCount to set\n */\n public void setRetryCount(final Integer retryCount) {\n this.retryCount = retryCount;\n }\n\n /**\n * @return the dynamicTaskNameParam\n */\n public String getDynamicTaskNameParam() {\n return dynamicTaskNameParam;\n }\n\n /**\n * @param dynamicTaskNameParam the dynamicTaskNameParam to set to be used by DYNAMIC tasks\n */\n public void setDynamicTaskNameParam(String dynamicTaskNameParam) {\n this.dynamicTaskNameParam = dynamicTaskNameParam;\n }\n\n /**\n * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link\n * WorkflowTask#getExpression()} combination.\n * @return the caseValueParam\n */\n @Deprecated\n public String getCaseValueParam() {\n return caseValueParam;\n }\n\n @Deprecated\n public String getDynamicForkJoinTasksParam() {\n return dynamicForkJoinTasksParam;\n }\n\n @Deprecated\n public void setDynamicForkJoinTasksParam(String dynamicForkJoinTasksParam) {\n this.dynamicForkJoinTasksParam = dynamicForkJoinTasksParam;\n }\n\n public String getDynamicForkTasksParam() {\n return dynamicForkTasksParam;\n }\n\n public void setDynamicForkTasksParam(String dynamicForkTasksParam) {\n this.dynamicForkTasksParam = dynamicForkTasksParam;\n }\n\n public String getDynamicForkTasksInputParamName() {\n return dynamicForkTasksInputParamName;\n }\n\n public void setDynamicForkTasksInputParamName(String dynamicForkTasksInputParamName) {\n this.dynamicForkTasksInputParamName = dynamicForkTasksInputParamName;\n }\n\n /**\n * @param caseValueParam the caseValueParam to set\n * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link\n * WorkflowTask#getExpression()} combination.\n */\n @Deprecated\n public void setCaseValueParam(String caseValueParam) {\n this.caseValueParam = caseValueParam;\n }\n\n /**\n * @return A javascript expression for decision cases. The result should be a scalar value that\n * is used to decide the case branches.\n * @see #getDecisionCases()\n * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link\n * WorkflowTask#getExpression()} combination.\n */\n @Deprecated\n public String getCaseExpression() {\n return caseExpression;\n }\n\n /**\n * @param caseExpression A javascript expression for decision cases. The result should be a\n * scalar value that is used to decide the case branches.\n * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link\n * WorkflowTask#getExpression()} combination.\n */\n @Deprecated\n public void setCaseExpression(String caseExpression) {\n this.caseExpression = caseExpression;\n }\n\n public String getScriptExpression() {\n return scriptExpression;\n }\n\n public void setScriptExpression(String expression) {\n this.scriptExpression = expression;\n }\n\n /**\n * @return the subWorkflow\n */\n public SubWorkflowParams getSubWorkflowParam() {\n return subWorkflowParam;\n }\n\n /**\n * @param subWorkflow the subWorkflowParam to set\n */\n public void setSubWorkflowParam(SubWorkflowParams subWorkflow) {\n this.subWorkflowParam = subWorkflow;\n }\n\n /**\n * @return the joinOn\n */\n public List getJoinOn() {\n return joinOn;\n }\n\n /**\n * @param joinOn the joinOn to set\n */\n public void setJoinOn(List joinOn) {\n this.joinOn = joinOn;\n }\n\n /**\n * @return the loopCondition\n */\n public String getLoopCondition() {\n return loopCondition;\n }\n\n /**\n * @param loopCondition the expression to set\n */\n public void setLoopCondition(String loopCondition) {\n this.loopCondition = loopCondition;\n }\n\n /**\n * @return the loopOver\n */\n public List getLoopOver() {\n return loopOver;\n }\n\n /**\n * @param loopOver the loopOver to set\n */\n public void setLoopOver(List loopOver) {\n this.loopOver = loopOver;\n }\n\n /**\n * @return Sink value for the EVENT type of task\n */\n public String getSink() {\n return sink;\n }\n\n /**\n * @param sink Name of the sink\n */\n public void setSink(String sink) {\n this.sink = sink;\n }\n\n /**\n * @return whether wait for an external event to complete the task, for EVENT and HTTP tasks\n */\n public Boolean isAsyncComplete() {\n return asyncComplete;\n }\n\n public void setAsyncComplete(Boolean asyncComplete) {\n this.asyncComplete = asyncComplete;\n }\n\n /**\n * @return If the task is optional. When set to true, the workflow execution continues even when\n * the task is in failed status.\n */\n public boolean isOptional() {\n return optional;\n }\n\n /**\n * @return Task definition associated to the Workflow Task\n */\n public TaskDef getTaskDefinition() {\n return taskDefinition;\n }\n\n /**\n * @param taskDefinition Task definition\n */\n public void setTaskDefinition(TaskDef taskDefinition) {\n this.taskDefinition = taskDefinition;\n }\n\n /**\n * @param optional when set to true, the task is marked as optional\n */\n public void setOptional(boolean optional) {\n this.optional = optional;\n }\n\n public Boolean getRateLimited() {\n return rateLimited;\n }\n\n public void setRateLimited(Boolean rateLimited) {\n this.rateLimited = rateLimited;\n }\n\n public Boolean isRateLimited() {\n return rateLimited != null && rateLimited;\n }\n\n public List getDefaultExclusiveJoinTask() {\n return defaultExclusiveJoinTask;\n }\n\n public void setDefaultExclusiveJoinTask(List defaultExclusiveJoinTask) {\n this.defaultExclusiveJoinTask = defaultExclusiveJoinTask;\n }\n\n /**\n * @return the evaluatorType\n */\n public String getEvaluatorType() {\n return evaluatorType;\n }\n\n /**\n * @param evaluatorType the evaluatorType to set\n */\n public void setEvaluatorType(String evaluatorType) {\n this.evaluatorType = evaluatorType;\n }\n\n /**\n * @return An evaluation expression for switch cases evaluated by corresponding evaluator. The\n * result should be a scalar value that is used to decide the case branches.\n * @see #getDecisionCases()\n */\n public String getExpression() {\n return expression;\n }\n\n /**\n * @param expression the expression to set\n */\n public void setExpression(String expression) {\n this.expression = expression;\n }\n\n /**\n * @return If the task is permissive. When set to true, and the task is in failed status,\n * fail-fast does not occur. The workflow execution continues until reaching join or end of\n * workflow, allowing idempotent execution of other tasks.\n */\n public boolean isPermissive() {\n return this.permissive;\n }\n\n /**\n * @param permissive when set to true, the task is marked as permissive\n */\n public void setPermissive(boolean permissive) {\n this.permissive = permissive;\n }\n\n private Collection> children() {\n Collection> workflowTaskLists = new LinkedList<>();\n\n switch (TaskType.of(type)) {\n case DECISION:\n case SWITCH:\n workflowTaskLists.addAll(decisionCases.values());\n workflowTaskLists.add(defaultCase);\n break;\n case FORK_JOIN:\n workflowTaskLists.addAll(forkTasks);\n break;\n case DO_WHILE:\n workflowTaskLists.add(loopOver);\n break;\n default:\n break;\n }\n return workflowTaskLists;\n }\n\n public List collectTasks() {\n List tasks = new LinkedList<>();\n tasks.add(this);\n for (List workflowTaskList : children()) {\n for (WorkflowTask workflowTask : workflowTaskList) {\n tasks.addAll(workflowTask.collectTasks());\n }\n }\n return tasks;\n }\n\n public WorkflowTask next(String taskReferenceName, WorkflowTask parent) {\n TaskType taskType = TaskType.of(type);\n\n switch (taskType) {\n case DO_WHILE:\n case DECISION:\n case SWITCH:\n for (List workflowTasks : children()) {\n Iterator iterator = workflowTasks.iterator();\n while (iterator.hasNext()) {\n WorkflowTask task = iterator.next();\n if (task.getTaskReferenceName().equals(taskReferenceName)) {\n break;\n }\n WorkflowTask nextTask = task.next(taskReferenceName, this);\n if (nextTask != null) {\n return nextTask;\n }\n if (task.has(taskReferenceName)) {\n break;\n }\n }\n if (iterator.hasNext()) {\n return iterator.next();\n }\n }\n if (taskType == TaskType.DO_WHILE && this.has(taskReferenceName)) {\n // come here means this is DO_WHILE task and `taskReferenceName` is the last\n // task in\n // this DO_WHILE task, because DO_WHILE task need to be executed to decide\n // whether to\n // schedule next iteration, so we just return the DO_WHILE task, and then ignore\n // generating this task again in deciderService.getNextTask()\n return this;\n }\n break;\n case FORK_JOIN:\n boolean found = false;\n for (List workflowTasks : children()) {\n Iterator iterator = workflowTasks.iterator();\n while (iterator.hasNext()) {\n WorkflowTask task = iterator.next();\n if (task.getTaskReferenceName().equals(taskReferenceName)) {\n found = true;\n break;\n }\n WorkflowTask nextTask = task.next(taskReferenceName, this);\n if (nextTask != null) {\n return nextTask;\n }\n if (task.has(taskReferenceName)) {\n break;\n }\n }\n if (iterator.hasNext()) {\n return iterator.next();\n }\n if (found && parent != null) {\n return parent.next(\n this.taskReferenceName,\n parent); // we need to return join task... -- get my sibling from my\n // parent..\n }\n }\n break;\n case DYNAMIC:\n case TERMINATE:\n case SIMPLE:\n return null;\n default:\n break;\n }\n return null;\n }\n\n public boolean has(String taskReferenceName) {\n if (this.getTaskReferenceName().equals(taskReferenceName)) {\n return true;\n }\n\n switch (TaskType.of(type)) {\n case DECISION:\n case SWITCH:\n case DO_WHILE:\n case FORK_JOIN:\n for (List childx : children()) {\n for (WorkflowTask child : childx) {\n if (child.has(taskReferenceName)) {\n return true;\n }\n }\n }\n break;\n default:\n break;\n }\n return false;\n }\n\n public WorkflowTask get(String taskReferenceName) {\n\n if (this.getTaskReferenceName().equals(taskReferenceName)) {\n return this;\n }\n for (List childx : children()) {\n for (WorkflowTask child : childx) {\n WorkflowTask found = child.get(taskReferenceName);\n if (found != null) {\n return found;\n }\n }\n }\n return null;\n }\n\n @Override\n public String toString() {\n return name + \"/\" + taskReferenceName;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n WorkflowTask that = (WorkflowTask) o;\n return getStartDelay() == that.getStartDelay()\n && isOptional() == that.isOptional()\n && Objects.equals(getName(), that.getName())\n && Objects.equals(getTaskReferenceName(), that.getTaskReferenceName())\n && Objects.equals(getDescription(), that.getDescription())\n && Objects.equals(getInputParameters(), that.getInputParameters())\n && Objects.equals(getType(), that.getType())\n && Objects.equals(getDynamicTaskNameParam(), that.getDynamicTaskNameParam())\n && Objects.equals(getCaseValueParam(), that.getCaseValueParam())\n && Objects.equals(getEvaluatorType(), that.getEvaluatorType())\n && Objects.equals(getExpression(), that.getExpression())\n && Objects.equals(getCaseExpression(), that.getCaseExpression())\n && Objects.equals(getDecisionCases(), that.getDecisionCases())\n && Objects.equals(\n getDynamicForkJoinTasksParam(), that.getDynamicForkJoinTasksParam())\n && Objects.equals(getDynamicForkTasksParam(), that.getDynamicForkTasksParam())\n && Objects.equals(\n getDynamicForkTasksInputParamName(),\n that.getDynamicForkTasksInputParamName())\n && Objects.equals(getDefaultCase(), that.getDefaultCase())\n && Objects.equals(getForkTasks(), that.getForkTasks())\n && Objects.equals(getSubWorkflowParam(), that.getSubWorkflowParam())\n && Objects.equals(getJoinOn(), that.getJoinOn())\n && Objects.equals(getSink(), that.getSink())\n && Objects.equals(isAsyncComplete(), that.isAsyncComplete())\n && Objects.equals(getDefaultExclusiveJoinTask(), that.getDefaultExclusiveJoinTask())\n && Objects.equals(getRetryCount(), that.getRetryCount());\n }\n\n @Override\n public int hashCode() {\n\n return Objects.hash(\n getName(),\n getTaskReferenceName(),\n getDescription(),\n getInputParameters(),\n getType(),\n getDynamicTaskNameParam(),\n getCaseValueParam(),\n getCaseExpression(),\n getEvaluatorType(),\n getExpression(),\n getDecisionCases(),\n getDynamicForkJoinTasksParam(),\n getDynamicForkTasksParam(),\n getDynamicForkTasksInputParamName(),\n getDefaultCase(),\n getForkTasks(),\n getStartDelay(),\n getSubWorkflowParam(),\n getJoinOn(),\n getSink(),\n isAsyncComplete(),\n isOptional(),\n getDefaultExclusiveJoinTask(),\n getRetryCount());\n }\n}\n\ncore/src/main/java/com/netflix/conductor/core/utils/ParametersUtils.java\n@Component\npublic class ParametersUtils {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ParametersUtils.class);\n private static final Pattern PATTERN =\n Pattern.compile(\n \"(?=(?> map = new TypeReference<>() {};\n\n public ParametersUtils(ObjectMapper objectMapper) {\n this.objectMapper = objectMapper;\n }\n\n public Map getTaskInput(\n Map inputParams,\n WorkflowModel workflow,\n TaskDef taskDefinition,\n String taskId) {\n if (workflow.getWorkflowDefinition().getSchemaVersion() > 1) {\n return getTaskInputV2(inputParams, workflow, taskId, taskDefinition);\n }\n return getTaskInputV1(workflow, inputParams);\n }\n\n public Map getTaskInputV2(\n Map input,\n WorkflowModel workflow,\n String taskId,\n TaskDef taskDefinition) {\n Map inputParams;\n\n if (input != null) {\n inputParams = clone(input);\n } else {\n inputParams = new HashMap<>();\n }\n if (taskDefinition != null && taskDefinition.getInputTemplate() != null) {\n clone(taskDefinition.getInputTemplate()).forEach(inputParams::putIfAbsent);\n }\n\n Map> inputMap = new HashMap<>();\n\n Map workflowParams = new HashMap<>();\n workflowParams.put(\"input\", workflow.getInput());\n workflowParams.put(\"output\", workflow.getOutput());\n workflowParams.put(\"status\", workflow.getStatus());\n workflowParams.put(\"workflowId\", workflow.getWorkflowId());\n workflowParams.put(\"parentWorkflowId\", workflow.getParentWorkflowId());\n workflowParams.put(\"parentWorkflowTaskId\", workflow.getParentWorkflowTaskId());\n workflowParams.put(\"workflowType\", workflow.getWorkflowName());\n workflowParams.put(\"version\", workflow.getWorkflowVersion());\n workflowParams.put(\"correlationId\", workflow.getCorrelationId());\n workflowParams.put(\"reasonForIncompletion\", workflow.getReasonForIncompletion());\n workflowParams.put(\"schemaVersion\", workflow.getWorkflowDefinition().getSchemaVersion());\n workflowParams.put(\"variables\", workflow.getVariables());\n\n inputMap.put(\"workflow\", workflowParams);\n\n // For new workflow being started the list of tasks will be empty\n workflow.getTasks().stream()\n .map(TaskModel::getReferenceTaskName)\n .map(workflow::getTaskByRefName)\n .forEach(\n task -> {\n Map taskParams = new HashMap<>();\n taskParams.put(\"input\", task.getInputData());\n taskParams.put(\"output\", task.getOutputData());\n taskParams.put(\"taskType\", task.getTaskType());\n if (task.getStatus() != null) {\n taskParams.put(\"status\", task.getStatus().toString());\n }\n taskParams.put(\"referenceTaskName\", task.getReferenceTaskName());\n taskParams.put(\"retryCount\", task.getRetryCount());\n taskParams.put(\"correlationId\", task.getCorrelationId());\n taskParams.put(\"pollCount\", task.getPollCount());\n taskParams.put(\"taskDefName\", task.getTaskDefName());\n taskParams.put(\"scheduledTime\", task.getScheduledTime());\n taskParams.put(\"startTime\", task.getStartTime());\n taskParams.put(\"endTime\", task.getEndTime());\n taskParams.put(\"workflowInstanceId\", task.getWorkflowInstanceId());\n taskParams.put(\"taskId\", task.getTaskId());\n taskParams.put(\n \"reasonForIncompletion\", task.getReasonForIncompletion());\n taskParams.put(\"callbackAfterSeconds\", task.getCallbackAfterSeconds());\n taskParams.put(\"workerId\", task.getWorkerId());\n taskParams.put(\"iteration\", task.getIteration());\n inputMap.put(\n task.isLoopOverTask()\n ? TaskUtils.removeIterationFromTaskRefName(\n task.getReferenceTaskName())\n : task.getReferenceTaskName(),\n taskParams);\n });\n\n Configuration option =\n Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);\n DocumentContext documentContext = JsonPath.parse(inputMap, option);\n Map replacedTaskInput = replace(inputParams, documentContext, taskId);\n if (taskDefinition != null && taskDefinition.getInputTemplate() != null) {\n // If input for a given key resolves to null, try replacing it with one from\n // inputTemplate, if it exists.\n replacedTaskInput.replaceAll(\n (key, value) ->\n (value == null) ? taskDefinition.getInputTemplate().get(key) : value);\n }\n return replacedTaskInput;\n }\n\n // deep clone using json - POJO\n private Map clone(Map inputTemplate) {\n try {\n byte[] bytes = objectMapper.writeValueAsBytes(inputTemplate);\n return objectMapper.readValue(bytes, map);\n } catch (IOException e) {\n throw new RuntimeException(\"Unable to clone input params\", e);\n }\n }\n\n public Map replace(Map input, Object json) {\n Object doc;\n if (json instanceof String) {\n doc = JsonPath.parse(json.toString());\n } else {\n doc = json;\n }\n Configuration option =\n Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);\n DocumentContext documentContext = JsonPath.parse(doc, option);\n return replace(input, documentContext, null);\n }\n\n public Object replace(String paramString) {\n Configuration option =\n Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);\n DocumentContext documentContext = JsonPath.parse(Collections.emptyMap(), option);\n return replaceVariables(paramString, documentContext, null);\n }\n\n @SuppressWarnings(\"unchecked\")\n private Map replace(\n Map input, DocumentContext documentContext, String taskId) {\n Map result = new HashMap<>();\n for (Entry e : input.entrySet()) {\n Object newValue;\n Object value = e.getValue();\n if (value instanceof String) {\n newValue = replaceVariables(value.toString(), documentContext, taskId);\n } else if (value instanceof Map) {\n // recursive call\n newValue = replace((Map) value, documentContext, taskId);\n } else if (value instanceof List) {\n newValue = replaceList((List) value, taskId, documentContext);\n } else {\n newValue = value;\n }\n result.put(e.getKey(), newValue);\n }\n return result;\n }\n\n @SuppressWarnings(\"unchecked\")\n private Object replaceList(List values, String taskId, DocumentContext io) {\n List replacedList = new LinkedList<>();\n for (Object listVal : values) {\n if (listVal instanceof String) {\n Object replaced = replaceVariables(listVal.toString(), io, taskId);\n replacedList.add(replaced);\n } else if (listVal instanceof Map) {\n Object replaced = replace((Map) listVal, io, taskId);\n replacedList.add(replaced);\n } else if (listVal instanceof List) {\n Object replaced = replaceList((List) listVal, taskId, io);\n replacedList.add(replaced);\n } else {\n replacedList.add(listVal);\n }\n }\n return replacedList;\n }\n\n private Object replaceVariables(\n String paramString, DocumentContext documentContext, String taskId) {\n return replaceVariables(paramString, documentContext, taskId, 0);\n }\n\n private Object replaceVariables(\n String paramString, DocumentContext documentContext, String taskId, int depth) {\n var matcher = PATTERN.matcher(paramString);\n var replacements = new LinkedList();\n while (matcher.find()) {\n var start = matcher.start();\n var end = matcher.end();\n var match = paramString.substring(start, end);\n String paramPath = match.substring(2, match.length() - 1);\n paramPath = replaceVariables(paramPath, documentContext, taskId, depth + 1).toString();\n // if the paramPath is blank, meaning no value in between ${ and }\n // like ${}, ${ } etc, set the value to empty string\n if (StringUtils.isBlank(paramPath)) {\n replacements.add(new Replacement(\"\", start, end));\n continue;\n }\n if (EnvUtils.isEnvironmentVariable(paramPath)) {\n String sysValue = EnvUtils.getSystemParametersValue(paramPath, taskId);\n if (sysValue != null) {\n replacements.add(new Replacement(sysValue, start, end));\n }\n } else {\n try {\n replacements.add(new Replacement(documentContext.read(paramPath), start, end));\n } catch (Exception e) {\n LOGGER.warn(\n \"Error reading documentContext for paramPath: {}. Exception: {}\",\n paramPath,\n e);\n replacements.add(new Replacement(null, start, end));\n }\n }\n }\n if (replacements.size() == 1\n && replacements.getFirst().getStartIndex() == 0\n && replacements.getFirst().getEndIndex() == paramString.length()\n && depth == 0) {\n return replacements.get(0).getReplacement();\n }\n Collections.sort(replacements);\n var builder = new StringBuilder(paramString);\n for (int i = replacements.size() - 1; i >= 0; i--) {\n var replacement = replacements.get(i);\n builder.replace(\n replacement.getStartIndex(),\n replacement.getEndIndex(),\n Objects.toString(replacement.getReplacement()));\n }\n return builder.toString().replaceAll(\"\\\\$\\\\$\\\\{\", \"\\\\${\");\n }\n\n @Deprecated\n // Workflow schema version 1 is deprecated and new workflows should be using version 2\n private Map getTaskInputV1(\n WorkflowModel workflow, Map inputParams) {\n Map input = new HashMap<>();\n if (inputParams == null) {\n return input;\n }\n Map workflowInput = workflow.getInput();\n inputParams.forEach(\n (paramName, value) -> {\n String paramPath = \"\" + value;\n String[] paramPathComponents = paramPath.split(\"\\\\.\");\n Utils.checkArgument(\n paramPathComponents.length == 3,\n \"Invalid input expression for \"\n + paramName\n + \", paramPathComponents.size=\"\n + paramPathComponents.length\n + \", expression=\"\n + paramPath);\n\n String source = paramPathComponents[0]; // workflow, or task reference name\n String type = paramPathComponents[1]; // input/output\n String name = paramPathComponents[2]; // name of the parameter\n if (\"workflow\".equals(source)) {\n input.put(paramName, workflowInput.get(name));\n } else {\n TaskModel task = workflow.getTaskByRefName(source);\n if (task != null) {\n if (\"input\".equals(type)) {\n input.put(paramName, task.getInputData().get(name));\n } else {\n input.put(paramName, task.getOutputData().get(name));\n }\n }\n }\n });\n return input;\n }\n\n public Map getWorkflowInput(\n WorkflowDef workflowDef, Map inputParams) {\n if (workflowDef != null && workflowDef.getInputTemplate() != null) {\n clone(workflowDef.getInputTemplate()).forEach(inputParams::putIfAbsent);\n }\n return inputParams;\n }\n\n private static class Replacement implements Comparable {\n private final int startIndex;\n private final int endIndex;\n private final Object replacement;\n\n public Replacement(Object replacement, int startIndex, int endIndex) {\n this.replacement = replacement;\n this.startIndex = startIndex;\n this.endIndex = endIndex;\n }\n\n public Object getReplacement() {\n return replacement;\n }\n\n public int getStartIndex() {\n return startIndex;\n }\n\n public int getEndIndex() {\n return endIndex;\n }\n\n @Override\n public int compareTo(Replacement o) {\n return Long.compare(startIndex, o.startIndex);\n }\n }\n}\n\ncommon/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskType.java\n@ProtoEnum\npublic enum TaskType {\n SIMPLE,\n DYNAMIC,\n FORK_JOIN,\n FORK_JOIN_DYNAMIC,\n DECISION,\n SWITCH,\n JOIN,\n DO_WHILE,\n SUB_WORKFLOW,\n START_WORKFLOW,\n EVENT,\n WAIT,\n HUMAN,\n USER_DEFINED,\n HTTP,\n LAMBDA,\n INLINE,\n EXCLUSIVE_JOIN,\n TERMINATE,\n KAFKA_PUBLISH,\n JSON_JQ_TRANSFORM,\n SET_VARIABLE,\n NOOP;\n\n /**\n * TaskType constants representing each of the possible enumeration values. Motivation: to not\n * have any hardcoded/inline strings used in the code.\n */\n public static final String TASK_TYPE_DECISION = \"DECISION\";\n\n public static final String TASK_TYPE_SWITCH = \"SWITCH\";\n public static final String TASK_TYPE_DYNAMIC = \"DYNAMIC\";\n public static final String TASK_TYPE_JOIN = \"JOIN\";\n public static final String TASK_TYPE_DO_WHILE = \"DO_WHILE\";\n public static final String TASK_TYPE_FORK_JOIN_DYNAMIC = \"FORK_JOIN_DYNAMIC\";\n public static final String TASK_TYPE_EVENT = \"EVENT\";\n public static final String TASK_TYPE_WAIT = \"WAIT\";\n public static final String TASK_TYPE_HUMAN = \"HUMAN\";\n public static final String TASK_TYPE_SUB_WORKFLOW = \"SUB_WORKFLOW\";\n public static final String TASK_TYPE_START_WORKFLOW = \"START_WORKFLOW\";\n public static final String TASK_TYPE_FORK_JOIN = \"FORK_JOIN\";\n public static final String TASK_TYPE_SIMPLE = \"SIMPLE\";\n public static final String TASK_TYPE_HTTP = \"HTTP\";\n public static final String TASK_TYPE_LAMBDA = \"LAMBDA\";\n public static final String TASK_TYPE_INLINE = \"INLINE\";\n public static final String TASK_TYPE_EXCLUSIVE_JOIN = \"EXCLUSIVE_JOIN\";\n public static final String TASK_TYPE_TERMINATE = \"TERMINATE\";\n public static final String TASK_TYPE_KAFKA_PUBLISH = \"KAFKA_PUBLISH\";\n public static final String TASK_TYPE_JSON_JQ_TRANSFORM = \"JSON_JQ_TRANSFORM\";\n public static final String TASK_TYPE_SET_VARIABLE = \"SET_VARIABLE\";\n public static final String TASK_TYPE_FORK = \"FORK\";\n public static final String TASK_TYPE_NOOP = \"NOOP\";\n\n private static final Set BUILT_IN_TASKS = new HashSet<>();\n\n static {\n BUILT_IN_TASKS.add(TASK_TYPE_DECISION);\n BUILT_IN_TASKS.add(TASK_TYPE_SWITCH);\n BUILT_IN_TASKS.add(TASK_TYPE_FORK);\n BUILT_IN_TASKS.add(TASK_TYPE_JOIN);\n BUILT_IN_TASKS.add(TASK_TYPE_EXCLUSIVE_JOIN);\n BUILT_IN_TASKS.add(TASK_TYPE_DO_WHILE);\n }\n\n /**\n * Converts a task type string to {@link TaskType}. For an unknown string, the value is\n * defaulted to {@link TaskType#USER_DEFINED}.\n *\n *

NOTE: Use {@link Enum#valueOf(Class, String)} if the default of USER_DEFINED is not\n * necessary.\n *\n * @param taskType The task type string.\n * @return The {@link TaskType} enum.\n */\n public static TaskType of(String taskType) {\n try {\n return TaskType.valueOf(taskType);\n } catch (IllegalArgumentException iae) {\n return TaskType.USER_DEFINED;\n }\n }\n\n public static boolean isBuiltIn(String taskType) {\n return BUILT_IN_TASKS.contains(taskType);\n }\n}\n\ncore/src/main/java/com/netflix/conductor/model/TaskModel.java\npublic class TaskModel {\n\n public enum Status {\n IN_PROGRESS(false, true, true),\n CANCELED(true, false, false),\n FAILED(true, false, true),\n FAILED_WITH_TERMINAL_ERROR(true, false, false),\n COMPLETED(true, true, true),\n COMPLETED_WITH_ERRORS(true, true, true),\n SCHEDULED(false, true, true),\n TIMED_OUT(true, false, true),\n SKIPPED(true, true, false);\n\n private final boolean terminal;\n\n private final boolean successful;\n\n private final boolean retriable;\n\n Status(boolean terminal, boolean successful, boolean retriable) {\n this.terminal = terminal;\n this.successful = successful;\n this.retriable = retriable;\n }\n\n public boolean isTerminal() {\n return terminal;\n }\n\n public boolean isSuccessful() {\n return successful;\n }\n\n public boolean isRetriable() {\n return retriable;\n }\n }\n\n private String taskType;\n\n private Status status;\n\n private String referenceTaskName;\n\n private int retryCount;\n\n private int seq;\n\n private String correlationId;\n\n private int pollCount;\n\n private String taskDefName;\n\n /** Time when the task was scheduled */\n private long scheduledTime;\n\n /** Time when the task was first polled */\n private long startTime;\n\n /** Time when the task completed executing */\n private long endTime;\n\n /** Time when the task was last updated */\n private long updateTime;\n\n private int startDelayInSeconds;\n\n private String retriedTaskId;\n\n private boolean retried;\n\n private boolean executed;\n\n private boolean callbackFromWorker = true;\n\n private long responseTimeoutSeconds;\n\n private String workflowInstanceId;\n\n private String workflowType;\n\n private String taskId;\n\n private String reasonForIncompletion;\n\n private long callbackAfterSeconds;\n\n private String workerId;\n\n private WorkflowTask workflowTask;\n\n private String domain;\n\n private Any inputMessage;\n\n private Any outputMessage;\n\n private int rateLimitPerFrequency;\n\n private int rateLimitFrequencyInSeconds;\n\n private String externalInputPayloadStoragePath;\n\n private String externalOutputPayloadStoragePath;\n\n private int workflowPriority;\n\n private String executionNameSpace;\n\n private String isolationGroupId;\n\n private int iteration;\n\n private String subWorkflowId;\n\n // Timeout after which the wait task should be marked as completed\n private long waitTimeout;\n\n /**\n * Used to note that a sub workflow associated with SUB_WORKFLOW task has an action performed on\n * it directly.\n */\n private boolean subworkflowChanged;\n\n @JsonIgnore private Map inputPayload = new HashMap<>();\n\n @JsonIgnore private Map outputPayload = new HashMap<>();\n\n @JsonIgnore private Map inputData = new HashMap<>();\n\n @JsonIgnore private Map outputData = new HashMap<>();\n\n public String getTaskType() {\n return taskType;\n }\n\n public void setTaskType(String taskType) {\n this.taskType = taskType;\n }\n\n public Status getStatus() {\n return status;\n }\n\n public void setStatus(Status status) {\n this.status = status;\n }\n\n @JsonIgnore\n public Map getInputData() {\n if (!inputPayload.isEmpty() && !inputData.isEmpty()) {\n inputData.putAll(inputPayload);\n inputPayload = new HashMap<>();\n return inputData;\n } else if (inputPayload.isEmpty()) {\n return inputData;\n } else {\n return inputPayload;\n }\n }\n\n @JsonIgnore\n public void setInputData(Map inputData) {\n if (inputData == null) {\n inputData = new HashMap<>();\n }\n this.inputData = inputData;\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @JsonProperty(\"inputData\")\n @Deprecated\n public void setRawInputData(Map inputData) {\n setInputData(inputData);\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @JsonProperty(\"inputData\")\n @Deprecated\n public Map getRawInputData() {\n return inputData;\n }\n\n public String getReferenceTaskName() {\n return referenceTaskName;\n }\n\n public void setReferenceTaskName(String referenceTaskName) {\n this.referenceTaskName = referenceTaskName;\n }\n\n public int getRetryCount() {\n return retryCount;\n }\n\n public void setRetryCount(int retryCount) {\n this.retryCount = retryCount;\n }\n\n public int getSeq() {\n return seq;\n }\n\n public void setSeq(int seq) {\n this.seq = seq;\n }\n\n public String getCorrelationId() {\n return correlationId;\n }\n\n public void setCorrelationId(String correlationId) {\n this.correlationId = correlationId;\n }\n\n public int getPollCount() {\n return pollCount;\n }\n\n public void setPollCount(int pollCount) {\n this.pollCount = pollCount;\n }\n\n public String getTaskDefName() {\n if (taskDefName == null || \"\".equals(taskDefName)) {\n taskDefName = taskType;\n }\n return taskDefName;\n }\n\n public void setTaskDefName(String taskDefName) {\n this.taskDefName = taskDefName;\n }\n\n public long getScheduledTime() {\n return scheduledTime;\n }\n\n public void setScheduledTime(long scheduledTime) {\n this.scheduledTime = scheduledTime;\n }\n\n public long getStartTime() {\n return startTime;\n }\n\n public void setStartTime(long startTime) {\n this.startTime = startTime;\n }\n\n public long getEndTime() {\n return endTime;\n }\n\n public void setEndTime(long endTime) {\n this.endTime = endTime;\n }\n\n public long getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(long updateTime) {\n this.updateTime = updateTime;\n }\n\n public int getStartDelayInSeconds() {\n return startDelayInSeconds;\n }\n\n public void setStartDelayInSeconds(int startDelayInSeconds) {\n this.startDelayInSeconds = startDelayInSeconds;\n }\n\n public String getRetriedTaskId() {\n return retriedTaskId;\n }\n\n public void setRetriedTaskId(String retriedTaskId) {\n this.retriedTaskId = retriedTaskId;\n }\n\n public boolean isRetried() {\n return retried;\n }\n\n public void setRetried(boolean retried) {\n this.retried = retried;\n }\n\n public boolean isExecuted() {\n return executed;\n }\n\n public void setExecuted(boolean executed) {\n this.executed = executed;\n }\n\n public boolean isCallbackFromWorker() {\n return callbackFromWorker;\n }\n\n public void setCallbackFromWorker(boolean callbackFromWorker) {\n this.callbackFromWorker = callbackFromWorker;\n }\n\n public long getResponseTimeoutSeconds() {\n return responseTimeoutSeconds;\n }\n\n public void setResponseTimeoutSeconds(long responseTimeoutSeconds) {\n this.responseTimeoutSeconds = responseTimeoutSeconds;\n }\n\n public String getWorkflowInstanceId() {\n return workflowInstanceId;\n }\n\n public void setWorkflowInstanceId(String workflowInstanceId) {\n this.workflowInstanceId = workflowInstanceId;\n }\n\n public String getWorkflowType() {\n return workflowType;\n }\n\n public void setWorkflowType(String workflowType) {\n this.workflowType = workflowType;\n }\n\n public String getTaskId() {\n return taskId;\n }\n\n public void setTaskId(String taskId) {\n this.taskId = taskId;\n }\n\n public String getReasonForIncompletion() {\n return reasonForIncompletion;\n }\n\n public void setReasonForIncompletion(String reasonForIncompletion) {\n this.reasonForIncompletion = reasonForIncompletion;\n }\n\n public long getCallbackAfterSeconds() {\n return callbackAfterSeconds;\n }\n\n public void setCallbackAfterSeconds(long callbackAfterSeconds) {\n this.callbackAfterSeconds = callbackAfterSeconds;\n }\n\n public String getWorkerId() {\n return workerId;\n }\n\n public void setWorkerId(String workerId) {\n this.workerId = workerId;\n }\n\n @JsonIgnore\n public Map getOutputData() {\n if (!outputPayload.isEmpty() && !outputData.isEmpty()) {\n // Combine payload + data\n // data has precedence over payload because:\n // with external storage enabled, payload contains the old values\n // while data contains the latest and if payload took precedence, it\n // would remove latest outputs\n outputPayload.forEach(outputData::putIfAbsent);\n outputPayload = new HashMap<>();\n return outputData;\n } else if (outputPayload.isEmpty()) {\n return outputData;\n } else {\n return outputPayload;\n }\n }\n\n @JsonIgnore\n public void setOutputData(Map outputData) {\n if (outputData == null) {\n outputData = new HashMap<>();\n }\n this.outputData = outputData;\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @JsonProperty(\"outputData\")\n @Deprecated\n public void setRawOutputData(Map inputData) {\n setOutputData(inputData);\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @JsonProperty(\"outputData\")\n @Deprecated\n public Map getRawOutputData() {\n return outputData;\n }\n\n public WorkflowTask getWorkflowTask() {\n return workflowTask;\n }\n\n public void setWorkflowTask(WorkflowTask workflowTask) {\n this.workflowTask = workflowTask;\n }\n\n public String getDomain() {\n return domain;\n }\n\n public void setDomain(String domain) {\n this.domain = domain;\n }\n\n public Any getInputMessage() {\n return inputMessage;\n }\n\n public void setInputMessage(Any inputMessage) {\n this.inputMessage = inputMessage;\n }\n\n public Any getOutputMessage() {\n return outputMessage;\n }\n\n public void setOutputMessage(Any outputMessage) {\n this.outputMessage = outputMessage;\n }\n\n public int getRateLimitPerFrequency() {\n return rateLimitPerFrequency;\n }\n\n public void setRateLimitPerFrequency(int rateLimitPerFrequency) {\n this.rateLimitPerFrequency = rateLimitPerFrequency;\n }\n\n public int getRateLimitFrequencyInSeconds() {\n return rateLimitFrequencyInSeconds;\n }\n\n public void setRateLimitFrequencyInSeconds(int rateLimitFrequencyInSeconds) {\n this.rateLimitFrequencyInSeconds = rateLimitFrequencyInSeconds;\n }\n\n public String getExternalInputPayloadStoragePath() {\n return externalInputPayloadStoragePath;\n }\n\n public void setExternalInputPayloadStoragePath(String externalInputPayloadStoragePath) {\n this.externalInputPayloadStoragePath = externalInputPayloadStoragePath;\n }\n\n public String getExternalOutputPayloadStoragePath() {\n return externalOutputPayloadStoragePath;\n }\n\n public void setExternalOutputPayloadStoragePath(String externalOutputPayloadStoragePath) {\n this.externalOutputPayloadStoragePath = externalOutputPayloadStoragePath;\n }\n\n public int getWorkflowPriority() {\n return workflowPriority;\n }\n\n public void setWorkflowPriority(int workflowPriority) {\n this.workflowPriority = workflowPriority;\n }\n\n public String getExecutionNameSpace() {\n return executionNameSpace;\n }\n\n public void setExecutionNameSpace(String executionNameSpace) {\n this.executionNameSpace = executionNameSpace;\n }\n\n public String getIsolationGroupId() {\n return isolationGroupId;\n }\n\n public void setIsolationGroupId(String isolationGroupId) {\n this.isolationGroupId = isolationGroupId;\n }\n\n public int getIteration() {\n return iteration;\n }\n\n public void setIteration(int iteration) {\n this.iteration = iteration;\n }\n\n public String getSubWorkflowId() {\n // For backwards compatibility\n if (StringUtils.isNotBlank(subWorkflowId)) {\n return subWorkflowId;\n } else {\n return this.getOutputData() != null && this.getOutputData().get(\"subWorkflowId\") != null\n ? (String) this.getOutputData().get(\"subWorkflowId\")\n : this.getInputData() != null\n ? (String) this.getInputData().get(\"subWorkflowId\")\n : null;\n }\n }\n\n public void setSubWorkflowId(String subWorkflowId) {\n this.subWorkflowId = subWorkflowId;\n // For backwards compatibility\n if (this.outputData != null && this.outputData.containsKey(\"subWorkflowId\")) {\n this.outputData.put(\"subWorkflowId\", subWorkflowId);\n }\n }\n\n public boolean isSubworkflowChanged() {\n return subworkflowChanged;\n }\n\n public void setSubworkflowChanged(boolean subworkflowChanged) {\n this.subworkflowChanged = subworkflowChanged;\n }\n\n public void incrementPollCount() {\n ++this.pollCount;\n }\n\n /**\n * @return {@link Optional} containing the task definition if available\n */\n public Optional getTaskDefinition() {\n return Optional.ofNullable(this.getWorkflowTask()).map(WorkflowTask::getTaskDefinition);\n }\n\n public boolean isLoopOverTask() {\n return iteration > 0;\n }\n\n public long getWaitTimeout() {\n return waitTimeout;\n }\n\n public void setWaitTimeout(long waitTimeout) {\n this.waitTimeout = waitTimeout;\n }\n\n /**\n * @return the queueWaitTime\n */\n public long getQueueWaitTime() {\n if (this.startTime > 0 && this.scheduledTime > 0) {\n if (this.updateTime > 0 && getCallbackAfterSeconds() > 0) {\n long waitTime =\n System.currentTimeMillis()\n - (this.updateTime + (getCallbackAfterSeconds() * 1000));\n return waitTime > 0 ? waitTime : 0;\n } else {\n return this.startTime - this.scheduledTime;\n }\n }\n return 0L;\n }\n\n /**\n * @return a copy of the task instance\n */\n public TaskModel copy() {\n TaskModel copy = new TaskModel();\n BeanUtils.copyProperties(this, copy);\n return copy;\n }\n\n public void externalizeInput(String path) {\n this.inputPayload = this.inputData;\n this.inputData = new HashMap<>();\n this.externalInputPayloadStoragePath = path;\n }\n\n public void externalizeOutput(String path) {\n this.outputPayload = this.outputData;\n this.outputData = new HashMap<>();\n this.externalOutputPayloadStoragePath = path;\n }\n\n public void internalizeInput(Map data) {\n this.inputData = new HashMap<>();\n this.inputPayload = data;\n }\n\n public void internalizeOutput(Map data) {\n this.outputData = new HashMap<>();\n this.outputPayload = data;\n }\n\n @Override\n public String toString() {\n return \"TaskModel{\"\n + \"taskType='\"\n + taskType\n + '\\''\n + \", status=\"\n + status\n + \", inputData=\"\n + inputData\n + \", referenceTaskName='\"\n + referenceTaskName\n + '\\''\n + \", retryCount=\"\n + retryCount\n + \", seq=\"\n + seq\n + \", correlationId='\"\n + correlationId\n + '\\''\n + \", pollCount=\"\n + pollCount\n + \", taskDefName='\"\n + taskDefName\n + '\\''\n + \", scheduledTime=\"\n + scheduledTime\n + \", startTime=\"\n + startTime\n + \", endTime=\"\n + endTime\n + \", updateTime=\"\n + updateTime\n + \", startDelayInSeconds=\"\n + startDelayInSeconds\n + \", retriedTaskId='\"\n + retriedTaskId\n + '\\''\n + \", retried=\"\n + retried\n + \", executed=\"\n + executed\n + \", callbackFromWorker=\"\n + callbackFromWorker\n + \", responseTimeoutSeconds=\"\n + responseTimeoutSeconds\n + \", workflowInstanceId='\"\n + workflowInstanceId\n + '\\''\n + \", workflowType='\"\n + workflowType\n + '\\''\n + \", taskId='\"\n + taskId\n + '\\''\n + \", reasonForIncompletion='\"\n + reasonForIncompletion\n + '\\''\n + \", callbackAfterSeconds=\"\n + callbackAfterSeconds\n + \", workerId='\"\n + workerId\n + '\\''\n + \", outputData=\"\n + outputData\n + \", workflowTask=\"\n + workflowTask\n + \", domain='\"\n + domain\n + '\\''\n + \", waitTimeout='\"\n + waitTimeout\n + '\\''\n + \", inputMessage=\"\n + inputMessage\n + \", outputMessage=\"\n + outputMessage\n + \", rateLimitPerFrequency=\"\n + rateLimitPerFrequency\n + \", rateLimitFrequencyInSeconds=\"\n + rateLimitFrequencyInSeconds\n + \", externalInputPayloadStoragePath='\"\n + externalInputPayloadStoragePath\n + '\\''\n + \", externalOutputPayloadStoragePath='\"\n + externalOutputPayloadStoragePath\n + '\\''\n + \", workflowPriority=\"\n + workflowPriority\n + \", executionNameSpace='\"\n + executionNameSpace\n + '\\''\n + \", isolationGroupId='\"\n + isolationGroupId\n + '\\''\n + \", iteration=\"\n + iteration\n + \", subWorkflowId='\"\n + subWorkflowId\n + '\\''\n + \", subworkflowChanged=\"\n + subworkflowChanged\n + '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n TaskModel taskModel = (TaskModel) o;\n return getRetryCount() == taskModel.getRetryCount()\n && getSeq() == taskModel.getSeq()\n && getPollCount() == taskModel.getPollCount()\n && getScheduledTime() == taskModel.getScheduledTime()\n && getStartTime() == taskModel.getStartTime()\n && getEndTime() == taskModel.getEndTime()\n && getUpdateTime() == taskModel.getUpdateTime()\n && getStartDelayInSeconds() == taskModel.getStartDelayInSeconds()\n && isRetried() == taskModel.isRetried()\n && isExecuted() == taskModel.isExecuted()\n && isCallbackFromWorker() == taskModel.isCallbackFromWorker()\n && getResponseTimeoutSeconds() == taskModel.getResponseTimeoutSeconds()\n && getCallbackAfterSeconds() == taskModel.getCallbackAfterSeconds()\n && getRateLimitPerFrequency() == taskModel.getRateLimitPerFrequency()\n && getRateLimitFrequencyInSeconds() == taskModel.getRateLimitFrequencyInSeconds()\n && getWorkflowPriority() == taskModel.getWorkflowPriority()\n && getIteration() == taskModel.getIteration()\n && isSubworkflowChanged() == taskModel.isSubworkflowChanged()\n && Objects.equals(getTaskType(), taskModel.getTaskType())\n && getStatus() == taskModel.getStatus()\n && Objects.equals(getInputData(), taskModel.getInputData())\n && Objects.equals(getReferenceTaskName(), taskModel.getReferenceTaskName())\n && Objects.equals(getCorrelationId(), taskModel.getCorrelationId())\n && Objects.equals(getTaskDefName(), taskModel.getTaskDefName())\n && Objects.equals(getRetriedTaskId(), taskModel.getRetriedTaskId())\n && Objects.equals(getWorkflowInstanceId(), taskModel.getWorkflowInstanceId())\n && Objects.equals(getWorkflowType(), taskModel.getWorkflowType())\n && Objects.equals(getTaskId(), taskModel.getTaskId())\n && Objects.equals(getReasonForIncompletion(), taskModel.getReasonForIncompletion())\n && Objects.equals(getWorkerId(), taskModel.getWorkerId())\n && Objects.equals(getWaitTimeout(), taskModel.getWaitTimeout())\n && Objects.equals(outputData, taskModel.outputData)\n && Objects.equals(outputPayload, taskModel.outputPayload)\n && Objects.equals(getWorkflowTask(), taskModel.getWorkflowTask())\n && Objects.equals(getDomain(), taskModel.getDomain())\n && Objects.equals(getInputMessage(), taskModel.getInputMessage())\n && Objects.equals(getOutputMessage(), taskModel.getOutputMessage())\n && Objects.equals(\n getExternalInputPayloadStoragePath(),\n taskModel.getExternalInputPayloadStoragePath())\n && Objects.equals(\n getExternalOutputPayloadStoragePath(),\n taskModel.getExternalOutputPayloadStoragePath())\n && Objects.equals(getExecutionNameSpace(), taskModel.getExecutionNameSpace())\n && Objects.equals(getIsolationGroupId(), taskModel.getIsolationGroupId())\n && Objects.equals(getSubWorkflowId(), taskModel.getSubWorkflowId());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n getTaskType(),\n getStatus(),\n getInputData(),\n getReferenceTaskName(),\n getRetryCount(),\n getSeq(),\n getCorrelationId(),\n getPollCount(),\n getTaskDefName(),\n getScheduledTime(),\n getStartTime(),\n getEndTime(),\n getUpdateTime(),\n getStartDelayInSeconds(),\n getRetriedTaskId(),\n isRetried(),\n isExecuted(),\n isCallbackFromWorker(),\n getResponseTimeoutSeconds(),\n getWorkflowInstanceId(),\n getWorkflowType(),\n getTaskId(),\n getReasonForIncompletion(),\n getCallbackAfterSeconds(),\n getWorkerId(),\n getWaitTimeout(),\n outputData,\n outputPayload,\n getWorkflowTask(),\n getDomain(),\n getInputMessage(),\n getOutputMessage(),\n getRateLimitPerFrequency(),\n getRateLimitFrequencyInSeconds(),\n getExternalInputPayloadStoragePath(),\n getExternalOutputPayloadStoragePath(),\n getWorkflowPriority(),\n getExecutionNameSpace(),\n getIsolationGroupId(),\n getIteration(),\n getSubWorkflowId(),\n isSubworkflowChanged());\n }\n\n public Task toTask() {\n Task task = new Task();\n BeanUtils.copyProperties(this, task);\n task.setStatus(Task.Status.valueOf(status.name()));\n\n // ensure that input/output is properly represented\n if (externalInputPayloadStoragePath != null) {\n task.setInputData(new HashMap<>());\n }\n if (externalOutputPayloadStoragePath != null) {\n task.setOutputData(new HashMap<>());\n }\n return task;\n }\n\n public static Task.Status mapToTaskStatus(TaskModel.Status status) {\n return Task.Status.valueOf(status.name());\n }\n\n public void addInput(String key, Object value) {\n this.inputData.put(key, value);\n }\n\n public void addInput(Map inputData) {\n if (inputData != null) {\n this.inputData.putAll(inputData);\n }\n }\n\n public void addOutput(String key, Object value) {\n this.outputData.put(key, value);\n }\n\n public void addOutput(Map outputData) {\n if (outputData != null) {\n this.outputData.putAll(outputData);\n }\n }\n\n public void clearOutput() {\n this.outputData.clear();\n this.outputPayload.clear();\n this.externalOutputPayloadStoragePath = null;\n }\n}\n\ncore/src/main/java/com/netflix/conductor/model/WorkflowModel.java\npublic class WorkflowModel {\n\n public enum Status {\n RUNNING(false, false),\n COMPLETED(true, true),\n FAILED(true, false),\n TIMED_OUT(true, false),\n TERMINATED(true, false),\n PAUSED(false, true);\n\n private final boolean terminal;\n private final boolean successful;\n\n Status(boolean terminal, boolean successful) {\n this.terminal = terminal;\n this.successful = successful;\n }\n\n public boolean isTerminal() {\n return terminal;\n }\n\n public boolean isSuccessful() {\n return successful;\n }\n }\n\n private Status status = Status.RUNNING;\n\n private long endTime;\n\n private String workflowId;\n\n private String parentWorkflowId;\n\n private String parentWorkflowTaskId;\n\n private List tasks = new LinkedList<>();\n\n private String correlationId;\n\n private String reRunFromWorkflowId;\n\n private String reasonForIncompletion;\n\n private String event;\n\n private Map taskToDomain = new HashMap<>();\n\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private Set failedReferenceTaskNames = new HashSet<>();\n\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n private Set failedTaskNames = new HashSet<>();\n\n private WorkflowDef workflowDefinition;\n\n private String externalInputPayloadStoragePath;\n\n private String externalOutputPayloadStoragePath;\n\n private int priority;\n\n private Map variables = new HashMap<>();\n\n private long lastRetriedTime;\n\n private String ownerApp;\n\n private Long createTime;\n\n private Long updatedTime;\n\n private String createdBy;\n\n private String updatedBy;\n\n // Capture the failed taskId if the workflow execution failed because of task failure\n private String failedTaskId;\n\n private Status previousStatus;\n\n @JsonIgnore private Map input = new HashMap<>();\n\n @JsonIgnore private Map output = new HashMap<>();\n\n @JsonIgnore private Map inputPayload = new HashMap<>();\n\n @JsonIgnore private Map outputPayload = new HashMap<>();\n\n public Status getPreviousStatus() {\n return previousStatus;\n }\n\n public void setPreviousStatus(Status status) {\n this.previousStatus = status;\n }\n\n public Status getStatus() {\n return status;\n }\n\n public void setStatus(Status status) {\n // update previous status if current status changed\n if (this.status != status) {\n setPreviousStatus(this.status);\n }\n this.status = status;\n }\n\n public long getEndTime() {\n return endTime;\n }\n\n public void setEndTime(long endTime) {\n this.endTime = endTime;\n }\n\n public String getWorkflowId() {\n return workflowId;\n }\n\n public void setWorkflowId(String workflowId) {\n this.workflowId = workflowId;\n }\n\n public String getParentWorkflowId() {\n return parentWorkflowId;\n }\n\n public void setParentWorkflowId(String parentWorkflowId) {\n this.parentWorkflowId = parentWorkflowId;\n }\n\n public String getParentWorkflowTaskId() {\n return parentWorkflowTaskId;\n }\n\n public void setParentWorkflowTaskId(String parentWorkflowTaskId) {\n this.parentWorkflowTaskId = parentWorkflowTaskId;\n }\n\n public List getTasks() {\n return tasks;\n }\n\n public void setTasks(List tasks) {\n this.tasks = tasks;\n }\n\n @JsonIgnore\n public Map getInput() {\n if (!inputPayload.isEmpty() && !input.isEmpty()) {\n input.putAll(inputPayload);\n inputPayload = new HashMap<>();\n return input;\n } else if (inputPayload.isEmpty()) {\n return input;\n } else {\n return inputPayload;\n }\n }\n\n @JsonIgnore\n public void setInput(Map input) {\n if (input == null) {\n input = new HashMap<>();\n }\n this.input = input;\n }\n\n @JsonIgnore\n public Map getOutput() {\n if (!outputPayload.isEmpty() && !output.isEmpty()) {\n output.putAll(outputPayload);\n outputPayload = new HashMap<>();\n return output;\n } else if (outputPayload.isEmpty()) {\n return output;\n } else {\n return outputPayload;\n }\n }\n\n @JsonIgnore\n public void setOutput(Map output) {\n if (output == null) {\n output = new HashMap<>();\n }\n this.output = output;\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @Deprecated\n @JsonProperty(\"input\")\n public Map getRawInput() {\n return input;\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @Deprecated\n @JsonProperty(\"input\")\n public void setRawInput(Map input) {\n setInput(input);\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @Deprecated\n @JsonProperty(\"output\")\n public Map getRawOutput() {\n return output;\n }\n\n /**\n * @deprecated Used only for JSON serialization and deserialization.\n */\n @Deprecated\n @JsonProperty(\"output\")\n public void setRawOutput(Map output) {\n setOutput(output);\n }\n\n public String getCorrelationId() {\n return correlationId;\n }\n\n public void setCorrelationId(String correlationId) {\n this.correlationId = correlationId;\n }\n\n public String getReRunFromWorkflowId() {\n return reRunFromWorkflowId;\n }\n\n public void setReRunFromWorkflowId(String reRunFromWorkflowId) {\n this.reRunFromWorkflowId = reRunFromWorkflowId;\n }\n\n public String getReasonForIncompletion() {\n return reasonForIncompletion;\n }\n\n public void setReasonForIncompletion(String reasonForIncompletion) {\n this.reasonForIncompletion = reasonForIncompletion;\n }\n\n public String getEvent() {\n return event;\n }\n\n public void setEvent(String event) {\n this.event = event;\n }\n\n public Map getTaskToDomain() {\n return taskToDomain;\n }\n\n public void setTaskToDomain(Map taskToDomain) {\n this.taskToDomain = taskToDomain;\n }\n\n public Set getFailedReferenceTaskNames() {\n return failedReferenceTaskNames;\n }\n\n public void setFailedReferenceTaskNames(Set failedReferenceTaskNames) {\n this.failedReferenceTaskNames = failedReferenceTaskNames;\n }\n\n public Set getFailedTaskNames() {\n return failedTaskNames;\n }\n\n public void setFailedTaskNames(Set failedTaskNames) {\n this.failedTaskNames = failedTaskNames;\n }\n\n public WorkflowDef getWorkflowDefinition() {\n return workflowDefinition;\n }\n\n public void setWorkflowDefinition(WorkflowDef workflowDefinition) {\n this.workflowDefinition = workflowDefinition;\n }\n\n public String getExternalInputPayloadStoragePath() {\n return externalInputPayloadStoragePath;\n }\n\n public void setExternalInputPayloadStoragePath(String externalInputPayloadStoragePath) {\n this.externalInputPayloadStoragePath = externalInputPayloadStoragePath;\n }\n\n public String getExternalOutputPayloadStoragePath() {\n return externalOutputPayloadStoragePath;\n }\n\n public void setExternalOutputPayloadStoragePath(String externalOutputPayloadStoragePath) {\n this.externalOutputPayloadStoragePath = externalOutputPayloadStoragePath;\n }\n\n public int getPriority() {\n return priority;\n }\n\n public void setPriority(int priority) {\n if (priority < 0 || priority > 99) {\n throw new IllegalArgumentException(\"priority MUST be between 0 and 99 (inclusive)\");\n }\n this.priority = priority;\n }\n\n public Map getVariables() {\n return variables;\n }\n\n public void setVariables(Map variables) {\n this.variables = variables;\n }\n\n public long getLastRetriedTime() {\n return lastRetriedTime;\n }\n\n public void setLastRetriedTime(long lastRetriedTime) {\n this.lastRetriedTime = lastRetriedTime;\n }\n\n public String getOwnerApp() {\n return ownerApp;\n }\n\n public void setOwnerApp(String ownerApp) {\n this.ownerApp = ownerApp;\n }\n\n public Long getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Long createTime) {\n this.createTime = createTime;\n }\n\n public Long getUpdatedTime() {\n return updatedTime;\n }\n\n public void setUpdatedTime(Long updatedTime) {\n this.updatedTime = updatedTime;\n }\n\n public String getCreatedBy() {\n return createdBy;\n }\n\n public void setCreatedBy(String createdBy) {\n this.createdBy = createdBy;\n }\n\n public String getUpdatedBy() {\n return updatedBy;\n }\n\n public void setUpdatedBy(String updatedBy) {\n this.updatedBy = updatedBy;\n }\n\n public String getFailedTaskId() {\n return failedTaskId;\n }\n\n public void setFailedTaskId(String failedTaskId) {\n this.failedTaskId = failedTaskId;\n }\n\n /**\n * Convenience method for accessing the workflow definition name.\n *\n * @return the workflow definition name.\n */\n public String getWorkflowName() {\n Utils.checkNotNull(workflowDefinition, \"Workflow definition is null\");\n return workflowDefinition.getName();\n }\n\n /**\n * Convenience method for accessing the workflow definition version.\n *\n * @return the workflow definition version.\n */\n public int getWorkflowVersion() {\n Utils.checkNotNull(workflowDefinition, \"Workflow definition is null\");\n return workflowDefinition.getVersion();\n }\n\n public boolean hasParent() {\n return StringUtils.isNotEmpty(parentWorkflowId);\n }\n\n /**\n * A string representation of all relevant fields that identify this workflow. Intended for use\n * in log and other system generated messages.\n */\n public String toShortString() {\n String name = workflowDefinition != null ? workflowDefinition.getName() : null;\n Integer version = workflowDefinition != null ? workflowDefinition.getVersion() : null;\n return String.format(\"%s.%s/%s\", name, version, workflowId);\n }\n\n public TaskModel getTaskByRefName(String refName) {\n if (refName == null) {\n throw new RuntimeException(\n \"refName passed is null. Check the workflow execution. For dynamic tasks, make sure referenceTaskName is set to a not null value\");\n }\n LinkedList found = new LinkedList<>();\n for (TaskModel task : tasks) {\n if (task.getReferenceTaskName() == null) {\n throw new RuntimeException(\n \"Task \"\n + task.getTaskDefName()\n + \", seq=\"\n + task.getSeq()\n + \" does not have reference name specified.\");\n }\n if (task.getReferenceTaskName().equals(refName)) {\n found.add(task);\n }\n }\n if (found.isEmpty()) {\n return null;\n }\n return found.getLast();\n }\n\n public void externalizeInput(String path) {\n this.inputPayload = this.input;\n this.input = new HashMap<>();\n this.externalInputPayloadStoragePath = path;\n }\n\n public void externalizeOutput(String path) {\n this.outputPayload = this.output;\n this.output = new HashMap<>();\n this.externalOutputPayloadStoragePath = path;\n }\n\n public void internalizeInput(Map data) {\n this.input = new HashMap<>();\n this.inputPayload = data;\n }\n\n public void internalizeOutput(Map data) {\n this.output = new HashMap<>();\n this.outputPayload = data;\n }\n\n @Override\n public String toString() {\n String name = workflowDefinition != null ? workflowDefinition.getName() : null;\n Integer version = workflowDefinition != null ? workflowDefinition.getVersion() : null;\n return String.format(\"%s.%s/%s.%s\", name, version, workflowId, status);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n WorkflowModel that = (WorkflowModel) o;\n return getEndTime() == that.getEndTime()\n && getPriority() == that.getPriority()\n && getLastRetriedTime() == that.getLastRetriedTime()\n && getStatus() == that.getStatus()\n && Objects.equals(getWorkflowId(), that.getWorkflowId())\n && Objects.equals(getParentWorkflowId(), that.getParentWorkflowId())\n && Objects.equals(getParentWorkflowTaskId(), that.getParentWorkflowTaskId())\n && Objects.equals(getTasks(), that.getTasks())\n && Objects.equals(getInput(), that.getInput())\n && Objects.equals(output, that.output)\n && Objects.equals(outputPayload, that.outputPayload)\n && Objects.equals(getCorrelationId(), that.getCorrelationId())\n && Objects.equals(getReRunFromWorkflowId(), that.getReRunFromWorkflowId())\n && Objects.equals(getReasonForIncompletion(), that.getReasonForIncompletion())\n && Objects.equals(getEvent(), that.getEvent())\n && Objects.equals(getTaskToDomain(), that.getTaskToDomain())\n && Objects.equals(getFailedReferenceTaskNames(), that.getFailedReferenceTaskNames())\n && Objects.equals(getFailedTaskNames(), that.getFailedTaskNames())\n && Objects.equals(getWorkflowDefinition(), that.getWorkflowDefinition())\n && Objects.equals(\n getExternalInputPayloadStoragePath(),\n that.getExternalInputPayloadStoragePath())\n && Objects.equals(\n getExternalOutputPayloadStoragePath(),\n that.getExternalOutputPayloadStoragePath())\n && Objects.equals(getVariables(), that.getVariables())\n && Objects.equals(getOwnerApp(), that.getOwnerApp())\n && Objects.equals(getCreateTime(), that.getCreateTime())\n && Objects.equals(getUpdatedTime(), that.getUpdatedTime())\n && Objects.equals(getCreatedBy(), that.getCreatedBy())\n && Objects.equals(getUpdatedBy(), that.getUpdatedBy());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n getStatus(),\n getEndTime(),\n getWorkflowId(),\n getParentWorkflowId(),\n getParentWorkflowTaskId(),\n getTasks(),\n getInput(),\n output,\n outputPayload,\n getCorrelationId(),\n getReRunFromWorkflowId(),\n getReasonForIncompletion(),\n getEvent(),\n getTaskToDomain(),\n getFailedReferenceTaskNames(),\n getFailedTaskNames(),\n getWorkflowDefinition(),\n getExternalInputPayloadStoragePath(),\n getExternalOutputPayloadStoragePath(),\n getPriority(),\n getVariables(),\n getLastRetriedTime(),\n getOwnerApp(),\n getCreateTime(),\n getUpdatedTime(),\n getCreatedBy(),\n getUpdatedBy());\n }\n\n public Workflow toWorkflow() {\n Workflow workflow = new Workflow();\n BeanUtils.copyProperties(this, workflow);\n workflow.setStatus(Workflow.WorkflowStatus.valueOf(this.status.name()));\n workflow.setTasks(tasks.stream().map(TaskModel::toTask).collect(Collectors.toList()));\n workflow.setUpdateTime(this.updatedTime);\n\n // ensure that input/output is properly represented\n if (externalInputPayloadStoragePath != null) {\n workflow.setInput(new HashMap<>());\n }\n if (externalOutputPayloadStoragePath != null) {\n workflow.setOutput(new HashMap<>());\n }\n return workflow;\n }\n\n public void addInput(String key, Object value) {\n this.input.put(key, value);\n }\n\n public void addInput(Map inputData) {\n if (inputData != null) {\n this.input.putAll(inputData);\n }\n }\n\n public void addOutput(String key, Object value) {\n this.output.put(key, value);\n }\n\n public void addOutput(Map outputData) {\n if (outputData != null) {\n this.output.putAll(outputData);\n }\n }\n}", "answers": [" return TaskType.SIMPLE.name();"], "length": 9148, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "e9a0ec64-a051-4b3a-a71e-214740a3660f", "reasoning": "The method getTaskType() should return the string identifier for the SIMPLE task type. In Conductor, task types are defined in TaskType enum, and the SIMPLE type is accessed via TaskType.SIMPLE.name(). Therefore the next line is the return statement for that value.", "reasoning_model_answer": "return TaskType.SIMPLE.name();", "assistant_with_reasoning": "\nThe method getTaskType() should return the string identifier for the SIMPLE task type. In Conductor, task types are defined in TaskType enum, and the SIMPLE type is accessed via TaskType.SIMPLE.name(). Therefore the next line is the return statement for that value.\n\nreturn TaskType.SIMPLE.name();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.801, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36685, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return TaskType.SIMPLE.name();", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.flowingcode.vaadin.addons.fontawesome.FontAwesome;\nimport com.nasc.application.data.core.User;\nimport com.nasc.application.security.AuthenticatedUser;\nimport com.nasc.application.views.about.AboutView;\nimport com.nasc.application.views.activeusers.ActiveUsersView;\nimport com.nasc.application.views.address.AddressMasterDetailView;\nimport com.nasc.application.views.auth.create.CreateUsers;\nimport com.nasc.application.views.dashboard.DashboardView;\nimport com.nasc.application.views.forms.adderss.AddressFormView;\nimport com.nasc.application.views.forms.bank.BankDetailsFormView;\nimport com.nasc.application.views.forms.personal.PersonalFormView;\nimport com.nasc.application.views.marks.entry.MarkEntryView;\nimport com.nasc.application.views.marks.table.MarksView;\nimport com.nasc.application.views.password.PasswordChangeView;\nimport com.nasc.application.views.professor.status.ProfessorStatusView;\nimport com.nasc.application.views.student.StudentMasterDetailsView;\nimport com.nasc.application.views.student.status.StudentsStatusView;\nimport com.nasc.application.views.subject.CreateSubjectCrud;\nimport com.nasc.application.views.valuevalut.ValueVaultView;\nimport com.vaadin.flow.component.applayout.AppLayout;\nimport com.vaadin.flow.component.applayout.DrawerToggle;\nimport com.vaadin.flow.component.avatar.Avatar;\nimport com.vaadin.flow.component.contextmenu.MenuItem;\nimport com.vaadin.flow.component.html.*;\nimport com.vaadin.flow.component.icon.Icon;\nimport com.vaadin.flow.component.menubar.MenuBar;\nimport com.vaadin.flow.component.orderedlayout.Scroller;\nimport com.vaadin.flow.component.sidenav.SideNav;\nimport com.vaadin.flow.component.sidenav.SideNavItem;\nimport com.vaadin.flow.router.PageTitle;\nimport com.vaadin.flow.router.PreserveOnRefresh;\nimport com.vaadin.flow.server.auth.AccessAnnotationChecker;\nimport com.vaadin.flow.theme.lumo.LumoUtility;\nimport org.vaadin.lineawesome.LineAwesomeIcon;\nimport java.util.Optional;", "context": "src/main/java/com/nasc/application/views/MainLayout.java\npackage com.nasc.application.views;\n\n\n\n/**\n * The main view is a top-level placeholder for other views.\n */\n@PreserveOnRefresh\npublic class MainLayout extends AppLayout {\n\n private H2 viewTitle;\n\n private final AuthenticatedUser authenticatedUser;\n private final AccessAnnotationChecker accessChecker;\n\n\nsrc/main/java/com/nasc/application/data/core/User.java\n@Entity\n@Table(name = \"application_user\")\npublic class User extends AbstractEntity {\n\n @CsvBindByName\n private String username;\n @CsvBindByName\n @Column(unique = true)\n private String registerNumber;\n @CsvBindByName\n private String email;\n @JsonIgnore\n @CsvBindByName\n private String password;\n @Enumerated(EnumType.STRING)\n @ElementCollection(fetch = FetchType.EAGER)\n private Set roles;\n @Enumerated(EnumType.STRING)\n private StudentSection studentSection;\n\n /*\n @Lob\n @Column(length = 1000000)\n private byte[] profilePicture;\n */\n\n private Boolean personalDetailsCompleted;\n private Boolean addressDetailsCompleted;\n private Boolean bankDetailsCompleted;\n\n @ManyToOne\n @JoinColumn(name = \"department_id\")\n private DepartmentEntity department;\n\n @ManyToOne\n @JoinColumn(name = \"academic_year_id\")\n private AcademicYearEntity academicYear;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)\n @JoinColumn(name = \"bank_details_id\")\n private BankDetails bankDetails;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\n @JoinColumn(name = \"address_details_id\")\n private AddressDetails addressDetails;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)\n @JoinColumn(name = \"personal_details_id\")\n private PersonalDetails personalDetails;\n\n public User() {\n this.personalDetailsCompleted = Boolean.FALSE;\n this.addressDetailsCompleted = Boolean.FALSE;\n this.bankDetailsCompleted = Boolean.FALSE;\n }\n\n public AcademicYearEntity getAcademicYear() {\n return academicYear;\n }\n\n public void setAcademicYear(AcademicYearEntity academicYear) {\n this.academicYear = academicYear;\n }\n\n public DepartmentEntity getDepartment() {\n return department;\n }\n\n public void setDepartment(DepartmentEntity department) {\n this.department = department;\n }\n\n public StudentSection getStudentSection() {\n return studentSection;\n }\n\n public void setStudentSection(StudentSection studentSection) {\n this.studentSection = studentSection;\n }\n\n public PersonalDetails getPersonalDetails() {\n return personalDetails;\n }\n\n public void setPersonalDetails(PersonalDetails personalDetails) {\n this.personalDetails = personalDetails;\n }\n\n\n public Boolean getPersonalDetailsCompleted() {\n return personalDetailsCompleted;\n }\n\n public void setPersonalDetailsCompleted(Boolean personalDetailsCompleted) {\n this.personalDetailsCompleted = personalDetailsCompleted;\n }\n\n public Boolean getAddressDetailsCompleted() {\n return addressDetailsCompleted;\n }\n\n public void setAddressDetailsCompleted(Boolean addressDetailsCompleted) {\n this.addressDetailsCompleted = addressDetailsCompleted;\n }\n\n public Boolean getBankDetailsCompleted() {\n return bankDetailsCompleted;\n }\n\n public void setBankDetailsCompleted(Boolean bankDetailsCompleted) {\n this.bankDetailsCompleted = bankDetailsCompleted;\n }\n\n public AddressDetails getAddressDetails() {\n return addressDetails;\n }\n\n public void setAddressDetails(AddressDetails addressDetails) {\n this.addressDetails = addressDetails;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getRegisterNumber() {\n return registerNumber;\n }\n\n public void setRegisterNumber(String registerNumber) {\n this.registerNumber = registerNumber;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Set getRoles() {\n return roles;\n }\n\n public void setRoles(Set roles) {\n this.roles = roles;\n }\n\n /*\n public byte[] getProfilePicture() {\n return profilePicture;\n }\n public void setProfilePicture(byte[] profilePicture) {\n this.profilePicture = profilePicture;\n }\n */\n public BankDetails getBankDetails() {\n return bankDetails;\n }\n\n public void setBankDetails(BankDetails bankDetails) {\n this.bankDetails = bankDetails;\n }\n\n //This is ued to indicate user completed all three forms are not.\n public boolean isFormsCompleted() {\n return personalDetailsCompleted && addressDetailsCompleted && bankDetailsCompleted;\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/forms/personal/PersonalFormView.java\n@PageTitle(\"Personal Information Form\")\n@Route(value = \"personal-information-form\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\", \"PROFESSOR\", \"STUDENT\"})\n@Uses(Icon.class)\npublic class PersonalFormView extends Composite {\n\n private final UserService userService;\n private final VerticalLayout mainLayout = new VerticalLayout();\n private final H3 title = new H3();\n private final FormLayout formLayout = new FormLayout();\n private final TextField firstName = new TextField();\n private final TextField lastName = new TextField();\n private final DatePicker birthday = new DatePicker();\n private final TextField phoneNumber = new TextField();\n private final EmailField email = new EmailField();\n private final ComboBox gender = new ComboBox<>();\n private final HorizontalLayout buttonLayout = new HorizontalLayout();\n private final Button saveButton = new Button();\n private final BeanValidationBinder binder = new BeanValidationBinder<>(PersonalDetails.class);\n\n public PersonalFormView(UserService userService) {\n this.userService = userService;\n configureLayout();\n initFormWithExistingDetails(); // Initialize the form with existing personal details\n }\n\n private void configureLayout() {\n mainLayout.setWidth(\"100%\");\n mainLayout.getStyle().set(\"flex-grow\", \"1\");\n mainLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.START);\n mainLayout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n title.setText(\"Personal Information\");\n title.setWidth(\"100%\");\n\n formLayout.setWidth(\"100%\");\n firstName.setLabel(\"First Name\");\n lastName.setLabel(\"Last Name\");\n birthday.setLabel(\"Birthday\");\n phoneNumber.setLabel(\"Phone Number\");\n email.setLabel(\"Email\");\n\n buttonLayout.addClassName(Gap.MEDIUM);\n buttonLayout.setWidth(\"100%\");\n buttonLayout.getStyle().set(\"flex-grow\", \"1\");\n\n saveButton.setText(\"Save\");\n saveButton.setWidth(\"min-content\");\n saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n mainLayout.add(title, formLayout, buttonLayout);\n formLayout.add(firstName,\n lastName,\n birthday,\n phoneNumber,\n email,\n gender);\n gender.setLabel(\"Gender\");\n gender.setItems(\"Male\", \"Female\", \"Other\");\n\n saveButton.addClickListener(e -> {\n if (isPersonalDetailsAlreadySaved()) {\n updatePersonalDetails();\n } else {\n savePersonalDetails();\n }\n });\n\n binder.addStatusChangeListener(e -> saveButton.setEnabled(binder.isValid()));\n\n buttonLayout.add(saveButton);\n\n getContent().add(mainLayout);\n }\n\n private void initFormWithExistingDetails() {\n User currentUser = userService.getCurrentUser();\n binder.bindInstanceFields(this);\n PersonalDetails existingPersonalDetails = currentUser.getPersonalDetails();\n if (existingPersonalDetails != null) {\n populateForm(existingPersonalDetails);\n saveButton.setText(\"Update\");\n }\n }\n\n private void populateForm(PersonalDetails existingPersonalDetails) {\n firstName.setValue(existingPersonalDetails.getFirstName());\n lastName.setValue(existingPersonalDetails.getLastName());\n birthday.setValue(existingPersonalDetails.getBirthday());\n phoneNumber.setValue(existingPersonalDetails.getPhoneNumber());\n email.setValue(existingPersonalDetails.getEmail());\n gender.setValue(existingPersonalDetails.getGender());\n }\n\n private boolean isPersonalDetailsAlreadySaved() {\n return userService.getCurrentUser().getPersonalDetails() != null;\n }\n\n private void updatePersonalDetails() {\n User currentUser = userService.getCurrentUser();\n PersonalDetails existingPersonalDetails = currentUser.getPersonalDetails();\n existingPersonalDetails.setFirstName(firstName.getValue());\n existingPersonalDetails.setLastName(lastName.getValue());\n existingPersonalDetails.setBirthday(birthday.getValue());\n existingPersonalDetails.setPhoneNumber(phoneNumber.getValue());\n existingPersonalDetails.setEmail(email.getValue());\n existingPersonalDetails.setGender(gender.getValue());\n userService.saveUserWithPersonalDetails(currentUser, existingPersonalDetails);\n NotificationUtils.createSubmitSuccess(\"Personal Form Updated Successfully.\");\n }\n\n private void savePersonalDetails() {\n User currentUser = userService.getCurrentUser();\n PersonalDetails personalDetailsFromForm = createPersonalDetailsFromForm();\n personalDetailsFromForm.setUser(currentUser);\n currentUser.setPersonalDetails(personalDetailsFromForm);\n userService.saveUserWithPersonalDetails(currentUser, personalDetailsFromForm);\n NotificationUtils.createSubmitSuccess(\"Personal Form Saved Successfully.\");\n }\n\n private PersonalDetails createPersonalDetailsFromForm() {\n PersonalDetails personalDetails = new PersonalDetails();\n personalDetails.setFirstName(firstName.getValue());\n personalDetails.setLastName(lastName.getValue());\n personalDetails.setBirthday(birthday.getValue());\n personalDetails.setPhoneNumber(phoneNumber.getValue());\n personalDetails.setEmail(email.getValue());\n personalDetails.setGender(gender.getValue());\n return personalDetails;\n }\n}\n\nsrc/main/java/com/nasc/application/views/activeusers/ActiveUsersView.java\n@Route(value = \"get-online-users\", layout = MainLayout.class)\n@RolesAllowed(\"ADMIN\")\npublic class ActiveUsersView extends Div {\n public ActiveUsersView(UserService userService) {\n add(createActiveUserGrid(userService));\n }\n\n private Component createActiveUserGrid(UserService userService) {\n // Header\n HorizontalLayout header = createHeader(\"Active Users\", \"Online\");\n\n // Grid\n Grid grid = new Grid<>();\n grid.addThemeVariants(GridVariant.MATERIAL_COLUMN_DIVIDERS);\n grid.setAllRowsVisible(true);\n\n // Columns\n grid.addColumn(UserDetails::getUsername)\n .setHeader(\"User Name\")\n .setAutoWidth(true)\n .setSortable(true);\n\n/* grid.addColumn(userDetails -> userDetails.getAuthorities().stream()\n .map(Object::toString)\n .collect(Collectors.joining(\", \")))\n .setHeader(\"User Roles\")\n .setAutoWidth(true)\n .setSortable(true);*/\n\n grid.addComponentColumn(userDetails -> {\n List roleNames = userDetails.getAuthorities().stream()\n .map(Object::toString)\n .collect(Collectors.toList());\n return createBadgeList(roleNames);\n }).setHeader(\"User Roles\").setAutoWidth(true).setSortable(true);\n\n\n // Set items\n grid.setItems(userService.getOnlineUsers());\n\n // Add it all together\n VerticalLayout activeUsersLayout = new VerticalLayout(header, grid);\n activeUsersLayout.addClassName(LumoUtility.Padding.LARGE);\n activeUsersLayout.setPadding(false);\n activeUsersLayout.setSpacing(false);\n activeUsersLayout.getElement().getThemeList().add(\"spacing-l\");\n return activeUsersLayout;\n }\n\n\n private HorizontalLayout createHeader(String title, String subtitle) {\n H2 h2 = new H2(title);\n h2.addClassNames(LumoUtility.FontSize.XLARGE, LumoUtility.Margin.NONE);\n\n Span span = new Span(subtitle);\n span.addClassNames(LumoUtility.TextColor.SECONDARY, LumoUtility.FontSize.XSMALL);\n\n VerticalLayout column = new VerticalLayout(h2, span);\n column.setPadding(false);\n column.setSpacing(false);\n\n HorizontalLayout header = new HorizontalLayout(column);\n header.setJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN);\n header.setSpacing(false);\n header.setWidthFull();\n return header;\n }\n\n private BadgeList createBadgeList(List roles) {\n List badges = new ArrayList<>();\n roles.forEach(role -> badges.add(new Badge(role)));\n return new BadgeList(badges);\n }\n}\n\nsrc/main/java/com/nasc/application/views/dashboard/DashboardView.java\n@PageTitle(\"Dashboard\")\n@Route(value = \"dashboard\", layout = MainLayout.class)\n@RouteAlias(value = \"\", layout = MainLayout.class)\n@PermitAll\npublic class DashboardView extends Main {\n\n public DashboardView(UserService userService) {\n addClassName(\"dashboard-view\");\n Board board = new Board();\n board.addRow(\n createHighlight(\"Total Users\", String.valueOf(userService.count())),\n createHighlight(\"Active Users\", String.valueOf(userService.getOnlineUsers().size())));\n add(board);\n }\n\n private Component createHighlight(String title, String value) {\n H2 h2 = new H2(title);\n h2.addClassNames(FontWeight.NORMAL, Margin.NONE, TextColor.SECONDARY, FontSize.SMALL);\n Span span = new Span(value);\n span.addClassNames(FontWeight.SEMIBOLD, FontSize.XXXLARGE);\n VerticalLayout layout = new VerticalLayout(h2, span);\n layout.addClassName(Padding.LARGE);\n layout.setPadding(false);\n layout.setSpacing(false);\n return layout;\n }\n}\n\nsrc/main/java/com/nasc/application/views/professor/status/ProfessorStatusView.java\n@PageTitle(\"Professor Status\")\n@Route(value = \"professor-status\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\"})\npublic class ProfessorStatusView extends VerticalLayout {\n private final DepartmentService departmentService;\n private final UserService userService;\n private final Anchor downloadLink;\n private final Button menuButton = new Button(\"Show/Hide Columns\", FontAwesome.Solid.LIST_CHECK.create());\n private final ProfessorStatusView.ColumnToggleContextMenu columnToggleContextMenu = new ProfessorStatusView.ColumnToggleContextMenu(menuButton);\n private Grid grid;\n private GridListDataView gridListDataView;\n private Grid.Column userColumn;\n // Layer\n private HorizontalLayout filterLayout;\n private ComboBox departmentFilter;\n private Button searchButton;\n\n public ProfessorStatusView(UserService userService, DepartmentService departmentService) {\n this.userService = userService;\n this.departmentService = departmentService;\n downloadLink = createDownloadLink(); // Add this line to create the download link\n addClassName(\"professor-status-view\");\n setSizeFull();\n createGrid();\n createFilterLayout();\n\n menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL);\n\n HorizontalLayout menuButtonLayout = new HorizontalLayout(menuButton, downloadLink);\n menuButtonLayout.setWidthFull();\n menuButtonLayout.setJustifyContentMode(JustifyContentMode.END);\n menuButtonLayout.setAlignItems(Alignment.CENTER);\n\n createDepartmentFilterComponent();\n\n createSearchButton();\n\n FlexLayout searchButtonLayout = new FlexLayout(searchButton);\n searchButtonLayout.setJustifyContentMode(JustifyContentMode.END);\n filterLayout.setWidthFull();\n filterLayout.expand(searchButtonLayout);\n filterLayout.add(departmentFilter, searchButtonLayout);\n\n add(filterLayout, menuButtonLayout, grid);\n }\n\n private void createSearchButton() {\n searchButton = new Button(\"Search\");\n searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL);\n searchButton.addClickListener(buttonClickEvent -> {\n DepartmentEntity selectedDepartment = departmentFilter.getValue();\n List professors = userService.findUsersByDepartmentAndRole(selectedDepartment, Role.PROFESSOR);\n gridListDataView = grid.setItems(professors);\n exportExport(professors);\n });\n }\n\n\n private void createFilterLayout() {\n filterLayout = new HorizontalLayout();\n filterLayout.setSpacing(true);\n filterLayout.setAlignItems(Alignment.BASELINE);\n }\n\n private void createDepartmentFilterComponent() {\n List allDepartment = departmentService.findAll();\n departmentFilter = new ComboBox<>();\n departmentFilter.setItems(allDepartment);\n departmentFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n departmentFilter.setItemLabelGenerator(departmentEntity -> departmentEntity.getName() + \" \" + departmentEntity.getShortName());\n departmentFilter.setLabel(\"Filter By Department\");\n }\n\n private static FontAwesome.Regular.Icon getThumbsUpIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_UP.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private static FontAwesome.Regular.Icon getThumbsDownIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_DOWN.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private Anchor createDownloadLink() {\n Anchor link = new Anchor();\n link.getElement().setAttribute(\"download\", true);\n Button exportButton = new Button(\"Export to CSV\", FontAwesome.Solid.FILE_EXPORT.create());\n exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL, ButtonVariant.LUMO_TERTIARY_INLINE);\n link.add(exportButton);\n return link;\n }\n\n private void createGrid() {\n createGridComponent();\n addColumnsToGrid();\n addFiltersToGrid();\n }\n\n private void addFiltersToGrid() {\n HeaderRow filterRow = grid.appendHeaderRow();\n\n // Username filter\n TextField userFilter = createTextFilter();\n userFilter.addValueChangeListener(event -> gridListDataView\n .addFilter(user -> StringUtils.containsIgnoreCase(user.getUsername(), userFilter.getValue())));\n filterRow.getCell(userColumn).setComponent(userFilter);\n\n // Status filters\n addStatusFilter(\"Personal Details\", \"personalDetailsCompleted\", filterRow);\n addStatusFilter(\"Address Details\", \"addressDetailsCompleted\", filterRow);\n addStatusFilter(\"Bank Details\", \"bankDetailsCompleted\", filterRow);\n\n ComboBox allFormsFilter = createAllFormsFilter();\n allFormsFilter.addValueChangeListener(this::handleAllFormsFilterChange);\n filterRow.getCell(grid.getColumnByKey(\"allFormsCompleted\")).setComponent(allFormsFilter);\n }\n\n private TextField createTextFilter() {\n TextField filter = new TextField();\n filter.setPlaceholder(\"Filter\");\n filter.setClearButtonVisible(true);\n filter.setWidthFull();\n filter.setValueChangeMode(ValueChangeMode.EAGER);\n filter.addThemeVariants(TextFieldVariant.LUMO_SMALL);\n return filter;\n }\n\n private void addStatusFilter(String columnName, String propertyKey, HeaderRow filterRow) {\n ComboBox statusFilter = createStatusFilter();\n statusFilter.addValueChangeListener(event -> handleStatusFilterChange(event, columnName));\n filterRow.getCell(grid.getColumnByKey(propertyKey)).setComponent(statusFilter);\n }\n\n private ComboBox createStatusFilter() {\n ComboBox statusFilter = new ComboBox<>();\n statusFilter.setItems(Arrays.asList(\"Pending\", \"Success\"));\n statusFilter.setPlaceholder(\"Filter\");\n statusFilter.setClearButtonVisible(true);\n statusFilter.setWidth(\"100%\");\n statusFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n return statusFilter;\n }\n\n private void handleStatusFilterChange(HasValue.ValueChangeEvent event, String columnName) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); //Every Time Drop Down Change, It removes filters from grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areStatusesEqual(user, columnName, filterValue));\n }\n }\n\n private boolean areStatusesEqual(User user, String columnName, String filterValue) {\n switch (columnName) {\n case \"Personal Details\" -> {\n return Boolean.TRUE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Address Details\" -> {\n return Boolean.TRUE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Bank Details\" -> {\n return Boolean.TRUE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n default -> {\n return true;\n }\n }\n }\n\n private ComboBox createAllFormsFilter() {\n ComboBox allFormsFilter = new ComboBox<>();\n allFormsFilter.setItems(Arrays.asList(\"Complete\", \"Incomplete\"));\n allFormsFilter.setPlaceholder(\"Filter\");\n allFormsFilter.setClearButtonVisible(true);\n allFormsFilter.setWidth(\"100%\");\n return allFormsFilter;\n }\n\n private void handleAllFormsFilterChange(HasValue.ValueChangeEvent event) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); // Every Time Drop Down Change, It removes filters from the grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areAllFormsComplete(user, filterValue));\n }\n }\n\n private boolean areAllFormsComplete(User user, String filterValue) {\n boolean allFormsComplete = user.isFormsCompleted();\n return (allFormsComplete && \"Complete\".equalsIgnoreCase(filterValue)) ||\n (!allFormsComplete && \"Incomplete\".equalsIgnoreCase(filterValue));\n }\n\n private void createGridComponent() {\n grid = new Grid<>();\n grid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_COLUMN_BORDERS);\n grid.setHeight(\"100%\");\n }\n\n private void addColumnsToGrid() {\n createUsernameColumn();\n createPersonalDetailsColumn();\n createAddressDetailsColumn();\n createBankDetailsColumn();\n createAllFormsCompletedColumn();\n }\n\n private void createUsernameColumn() {\n userColumn = grid.addColumn(User::getUsername).setHeader(\"Username\").setKey(\"username\").setComparator((User::getUsername));\n }\n\n private void createPersonalDetailsColumn() {\n Grid.Column personalDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getPersonalDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getPersonalDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getPersonalDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n })).setHeader(\"Personal Details\").setKey(\"personalDetailsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"Personal Details Completed\", personalDetailsColumn);\n }\n\n private void createAddressDetailsColumn() {\n Grid.Column addressDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getAddressDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getAddressDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getAddressDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n })).setHeader(\"Address Details\").setKey(\"addressDetailsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"Address Details Completed\", addressDetailsColumn);\n }\n\n private void createBankDetailsColumn() {\n Grid.Column bankDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getBankDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getBankDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getBankDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n })).setHeader(\"Bank Details\").setKey(\"bankDetailsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"Bank Details\", bankDetailsColumn);\n }\n\n private void createAllFormsCompletedColumn() {\n Grid.Column allFormsCompletedColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n boolean allFormsCompleted = user.isFormsCompleted();\n Span span = new Span(allFormsCompleted ? getThumbsUpIcon() : getThumbsDownIcon(),\n new Span(allFormsCompleted ? \"Complete\" : \"Incomplete\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (allFormsCompleted ? \"success\" : \"error\"));\n return span;\n })).setHeader(\"All Forms Completed\").setKey(\"allFormsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"All Forms Completed\", allFormsCompletedColumn);\n }\n\n private Icon createIcon(VaadinIcon vaadinIcon) {\n Icon icon = vaadinIcon.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private void exportExport(List users) {\n\n try {\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n\n try (CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8))) {\n\n // Write header\n String[] header = {\n \"Username\", \"Register Number\", \"Email\", \"Department\",\n \"Bank Name\", \"Account Holder Name\", \"Account Number\", \"IFSC Code\", \"Branch Name\",\n \"Branch Address\", \"PAN Number\", \"First Name\", \"Last Name\", \"Phone Number\",\n \"Birthday\", \"Gender\", \"Address\", \"Pin code\", \"City\", \"State\", \"Country\"\n };\n csvWriter.writeNext(header);\n\n for (User user : users) {\n List data = new ArrayList<>();\n\n // Common information\n data.add(user.getUsername());\n data.add(user.getRegisterNumber());\n data.add(user.getEmail());\n data.add(user.getDepartment().toString());\n\n // Bank details (conditionally added)\n if (Boolean.TRUE.equals(user.getBankDetailsCompleted())) {\n data.add(user.getBankDetails().getBankName());\n data.add(user.getBankDetails().getAccountHolderName());\n data.add(user.getBankDetails().getAccountNumber());\n data.add(user.getBankDetails().getIfscCode());\n data.add(user.getBankDetails().getBranchName());\n data.add(user.getBankDetails().getBranchAddress());\n data.add(user.getBankDetails().getPanNumber());\n } else {\n // Add empty values or placeholders for bank details if not completed\n data.addAll(Collections.nCopies(7, \"\"));\n }\n\n // Personal details\n if (Boolean.TRUE.equals(user.getPersonalDetailsCompleted())) {\n data.add(user.getPersonalDetails().getFirstName());\n data.add(user.getPersonalDetails().getLastName());\n data.add(user.getPersonalDetails().getPhoneNumber());\n data.add(user.getPersonalDetails().getBirthday().toString());\n data.add(user.getPersonalDetails().getGender());\n } else {\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Address details (conditionally added)\n if (Boolean.TRUE.equals(user.getAddressDetailsCompleted())) {\n data.add(user.getAddressDetails().getAddress());\n data.add(user.getAddressDetails().getPinCode());\n data.add(user.getAddressDetails().getCity());\n data.add(user.getAddressDetails().getState());\n data.add(user.getAddressDetails().getCountry());\n } else {\n // Add empty values or placeholders for address details if not completed\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Convert the list to an array and write to CSV\n csvWriter.writeNext(data.toArray(new String[0]));\n }\n\n DepartmentEntity department = departmentFilter.getValue();\n\n StringJoiner stringJoiner = new StringJoiner(\"_\");\n stringJoiner.add(department.getName());\n stringJoiner.add(department.getShortName());\n\n String fileName = stringJoiner + \".csv\";\n StreamResource resource = new StreamResource(fileName,\n () -> new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));\n\n downloadLink.setHref(resource);\n }\n } catch (IOException e) {\n NotificationUtils.showErrorNotification(\"Error exporting data to CSV\");\n }\n }\n\n private static class ColumnToggleContextMenu extends ContextMenu {\n public ColumnToggleContextMenu(Component target) {\n super(target);\n setOpenOnClick(true);\n }\n\n void addColumnToggleItem(String label, Grid.Column column) {\n MenuItem menuItem = this.addItem(label, e -> column.setVisible(e.getSource().isChecked()));\n menuItem.setCheckable(true);\n menuItem.setChecked(column.isVisible());\n menuItem.setKeepOpen(true);\n }\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/address/AddressMasterDetailView.java\n@PageTitle(\"Address Master Detail\")\n@Route(value = \"student-master-detail/:sampleAddressID?/:action?(edit)\", layout = MainLayout.class)\n@RolesAllowed(\"HOD\")\n@Slf4j\npublic class AddressMasterDetailView extends Div implements BeforeEnterObserver, BeforeLeaveObserver {\n\n private final String SAMPLEADDRESS_ID = \"sampleAddressID\";\n private final String SAMPLEADDRESS_EDIT_ROUTE_TEMPLATE = \"student-master-detail/%s/edit\";\n private final Grid grid = new Grid<>(AddressDetails.class, false);\n private final BeanValidationBinder binder;\n private final CountryService countryService;\n private final StateService stateService;\n private TextField username;\n private TextField city;\n private TextField registerNumber;\n private TextField address;\n private final Button cancel = new Button(\"Cancel\");\n private final Button save = new Button(\"Save\");\n private TextField pinCode;\n private Select state;\n private final SampleAddressService sampleAddressService;\n private Select country;\n private AddressDetails addressDetails;\n\n public AddressMasterDetailView(SampleAddressService sampleAddressService,\n CountryService countryService,\n StateService stateService) {\n this.sampleAddressService = sampleAddressService;\n this.countryService = countryService;\n this.stateService = stateService;\n addClassNames(\"address-master-detail-view\");\n\n // Create UI\n SplitLayout splitLayout = new SplitLayout();\n\n createGridLayout(splitLayout);\n createEditorLayout(splitLayout);\n\n add(splitLayout);\n\n // Configure Grid\n grid.addColumn(AddressDetails -> AddressDetails.getUser().getUsername())\n .setHeader(\"User Name\")\n .setAutoWidth(true)\n .setComparator(Comparator.comparing(addressDetails -> addressDetails.getUser().getUsername()));\n\n grid.addColumn(AddressDetails -> AddressDetails.getUser().getRegisterNumber())\n .setHeader(\"Register Number\")\n .setAutoWidth(true)\n .setComparator(Comparator.comparing(addressDetails1 -> addressDetails1.getUser().getRegisterNumber()));\n\n\n grid.addColumn(\"address\").setAutoWidth(true);\n grid.addColumn(\"pinCode\").setAutoWidth(true);\n grid.addColumn(\"city\").setAutoWidth(true);\n grid.addColumn(\"state\").setAutoWidth(true);\n grid.addColumn(\"country\").setAutoWidth(true);\n grid.setItems(query -> sampleAddressService.list(\n PageRequest.of(query.getPage(), query.getPageSize(), VaadinSpringDataHelpers.toSpringDataSort(query)))\n .stream());\n grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);\n\n // when a row is selected or deselected, populate form\n grid.asSingleSelect().addValueChangeListener(event -> {\n if (event.getValue() != null) {\n UI.getCurrent().navigate(String.format(SAMPLEADDRESS_EDIT_ROUTE_TEMPLATE, event.getValue().getId()));\n } else {\n clearForm();\n UI.getCurrent().navigate(AddressMasterDetailView.class);\n }\n });\n\n // Configure Form\n binder = new BeanValidationBinder<>(AddressDetails.class);\n\n // Bind fields. This is where you'd define e.g. validation rules\n binder.bindInstanceFields(this);\n\n binder.forField(state)\n .bind(AddressDetails::getState, AddressDetails::setState);\n\n binder.forField(country)\n .bind(AddressDetails::getCountry, AddressDetails::setCountry);\n\n cancel.addClickListener(e -> {\n clearForm();\n refreshGrid();\n });\n\n save.addClickListener(e -> {\n try {\n binder.writeBean(this.addressDetails);\n sampleAddressService.update(this.addressDetails);\n\n UI.getCurrent().navigate(AddressMasterDetailView.class);\n\n refreshGrid();\n NotificationUtils.showSuccessNotification(\"Data updated\");\n clearForm();\n } catch (ObjectOptimisticLockingFailureException exception) {\n NotificationUtils.showErrorNotification(\"Error updating the data. Somebody else has updated the record while you were making changes.\");\n } catch (ValidationException validationException) {\n NotificationUtils.showErrorNotification(\"Failed to update the data. Check again that all values are valid\");\n }\n });\n }\n\n @Override\n public void beforeEnter(BeforeEnterEvent event) {\n Optional sampleAddressId = event.getRouteParameters().get(SAMPLEADDRESS_ID).map(Long::parseLong);\n if (sampleAddressId.isPresent()) {\n Optional sampleAddressFromBackend = sampleAddressService.get(sampleAddressId.get());\n if (sampleAddressFromBackend.isPresent()) {\n populateForm(sampleAddressFromBackend.get());\n } else {\n String message = String.format(\"The requested sampleAddress was not found, ID = %s\", sampleAddressId.get());\n NotificationUtils.showErrorNotification(message);\n refreshGrid();\n event.forwardTo(AddressMasterDetailView.class);\n }\n }\n }\n\n private void createEditorLayout(SplitLayout splitLayout) {\n Div editorLayoutDiv = new Div();\n editorLayoutDiv.setClassName(\"editor-layout\");\n\n Div editorDiv = new Div();\n editorDiv.setClassName(\"editor\");\n editorLayoutDiv.add(editorDiv);\n\n FormLayout formLayout = new FormLayout();\n username = new TextField(\"User Name\");\n registerNumber = new TextField(\"Register Number\");\n address = new TextField(\"address\");\n pinCode = new TextField(\"Postal Code\");\n city = new TextField(\"City\");\n\n state = new Select<>();\n state.setLabel(\"State\");\n state.setItems(stateService.getAllStates());\n state.setPlaceholder(\"Select State\");\n state.setRequiredIndicatorVisible(true);\n\n country = new Select<>();\n country.setLabel(\"Country\");\n country.setItems(countryService.getAllCountries());\n country.setPlaceholder(\"Select Country\");\n country.setRequiredIndicatorVisible(true);\n\n username.setEnabled(false);\n registerNumber.setEnabled(false);\n\n formLayout.add(username, registerNumber, address, pinCode, city, state, country);\n\n editorDiv.add(formLayout);\n createButtonLayout(editorLayoutDiv);\n\n splitLayout.addToSecondary(editorLayoutDiv);\n }\n\n private void createButtonLayout(Div editorLayoutDiv) {\n HorizontalLayout buttonLayout = new HorizontalLayout();\n buttonLayout.setClassName(\"button-layout\");\n cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);\n save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n buttonLayout.add(save, cancel);\n editorLayoutDiv.add(buttonLayout);\n }\n\n private void createGridLayout(SplitLayout splitLayout) {\n Div wrapper = new Div();\n wrapper.setClassName(\"grid-wrapper\");\n splitLayout.addToPrimary(wrapper);\n wrapper.add(grid);\n }\n\n private void refreshGrid() {\n grid.select(null);\n grid.getDataProvider().refreshAll();\n }\n\n private void clearForm() {\n populateForm(null);\n }\n\n private void populateForm(AddressDetails value) {\n this.addressDetails = value;\n\n // Bind the rest of the fields\n binder.readBean(this.addressDetails);\n\n // Set values for disabled fields\n if (value != null && value.getUser() != null) {\n username.setValue(value.getUser().getUsername());\n registerNumber.setValue(value.getUser().getRegisterNumber());\n } else {\n // Clear values if no addressDetails provided\n username.clear();\n registerNumber.clear();\n }\n }\n\n @Override\n public void beforeLeave(BeforeLeaveEvent event) {\n // only prevent if certain condition is met. In my example I prevent navigation if binder has changes.\n if (binder.hasChanges()) {\n\n // prevents navigation\n BeforeLeaveEvent.ContinueNavigationAction action = event.postpone();\n\n // after you prevented the navigation, you are still able to proceed with the navigation, by using action.proceed();\n // it is good practice IMO to give the user the choice to navigate away anyway, if they wish so.\n ConfirmDialog dialog = new ConfirmDialog(\n \"Unsaved Changes\",\n \"You have unsaved changes. Are you sure you want to leave this anyway?\",\n \"Yes\", confirmEvent -> {\n // do the navigation anyway\n action.proceed();\n },\n \"No\", cancelEvent -> {\n // navigation was already prevented with event.postpone() so nothing has to be done here\n }\n );\n dialog.open();\n }\n }\n}\n\nsrc/main/java/com/nasc/application/views/subject/CreateSubjectCrud.java\n@Component\n@UIScope\n@Route(value = \"create-subject\", layout = MainLayout.class)\n@RolesAllowed(\"HOD\")\n@PageTitle(\"Create Subject\")\npublic class CreateSubjectCrud extends VerticalLayout {\n public static final String EDIT_COLUMN = \"vaadin-crud-edit-column\";\n private final SubjectService service;\n private final Crud crud;\n\n @Autowired\n public CreateSubjectCrud(SubjectService service) {\n this.service = service;\n crud = new Crud<>(SubjectEntity.class, createEditor());\n createGrid();\n setupDataProvider();\n HorizontalLayout horizontalLayout = new HorizontalLayout();\n Button exportButton = new Button(\n \"Export\",\n FontAwesome.Solid.FILE_EXPORT.create(),\n e -> {\n int size = crud.getGrid().getDataProvider().size(new Query<>());\n if (size > 0) {\n String fileName = \"Department Subjects\";\n GridExporter.newWithDefaults(crud.getGrid())\n //Removing Edit Column For Export\n .withColumnFilter(stateEntityColumn -> !stateEntityColumn.getKey().equals(EDIT_COLUMN))\n .withFileName(fileName)\n .withColumnConfigurationBuilder(new ColumnConfigurationBuilder())\n .open();\n }\n }\n );\n exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);\n horizontalLayout.add(exportButton);\n horizontalLayout.setWidthFull();\n horizontalLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.END);\n horizontalLayout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n Button newItemBtn = new Button(\"Create New Subject\", LumoIcon.PLUS.create());\n newItemBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n crud.setNewButton(newItemBtn);\n\n setAlignItems(Alignment.STRETCH);\n expand(crud);\n setSizeFull();\n\n add(horizontalLayout, crud);\n }\n\n private CrudEditor createEditor() {\n MajorOfPaper[] majorOfPaperEnum = MajorOfPaper.values();\n PaperType[] paperTypeEnum = PaperType.values();\n Semester[] semesterEnum = Semester.values();\n\n TextField subjectNameField = new TextField(\"Subject Name\");\n TextField subjectShortNameField = new TextField(\"Subject Short Name\");\n TextField subjectCodeField = new TextField(\"Subject Code\");\n\n ComboBox typeOfPaperComboBox = new ComboBox<>(\"Type of Paper\");\n typeOfPaperComboBox.setItems(paperTypeEnum);\n typeOfPaperComboBox.setItemLabelGenerator(PaperType::getDisplayName);\n\n ComboBox majorOfPaperComboBox = new ComboBox<>(\"Major of Paper\");\n majorOfPaperComboBox.setItems(majorOfPaperEnum);\n majorOfPaperComboBox.setItemLabelGenerator(MajorOfPaper::getDisplayName);\n\n ComboBox semesterComboBox = new ComboBox<>(\"Semester\");\n semesterComboBox.setItems(semesterEnum);\n semesterComboBox.setItemLabelGenerator(Semester::getDisplayName);\n\n FormLayout form = new FormLayout(subjectNameField, subjectShortNameField, subjectCodeField,\n typeOfPaperComboBox, majorOfPaperComboBox, semesterComboBox);\n form.setMaxWidth(\"480px\");\n form.setResponsiveSteps(new FormLayout.ResponsiveStep(\"0\", 1),\n new FormLayout.ResponsiveStep(\"30em\", 2));\n\n Binder binder = new Binder<>(SubjectEntity.class);\n binder.forField(subjectNameField).asRequired().bind(SubjectEntity::getSubjectName, SubjectEntity::setSubjectName);\n binder.forField(subjectCodeField).bind(SubjectEntity::getSubjectCode, SubjectEntity::setSubjectCode);\n binder.forField(subjectShortNameField).asRequired().bind(SubjectEntity::getSubjectShortForm, SubjectEntity::setSubjectShortForm);\n binder.forField(typeOfPaperComboBox).bind(SubjectEntity::getPaperType, SubjectEntity::setPaperType);\n binder.forField(majorOfPaperComboBox).bind(SubjectEntity::getMajorOfPaper, SubjectEntity::setMajorOfPaper);\n binder.forField(semesterComboBox).bind(SubjectEntity::getSemester, SubjectEntity::setSemester);\n\n // Add bindings for other fields as needed\n return new BinderCrudEditor<>(binder, form);\n }\n\n private void createGrid() {\n Grid grid = crud.getGrid();\n\n grid.removeColumnByKey(\"id\");\n grid.removeColumnByKey(\"department\");\n\n String[] columns = {\"subjectName\", \"subjectShortForm\", \"subjectCode\", \"paperType\", \"majorOfPaper\", \"semester\", EDIT_COLUMN};\n List> list = Arrays.stream(columns).map(grid::getColumnByKey).toList();\n grid.setColumnOrder(list);\n\n grid.getColumnByKey(EDIT_COLUMN).setHeader(\"Edit\");\n grid.getColumnByKey(EDIT_COLUMN).setWidth(\"100px\");\n grid.getColumnByKey(EDIT_COLUMN).setResizable(false);\n\n grid.getColumnByKey(\"paperType\").setRenderer(new TextRenderer<>(item -> item.getPaperType().getDisplayName()));\n grid.getColumnByKey(\"majorOfPaper\").setRenderer(new TextRenderer<>(item -> item.getMajorOfPaper().getDisplayName()));\n grid.getColumnByKey(\"semester\").setRenderer(new TextRenderer<>(item -> item.getSemester().getDisplayName()));\n }\n\n private void setupDataProvider() {\n GenericDataProvider genericDataProvider =\n new GenericDataProvider<>(SubjectEntity.class, service);\n crud.setDataProvider(genericDataProvider);\n crud.addDeleteListener(deleteEvent -> {\n genericDataProvider.delete(deleteEvent.getItem());\n NotificationUtils.showSuccessNotification(\"Subject deleted successfully\");\n });\n crud.addSaveListener(saveEvent -> {\n genericDataProvider.persist(saveEvent.getItem());\n NotificationUtils.showSuccessNotification(\"Subject saved successfully\");\n });\n }\n}\n\nsrc/main/java/com/nasc/application/security/AuthenticatedUser.java\n@Component\npublic class AuthenticatedUser {\n\n private final UserRepository userRepository;\n private final AuthenticationContext authenticationContext;\n\n private final SessionRegistry sessionRegistry;\n\n public AuthenticatedUser(AuthenticationContext authenticationContext, UserRepository userRepository, SessionRegistry sessionRegistry) {\n this.userRepository = userRepository;\n this.authenticationContext = authenticationContext;\n this.sessionRegistry = sessionRegistry;\n }\n\n @Transactional\n public Optional get() {\n return authenticationContext.getAuthenticatedUser(UserDetails.class)\n .map(userDetails -> userRepository.findByUsername(userDetails.getUsername()));\n }\n\n @Transactional\n public void logout() {\n // Get the current authentication\n UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n\n // Manually expire the session in the SessionRegistry\n expireUserSessions(userDetails);\n\n // Perform the Vaadin logout\n authenticationContext.logout();\n }\n\n private void expireUserSessions(UserDetails userDetails) {\n // Obtain the list of sessions for the user\n List userSessions = sessionRegistry.getAllSessions(userDetails, false);\n\n // Expire all sessions for the user\n userSessions.forEach(SessionInformation::expireNow);\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/valuevalut/ValueVaultView.java\n@PageTitle(\"Value Vault\")\n@Route(value = \"value-vault\", layout = MainLayout.class)\n@RolesAllowed(\"EDITOR\")\n@UIScope\n@Component\npublic class ValueVaultView extends Div {\n\n public ValueVaultView(\n CreateStateCrud createStateCrud,\n CreateDistrictCrud createDistrictCrud,\n CreateCountryCrud createCountryCrud,\n CreateBloodGroupCrud createBloodGroupCrud,\n CreateDepartmentCrud createDepartmentCrud,\n CreateAcademicYearCrud createAcademicYearCrud\n ) {\n TabSheet tabSheet = new TabSheet();\n tabSheet.add(\"State\", createStateCrud);\n tabSheet.add(\"District\", createDistrictCrud);\n tabSheet.add(\"Country\", createCountryCrud);\n tabSheet.add(\"Blood Group\", createBloodGroupCrud);\n tabSheet.add(\"Department\", createDepartmentCrud);\n tabSheet.add(\"Academic Year\", createAcademicYearCrud);\n tabSheet.setSizeFull();\n setSizeFull();\n add(tabSheet);\n }\n}\n\nsrc/main/java/com/nasc/application/views/student/status/StudentsStatusView.java\n@PageTitle(\"Students Status\")\n@Route(value = \"students-status\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\", \"PROFESSOR\"})\npublic class StudentsStatusView extends VerticalLayout {\n private final UserService userService;\n private final AcademicYearService academicYearService;\n private final DepartmentService departmentService;\n private final Button menuButton = new Button(\"Show/Hide Columns\", FontAwesome.Solid.LIST_CHECK.create());\n private final Anchor downloadLink;\n private final ColumnToggleContextMenu columnToggleContextMenu = new ColumnToggleContextMenu(menuButton);\n private Grid grid;\n private GridListDataView gridListDataView;\n private Grid.Column userColumn;\n private Grid.Column RegisterNumberColumn;\n private final Button searchButton;\n private ComboBox academicYearFilter;\n private ComboBox departmentFilter;\n private ComboBox studentSectionFilter;\n //Layouts\n private HorizontalLayout filterLayout;\n private HorizontalLayout exportAndColumnListLayout;\n\n public StudentsStatusView(UserService userService,\n AcademicYearService academicYearService,\n DepartmentService departmentService\n ) {\n this.userService = userService;\n this.departmentService = departmentService;\n this.academicYearService = academicYearService;\n addClassName(\"students-status-view\");\n setSizeFull();\n createDepartmentFilterComponent();\n createAcademicYearFilterComponent();\n createStudentSectionComboBox();\n createExportAndColumnListLayout();\n downloadLink = createDownloadLink();\n\n menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL);\n\n exportAndColumnListLayout.add(menuButton, downloadLink);\n createGrid();\n createFilterLayout();\n\n searchButton = new Button(\"Search\");\n searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL);\n searchButton.addClickListener(buttonClickEvent -> handleAcademicYearFilterChange());\n\n FlexLayout searchButtonLayout = new FlexLayout(searchButton);\n searchButtonLayout.setJustifyContentMode(JustifyContentMode.END);\n filterLayout.setWidthFull();\n filterLayout.expand(searchButtonLayout);\n filterLayout.add(departmentFilter, academicYearFilter, studentSectionFilter, searchButtonLayout);\n\n add(filterLayout, exportAndColumnListLayout, grid);\n }\n\n private void createFilterLayout() {\n filterLayout = new HorizontalLayout();\n filterLayout.setSpacing(true);\n filterLayout.setAlignItems(Alignment.BASELINE);\n }\n\n private static FontAwesome.Regular.Icon getThumbsUpIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_UP.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private static FontAwesome.Regular.Icon getThumbsDownIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_DOWN.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private void createExportAndColumnListLayout() {\n exportAndColumnListLayout = new HorizontalLayout();\n exportAndColumnListLayout.setWidthFull();\n exportAndColumnListLayout.setJustifyContentMode(JustifyContentMode.END);\n exportAndColumnListLayout.setAlignItems(Alignment.CENTER);\n exportAndColumnListLayout.setSpacing(true);\n }\n\n private Anchor createDownloadLink() {\n Anchor link = new Anchor();\n link.getElement().setAttribute(\"download\", true);\n Button exportButton = new Button(\"Export to CSV\", FontAwesome.Solid.FILE_EXPORT.create());\n exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL, ButtonVariant.LUMO_TERTIARY_INLINE);\n link.add(exportButton);\n return link;\n }\n\n private void createDepartmentFilterComponent() {\n List allDepartment = departmentService.findAll();\n departmentFilter = new ComboBox<>();\n departmentFilter.setLabel(\"Filter by Department\");\n departmentFilter.setItems(allDepartment);\n departmentFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n departmentFilter.setItemLabelGenerator(departmentEntity -> departmentEntity.getName() + \" \" + departmentEntity.getShortName());\n\n }\n\n private void createAcademicYearFilterComponent() {\n List academicYears = academicYearService.findAll();\n academicYearFilter = new ComboBox<>();\n academicYearFilter.setLabel(\"Filter by Academic Year\");\n academicYearFilter.setItems(academicYears);\n academicYearFilter.setItemLabelGenerator(this::generateAcademicYearLabel);\n academicYearFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n }\n\n private void createStudentSectionComboBox() {\n StudentSection[] values = StudentSection.values();\n studentSectionFilter = new ComboBox<>(\"Filter By Student Section\");\n studentSectionFilter.setItems(values);\n studentSectionFilter.setItemLabelGenerator(StudentSection::getDisplayName);\n studentSectionFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n }\n\n private void createGrid() {\n createGridComponent();\n addColumnsToGrid();\n addFiltersToGrid();\n }\n\n private String generateAcademicYearLabel(AcademicYearEntity academicYear) {\n return academicYear.getStartYear() + \" - \" + academicYear.getEndYear();\n }\n\n private void handleAcademicYearFilterChange() {\n refreshGridData();\n }\n\n private static Component createFilterFilter(Consumer filterChangeConsumer) {\n TextField textField = new TextField();\n textField.setValueChangeMode(ValueChangeMode.EAGER);\n textField.setClearButtonVisible(true);\n textField.addThemeVariants(TextFieldVariant.LUMO_SMALL);\n textField.setWidthFull();\n // CASE IN SENSITIVE\n textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase()));\n return textField;\n }\n\n private void addFiltersToGrid() {\n HeaderRow filterRow = grid.appendHeaderRow();\n\n // Username filter\n filterRow.getCell(userColumn)\n .setComponent(createFilterFilter(name -> gridListDataView.setFilter(user -> user\n .getUsername()\n .toLowerCase()\n .contains(name))));\n\n filterRow.getCell(RegisterNumberColumn)\n .setComponent(createFilterFilter(name -> gridListDataView.setFilter(user -> user\n .getRegisterNumber()\n .toLowerCase()\n .contains(name))));\n\n // Status filters\n addStatusFilter(\"Personal Details\", \"personalDetailsCompleted\", filterRow);\n addStatusFilter(\"Address Details\", \"addressDetailsCompleted\", filterRow);\n addStatusFilter(\"Bank Details\", \"bankDetailsCompleted\", filterRow);\n\n ComboBox allFormsFilter = createAllFormsFilter();\n allFormsFilter.addValueChangeListener(this::handleAllFormsFilterChange);\n filterRow.getCell(grid.getColumnByKey(\"allFormsCompleted\")).setComponent(allFormsFilter);\n }\n\n private void addStatusFilter(String columnName, String propertyKey, HeaderRow filterRow) {\n ComboBox statusFilter = createStatusFilter();\n statusFilter.addValueChangeListener(event -> handleStatusFilterChange(event, columnName));\n filterRow.getCell(grid.getColumnByKey(propertyKey)).setComponent(statusFilter);\n }\n\n private ComboBox createStatusFilter() {\n ComboBox statusFilter = new ComboBox<>();\n statusFilter.setItems(Arrays.asList(\"Pending\", \"Success\"));\n statusFilter.setPlaceholder(\"Filter\");\n statusFilter.setClearButtonVisible(true);\n statusFilter.setWidth(\"100%\");\n statusFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n return statusFilter;\n }\n\n private void handleStatusFilterChange(HasValue.ValueChangeEvent event, String columnName) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); //Every Time Drop Down Change, It removes filters from grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areStatusesEqual(user, columnName, filterValue));\n }\n }\n\n private boolean areStatusesEqual(User user, String columnName, String filterValue) {\n switch (columnName) {\n case \"Personal Details\" -> {\n return Boolean.TRUE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Address Details\" -> {\n return Boolean.TRUE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Bank Details\" -> {\n return Boolean.TRUE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n default -> {\n return true;\n }\n }\n }\n\n private ComboBox createAllFormsFilter() {\n ComboBox allFormsFilter = new ComboBox<>();\n allFormsFilter.setItems(Arrays.asList(\"Complete\", \"Incomplete\"));\n allFormsFilter.setPlaceholder(\"Filter\");\n allFormsFilter.setClearButtonVisible(true);\n allFormsFilter.setWidth(\"100%\");\n allFormsFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n return allFormsFilter;\n }\n\n private void handleAllFormsFilterChange(HasValue.ValueChangeEvent event) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); // Every Time Drop Down Change, It removes filters from the grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areAllFormsComplete(user, filterValue));\n }\n }\n\n private boolean areAllFormsComplete(User user, String filterValue) {\n boolean allFormsComplete = user.isFormsCompleted();\n return (allFormsComplete && \"Complete\".equalsIgnoreCase(filterValue)) ||\n (!allFormsComplete && \"Incomplete\".equalsIgnoreCase(filterValue));\n }\n\n private void createGridComponent() {\n grid = new Grid<>();\n grid.setHeight(\"100%\");\n grid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_COLUMN_BORDERS);\n }\n\n private void refreshGridData() {\n AcademicYearEntity academicYearEntity = academicYearFilter.getValue();\n StudentSection studentSection = studentSectionFilter.getValue();\n DepartmentEntity department = departmentFilter.getValue();\n\n if (academicYearEntity != null && studentSection != null && department != null) {\n List users = getStudentsByRoleForLoggedInUserDepartment(department, academicYearEntity, studentSection);\n if (users.isEmpty()) {\n if (users.isEmpty()) {\n NotificationUtils.showWarningNotification(\"No information recorded for the selected academic year\");\n }\n }\n gridListDataView = grid.setItems(users);\n exportToCSV(users);\n }\n }\n\n private void addColumnsToGrid() {\n createUsernameColumn();\n createRegisterNumberColumn();\n createPersonalDetailsColumn();\n createAddressDetailsColumn();\n createBankDetailsColumn();\n createAllFormsCompletedColumn();\n }\n\n private void createUsernameColumn() {\n userColumn = grid.addColumn(User::getUsername)\n .setHeader(\"Username\")\n .setKey(\"username\")\n .setFrozen(true)\n .setComparator((User::getUsername));\n }\n\n private void createRegisterNumberColumn() {\n RegisterNumberColumn = grid.addColumn(User::getRegisterNumber)\n .setHeader(\"Register Number\")\n .setKey(\"Register Number\")\n .setFrozen(true)\n .setComparator((User::getRegisterNumber));\n }\n\n private void createPersonalDetailsColumn() {\n Grid.Column personalDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getPersonalDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getPersonalDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getPersonalDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n }))\n .setHeader(\"Personal Details\")\n .setKey(\"personalDetailsCompleted\")\n .setComparator(User::getUsername);\n\n columnToggleContextMenu.addColumnToggleItem(\"Personal Details Completed\", personalDetailsColumn);\n }\n\n private void createAddressDetailsColumn() {\n Grid.Column addressDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getAddressDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getAddressDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getAddressDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n }))\n .setHeader(\"Address Details\")\n .setKey(\"addressDetailsCompleted\")\n .setComparator(User::getUsername);\n\n\n columnToggleContextMenu.addColumnToggleItem(\"Address Details Completed\", addressDetailsColumn);\n }\n\n private void createBankDetailsColumn() {\n Grid.Column bankDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getBankDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getBankDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getBankDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n }))\n .setHeader(\"Bank Details\")\n .setKey(\"bankDetailsCompleted\")\n .setComparator(User::getUsername);\n\n columnToggleContextMenu.addColumnToggleItem(\"Bank Details\", bankDetailsColumn);\n }\n\n private void createAllFormsCompletedColumn() {\n Grid.Column allFormsCompletedColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n boolean allFormsCompleted = user.isFormsCompleted();\n Span span = new Span(allFormsCompleted ? getThumbsUpIcon() : getThumbsDownIcon(),\n new Span(allFormsCompleted ? \"Complete\" : \"Incomplete\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (allFormsCompleted ? \"success\" : \"error\"));\n return span;\n }))\n .setHeader(\"All Forms Completed\")\n .setKey(\"allFormsCompleted\")\n .setComparator(User::getUsername);\n\n columnToggleContextMenu.addColumnToggleItem(\"All Forms Completed\", allFormsCompletedColumn);\n }\n\n private List getStudentsByRoleForLoggedInUserDepartment(DepartmentEntity department,\n AcademicYearEntity academicYear,\n StudentSection studentSection\n ) {\n return userService.findStudentsByDepartmentAndRoleAndAcademicYearAndSection(\n department,\n Role.STUDENT,\n academicYear,\n studentSection\n );\n }\n\n private Icon createIcon(VaadinIcon vaadinIcon) {\n Icon icon = vaadinIcon.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private void exportToCSV(List users) {\n\n try {\n AcademicYearEntity academicYearEntity = academicYearFilter.getValue();\n // Prepare data for export\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n\n try (CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8))) {\n\n // Write header\n String[] header = {\n \"Username\", \"Register Number\", \"Email\", \"Department\", \"Academic Year\",\n \"Bank Name\", \"Account Holder Name\", \"Account Number\", \"IFSC Code\", \"Branch Name\",\n \"Branch Address\", \"PAN Number\", \"First Name\", \"Last Name\", \"Phone Number\",\n \"Birthday\", \"Gender\", \"Address\", \"Pin code\", \"City\", \"State\", \"Country\"\n };\n csvWriter.writeNext(header);\n\n for (User user : users) {\n List data = new ArrayList<>();\n\n // Common information\n data.add(user.getUsername());\n data.add(user.getRegisterNumber());\n data.add(user.getEmail());\n data.add(user.getDepartment().toString());\n data.add(academicYearEntity.getStartYear() + \" - \" + academicYearEntity.getEndYear());\n\n // Bank details (conditionally added)\n if (Boolean.TRUE.equals(user.getBankDetailsCompleted())) {\n data.add(user.getBankDetails().getBankName());\n data.add(user.getBankDetails().getAccountHolderName());\n data.add(user.getBankDetails().getAccountNumber());\n data.add(user.getBankDetails().getIfscCode());\n data.add(user.getBankDetails().getBranchName());\n data.add(user.getBankDetails().getBranchAddress());\n data.add(user.getBankDetails().getPanNumber());\n } else {\n // Add empty values or placeholders for bank details if not completed\n data.addAll(Collections.nCopies(7, \"\"));\n }\n\n // Personal details\n if (Boolean.TRUE.equals(user.getPersonalDetailsCompleted())) {\n data.add(user.getPersonalDetails().getFirstName());\n data.add(user.getPersonalDetails().getLastName());\n data.add(user.getPersonalDetails().getPhoneNumber());\n data.add(user.getPersonalDetails().getBirthday().toString());\n data.add(user.getPersonalDetails().getGender());\n } else {\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Address details (conditionally added)\n if (Boolean.TRUE.equals(user.getAddressDetailsCompleted())) {\n data.add(user.getAddressDetails().getAddress());\n data.add(user.getAddressDetails().getPinCode());\n data.add(user.getAddressDetails().getCity());\n data.add(user.getAddressDetails().getState());\n data.add(user.getAddressDetails().getCountry());\n } else {\n // Add empty values or placeholders for address details if not completed\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Convert the list to an array and write to CSV`\n csvWriter.writeNext(data.toArray(new String[0]));\n }\n\n String fileName = \"STUDENTS_\"\n + academicYearFilter.getValue().getStartYear()\n + \"_\"\n + academicYearFilter.getValue().getEndYear()\n + \".csv\";\n\n StreamResource resource = new StreamResource(fileName,\n () -> new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));\n\n downloadLink.setHref(resource);\n\n }\n } catch (IOException e) {\n NotificationUtils.showErrorNotification(\"Error exporting data to CSV\");\n }\n }\n\n private static class ColumnToggleContextMenu extends ContextMenu {\n public ColumnToggleContextMenu(Component target) {\n super(target);\n setOpenOnClick(true);\n }\n\n void addColumnToggleItem(String label, Grid.Column column) {\n MenuItem menuItem = this.addItem(label, e -> column.setVisible(e.getSource().isChecked()));\n menuItem.setCheckable(true);\n menuItem.setChecked(column.isVisible());\n menuItem.setKeepOpen(true);\n }\n }\n}\n\nsrc/main/java/com/nasc/application/views/student/StudentMasterDetailsView.java\n@PageTitle(\"Student Master Details\")\n@Route(value = \"student-master-details/:samplePersonID?/:action?(edit)\", layout = MainLayout.class)\n@RolesAllowed(\"ADMIN\")\n@Uses(Icon.class)\npublic class StudentMasterDetailsView extends Div implements BeforeEnterObserver {\n\n private final String SAMPLEPERSON_ID = \"samplePersonID\";\n private final String SAMPLEPERSON_EDIT_ROUTE_TEMPLATE = \"student-master-details/%s/edit\";\n private final Grid grid = new Grid<>(SamplePerson.class, false);\n private TextField firstName;\n private TextField lastName;\n private TextField email;\n private TextField phone;\n private DatePicker dateOfBirth;\n private TextField occupation;\n private TextField role;\n private Checkbox important;\n\n private final Button cancel = new Button(\"Cancel\");\n private final Button save = new Button(\"Save\");\n\n private final BeanValidationBinder binder;\n\n private SamplePerson samplePerson;\n\n private final SamplePersonService samplePersonService;\n\n public StudentMasterDetailsView(SamplePersonService samplePersonService) {\n this.samplePersonService = samplePersonService;\n addClassNames(\"student-master-details-view\");\n\n\n // Create UI\n SplitLayout splitLayout = new SplitLayout();\n\n createGridLayout(splitLayout);\n createEditorLayout(splitLayout);\n\n add(splitLayout);\n\n // Configure Grid\n grid.addColumn(\"firstName\").setAutoWidth(true);\n grid.addColumn(\"lastName\").setAutoWidth(true);\n grid.addColumn(\"email\").setAutoWidth(true);\n grid.addColumn(\"phone\").setAutoWidth(true);\n grid.addColumn(\"dateOfBirth\").setAutoWidth(true);\n grid.addColumn(\"occupation\").setAutoWidth(true);\n grid.addColumn(\"role\").setAutoWidth(true);\n LitRenderer importantRenderer = LitRenderer.of(\n \"\")\n .withProperty(\"icon\", important -> important.isImportant() ? \"check\" : \"minus\").withProperty(\"color\",\n important -> important.isImportant()\n ? \"var(--lumo-primary-text-color)\"\n : \"var(--lumo-disabled-text-color)\");\n\n grid.addColumn(importantRenderer).setHeader(\"Important\").setAutoWidth(true);\n\n grid.setItems(query -> samplePersonService.list(\n PageRequest.of(query.getPage(), query.getPageSize(), VaadinSpringDataHelpers.toSpringDataSort(query)))\n .stream());\n grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);\n\n // when a row is selected or deselected, populate form\n grid.asSingleSelect().addValueChangeListener(event -> {\n if (event.getValue() != null) {\n UI.getCurrent().navigate(String.format(SAMPLEPERSON_EDIT_ROUTE_TEMPLATE, event.getValue().getId()));\n } else {\n clearForm();\n UI.getCurrent().navigate(StudentMasterDetailsView.class);\n }\n });\n\n // Configure Form\n binder = new BeanValidationBinder<>(SamplePerson.class);\n\n // Bind fields. This is where you'd define e.g. validation rules\n\n binder.bindInstanceFields(this);\n\n cancel.addClickListener(e -> {\n clearForm();\n refreshGrid();\n });\n\n save.addClickListener(e -> {\n try {\n if (this.samplePerson == null) {\n this.samplePerson = new SamplePerson();\n }\n binder.writeBean(this.samplePerson);\n samplePersonService.update(this.samplePerson);\n clearForm();\n refreshGrid();\n NotificationUtils.showInfoNotification(\"Data updated\");\n UI.getCurrent().navigate(StudentMasterDetailsView.class);\n } catch (ObjectOptimisticLockingFailureException exception) {\n NotificationUtils.showErrorNotification(\"Error updating the data. Somebody else has updated the record while you were making changes.\");\n } catch (ValidationException validationException) {\n NotificationUtils.showErrorNotification(\"Failed to update the data. Check again that all values are valid\");\n }\n });\n }\n\n @Override\n public void beforeEnter(BeforeEnterEvent event) {\n Optional samplePersonId = event.getRouteParameters().get(SAMPLEPERSON_ID).map(Long::parseLong);\n if (samplePersonId.isPresent()) {\n Optional samplePersonFromBackend = samplePersonService.get(samplePersonId.get());\n if (samplePersonFromBackend.isPresent()) {\n populateForm(samplePersonFromBackend.get());\n } else {\n String message = String.format(\"The requested samplePerson was not found, ID = %s\", samplePersonId.get());\n NotificationUtils.showErrorNotification(message);\n // refresh grid\n refreshGrid();\n event.forwardTo(StudentMasterDetailsView.class);\n }\n }\n }\n\n private void createEditorLayout(SplitLayout splitLayout) {\n Div editorLayoutDiv = new Div();\n editorLayoutDiv.setClassName(\"editor-layout\");\n\n Div editorDiv = new Div();\n editorDiv.setClassName(\"editor\");\n editorLayoutDiv.add(editorDiv);\n\n FormLayout formLayout = new FormLayout();\n firstName = new TextField(\"First Name\");\n lastName = new TextField(\"Last Name\");\n email = new TextField(\"Email\");\n phone = new TextField(\"Phone\");\n dateOfBirth = new DatePicker(\"Date Of Birth\");\n occupation = new TextField(\"Occupation\");\n role = new TextField(\"Role\");\n important = new Checkbox(\"Important\");\n formLayout.add(firstName, lastName, email, phone, dateOfBirth, occupation, role, important);\n\n editorDiv.add(formLayout);\n createButtonLayout(editorLayoutDiv);\n\n splitLayout.addToSecondary(editorLayoutDiv);\n }\n\n private void createButtonLayout(Div editorLayoutDiv) {\n HorizontalLayout buttonLayout = new HorizontalLayout();\n buttonLayout.setClassName(\"button-layout\");\n cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);\n save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n buttonLayout.add(save, cancel);\n editorLayoutDiv.add(buttonLayout);\n }\n\n private void createGridLayout(SplitLayout splitLayout) {\n Div wrapper = new Div();\n wrapper.setClassName(\"grid-wrapper\");\n splitLayout.addToPrimary(wrapper);\n wrapper.add(grid);\n }\n\n private void refreshGrid() {\n grid.select(null);\n grid.getDataProvider().refreshAll();\n }\n\n private void clearForm() {\n populateForm(null);\n }\n\n private void populateForm(SamplePerson value) {\n this.samplePerson = value;\n binder.readBean(this.samplePerson);\n\n }\n}\n\nsrc/main/java/com/nasc/application/views/about/AboutView.java\n@PageTitle(\"About\")\n@Route(value = \"about\", layout = MainLayout.class)\n@AnonymousAllowed\npublic class AboutView extends VerticalLayout {\n\n public AboutView() {\n setSpacing(false);\n\n Image img = new Image(\"images/NASC_LOGO.jpg\", \"NASC LOGO\");\n img.setWidth(\"200px\");\n add(img);\n\n H2 header = new H2(\"\\\"Automate the Future\\\"\");\n header.addClassNames(Margin.Top.XLARGE, Margin.Bottom.MEDIUM);\n add(header);\n add(new Paragraph(\"NASC PORTAL WAS DESIGNED AND DEVELOPED BY DEPARTMENT OF COMPUTER SCIENCE\"));\n\n setSizeFull();\n setJustifyContentMode(JustifyContentMode.CENTER);\n setDefaultHorizontalComponentAlignment(Alignment.CENTER);\n getStyle().set(\"text-align\", \"center\");\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/password/PasswordChangeView.java\n@PageTitle(\"Change Password\")\n@Route(value = \"password-change\", layout = MainLayout.class)\n@PermitAll\npublic class PasswordChangeView extends VerticalLayout {\n\n private final TextField oldPassword;\n private final PasswordField newPassword;\n private final PasswordField confirmPassword;\n private final UserService userService;\n\n public PasswordChangeView(UserService userService) {\n oldPassword = new TextField(\"Old Password\");\n newPassword = new PasswordField(\"New Password\");\n confirmPassword = new PasswordField(\"Confirm Password\");\n\n this.userService = userService;\n Button changeButton = new Button(\"Change Password\");\n changeButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n changeButton.addClickListener(event -> handleChangeButtonClick());\n\n FormLayout formLayout2Col = new FormLayout();\n formLayout2Col.add(oldPassword, newPassword, confirmPassword);\n HorizontalLayout layoutRow = new HorizontalLayout();\n layoutRow.add(changeButton);\n add(formLayout2Col, layoutRow);\n }\n\n private void handleChangeButtonClick() {\n try {\n String oldPasswordValue = oldPassword.getValue();\n String newPasswordValue = newPassword.getValue();\n String confirmPasswordValue = confirmPassword.getValue();\n userService.changePassword(oldPasswordValue, newPasswordValue, confirmPasswordValue);\n NotificationUtils.createSubmitSuccess(\"Password changed successfully\");\n } catch (Exception e) {\n String message = e.getMessage();\n NotificationUtils.showErrorNotification(message);\n }\n }\n}\n\nsrc/main/java/com/nasc/application/views/marks/entry/MarkEntryView.java\n@Route(value = \"subject-view\", layout = MainLayout.class)\n@PageTitle(\"Subject View\")\n@RolesAllowed({\"HOD\", \"ADMIN\", \"PROFESSOR\"})\npublic class MarkEntryView extends Div {\n\n private final VerticalLayout primaryLayout;\n private final VerticalLayout secondaryLayout;\n private final SplitLayout splitLayout;\n\n // service\n private final ExamService examService;\n private final DepartmentService departmentService;\n private final SubjectService subjectService;\n private final MarksService marksService;\n private final UserService userService;\n private final AcademicYearService academicYearService;\n\n private ComboBox departmentComboBox;\n private ComboBox semesterComboBox;\n private ComboBox subjectComboBox;\n private TextField subjectShortFormTextField;\n private TextField majorTextField;\n private TextField typeOfPaperTextField;\n private TextField subjectCodeTextField;\n private ComboBox academicYearComboBox;\n private ComboBox studentSectionComboBox;\n\n //Exam Fields\n private DatePicker examDateDatePicker;\n private ComboBox examTypeComboBox;\n // Global declaration for current user\n private final User currentUser;\n private NumberField minMarksNumberField;\n private NumberField portionCoveredNumberField;\n private IntegerField examDurationIntegerField;\n private DatePicker examCorrectionDatePicker;\n private MultiSelectComboBox userMultiSelectComboBox;\n private Button createExamButton;\n private Button markEnterButton;\n private NumberField maxMarksNumberField;\n\n //Layouts\n private FormLayout markFormLayout;\n private FormLayout examFormLayout;\n private FormLayout formLayout;\n\n //Exam ComboBoxes\n private ComboBox examComboBox;\n\n @Autowired\n public MarkEntryView(DepartmentService departmentService,\n SubjectService subjectService,\n MarksService marksService,\n UserService userService,\n ExamService examService,\n AuthenticatedUser authenticatedUser,\n AcademicYearService academicYearService\n ) {\n this.departmentService = departmentService;\n this.subjectService = subjectService;\n this.examService = examService;\n this.marksService = marksService;\n this.userService = userService;\n this.academicYearService = academicYearService;\n\n primaryLayout = new VerticalLayout();\n secondaryLayout = new VerticalLayout();\n\n primaryLayout.setMaxHeight(\"90vh\");\n secondaryLayout.setMaxHeight(\"90vh\");\n splitLayout = new SplitLayout(primaryLayout, secondaryLayout);\n\n currentUser = authenticatedUser.get().orElse(null); // If user not exists then it will be null\n\n initMarkForm();\n\n initExamComboBoxes();\n primaryLayout.add(new Divider());\n\n initExamForm();\n\n departmentComboBox.addValueChangeListener(event -> updateSubjectOptions());\n semesterComboBox.addValueChangeListener(event -> updateSubjectOptions());\n markEnterButton.addClickListener(event -> {\n // Fetch the selected exam\n ExamEntity selectedExam = examComboBox.getValue();\n\n // Update the student input fields based on the selected exam\n updateStudentFieldsForExam(selectedExam);\n });\n\n semesterComboBox.addValueChangeListener(event -> updateSubjectOptions());\n subjectComboBox.addValueChangeListener(event -> {\n\n // No need to call updateSubjectOptions again, as it is automatically called when department or semester changes\n DepartmentEntity selectedDepartment = departmentComboBox.getValue();\n Semester selectedSemester = semesterComboBox.getValue();\n\n // Fetch exams based on the selected subject, department, and semester\n updateExamOptions(selectedDepartment, selectedSemester);\n });\n }\n\n private void initMarkForm() {\n\n // Populate department and semester dropdowns\n List departments = departmentService.findAll();\n Semester[] semester = Semester.values();\n List academicYears = academicYearService.findAll();\n StudentSection[] values = StudentSection.values();\n\n //Creating forms\n markFormLayout = new FormLayout();\n\n departmentComboBox = new ComboBox<>(\"Select Department\", departments);\n semesterComboBox = new ComboBox<>(\"Select Semester\");\n semesterComboBox.setItems(semester);\n semesterComboBox.setItemLabelGenerator(Semester::getDisplayName);\n\n // Setup subject dropdown and subject code text-field\n subjectComboBox = new ComboBox<>(\"Select Subject\");\n\n academicYearComboBox = new ComboBox<>(\"Academic Year\");\n academicYearComboBox.setItems(academicYears);\n academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + \"-\" + item.getEndYear());\n\n studentSectionComboBox = new ComboBox<>(\"Select Student Section\");\n studentSectionComboBox.setItems(values);\n studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName);\n\n subjectComboBox.setPlaceholder(\"Select a subject\");\n\n subjectShortFormTextField = new TextField(\"Subject Short Form\");\n subjectShortFormTextField.setReadOnly(true);\n\n majorTextField = new TextField(\"Major\");\n majorTextField.setReadOnly(true);\n\n subjectCodeTextField = new TextField(\"Subject Code\");\n subjectCodeTextField.setReadOnly(true);\n\n typeOfPaperTextField = new TextField(\"Type Of Paper\");\n typeOfPaperTextField.setReadOnly(true);\n\n markEnterButton = new Button(\"Start Entering Mark\");\n markEnterButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n // Add a listener to handle subject selection\n subjectComboBox.addValueChangeListener(event -> handleSubjectSelection());\n\n markFormLayout.add(departmentComboBox,\n semesterComboBox,\n subjectComboBox,\n subjectShortFormTextField,\n majorTextField,\n typeOfPaperTextField,\n subjectCodeTextField,\n academicYearComboBox,\n studentSectionComboBox\n );\n\n primaryLayout.add(markFormLayout);\n\n add(splitLayout);\n }\n\n // HELPER\n private static Checkbox getCheckbox(NumberField studentMarkField) {\n Checkbox absentCheckbox = new Checkbox(\"Absent\");\n absentCheckbox.addValueChangeListener(event -> {\n if (event.getValue()) {\n // If absent, set text field to 0.0 and make it read-only\n studentMarkField.setValue(0.0);\n studentMarkField.setReadOnly(true);\n } else {\n // If not absent, clear the text field and make it editable\n studentMarkField.clear();\n studentMarkField.setReadOnly(false);\n }\n });\n return absentCheckbox;\n }\n\n private void createExam() {\n ExamEntity newExam = createNewExam(); // Implement this method to create a new exam\n examComboBox.setItems(examService.getAllExams()); // Refresh the examComboBox\n examComboBox.setValue(newExam); // Set the newly created exam as the selected exam\n handleExamSelection(); // Trigger the handleExamSelection logic\n }\n\n private void initExamForm() {\n\n //Creating exam form\n examFormLayout = new FormLayout();\n\n Set rolesToFilter = new HashSet<>();\n rolesToFilter.add(Role.PROFESSOR);\n rolesToFilter.add(Role.HOD);\n\n // Removed Current User\n List users = userService.findUsersByRoles(rolesToFilter);\n users.remove(currentUser);\n\n ExamType[] examTypeEnum = ExamType.values();\n\n examDateDatePicker = new DatePicker(\"Exam Date\");\n examTypeComboBox = new ComboBox<>(\"Exam Type\", examTypeEnum);\n examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName);\n\n minMarksNumberField = new NumberField(\"Minimum Marks\");\n minMarksNumberField.setStep(0.50);\n maxMarksNumberField = new NumberField(\"Maximum Marks\");\n maxMarksNumberField.setStep(0.50);\n\n portionCoveredNumberField = new NumberField(\"Portion Covered\");\n\n examDurationIntegerField = new IntegerField(\"Exam Duration (minutes)\");\n examCorrectionDatePicker = new DatePicker(\"Exam Correction Date\");\n\n createExamButton = new Button(\"Create Exam\", event -> createExam());\n createExamButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n userMultiSelectComboBox = new MultiSelectComboBox<>(\"Subject Staffs\");\n userMultiSelectComboBox.setItems(users);\n userMultiSelectComboBox.setPlaceholder(\"Select persons\");\n userMultiSelectComboBox.setAutoExpand(MultiSelectComboBox.AutoExpandMode.BOTH);\n userMultiSelectComboBox.setItemLabelGenerator(item -> item.getUsername() + \" [\" + item.getRegisterNumber() + \"]\");\n\n examFormLayout.add(\n examDateDatePicker,\n examTypeComboBox,\n minMarksNumberField,\n maxMarksNumberField,\n portionCoveredNumberField,\n examDurationIntegerField,\n examCorrectionDatePicker,\n userMultiSelectComboBox,\n createExamButton\n );\n\n primaryLayout.add(examFormLayout);\n }\n\n private void updateSubjectOptions() {\n DepartmentEntity selectedDepartment = departmentComboBox.getValue();\n Semester selectedSemester = semesterComboBox.getValue();\n\n if (selectedDepartment != null && selectedSemester != null) {\n // Fetch subjects based on the selected department and semester\n List subjects = subjectService.getSubjectsByDepartmentAndSemester(\n selectedDepartment,\n selectedSemester\n );\n\n // Update the subject dropdown options\n subjectComboBox.setItems(subjects);\n subjectComboBox.setItemLabelGenerator(\n subject -> subject.getSubjectName() + \" - \" + subject.getSubjectShortForm()\n );\n } else {\n\n // Clear subject dropdown if either department or semester is not selected\n subjectComboBox.setItems();\n }\n }\n\n private void handleSubjectSelection() {\n SubjectEntity selectedSubject = subjectComboBox.getValue();\n\n if (selectedSubject != null) {\n subjectShortFormTextField.setValue(selectedSubject.getSubjectShortForm());\n subjectCodeTextField.setValue(selectedSubject.getSubjectCode());\n\n // Added toSting because value ENUM\n majorTextField.setValue(selectedSubject.getMajorOfPaper().getDisplayName());\n typeOfPaperTextField.setValue(selectedSubject.getPaperType().getDisplayName());\n } else {\n subjectShortFormTextField.clear();\n majorTextField.clear();\n typeOfPaperTextField.clear();\n }\n }\n\n private ExamEntity createNewExam() {\n // Implement the logic to create a new exam\n ExamEntity exam = new ExamEntity();\n exam.setDepartment(departmentComboBox.getValue());\n exam.setSemester(semesterComboBox.getValue());\n exam.setExamType(examTypeComboBox.getValue());\n exam.setExamDate(examDateDatePicker.getValue());\n exam.setSubject(subjectComboBox.getValue());\n exam.setMinMarks(minMarksNumberField.getValue());\n exam.setMaxMarks(maxMarksNumberField.getValue());\n exam.setPortionCovered(portionCoveredNumberField.getValue());\n exam.setExamDuration(examDurationIntegerField.getValue());\n exam.setExamCorrectionDate(examCorrectionDatePicker.getValue());\n\n Set selectedProfessors = userMultiSelectComboBox.getSelectedItems();\n if (!selectedProfessors.isEmpty()) {\n // Add both the current user and selected professors to the responsibleUsers set\n Set responsibleUsers = new HashSet<>(selectedProfessors);\n responsibleUsers.add(currentUser);\n\n exam.setResponsibleUsers(responsibleUsers);\n } else {\n // If no professors are selected, only add the current user\n exam.setResponsibleUsers(Set.of(currentUser));\n }\n\n examService.saveExam(exam); // Save the new exam\n return exam;\n }\n\n private boolean createNewMarks(User student, SubjectEntity subject, ExamEntity exam, Double marksObtained, boolean isAbsent) {\n // Check if the obtained marks are valid\n if (!isAbsent) {\n if (isValidMark(marksObtained, exam)) {\n // Check if a mark already exists for the selected student, subject, and exam\n boolean markExists = marksService.existsByStudentAndSubjectAndExam(student, subject, exam);\n\n if (markExists) {\n // If a mark already exists, update the existing mark\n updateMarks(student, subject, marksObtained, isAbsent, exam);\n } else {\n // Create a new MarksEntity\n MarksEntity marksEntity = new MarksEntity();\n marksEntity.setStudent(student);\n marksEntity.setSubject(subject);\n marksEntity.setExam(exam);\n marksEntity.setMarksObtained(marksObtained);\n\n // Save the marks\n marksService.saveMarks(marksEntity);\n\n NotificationUtils.showSuccessNotification(\"Marks saved successfully\");\n }\n return true;\n } else {\n NotificationUtils.showErrorNotification(\"Please enter valid marks within the specified range\");\n }\n } else {\n // Check if a mark already exists for the selected student, subject, and exam\n boolean markExists = marksService.existsByStudentAndSubjectAndExam(student, subject, exam);\n\n if (!markExists) {\n // If no mark exists, create a new MarksEntity with absent status\n MarksEntity marksEntity = new MarksEntity();\n marksEntity.setStudent(student);\n marksEntity.setSubject(subject);\n marksEntity.setExam(exam);\n marksEntity.setAbsent(true);\n marksEntity.setMarksObtained(0.0);\n marksService.saveMarks(marksEntity);\n\n NotificationUtils.showSuccessNotification(\"Marks saved successfully\");\n return true;\n } else {\n NotificationUtils.showInfoNotification(\"Marks for the selected student, subject, and exam already exist.\");\n }\n }\n return false;\n }\n\n private boolean updateMarks(User student, SubjectEntity subject, Double marksObtained, boolean isAbsent, ExamEntity exam) {\n MarksEntity existingMarks = marksService.findMarkByStudentAndSubject(student, subject, exam).orElse(null);\n if (existingMarks != null) {\n existingMarks.setAbsent(isAbsent);\n if (!isAbsent) {\n if (isValidMark(marksObtained, existingMarks.getExam())) {\n // If marksObtained is not null and within the valid range, update the marks\n existingMarks.setMarksObtained(marksObtained);\n } else {\n // Display an error notification for invalid marks\n NotificationUtils.showErrorNotification(\"Invalid marks. Please enter valid marks within the specified range.\");\n return false;\n }\n } else {\n // If the user is marked as absent, set obtained marks to null\n existingMarks.setMarksObtained(0.00);\n }\n // Save the updated marks\n marksService.saveMarks(existingMarks);\n\n // Display a success notification\n NotificationUtils.showSuccessNotification(\"Marks updated successfully\");\n\n return true;\n } else {\n // If the mark does not exist, you may want to handle this case accordingly\n NotificationUtils.showErrorNotification(\"Marks do not exist for the selected student and subject.\");\n }\n return false;\n }\n\n private void handleExamSelection() {\n ExamEntity selectedExam = examComboBox.getValue();\n\n if (selectedExam != null) {\n // You can add logic here based on the selected exam\n String message = \"Selected exam: \" + selectedExam.getExamType();\n NotificationUtils.showInfoNotification(message);\n } else {\n // Handle the case where no exam is selected\n NotificationUtils.showErrorNotification(\"Please select an exam\");\n }\n }\n\n private void initExamComboBoxes() {\n formLayout = new FormLayout();\n examComboBox = new ComboBox<>(\"Select Exam\");\n examComboBox.setItemLabelGenerator(item ->\n \"DEPT: \" + item.getDepartment().getShortName()\n + \", SUB: \" + item.getSubject().getSubjectShortForm()\n + \", EXAM TYPE: \" + item.getExamType().getDisplayName()\n + \", EXAM DATE: \" + item.getExamDate().format(UIUtils.dateTimeFormatter)\n );\n\n // Add a listener to handle student and exam selection\n examComboBox.addValueChangeListener(event -> handleExamSelection());\n\n formLayout.add(examComboBox, markEnterButton);\n primaryLayout.add(formLayout);\n }\n\n private boolean saveMarksForStudent(User selectedStudent,\n NumberField marksObtainedTextField,\n Checkbox absentCheckbox) {\n SubjectEntity selectedSubject = subjectComboBox.getValue();\n ExamEntity selectedExam = examComboBox.getValue();\n Double marksObtained = marksObtainedTextField.getValue();\n boolean isAbsent = absentCheckbox.getValue();\n\n if (selectedStudent != null && selectedSubject != null && selectedExam != null) {\n try {\n if (marksService.existsByStudentAndSubjectAndExam(\n selectedStudent,\n selectedSubject,\n selectedExam\n )) {\n // The mark already exists, switch to update mode\n return updateMarks(selectedStudent, selectedSubject, marksObtained, isAbsent, selectedExam);\n } else {\n\n // Create a new MarksEntity\n return createNewMarks(selectedStudent, selectedSubject, selectedExam, marksObtained, isAbsent);\n }\n } catch (NumberFormatException e) {\n NotificationUtils.showErrorNotification(\"Please enter a valid number for Marks Obtained\");\n }\n } else {\n NotificationUtils.showErrorNotification(\"Please select a student, subject, and exam before saving marks\");\n }\n\n // Return false if there was an error or marks were not saved/updated\n return false;\n }\n\n private void updateExamOptions(DepartmentEntity department, Semester semester) {\n SubjectEntity selectedSubject = subjectComboBox.getValue();\n\n if (selectedSubject != null) {\n // Fetch exams based on the selected subject, department, and semester\n List exams = examService.getExamsByCriteria(\n currentUser,\n department,\n semester,\n selectedSubject\n );\n\n // Update the examComboBox options\n examComboBox.setItems(exams);\n } else {\n // Clear examComboBox if subject is not selected\n examComboBox.setItems();\n }\n }\n\n private boolean isValidMark(Double obtainedMark, ExamEntity exam) {\n if (obtainedMark == null || exam == null) {\n return false; // Invalid if obtainedMark or exam is null\n }\n\n Double maxMark = exam.getMaxMarks();\n if (maxMark == null) {\n return false; // Invalid if maxMark is null\n }\n\n // Check if obtainedMark is within the valid range\n return obtainedMark >= 0 && obtainedMark <= maxMark;\n }\n\n private void updateStudentFieldsForExam(ExamEntity exam) {\n // Clear the existing components in the secondary layout\n secondaryLayout.removeAll();\n\n // Fetch the students for the selected department, role, and academic year\n AcademicYearEntity academicYear = academicYearComboBox.getValue();\n StudentSection studentSection = studentSectionComboBox.getValue();\n\n List students = userService.findStudentsByDepartmentAndRoleAndAcademicYearAndSection(\n departmentComboBox.getValue(),\n Role.STUDENT,\n academicYear,\n studentSection\n );\n\n // Create a title for the secondary layout\n H3 examTittle = new H3(\"Exam: \" + exam.getExamType() + \" - \" + exam.getSemester());\n String subjectDetails = \"Subject: \" + exam.getSubject().getSubjectName()\n + \" - \" + exam.getSubject().getSubjectShortForm()\n + \" - \" + exam.getSubject().getSubjectCode()\n + \" - \" + exam.getSubject().getMajorOfPaper().getDisplayName()\n + \" - \" + exam.getSubject().getPaperType().getDisplayName();\n H4 subjectTittle = new H4(subjectDetails);\n secondaryLayout.add(examTittle, subjectTittle);\n\n // Update the student input fields based on the selected exam\n students.forEach(student -> {\n String username = student.getUsername();\n String registerNumber = student.getRegisterNumber();\n NumberField studentMarkField = new NumberField(username + \" [\" + registerNumber + \"]\");\n studentMarkField.setStep(0.05);\n studentMarkField.setPlaceholder(\"Enter marks\");\n\n Checkbox absentCheckbox = getCheckbox(studentMarkField);\n\n Button saveButton = new Button(\"Save\");\n saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n // Inside updateStudentFieldsForExam method\n saveButton.addClickListener(event -> {\n boolean marksSaved = saveMarksForStudent(student, studentMarkField, absentCheckbox);\n\n // Update the button text based on whether marks were saved or updated\n if (marksSaved) {\n saveButton.setText(\"Update\");\n } else {\n saveButton.setText(\"Save\");\n }\n });\n\n // Fetch existing marks for the selected exam and student\n MarksEntity existingMarksEntity = marksService.findMarkByStudentAndSubject(student, subjectComboBox.getValue(), exam)\n .orElse(null);\n\n if (existingMarksEntity != null) {\n // Set the initial value of the NumberField to existing marks\n studentMarkField.setValue(existingMarksEntity.getMarksObtained());\n saveButton.setText(\"Update\");\n }\n\n absentCheckbox.setValue(existingMarksEntity != null && existingMarksEntity.isAbsent());\n\n // Set text field to 0.0 and read-only if the student is absent\n if (absentCheckbox.getValue()) {\n studentMarkField.setValue(0.0);\n studentMarkField.setReadOnly(true);\n }\n\n // Create a \"Save\" button for each student\n FormLayout studentLayout = new FormLayout(studentMarkField, absentCheckbox, saveButton);\n\n secondaryLayout.add(studentLayout);\n });\n }\n}\n\nsrc/main/java/com/nasc/application/views/forms/bank/BankDetailsFormView.java\n@PageTitle(\"Bank Details Form\")\n@Route(value = \"bank-details-form\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\", \"PROFESSOR\", \"STUDENT\"})\npublic class BankDetailsFormView extends Div {\n private final TextField accountHolderName = new TextField(\"Account Holder Name\");\n private final TextField bankName = new TextField(\"Bank Name\");\n private final TextField accountNumber = new TextField(\"Account Number\");\n private final TextField ifscCode = new TextField(\"IFSC Code\");\n private final TextField branchName = new TextField(\"Branch Name\");\n private final TextField branchAddress = new TextField(\"Branch Address\");\n private final TextField panNumber = new TextField(\"Permanent Account Number\");\n private final Button saveButton = new Button(\"Save\");\n private final UserService userService;\n private final BeanValidationBinder binder = new BeanValidationBinder<>(BankDetails.class);\n\n @Autowired\n public BankDetailsFormView(UserService userService) {\n this.userService = userService;\n addClassName(\"bank-details-form-view\");\n add(createTitle(), createFormLayout(), createButtonLayout());\n\n binder.bindInstanceFields(this);\n\n saveButton.addClickListener(e -> {\n if (isBankDetailsAlreadySaved()) {\n updateBankDetails();\n } else {\n saveBankDetails();\n }\n });\n\n initFormWithExistingDetails();\n binder.addStatusChangeListener(e -> saveButton.setEnabled(binder.isValid()));\n\n }\n\n private Component createTitle() {\n return new H3(\"Bank Account Details\");\n }\n\n private Component createFormLayout() {\n return new FormLayout(\n accountHolderName, bankName, accountNumber,\n ifscCode, branchName, branchAddress, panNumber\n );\n }\n\n private Component createButtonLayout() {\n saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n HorizontalLayout buttonLayout = new HorizontalLayout(saveButton);\n buttonLayout.addClassName(\"button-layout\");\n return buttonLayout;\n }\n\n private void initFormWithExistingDetails() {\n User currentUser = userService.getCurrentUser();\n BankDetails existingBankDetails = currentUser.getBankDetails();\n\n if (existingBankDetails != null) {\n populateForm(existingBankDetails);\n saveButton.setText(\"Update\");\n }\n }\n\n private void populateForm(BankDetails bankDetails) {\n accountHolderName.setValue(bankDetails.getAccountHolderName());\n bankName.setValue(bankDetails.getBankName());\n accountNumber.setValue(bankDetails.getAccountNumber());\n ifscCode.setValue(bankDetails.getIfscCode());\n branchName.setValue(bankDetails.getBranchName());\n branchAddress.setValue(bankDetails.getBranchAddress());\n panNumber.setValue(bankDetails.getPanNumber());\n }\n\n private boolean isBankDetailsAlreadySaved() {\n return userService.getCurrentUser().getBankDetails() != null;\n }\n\n private void saveBankDetails() {\n User currentUser = userService.getCurrentUser();\n BankDetails newBankDetails = createBankDetailsFromForm();\n\n // Associate bank details with the current user\n newBankDetails.setUser(currentUser);\n\n // Set the new bank details to the current user\n currentUser.setBankDetails(newBankDetails);\n\n // Save the user with bank details\n userService.saveUserWithBankDetails(currentUser, newBankDetails);\n NotificationUtils.createSubmitSuccess(\"Bank details saved successfully\");\n }\n\n private void updateBankDetails() {\n User currentUser = userService.getCurrentUser();\n BankDetails existingBankDetails = currentUser.getBankDetails();\n\n // Print values before update\n System.out.println(\"Before Update: \" + existingBankDetails);\n\n // Update existing bank details\n existingBankDetails.setAccountHolderName(accountHolderName.getValue());\n existingBankDetails.setBankName(bankName.getValue());\n existingBankDetails.setAccountNumber(accountNumber.getValue());\n existingBankDetails.setIfscCode(ifscCode.getValue());\n existingBankDetails.setBranchName(branchName.getValue());\n existingBankDetails.setBranchAddress(branchAddress.getValue());\n existingBankDetails.setPanNumber(panNumber.getValue());\n\n // Save the user with updated bank details\n userService.saveUserWithBankDetails(currentUser, existingBankDetails);\n\n NotificationUtils.createSubmitSuccess(\"Bank details updated successfully\");\n }\n\n private BankDetails createBankDetailsFromForm() {\n BankDetails bankDetails = new BankDetails();\n bankDetails.setAccountHolderName(accountHolderName.getValue());\n bankDetails.setBankName(bankName.getValue());\n bankDetails.setAccountNumber(accountNumber.getValue());\n bankDetails.setIfscCode(ifscCode.getValue());\n bankDetails.setBranchName(branchName.getValue());\n bankDetails.setBranchAddress(branchAddress.getValue());\n bankDetails.setPanNumber(panNumber.getValue());\n return bankDetails;\n }\n}\n\nsrc/main/java/com/nasc/application/views/forms/adderss/AddressFormView.java\n@PageTitle(\"Address Form\")\n@Route(value = \"address-form\", layout = MainLayout.class)\n@RolesAllowed({\"STUDENT\", \"PROFESSOR\", \"HOD\"})\npublic class AddressFormView extends Composite {\n private final VerticalLayout layoutColumn2 = new VerticalLayout();\n private final FormLayout formLayout2Col = new FormLayout();\n private final HorizontalLayout layoutRow = new HorizontalLayout();\n private final TextArea address = new TextArea();\n private final TextField pinCode = new TextField();\n private final TextField city = new TextField();\n private final Select state = new Select<>();\n private final Select country = new Select<>();\n private final UserService userService;\n private final BeanValidationBinder binder = new BeanValidationBinder<>(AddressDetails.class);\n Button saveButtonPrimary = new Button();\n\n public AddressFormView(CountryService countryService, StateService stateService, UserService userService) {\n this.userService = userService;\n binder.bindInstanceFields(this);\n initLayout(countryService, stateService);\n initFormWithExistingDetails();\n }\n\n private void initLayout(CountryService countryService, StateService stateService) {\n\n List allCountries = countryService.getAllCountries();\n List allStates = stateService.getAllStates();\n\n H3 h3 = new H3(\"Address Form\");\n\n address.setLabel(\"Address\");\n address.setRequiredIndicatorVisible(true);\n\n pinCode.setLabel(\"Pin Code\");\n pinCode.setRequiredIndicatorVisible(true);\n\n city.setLabel(\"City\");\n city.setRequiredIndicatorVisible(true);\n\n // Set up styles and layout properties\n getContent().setWidthFull();\n getContent().getStyle().set(\"flex-grow\", \"1\");\n getContent().setJustifyContentMode(JustifyContentMode.START);\n getContent().setAlignItems(Alignment.CENTER);\n layoutColumn2.setWidthFull();\n layoutColumn2.setMaxWidth(\"800px\");\n layoutColumn2.setSpacing(true);\n\n // Set up components\n h3.getStyle().set(\"margin-bottom\", \"20px\");\n address.setWidth(\"100%\");\n formLayout2Col.setWidth(\"100%\");\n pinCode.setWidth(\"100%\");\n\n country.setLabel(\"Country\");\n country.setItems(allCountries);\n country.setPlaceholder(\"Select Country\");\n country.setRequiredIndicatorVisible(true);\n country.getStyle().setWidth(\"100%\");\n\n state.setLabel(\"State\");\n state.setPlaceholder(\"Select State\");\n state.setItems(allStates);\n state.setRequiredIndicatorVisible(true);\n state.getStyle().setWidth(\"100%\");\n\n layoutRow.setSpacing(true);\n\n // Customize button styles\n saveButtonPrimary.setText(\"Save\");\n saveButtonPrimary.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n binder.addStatusChangeListener(e -> saveButtonPrimary.setEnabled(binder.isValid()));\n\n saveButtonPrimary.addClickListener(\n event -> {\n try {\n binder.writeBean(createAddressDetailsFromForm());\n if (isAddressDetailsAlreadySaved()) {\n updateAddressDetails();\n } else {\n saveAddressDetails();\n }\n } catch (ValidationException e) {\n Notification.show(e.getMessage());\n }\n });\n\n // Build the layout hierarchy\n getContent().add(layoutColumn2);\n layoutColumn2.add(h3, address, formLayout2Col, layoutRow);\n formLayout2Col.add(pinCode, city, country, state);\n layoutRow.add(saveButtonPrimary);\n }\n\n private void initFormWithExistingDetails() {\n User currentUser = userService.getCurrentUser();\n AddressDetails existingAddressDetails = currentUser.getAddressDetails();\n\n if (existingAddressDetails != null) {\n populateForm(existingAddressDetails);\n saveButtonPrimary.setText(\"Update\");\n }\n }\n\n private void populateForm(AddressDetails existingAddress) {\n address.setValue(existingAddress.getAddress());\n pinCode.setValue(existingAddress.getPinCode());\n city.setValue(existingAddress.getCity());\n country.setValue(existingAddress.getCountry());\n state.setValue(existingAddress.getState());\n }\n\n private boolean isAddressDetailsAlreadySaved() {\n return userService.getCurrentUser().getBankDetails() != null;\n }\n\n private void updateAddressDetails() {\n User currentUser = userService.getCurrentUser();\n AddressDetails existingAddressDetails = currentUser.getAddressDetails();\n existingAddressDetails.setAddress(address.getValue());\n existingAddressDetails.setPinCode(pinCode.getValue());\n existingAddressDetails.setCity(city.getValue());\n existingAddressDetails.setState(state.getValue());\n existingAddressDetails.setCountry(country.getValue());\n userService.saveUserWithAddressDetails(currentUser, existingAddressDetails);\n NotificationUtils.createSubmitSuccess(\"Address details updated successfully\");\n }\n\n private void saveAddressDetails() {\n User currentUser = userService.getCurrentUser();\n AddressDetails addressDetailsFromForm = createAddressDetailsFromForm();\n addressDetailsFromForm.setUser(currentUser);\n currentUser.setAddressDetails(addressDetailsFromForm);\n userService.saveUserWithAddressDetails(currentUser, addressDetailsFromForm);\n NotificationUtils.createSubmitSuccess(\"Address details saved successfully\");\n }\n\n private AddressDetails createAddressDetailsFromForm() {\n AddressDetails addressDetails = new AddressDetails();\n addressDetails.setAddress(address.getValue());\n addressDetails.setPinCode(pinCode.getValue());\n addressDetails.setCity(city.getValue());\n addressDetails.setState(state.getValue());\n addressDetails.setCountry(country.getValue());\n return addressDetails;\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/marks/table/MarksView.java\n@Route(value = \"marks\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\", \"ADMIN\", \"PROFESSOR\"})\n@PageTitle(\"Marks\")\n@CssImport(\n themeFor = \"vaadin-grid\",\n value = \"./recipe/gridcell/grid-cell.css\"\n)\n@Slf4j\npublic class MarksView extends VerticalLayout {\n\n // Service\n private final MarksService marksService;\n private final DepartmentService departmentService;\n private final AcademicYearService academicYearService;\n private final Button menuButton = new Button(\"Show/Hide Columns\");\n private final SubjectService subjectService;\n private final UserService userService;\n // Grid\n private final GridPro marksGrid = new GridPro<>(StudentMarksDTO.class);\n private GridListDataView dataProvider;\n // Combobox\n private final ComboBox examTypeComboBox = new ComboBox<>(\"Select Exam Type\");\n private final ComboBox semesterComboBox = new ComboBox<>(\"Select Semester\");\n private final ComboBox departmentComboBox = new ComboBox<>(\"Select Department\");\n private final ComboBox academicYearComboBox = new ComboBox<>(\"Select Academic Year\");\n private final ComboBox studentSectionComboBox = new ComboBox<>(\"Select Student Section\");\n\n // UTILS\n private final ColumnToggleContextMenu contextMenu = new ColumnToggleContextMenu(menuButton);\n private final HeaderRow headerRow;\n private GridExporter gridExporter;\n\n public MarksView(MarksService marksService,\n DepartmentService departmentService,\n AcademicYearService academicYearService,\n SubjectService subjectService,\n UserService userService\n ) {\n this.marksService = marksService;\n this.departmentService = departmentService;\n this.academicYearService = academicYearService;\n this.subjectService = subjectService;\n this.userService = userService;\n\n configureComboBoxes();\n\n marksGrid.removeAllColumns();\n marksGrid.setSizeFull();\n marksGrid.setEditOnClick(true);\n marksGrid.setSingleCellEdit(true);\n marksGrid.setMultiSort(true);\n marksGrid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT, GridVariant.LUMO_COLUMN_BORDERS);\n marksGrid.addThemeVariants(GridProVariant.LUMO_ROW_STRIPES);\n // marksGrid.setAllRowsVisible(true); // TO AVOID SCROLLER DISPLAY ALL THE ROWS\n\n headerRow = marksGrid.appendHeaderRow();\n\n // Button\n Button searchButton = new Button(\"Search/Refresh\");\n searchButton.addClickListener(e -> updateGridData());\n searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL);\n\n menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL);\n HorizontalLayout filterLayout = new HorizontalLayout();\n filterLayout.setAlignItems(Alignment.BASELINE);\n filterLayout.add(\n departmentComboBox,\n academicYearComboBox,\n semesterComboBox,\n examTypeComboBox,\n studentSectionComboBox,\n searchButton\n );\n\n Button exportButton = new Button(\"Export\",\n FontAwesome.Solid.FILE_EXPORT.create(),\n e -> {\n ExamType selectedExamType = examTypeComboBox.getValue();\n Semester selectedSemester = semesterComboBox.getValue();\n DepartmentEntity selectedDepartment = departmentComboBox.getValue();\n AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue();\n StudentSection studentSection = studentSectionComboBox.getValue();\n\n // Check Grid and Filter Before Export\n int size = marksGrid.getDataProvider().size(new Query<>());\n if (!isFilterInValid() && size > 0) {\n String fileName = selectedDepartment.getShortName()\n + \"_\"\n + selectedAcademicYear.getStartYear() + \"-\" + selectedAcademicYear.getEndYear()\n + \"_\"\n + studentSection.getDisplayName()\n + \"_\"\n + selectedSemester.getDisplayName()\n + \"_\"\n + selectedExamType.getDisplayName() + \"_Marks\";\n\n XlsxFormat xlsxFormat = new XlsxFormat();\n PdfFormat pdfFormat = new PdfFormat();\n HtmlFormat htmlFormat = new HtmlFormat();\n\n gridExporter = GridExporter\n .newWithDefaults(marksGrid)\n .withFileName(fileName)\n // Ignoring chart column\n .withColumnFilter(studentMarksDTOColumn ->\n studentMarksDTOColumn.isVisible() &&\n !studentMarksDTOColumn.getKey().equals(\"Chart\"))\n .withAvailableFormats(xlsxFormat, pdfFormat, htmlFormat)\n .withPreSelectedFormat(xlsxFormat)\n .withColumnConfigurationBuilder(new ColumnConfigurationBuilder());\n\n gridExporter.open();\n }\n }\n );\n exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);\n HorizontalLayout horizontalLayout = new HorizontalLayout(menuButton, exportButton);\n horizontalLayout.setWidthFull();\n horizontalLayout.setJustifyContentMode(JustifyContentMode.END);\n horizontalLayout.setAlignItems(Alignment.CENTER);\n\n add(new H3(\"Marks View\"), filterLayout, horizontalLayout, marksGrid);\n\n setSizeFull();\n }\n\n private boolean isFilterInValid() {\n return examTypeComboBox.getValue() == null ||\n semesterComboBox.getValue() == null ||\n departmentComboBox.getValue() == null ||\n academicYearComboBox.getValue() == null ||\n studentSectionComboBox.getValue() == null;\n }\n\n private static Component createFilterHeader(Consumer filterChangeConsumer) {\n TextField textField = new TextField();\n textField.setValueChangeMode(ValueChangeMode.EAGER);\n textField.setClearButtonVisible(true);\n textField.addThemeVariants(TextFieldVariant.LUMO_SMALL);\n textField.setWidthFull();\n // CASE IN SENSITIVE\n textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase()));\n return textField;\n }\n\n private void configureComboBoxes() {\n List academicYears = academicYearService.findAll();\n List departments = departmentService.findAll();\n Semester[] semesters = Semester.values();\n ExamType[] examTypes = ExamType.values();\n StudentSection[] studentSections = StudentSection.values();\n\n semesterComboBox.setItems(semesters);\n semesterComboBox.setItemLabelGenerator(Semester::getDisplayName);\n semesterComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n semesterComboBox.setRequiredIndicatorVisible(true);\n\n examTypeComboBox.setItems(examTypes);\n examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName);\n examTypeComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n examTypeComboBox.setRequiredIndicatorVisible(true);\n\n academicYearComboBox.setItems(academicYears);\n academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + \" - \" + item.getEndYear());\n academicYearComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n academicYearComboBox.setRequiredIndicatorVisible(true);\n\n departmentComboBox.setItems(departments);\n departmentComboBox.setItemLabelGenerator(item -> item.getName() + \" - \" + item.getShortName());\n departmentComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n departmentComboBox.setRequiredIndicatorVisible(true);\n\n studentSectionComboBox.setItems(studentSections);\n studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName);\n studentSectionComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n studentSectionComboBox.setRequiredIndicatorVisible(true);\n }\n\n private void updateTotalPassFailCounts(List allStudentMarks, PassFailCounts counts) {\n counts.totalPass = 0;\n counts.totalFail = 0;\n counts.totalPresent = 0;\n counts.totalAbsent = 0;\n counts.subjectPassCounts.clear();\n counts.subjectFailCounts.clear();\n counts.subjectPresentCounts.clear();\n counts.subjectAbsentCounts.clear();\n\n for (StudentMarksDTO studentMarksDTO : allStudentMarks) {\n updateTotalPassFailCounts(studentMarksDTO, counts);\n }\n }\n\n private void updateTotalPassFailCounts(StudentMarksDTO studentMarksDTO, PassFailCounts counts) {\n for (Map.Entry entry : studentMarksDTO.getSubjectInfoMap().entrySet()) {\n SubjectEntity subject = entry.getKey();\n StudentSubjectInfo subjectInfo = entry.getValue();\n\n if (subjectInfo.getMarks() != null && subjectInfo.getPassMarks() != null) {\n boolean passed = subjectInfo.getMarks() >= subjectInfo.getPassMarks();\n if (passed) {\n counts.totalPass++;\n counts.subjectPassCounts.put(subject, counts.subjectPassCounts.getOrDefault(subject, 0) + 1);\n } else {\n counts.totalFail++;\n counts.subjectFailCounts.put(subject, counts.subjectFailCounts.getOrDefault(subject, 0) + 1);\n }\n }\n\n // PRE & ABS\n if (subjectInfo.getAbsent() != null) {\n if (subjectInfo.getAbsent()) {\n counts.totalAbsent++;\n counts.subjectAbsentCounts.put(subject, counts.subjectAbsentCounts.getOrDefault(subject, 0) + 1);\n } else {\n counts.totalPresent++;\n counts.subjectPresentCounts.put(subject, counts.subjectPresentCounts.getOrDefault(subject, 0) + 1);\n }\n }\n }\n }\n\n private void updateGridData() {\n\n // Clearing all the list that where in previous one!\n contextMenu.removeAll();\n\n ExamType selectedExamType = examTypeComboBox.getValue();\n Semester selectedSemester = semesterComboBox.getValue();\n DepartmentEntity selectedDepartment = departmentComboBox.getValue();\n AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue();\n StudentSection studentSection = studentSectionComboBox.getValue();\n\n if (isAllFiltersNotNull(\n selectedExamType,\n selectedSemester,\n selectedDepartment,\n selectedAcademicYear,\n studentSection\n )) {\n NotificationUtils.showErrorNotification(\"Please select values for all the filters!\");\n return;\n }\n\n // Set up grid data for all students\n List allStudents = userService.findStudentsByDepartmentAndRoleAndAcademicYearAndSection(\n selectedDepartment,\n Role.STUDENT,\n selectedAcademicYear,\n studentSection\n );\n\n // Check if there is no data\n if (allStudents == null || allStudents.isEmpty()) {\n NotificationUtils.showErrorNotification(\"No data available.\");\n return;\n }\n\n List allStudentMarks = new ArrayList<>();\n\n for (User student : allStudents) {\n // Fetch marks for each student\n List studentMarksList = marksService.getStudentMarksByFilters(\n selectedExamType,\n selectedSemester,\n student\n );\n\n // Add the marks to the list\n allStudentMarks.addAll(studentMarksList);\n }\n\n PassFailCounts passFailCounts = new PassFailCounts();\n updateTotalPassFailCounts(allStudentMarks, passFailCounts);\n\n // Set up columns dynamically based on subject names\n List subjects = subjectEntities(selectedDepartment, selectedSemester);\n\n marksGrid.removeAllColumns();\n\n String studentFooterString = \"TOTAL STUDENT: \" + allStudents.size();\n String studentFooterOuterHtml = String.format(\"%s\", studentFooterString);\n Grid.Column studentName = marksGrid.addColumn(studentMarksDTO -> studentMarksDTO.getStudent().getUsername())\n .setHeader(\"Student Name\")\n .setSortable(true)\n .setKey(\"Student Name\")\n .setAutoWidth(true)\n .setFrozen(true)\n .setFooter(new Html(studentFooterOuterHtml));\n\n headerRow.getCell(studentName).setComponent(createFilterHeader(name ->\n dataProvider.setFilter(studentMarksDTO -> studentMarksDTO.getStudent().getUsername().toLowerCase().contains(name)))); // CASE INSENSITIVE\n\n Grid.Column registerNumber = marksGrid.addColumn(studentMarksDTO -> studentMarksDTO.getStudent().getRegisterNumber())\n .setHeader(\"Register Number\")\n .setAutoWidth(true)\n .setSortable(true)\n .setFrozen(true)\n .setKey(\"Register Number\");\n\n headerRow.getCell(registerNumber).setComponent(createFilterHeader(regNumber ->\n dataProvider.setFilter(studentMarksDTO -> studentMarksDTO.getStudent().getRegisterNumber().toLowerCase().contains(regNumber)))); // CASE INSENSITIVE\n\n contextMenu.addColumnToggleItem(studentName);\n contextMenu.addColumnToggleItem(registerNumber);\n\n setupColumns(subjects);\n\n for (SubjectEntity subject : subjects) {\n Grid.Column columnByKey = marksGrid.getColumnByKey(UIUtils.toCapitalize(subject.getSubjectName()));\n if (columnByKey != null) {\n Integer pass = passFailCounts.subjectPassCounts.getOrDefault(subject, 0);\n Integer totalStudents = passFailCounts.subjectPresentCounts.getOrDefault(subject, 0);\n int average = totalStudents > 0 ? (pass * 100) / totalStudents : 0;\n int fail = totalStudents - pass;\n\n HorizontalLayout layout = new HorizontalLayout();\n layout.setAlignItems(Alignment.BASELINE);\n layout.setJustifyContentMode(JustifyContentMode.CENTER);\n layout.setMargin(false);\n layout.setPadding(false);\n\n FontAwesome.Solid.Icon icon = FontAwesome.Solid.CHART_PIE.create();\n Button chartButton = new Button(icon);\n\n // Adding chart\n chartButton.addClickListener(e -> openPieChartDialog(pass, fail, subject));\n chartButton.addThemeVariants(ButtonVariant.LUMO_SMALL);\n String labelText = String.format(\"P: %d F: %d AVG: %d%%\", pass, fail, average);\n String outerHtml = String.format(\"%s\", labelText);\n layout.add(new Html(outerHtml), chartButton);\n columnByKey.setFooter(layout);\n }\n\n Grid.Column attendanceStatus = marksGrid.getColumnByKey(UIUtils.toCapitalize(subject.getSubjectName() + \" Attendance\"));\n if (attendanceStatus != null) {\n Integer present = passFailCounts.subjectPresentCounts.getOrDefault(subject, 0);\n Integer absent = passFailCounts.subjectAbsentCounts.getOrDefault(subject, 0);\n int totalStudents = present + absent;\n int average = totalStudents > 0 ? (present * 100) / totalStudents : 0;\n String labelText = String.format(\"PRE: %d ABS: %d AVG: %d%%\", present, absent, average);\n String outerHtml = String.format(\"%s\", labelText);\n attendanceStatus.setFooter(new Html(outerHtml));\n }\n }\n\n // Calculate the total pass and fail counts for each student\n for (StudentMarksDTO studentMarksDTO : allStudentMarks) {\n int totalPass = 0;\n int totalFail = 0;\n int totalAbsent = 0;\n int totalPresent = 0;\n\n for (Map.Entry entry : studentMarksDTO.getSubjectInfoMap().entrySet()) {\n StudentSubjectInfo subjectInfo = entry.getValue();\n\n if (subjectInfo.getMarks() != null && subjectInfo.getPassMarks() != null) {\n boolean passed = subjectInfo.getMarks() >= subjectInfo.getPassMarks();\n if (passed) {\n totalPass++;\n } else {\n totalFail++;\n }\n }\n\n if (subjectInfo.getAbsent() != null) {\n if (subjectInfo.getAbsent()) {\n totalAbsent++;\n } else {\n totalPresent++;\n }\n }\n }\n\n // Set the total pass/fail counts for the student\n studentMarksDTO.setTotalPass(totalPass);\n studentMarksDTO.setTotalFail(totalFail);\n studentMarksDTO.setTotalAbsent(totalAbsent);\n studentMarksDTO.setTotalPresent(totalPresent);\n }\n\n Grid.Column totalPassFailColumn = marksGrid.addColumn(studentMarksDTO ->\n studentMarksDTO.getTotalPass() + \"/\" + studentMarksDTO.getTotalFail())\n .setHeader(\"PASS/FAIL\")\n .setSortable(true)\n .setTextAlign(ColumnTextAlign.CENTER)\n .setAutoWidth(true)\n .setKey(\"Pass/Fail\");\n\n Grid.Column totalPresentAbsentColumn = marksGrid.addColumn(studentMarksDTO ->\n studentMarksDTO.getTotalPresent() + \"/\" + studentMarksDTO.getTotalAbsent())\n .setHeader(\"PRE/ABS\")\n .setSortable(true)\n .setTextAlign(ColumnTextAlign.CENTER)\n .setAutoWidth(true)\n .setKey(\"Pre/Abs\");\n\n\n contextMenu.addColumnToggleItem(totalPassFailColumn);\n contextMenu.addColumnToggleItem(totalPresentAbsentColumn);\n\n // Chart Column\n Grid.Column chartButtonColumn = marksGrid.addComponentColumn(studentMarksDTO -> {\n FontAwesome.Solid.Icon icon = FontAwesome.Solid.CHART_COLUMN.create();\n Button chartButton = new Button(icon);\n chartButton.addClickListener(e -> openChartDialog(studentMarksDTO));\n chartButton.addThemeVariants(ButtonVariant.LUMO_SMALL);\n return chartButton;\n })\n .setHeader(\"Chart\")\n .setFlexGrow(0) // TO AVOID IT TAKES EXTRA SPACE\n .setFrozenToEnd(true)\n .setSortable(false)\n .setTextAlign(ColumnTextAlign.CENTER)\n .setKey(\"Chart\");\n\n contextMenu.addColumnToggleItem(chartButtonColumn);\n\n dataProvider = marksGrid.setItems(allStudentMarks);\n }\n\n private boolean isAllFiltersNotNull(ExamType selectedExamType,\n Semester selectedSemester,\n DepartmentEntity selectedDepartment,\n AcademicYearEntity selectedAcademicYear,\n StudentSection studentSection\n ) {\n\n if (selectedExamType == null) {\n examTypeComboBox.setErrorMessage(\"Exam Type is required\");\n examTypeComboBox.setInvalid(true);\n }\n if (selectedSemester == null) {\n semesterComboBox.setErrorMessage(\"Semester is required\");\n semesterComboBox.setInvalid(true);\n }\n if (selectedDepartment == null) {\n departmentComboBox.setErrorMessage(\"Department is required\");\n departmentComboBox.setInvalid(true);\n }\n if (selectedAcademicYear == null) {\n academicYearComboBox.setErrorMessage(\"Academic Year is required\");\n academicYearComboBox.setInvalid(true);\n }\n if (studentSection == null) {\n studentSectionComboBox.setErrorMessage(\"Student Section is required\");\n studentSectionComboBox.setInvalid(true);\n }\n return selectedExamType == null\n || selectedSemester == null\n || selectedDepartment == null\n || selectedAcademicYear == null\n || studentSection == null;\n }\n\n private Chart createPieBarChart(Integer pass, int fail, SubjectEntity subject) {\n\n Chart chart = new Chart(ChartType.PIE);\n Configuration conf = chart.getConfiguration();\n String title = subject.getDepartment().getName();\n String subTittle = subject.getSubjectName() + \" [\" + subject.getSubjectCode() + \"]\";\n conf.setTitle(title);\n conf.setSubTitle(subTittle);\n Tooltip tooltip = new Tooltip();\n tooltip.setValueDecimals(1);\n conf.setTooltip(tooltip);\n\n PlotOptionsPie plotOptions = new PlotOptionsPie();\n plotOptions.setAllowPointSelect(true);\n plotOptions.setCursor(Cursor.POINTER);\n plotOptions.setShowInLegend(true);\n conf.setPlotOptions(plotOptions);\n\n DataSeries series = new DataSeries();\n DataSeriesItem chrome = new DataSeriesItem(\"Pass\", pass);\n chrome.setSliced(true);\n chrome.setSelected(true);\n series.add(chrome);\n series.add(new DataSeriesItem(\"Fail\", fail));\n conf.setSeries(series);\n chart.setVisibilityTogglingDisabled(true);\n return chart;\n }\n\n private void setupColumns(List subjects) {\n for (SubjectEntity subject : subjects) {\n NumberField markField = new NumberField();\n markField.setStep(0.50);\n markField.setValue(0.0); // Default value for the fields\n markField.setWidthFull();\n\n String subjectCapitalize = UIUtils.toCapitalize(subject.getSubjectName());\n Grid.Column marksColumn = marksGrid.addEditColumn(studentMarksDTO ->\n {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap()\n .entrySet()\n .stream()\n .filter(entry -> entry.getKey().getSubjectName().equals(subject.getSubjectName()))\n .findFirst()\n .map(Map.Entry::getValue)\n .orElse(new StudentSubjectInfo());\n\n return subjectInfo.getMarks() != null ? subjectInfo.getMarks() : 0.0;\n\n })\n .custom(markField, (studentMarksDTO, newValue) -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap()\n .computeIfAbsent(subject, s -> new StudentSubjectInfo());\n\n // Validate the new mark against the maximum allowed mark\n if (subjectInfo.getMaxMarks() != null) /* To avoid NullPointerException on maxMark */ {\n if (newValue != null && newValue >= 0 && newValue <= subjectInfo.getMaxMarks()) {\n subjectInfo.setMarks(newValue);\n marksService.updateStudentMarks(studentMarksDTO);\n dataProvider.refreshItem(studentMarksDTO);\n } else {\n NotificationUtils.showErrorNotification(\"Invalid mark value\");\n }\n }\n })\n .setHeader(subjectCapitalize)\n .setFlexGrow(0)\n .setAutoWidth(true)\n .setSortable(true)\n .setClassNameGenerator(studentMarksDTO -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap()\n .entrySet()\n .stream()\n .filter(entry -> entry.getKey().getSubjectName().equals(subject.getSubjectName()))\n .findFirst()\n .map(Map.Entry::getValue)\n .orElse(new StudentSubjectInfo()); // Create a default if not found\n\n // Check for null values before comparing marks and pass marks\n Double marks = subjectInfo.getMarks();\n Double passMarks = subjectInfo.getPassMarks();\n Boolean absent = subjectInfo.getAbsent();\n\n // Add your logic to determine pass, fail, or absent based on marks, pass marks, and absent status\n if (absent != null && absent) {\n // Student is absent\n return \"absent-color\";\n } else if (marks != null && passMarks != null) {\n // Check for pass or fail based on marks and pass marks\n boolean passed = marks >= passMarks;\n // Return the appropriate CSS class based on pass/fail\n return passed ? \"pass-color\" : \"fail-color\";\n } else {\n return \"na-color\";\n }\n })\n .setTextAlign(ColumnTextAlign.CENTER)\n .setKey(subjectCapitalize);\n\n ComboBox passFailFilter = createPassFailFilter(passOrFail -> {\n // Remove any existing filters before applying new ones\n dataProvider.removeFilters();\n\n if (\"Pass\".equalsIgnoreCase(passOrFail)) {\n // Show only rows where the student passed for the selected subject\n dataProvider.addFilter(studentMarksDTO -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap().get(subject);\n return subjectInfo != null && subjectInfo.getMarks() != null && subjectInfo.getMarks() >= subjectInfo.getPassMarks();\n });\n } else if (\"Fail\".equalsIgnoreCase(passOrFail)) {\n // Show only rows where the student failed for the selected subject\n dataProvider.addFilter(studentMarksDTO -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap().get(subject);\n return subjectInfo != null && (subjectInfo.getMarks() == null || subjectInfo.getMarks() < subjectInfo.getPassMarks());\n });\n }\n });\n\n headerRow.getCell(marksColumn).setComponent(passFailFilter);\n\n String subjectShortForm = UIUtils.toCapitalize(subject.getSubjectShortForm());\n Grid.Column attendanceStatus = marksGrid.addColumn(new TextRenderer<>(\n studentMarksDTO -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap()\n .entrySet()\n .stream()\n .filter(entry -> entry.getKey().getSubjectName().equals(subject.getSubjectName()))\n .findFirst()\n .map(Map.Entry::getValue).orElse(null);\n\n // Create a span with a badge\n Boolean isAbsent = subjectInfo != null ? subjectInfo.getAbsent() : null;\n Text text = new Text(\"\");\n if (isAbsent != null) {\n text.setText(Boolean.TRUE.equals(isAbsent) ? \"Absent\" : \"Present\");\n } else {\n text.setText(\"N/A\");\n }\n return text.getText();\n })\n )\n .setClassNameGenerator(studentMarksDTO -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap()\n .entrySet()\n .stream()\n .filter(entry -> entry.getKey().getSubjectName().equals(subject.getSubjectName()))\n .findFirst()\n .map(Map.Entry::getValue).orElse(null);\n\n Boolean isAbsent = subjectInfo != null ? subjectInfo.getAbsent() : null;\n if (isAbsent != null)\n return isAbsent ? \"absent-color\" : \"present-color\"; // Attendance\n return \"na-color\";\n })\n .setHeader(subjectShortForm)\n .setSortable(true)\n .setFlexGrow(0)\n .setAutoWidth(true)\n .setTextAlign(ColumnTextAlign.CENTER)\n .setComparator((studentMarksDTO1, studentMarksDTO2) -> {\n boolean isAbsent1 = isAbsentForCurrentCell(studentMarksDTO1, subject);\n boolean isAbsent2 = isAbsentForCurrentCell(studentMarksDTO2, subject);\n return Boolean.compare(isAbsent1, isAbsent2); // Compare based on the \"Absent\" status\n })\n .setKey(subjectCapitalize + \" Attendance\");\n\n marksGrid.addCellEditStartedListener(event -> {\n StudentMarksDTO studentMarksDTO = event.getItem();\n\n // Check if the subject has marks information for the current student\n boolean hasMarks = studentMarksDTO.getSubjectInfoMap().containsKey(subject);\n\n // Check if the student is marked as absent for the given subject\n boolean isAbsent = hasMarks && isAbsentForCurrentCell(studentMarksDTO, subject);\n\n markField.setReadOnly(isAbsent || !hasMarks);\n });\n\n ComboBox presentAbsentFilter = createPresentAbsentFilter(presentAbsent -> {\n // Remove any existing filters before applying new ones\n dataProvider.removeFilters();\n\n if (\"Present\".equalsIgnoreCase(presentAbsent)) {\n // Show only rows where the student is present for the selected subject\n dataProvider.addFilter(studentMarksDTO -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap().get(subject);\n return subjectInfo != null && subjectInfo.getAbsent() != null && !subjectInfo.getAbsent();\n });\n } else if (\"Absent\".equalsIgnoreCase(presentAbsent)) {\n // Show only rows where the student is absent for the selected subject\n dataProvider.addFilter(studentMarksDTO -> {\n StudentSubjectInfo subjectInfo = studentMarksDTO.getSubjectInfoMap().get(subject);\n return subjectInfo != null && subjectInfo.getAbsent() != null && subjectInfo.getAbsent();\n });\n }\n });\n headerRow.getCell(attendanceStatus).setComponent(presentAbsentFilter);\n\n contextMenu.addColumnToggleItem(marksColumn);\n contextMenu.addColumnToggleItem(attendanceStatus);\n }\n }\n\n // Filters\n private ComboBox createFilterComponent(List items) {\n ComboBox comboBox = new ComboBox<>();\n comboBox.setItems(items);\n comboBox.setPlaceholder(\"Filter\");\n comboBox.setClearButtonVisible(true);\n comboBox.setWidth(\"100%\");\n comboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n return comboBox;\n }\n\n private ComboBox createPresentAbsentFilter(Consumer filterChangeConsumer) {\n ComboBox filter = createFilterComponent(Arrays.asList(\"Present\", \"Absent\"));\n filter.setItemLabelGenerator(s -> s.substring(0, 3));\n filter.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue()));\n return filter;\n }\n\n private ComboBox createPassFailFilter(Consumer filterChangeConsumer) {\n ComboBox filter = createFilterComponent(Arrays.asList(\"Pass\", \"Fail\"));\n filter.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue()));\n return filter;\n }\n\n private boolean isAbsentForCurrentCell(StudentMarksDTO studentMarksDTO, SubjectEntity subject) {\n return studentMarksDTO.getSubjectInfoMap()\n .entrySet()\n .stream()\n .filter(entry -> entry.getKey().getSubjectName().equals(subject.getSubjectName()))\n .findFirst()\n .map(Map.Entry::getValue)\n .map(StudentSubjectInfo::getAbsent)\n .orElse(false); // Default to false if not found\n }\n\n // CONTEXT CLASS\n private static class PassFailCounts {\n int totalPass;\n int totalFail;\n int totalPresent;\n int totalAbsent;\n\n // Map to store counts for each subject\n Map subjectPassCounts = new HashMap<>();\n Map subjectFailCounts = new HashMap<>();\n Map subjectPresentCounts = new HashMap<>();\n Map subjectAbsentCounts = new HashMap<>();\n }\n\n private List subjectEntities(DepartmentEntity department, Semester semester) {\n return subjectService.getSubjectsByDepartmentAndSemester(department, semester);\n }\n\n // Utility\n private static class ColumnToggleContextMenu extends ContextMenu {\n public ColumnToggleContextMenu(Component target) {\n super(target);\n setOpenOnClick(true);\n }\n\n void addColumnToggleItem(Grid.Column column) {\n MenuItem menuItem = this.addItem(column.getKey(), e -> column.setVisible(e.getSource().isChecked()));\n menuItem.setCheckable(true);\n menuItem.setChecked(column.isVisible());\n menuItem.setKeepOpen(true);\n }\n }\n\n // Method to open the chart dialog\n private void openChartDialog(StudentMarksDTO studentMarksDTO) {\n Chart chart = createStackedBarChart(studentMarksDTO);\n Button downloadButton = new Button(\"Download\");\n downloadButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n downloadButton.getStyle().set(\"margin-left\", \"auto\"); // To set the button on left corner\n\n // Wrapper\n User student = studentMarksDTO.getStudent();\n String fileName = student.getUsername() + \" [\" + student.getRegisterNumber() + \"].svg\";\n createChartDialog(chart, downloadButton, fileName);\n }\n\n private void openPieChartDialog(Integer pass, int fail, SubjectEntity subject) {\n Chart chart = createPieBarChart(pass, fail, subject);\n Button downloadButton = new Button(\"Download\");\n downloadButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n downloadButton.getStyle().set(\"margin-left\", \"auto\"); // To set the button on left corner\n\n // Wrapper\n String fileName = subject.getSubjectName() + \"[\" + subject.getSubjectCode() + \"]\" + \".svg\";\n createChartDialog(chart, downloadButton, fileName);\n }\n\n private void createChartDialog(Chart chart, Button downloadButton, String fileName) {\n FileDownloadWrapper buttonWrapper = new FileDownloadWrapper(\n new StreamResource(fileName, () -> {\n Configuration configuration = chart.getConfiguration();\n String svg = \"\";\n try (SVGGenerator generator = new SVGGenerator()) {\n svg = generator.generate(configuration);\n } catch (IOException | InterruptedException ex) {\n log.error(ex.getMessage());\n }\n return new ByteArrayInputStream(svg.getBytes());\n }));\n buttonWrapper.wrapComponent(downloadButton);\n\n Dialog dialog = new Dialog();\n dialog.setWidth(\"50%\");\n dialog.add(chart);\n dialog.open();\n dialog.getFooter().add(buttonWrapper);\n }\n\n // Method to create a stacked bar chart for a student\n private Chart createStackedBarChart(StudentMarksDTO studentMarksDTO) {\n Chart chart = new Chart(ChartType.COLUMN);\n Configuration configuration = chart.getConfiguration();\n configuration.setTitle(\"Student Marks Column Chart\");\n\n User student = studentMarksDTO.getStudent();\n String title = student.getUsername() + \" [\" + student.getRegisterNumber() + \"]\";\n configuration.setSubTitle(title);\n\n XAxis xAxis = new XAxis();\n xAxis.setTitle(\"Subjects\");\n\n YAxis yAxis = new YAxis();\n yAxis.setTitle(\"Marks\");\n\n configuration.addxAxis(xAxis);\n configuration.addyAxis(yAxis);\n\n // Retrieve the student's marks for each subject\n Map subjectInfoMap = studentMarksDTO.getSubjectInfoMap();\n\n for (Map.Entry entry : subjectInfoMap.entrySet()) {\n SubjectEntity subject = entry.getKey();\n StudentSubjectInfo subjectInfo = entry.getValue();\n\n ListSeries series = new ListSeries(subject.getSubjectName());\n if (subjectInfo.getMarks() != null) {\n series.addData(subjectInfo.getMarks());\n }\n configuration.addSeries(series);\n }\n\n PlotOptionsBar plotOptions = new PlotOptionsBar();\n plotOptions.setStacking(Stacking.NORMAL);\n configuration.setPlotOptions(plotOptions);\n\n return chart;\n }\n}", "answers": [" public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {"], "length": 9606, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "6b91a987-5035-411f-9de9-58627c805ae9", "reasoning": "The snippet ends with the import statements for the MainLayout class. The class definition earlier declares two final fields: authenticatedUser and accessChecker. The next logical line after the imports is the constructor that initializes these fields. Therefore, the next line should be the constructor signature for MainLayout, taking AuthenticatedUser and AccessAnnotationChecker as parameters.", "reasoning_model_answer": "public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {", "assistant_with_reasoning": "\nThe snippet ends with the import statements for the MainLayout class. The class definition earlier declares two final fields: authenticatedUser and accessChecker. The next logical line after the imports is the constructor that initializes these fields. Therefore, the next line should be the constructor signature for MainLayout, taking AuthenticatedUser and AccessAnnotationChecker as parameters.\n\npublic MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.514, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37978, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import org.jfree.ui.RectangleEdge;\r\nimport org.jfree.ui.RectangleInsets;\r\nimport org.jfree.util.ObjectUtilities;\r\nimport org.jfree.util.PaintUtilities;\r\nimport org.jfree.util.UnitType;\r\nimport java.awt.BasicStroke;\r\nimport java.awt.Color;\r\nimport java.awt.Font;\r\nimport java.awt.FontMetrics;\r\nimport java.awt.Graphics2D;\r\nimport java.awt.Paint;\r\nimport java.awt.Stroke;\r\nimport java.awt.geom.Area;\r\nimport java.awt.geom.Ellipse2D;\r\nimport java.awt.geom.Line2D;\r\nimport java.awt.geom.Point2D;\r\nimport java.awt.geom.Rectangle2D;\r\nimport java.awt.geom.RoundRectangle2D;\r\nimport java.io.IOException;\r\nimport java.io.ObjectInputStream;\r\nimport java.io.ObjectOutputStream;\r\nimport java.io.Serializable;\r\nimport java.text.DecimalFormat;\r\nimport java.text.NumberFormat;\r\nimport java.util.Arrays;\r\nimport java.util.ResourceBundle;\r\nimport org.jfree.chart.LegendItemCollection;\r\nimport org.jfree.chart.axis.NumberAxis;\r\nimport org.jfree.chart.axis.ValueAxis;\r\nimport org.jfree.chart.event.PlotChangeEvent;\r\nimport org.jfree.chart.util.ParamChecks;\r\nimport org.jfree.chart.util.ResourceBundleWrapper;\r\nimport org.jfree.data.Range;\r\nimport org.jfree.data.general.DatasetChangeEvent;\r\nimport org.jfree.data.general.DefaultValueDataset;\r\nimport org.jfree.data.general.ValueDataset;\r\nimport org.jfree.io.SerialUtilities;\r", "context": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/ThermometerPlot.java\n/* ===========================================================\r\n * JFreeChart : a free chart library for the Java(tm) platform\r\n * ===========================================================\r\n *\r\n * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.\r\n *\r\n * Project Info: http://www.jfree.org/jfreechart/index.html\r\n *\r\n * This library is free software; you can redistribute it and/or modify it\r\n * under the terms of the GNU Lesser General Public License as published by\r\n * the Free Software Foundation; either version 2.1 of the License, or\r\n * (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\r\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\r\n * License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\r\n * USA.\r\n *\r\n * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. \r\n * Other names may be trademarks of their respective owners.]\r\n *\r\n * --------------------\r\n * ThermometerPlot.java\r\n * --------------------\r\n *\r\n * (C) Copyright 2000-2013, by Bryan Scott and Contributors.\r\n *\r\n * Original Author: Bryan Scott (based on MeterPlot by Hari).\r\n * Contributor(s): David Gilbert (for Object Refinery Limited).\r\n * Arnaud Lelievre;\r\n * Julien Henry (see patch 1769088) (DG);\r\n *\r\n * Changes\r\n * -------\r\n * 11-Apr-2002 : Version 1, contributed by Bryan Scott;\r\n * 15-Apr-2002 : Changed to implement VerticalValuePlot;\r\n * 29-Apr-2002 : Added getVerticalValueAxis() method (DG);\r\n * 25-Jun-2002 : Removed redundant imports (DG);\r\n * 17-Sep-2002 : Reviewed with Checkstyle utility (DG);\r\n * 18-Sep-2002 : Extensive changes made to API, to iron out bugs and\r\n * inconsistencies (DG);\r\n * 13-Oct-2002 : Corrected error datasetChanged which would generate exceptions\r\n * when value set to null (BRS).\r\n * 23-Jan-2003 : Removed one constructor (DG);\r\n * 26-Mar-2003 : Implemented Serializable (DG);\r\n * 02-Jun-2003 : Removed test for compatible range axis (DG);\r\n * 01-Jul-2003 : Added additional check in draw method to ensure value not\r\n * null (BRS);\r\n * 08-Sep-2003 : Added internationalization via use of properties\r\n * resourceBundle (RFE 690236) (AL);\r\n * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);\r\n * 29-Sep-2003 : Updated draw to set value of cursor to non-zero and allow\r\n * painting of axis. An incomplete fix and needs to be set for\r\n * left or right drawing (BRS);\r\n * 19-Nov-2003 : Added support for value labels to be displayed left of the\r\n * thermometer\r\n * 19-Nov-2003 : Improved axis drawing (now default axis does not draw axis line\r\n * and is closer to the bulb). Added support for the positioning\r\n * of the axis to the left or right of the bulb. (BRS);\r\n * 03-Dec-2003 : Directly mapped deprecated setData()/getData() method to\r\n * get/setDataset() (TM);\r\n * 21-Jan-2004 : Update for renamed method in ValueAxis (DG);\r\n * 07-Apr-2004 : Changed string width calculation (DG);\r\n * 12-Nov-2004 : Implemented the new Zoomable interface (DG);\r\n * 06-Jan-2004 : Added getOrientation() method (DG);\r\n * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);\r\n * 29-Mar-2005 : Fixed equals() method (DG);\r\n * 05-May-2005 : Updated draw() method parameters (DG);\r\n * 09-Jun-2005 : Fixed more bugs in equals() method (DG);\r\n * 10-Jun-2005 : Fixed minor bug in setDisplayRange() method (DG);\r\n * ------------- JFREECHART 1.0.x ---------------------------------------------\r\n * 14-Nov-2006 : Fixed margin when drawing (DG);\r\n * 03-May-2007 : Fixed datasetChanged() to handle null dataset, added null\r\n * argument check and event notification to setRangeAxis(),\r\n * added null argument check to setPadding(), setValueFont(),\r\n * setValuePaint(), setValueFormat() and setMercuryPaint(),\r\n * deprecated get/setShowValueLines(), deprecated\r\n * getMinimum/MaximumVerticalDataValue(), and fixed serialization\r\n * bug (DG);\r\n * 24-Sep-2007 : Implemented new methods in Zoomable interface (DG);\r\n * 08-Oct-2007 : Added attributes for thermometer dimensions - see patch 1769088\r\n * by Julien Henry (DG);\r\n * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by\r\n * Jess Thrysoee (DG);\r\n * 02-Jul-2013 : Use ParamChecks (DG);\r\n *\r\n */\r\n\r\npackage org.jfree.chart.plot;\r\n\r\n\r\n\r\n/**\r\n * A plot that displays a single value (from a {@link ValueDataset}) in a\r\n * thermometer type display.\r\n *

\r\n * This plot supports a number of options:\r\n *

    \r\n *
  1. three sub-ranges which could be viewed as 'Normal', 'Warning'\r\n * and 'Critical' ranges.
  2. \r\n *
  3. the thermometer can be run in two modes:\r\n *
      \r\n *
    • fixed range, or
    • \r\n *
    • range adjusts to current sub-range.
    • \r\n *
    \r\n *
  4. \r\n *
  5. settable units to be displayed.
  6. \r\n *
  7. settable display location for the value text.
  8. \r\n *
\r\n */\r\npublic class ThermometerPlot extends Plot implements ValueAxisPlot,\r\n Zoomable, Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 4087093313147984390L;\r\n\r\n /** A constant for unit type 'None'. */\r\n public static final int UNITS_NONE = 0;\r\n\r\n /** A constant for unit type 'Fahrenheit'. */\r\n public static final int UNITS_FAHRENHEIT = 1;\r\n\r\n /** A constant for unit type 'Celcius'. */\r\n public static final int UNITS_CELCIUS = 2;\r\n\r\n /** A constant for unit type 'Kelvin'. */\r\n public static final int UNITS_KELVIN = 3;\r\n\r\n /** A constant for the value label position (no label). */\r\n public static final int NONE = 0;\r\n\r\n /** A constant for the value label position (right of the thermometer). */\r\n public static final int RIGHT = 1;\r\n\r\n /** A constant for the value label position (left of the thermometer). */\r\n public static final int LEFT = 2;\r\n\r\n /** A constant for the value label position (in the thermometer bulb). */\r\n public static final int BULB = 3;\r\n\r\n /** A constant for the 'normal' range. */\r\n public static final int NORMAL = 0;\r\n\r\n /** A constant for the 'warning' range. */\r\n public static final int WARNING = 1;\r\n\r\n /** A constant for the 'critical' range. */\r\n public static final int CRITICAL = 2;\r\n\r\n /**\r\n * The bulb radius.\r\n *\r\n * @deprecated As of 1.0.7, use {@link #getBulbRadius()}.\r\n */\r\n protected static final int BULB_RADIUS = 40;\r\n\r\n /**\r\n * The bulb diameter.\r\n *\r\n * @deprecated As of 1.0.7, use {@link #getBulbDiameter()}.\r\n */\r\n protected static final int BULB_DIAMETER = BULB_RADIUS * 2;\r\n\r\n /**\r\n * The column radius.\r\n *\r\n * @deprecated As of 1.0.7, use {@link #getColumnRadius()}.\r\n */\r\n protected static final int COLUMN_RADIUS = 20;\r\n\r\n /**\r\n * The column diameter.\r\n *\r\n * @deprecated As of 1.0.7, use {@link #getColumnDiameter()}.\r\n */\r\n protected static final int COLUMN_DIAMETER = COLUMN_RADIUS * 2;\r\n\r\n /**\r\n * The gap radius.\r\n *\r\n * @deprecated As of 1.0.7, use {@link #getGap()}.\r\n */\r\n protected static final int GAP_RADIUS = 5;\r\n\r\n /**\r\n * The gap diameter.\r\n *\r\n * @deprecated As of 1.0.7, use {@link #getGap()} times two.\r\n */\r\n protected static final int GAP_DIAMETER = GAP_RADIUS * 2;\r\n\r\n /** The axis gap. */\r\n protected static final int AXIS_GAP = 10;\r\n\r\n /** The unit strings. */\r\n protected static final String[] UNITS = {\"\", \"\\u00B0F\", \"\\u00B0C\",\r\n \"\\u00B0K\"};\r\n\r\n /** Index for low value in subrangeInfo matrix. */\r\n protected static final int RANGE_LOW = 0;\r\n\r\n /** Index for high value in subrangeInfo matrix. */\r\n protected static final int RANGE_HIGH = 1;\r\n\r\n /** Index for display low value in subrangeInfo matrix. */\r\n protected static final int DISPLAY_LOW = 2;\r\n\r\n /** Index for display high value in subrangeInfo matrix. */\r\n protected static final int DISPLAY_HIGH = 3;\r\n\r\n /** The default lower bound. */\r\n protected static final double DEFAULT_LOWER_BOUND = 0.0;\r\n\r\n /** The default upper bound. */\r\n protected static final double DEFAULT_UPPER_BOUND = 100.0;\r\n\r\n /**\r\n * The default bulb radius.\r\n *\r\n * @since 1.0.7\r\n */\r\n protected static final int DEFAULT_BULB_RADIUS = 40;\r\n\r\n /**\r\n * The default column radius.\r\n *\r\n * @since 1.0.7\r\n */\r\n protected static final int DEFAULT_COLUMN_RADIUS = 20;\r\n\r\n /**\r\n * The default gap between the outlines representing the thermometer.\r\n *\r\n * @since 1.0.7\r\n */\r\n protected static final int DEFAULT_GAP = 5;\r\n\r\n /** The dataset for the plot. */\r\n private ValueDataset dataset;\r\n\r\n /** The range axis. */\r\n private ValueAxis rangeAxis;\r\n\r\n /** The lower bound for the thermometer. */\r\n private double lowerBound = DEFAULT_LOWER_BOUND;\r\n\r\n /** The upper bound for the thermometer. */\r\n private double upperBound = DEFAULT_UPPER_BOUND;\r\n\r\n /**\r\n * The value label position.\r\n *\r\n * @since 1.0.7\r\n */\r\n private int bulbRadius = DEFAULT_BULB_RADIUS;\r\n\r\n /**\r\n * The column radius.\r\n *\r\n * @since 1.0.7\r\n */\r\n private int columnRadius = DEFAULT_COLUMN_RADIUS;\r\n\r\n /**\r\n * The gap between the two outlines the represent the thermometer.\r\n *\r\n * @since 1.0.7\r\n */\r\n\nlib/jfreechart-1.0.19/source/org/jfree/data/general/DatasetChangeEvent.java\npublic class DatasetChangeEvent extends java.util.EventObject {\r\n\r\n /**\r\n * The dataset that generated the change event.\r\n */\r\n private Dataset dataset;\r\n\r\n /**\r\n * Constructs a new event. The source is either the dataset or the\r\n * {@link org.jfree.chart.plot.Plot} class. The dataset can be\r\n * null (in this case the source will be the\r\n * {@link org.jfree.chart.plot.Plot} class).\r\n *\r\n * @param source the source of the event.\r\n * @param dataset the dataset that generated the event (null\r\n * permitted).\r\n */\r\n public DatasetChangeEvent(Object source, Dataset dataset) {\r\n super(source);\r\n this.dataset = dataset;\r\n }\r\n\r\n /**\r\n * Returns the dataset that generated the event. Note that the dataset\r\n * may be null since adding a null dataset to a\r\n * plot will generated a change event.\r\n *\r\n * @return The dataset (possibly null).\r\n */\r\n public Dataset getDataset() {\r\n return this.dataset;\r\n }\r\n\r\n}\r\n\nlib/jfreechart-1.0.19/source/org/jfree/data/Range.java\npublic strictfp class Range implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -906333695431863380L;\r\n\r\n /** The lower bound of the range. */\r\n private double lower;\r\n\r\n /** The upper bound of the range. */\r\n private double upper;\r\n\r\n /**\r\n * Creates a new range.\r\n *\r\n * @param lower the lower bound (must be <= upper bound).\r\n * @param upper the upper bound (must be >= lower bound).\r\n */\r\n public Range(double lower, double upper) {\r\n if (lower > upper) {\r\n String msg = \"Range(double, double): require lower (\" + lower\r\n + \") <= upper (\" + upper + \").\";\r\n throw new IllegalArgumentException(msg);\r\n }\r\n this.lower = lower;\r\n this.upper = upper;\r\n }\r\n\r\n /**\r\n * Returns the lower bound for the range.\r\n *\r\n * @return The lower bound.\r\n */\r\n public double getLowerBound() {\r\n return this.lower;\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the range.\r\n *\r\n * @return The upper bound.\r\n */\r\n public double getUpperBound() {\r\n return this.upper;\r\n }\r\n\r\n /**\r\n * Returns the length of the range.\r\n *\r\n * @return The length.\r\n */\r\n public double getLength() {\r\n return this.upper - this.lower;\r\n }\r\n\r\n /**\r\n * Returns the central value for the range.\r\n *\r\n * @return The central value.\r\n */\r\n public double getCentralValue() {\r\n return this.lower / 2.0 + this.upper / 2.0;\r\n }\r\n\r\n /**\r\n * Returns true if the range contains the specified value and\r\n * false otherwise.\r\n *\r\n * @param value the value to lookup.\r\n *\r\n * @return true if the range contains the specified value.\r\n */\r\n public boolean contains(double value) {\r\n return (value >= this.lower && value <= this.upper);\r\n }\r\n\r\n /**\r\n * Returns true if the range intersects with the specified\r\n * range, and false otherwise.\r\n *\r\n * @param b0 the lower bound (should be <= b1).\r\n * @param b1 the upper bound (should be >= b0).\r\n *\r\n * @return A boolean.\r\n */\r\n public boolean intersects(double b0, double b1) {\r\n if (b0 <= this.lower) {\r\n return (b1 > this.lower);\r\n }\r\n else {\r\n return (b0 < this.upper && b1 >= b0);\r\n }\r\n }\r\n\r\n /**\r\n * Returns true if the range intersects with the specified\r\n * range, and false otherwise.\r\n *\r\n * @param range another range (null not permitted).\r\n *\r\n * @return A boolean.\r\n *\r\n * @since 1.0.9\r\n */\r\n public boolean intersects(Range range) {\r\n return intersects(range.getLowerBound(), range.getUpperBound());\r\n }\r\n\r\n /**\r\n * Returns the value within the range that is closest to the specified\r\n * value.\r\n *\r\n * @param value the value.\r\n *\r\n * @return The constrained value.\r\n */\r\n public double constrain(double value) {\r\n double result = value;\r\n if (!contains(value)) {\r\n if (value > this.upper) {\r\n result = this.upper;\r\n }\r\n else if (value < this.lower) {\r\n result = this.lower;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Creates a new range by combining two existing ranges.\r\n *

\r\n * Note that:\r\n *

    \r\n *
  • either range can be null, in which case the other\r\n * range is returned;
  • \r\n *
  • if both ranges are null the return value is\r\n * null.
  • \r\n *
\r\n *\r\n * @param range1 the first range (null permitted).\r\n * @param range2 the second range (null permitted).\r\n *\r\n * @return A new range (possibly null).\r\n */\r\n public static Range combine(Range range1, Range range2) {\r\n if (range1 == null) {\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n return range1;\r\n }\r\n double l = Math.min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = Math.max(range1.getUpperBound(), range2.getUpperBound());\r\n return new Range(l, u);\r\n }\r\n\r\n /**\r\n * Returns a new range that spans both range1 and \r\n * range2. This method has a special handling to ignore\r\n * Double.NaN values.\r\n *\r\n * @param range1 the first range (null permitted).\r\n * @param range2 the second range (null permitted).\r\n *\r\n * @return A new range (possibly null).\r\n *\r\n * @since 1.0.15\r\n */\r\n public static Range combineIgnoringNaN(Range range1, Range range2) {\r\n if (range1 == null) {\r\n if (range2 != null && range2.isNaNRange()) {\r\n return null;\r\n }\r\n return range2;\r\n }\r\n if (range2 == null) {\r\n if (range1.isNaNRange()) {\r\n return null;\r\n }\r\n return range1;\r\n }\r\n double l = min(range1.getLowerBound(), range2.getLowerBound());\r\n double u = max(range1.getUpperBound(), range2.getUpperBound());\r\n if (Double.isNaN(l) && Double.isNaN(u)) {\r\n return null;\r\n }\r\n return new Range(l, u);\r\n }\r\n \r\n /**\r\n * Returns the minimum value. If either value is NaN, the other value is \r\n * returned. If both are NaN, NaN is returned.\r\n * \r\n * @param d1 value 1.\r\n * @param d2 value 2.\r\n * \r\n * @return The minimum of the two values. \r\n */\r\n private static double min(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.min(d1, d2);\r\n }\r\n\r\n private static double max(double d1, double d2) {\r\n if (Double.isNaN(d1)) {\r\n return d2;\r\n }\r\n if (Double.isNaN(d2)) {\r\n return d1;\r\n }\r\n return Math.max(d1, d2);\r\n }\r\n\r\n /**\r\n * Returns a range that includes all the values in the specified\r\n * range AND the specified value.\r\n *\r\n * @param range the range (null permitted).\r\n * @param value the value that must be included.\r\n *\r\n * @return A range.\r\n *\r\n * @since 1.0.1\r\n */\r\n public static Range expandToInclude(Range range, double value) {\r\n if (range == null) {\r\n return new Range(value, value);\r\n }\r\n if (value < range.getLowerBound()) {\r\n return new Range(value, range.getUpperBound());\r\n }\r\n else if (value > range.getUpperBound()) {\r\n return new Range(range.getLowerBound(), value);\r\n }\r\n else {\r\n return range;\r\n }\r\n }\r\n\r\n /**\r\n * Creates a new range by adding margins to an existing range.\r\n *\r\n * @param range the range (null not permitted).\r\n * @param lowerMargin the lower margin (expressed as a percentage of the\r\n * range length).\r\n * @param upperMargin the upper margin (expressed as a percentage of the\r\n * range length).\r\n *\r\n * @return The expanded range.\r\n */\r\n public static Range expand(Range range,\r\n double lowerMargin, double upperMargin) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n double length = range.getLength();\r\n double lower = range.getLowerBound() - length * lowerMargin;\r\n double upper = range.getUpperBound() + length * upperMargin;\r\n if (lower > upper) {\r\n lower = lower / 2.0 + upper / 2.0;\r\n upper = lower;\r\n }\r\n return new Range(lower, upper);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (null not permitted).\r\n * @param delta the shift amount.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta) {\r\n return shift(base, delta, false);\r\n }\r\n\r\n /**\r\n * Shifts the range by the specified amount.\r\n *\r\n * @param base the base range (null not permitted).\r\n * @param delta the shift amount.\r\n * @param allowZeroCrossing a flag that determines whether or not the\r\n * bounds of the range are allowed to cross\r\n * zero after adjustment.\r\n *\r\n * @return A new range.\r\n */\r\n public static Range shift(Range base, double delta,\r\n boolean allowZeroCrossing) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (allowZeroCrossing) {\r\n return new Range(base.getLowerBound() + delta,\r\n base.getUpperBound() + delta);\r\n }\r\n else {\r\n return new Range(shiftWithNoZeroCrossing(base.getLowerBound(),\r\n delta), shiftWithNoZeroCrossing(base.getUpperBound(),\r\n delta));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the given value adjusted by delta but\r\n * with a check to prevent the result from crossing 0.0.\r\n *\r\n * @param value the value.\r\n * @param delta the adjustment.\r\n *\r\n * @return The adjusted value.\r\n */\r\n private static double shiftWithNoZeroCrossing(double value, double delta) {\r\n if (value > 0.0) {\r\n return Math.max(value + delta, 0.0);\r\n }\r\n else if (value < 0.0) {\r\n return Math.min(value + delta, 0.0);\r\n }\r\n else {\r\n return value + delta;\r\n }\r\n }\r\n\r\n /**\r\n * Scales the range by the specified factor.\r\n *\r\n * @param base the base range (null not permitted).\r\n * @param factor the scaling factor (must be non-negative).\r\n *\r\n * @return A new range.\r\n *\r\n * @since 1.0.9\r\n */\r\n public static Range scale(Range base, double factor) {\r\n ParamChecks.nullNotPermitted(base, \"base\");\r\n if (factor < 0) {\r\n throw new IllegalArgumentException(\"Negative 'factor' argument.\");\r\n }\r\n return new Range(base.getLowerBound() * factor,\r\n base.getUpperBound() * factor);\r\n }\r\n\r\n /**\r\n * Tests this object for equality with an arbitrary object.\r\n *\r\n * @param obj the object to test against (null permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (!(obj instanceof Range)) {\r\n return false;\r\n }\r\n Range range = (Range) obj;\r\n if (!(this.lower == range.lower)) {\r\n return false;\r\n }\r\n if (!(this.upper == range.upper)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns true if both the lower and upper bounds are \r\n * Double.NaN, and false otherwise.\r\n * \r\n * @return A boolean.\r\n * \r\n * @since 1.0.18\r\n */\r\n public boolean isNaNRange() {\r\n return Double.isNaN(this.lower) && Double.isNaN(this.upper);\r\n }\r\n \r\n /**\r\n * Returns a hash code.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n long temp;\r\n temp = Double.doubleToLongBits(this.lower);\r\n result = (int) (temp ^ (temp >>> 32));\r\n temp = Double.doubleToLongBits(this.upper);\r\n result = 29 * result + (int) (temp ^ (temp >>> 32));\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a string representation of this Range.\r\n *\r\n * @return A String \"Range[lower,upper]\" where lower=lower range and\r\n * upper=upper range.\r\n */\r\n @Override\r\n public String toString() {\r\n return (\"Range[\" + this.lower + \",\" + this.upper + \"]\");\r\n }\r\n\r\n}\r\n\nlib/jfreechart-1.0.19/source/org/jfree/chart/axis/ValueAxis.java\npublic abstract class ValueAxis extends Axis\r\n implements Cloneable, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 3698345477322391456L;\r\n\r\n /** The default axis range. */\r\n public static final Range DEFAULT_RANGE = new Range(0.0, 1.0);\r\n\r\n /** The default auto-range value. */\r\n public static final boolean DEFAULT_AUTO_RANGE = true;\r\n\r\n /** The default inverted flag setting. */\r\n public static final boolean DEFAULT_INVERTED = false;\r\n\r\n /** The default minimum auto range. */\r\n public static final double DEFAULT_AUTO_RANGE_MINIMUM_SIZE = 0.00000001;\r\n\r\n /** The default value for the lower margin (0.05 = 5%). */\r\n public static final double DEFAULT_LOWER_MARGIN = 0.05;\r\n\r\n /** The default value for the upper margin (0.05 = 5%). */\r\n public static final double DEFAULT_UPPER_MARGIN = 0.05;\r\n\r\n /**\r\n * The default lower bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_LOWER_BOUND = 0.0;\r\n\r\n /**\r\n * The default upper bound for the axis.\r\n *\r\n * @deprecated From 1.0.5 onwards, the axis defines a defaultRange\r\n * attribute (see {@link #getDefaultAutoRange()}).\r\n */\r\n public static final double DEFAULT_UPPER_BOUND = 1.0;\r\n\r\n /** The default auto-tick-unit-selection value. */\r\n public static final boolean DEFAULT_AUTO_TICK_UNIT_SELECTION = true;\r\n\r\n /** The maximum tick count. */\r\n public static final int MAXIMUM_TICK_COUNT = 500;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the positive end of\r\n * the axis line.\r\n */\r\n private boolean positiveArrowVisible;\r\n\r\n /**\r\n * A flag that controls whether an arrow is drawn at the negative end of\r\n * the axis line.\r\n */\r\n private boolean negativeArrowVisible;\r\n\r\n /** The shape used for an up arrow. */\r\n private transient Shape upArrow;\r\n\r\n /** The shape used for a down arrow. */\r\n private transient Shape downArrow;\r\n\r\n /** The shape used for a left arrow. */\r\n private transient Shape leftArrow;\r\n\r\n /** The shape used for a right arrow. */\r\n private transient Shape rightArrow;\r\n\r\n /** A flag that affects the orientation of the values on the axis. */\r\n private boolean inverted;\r\n\r\n /** The axis range. */\r\n private Range range;\r\n\r\n /**\r\n * Flag that indicates whether the axis automatically scales to fit the\r\n * chart data.\r\n */\r\n private boolean autoRange;\r\n\r\n /** The minimum size for the 'auto' axis range (excluding margins). */\r\n private double autoRangeMinimumSize;\r\n\r\n /**\r\n * The default range is used when the dataset is empty and the axis needs\r\n * to determine the auto range.\r\n *\r\n * @since 1.0.5\r\n */\r\n private Range defaultAutoRange;\r\n\r\n /**\r\n * The upper margin percentage. This indicates the amount by which the\r\n * maximum axis value exceeds the maximum data value (as a percentage of\r\n * the range on the axis) when the axis range is determined automatically.\r\n */\r\n private double upperMargin;\r\n\r\n /**\r\n * The lower margin. This is a percentage that indicates the amount by\r\n * which the minimum axis value is \"less than\" the minimum data value when\r\n * the axis range is determined automatically.\r\n */\r\n private double lowerMargin;\r\n\r\n /**\r\n * If this value is positive, the amount is subtracted from the maximum\r\n * data value to determine the lower axis range. This can be used to\r\n * provide a fixed \"window\" on dynamic data.\r\n */\r\n private double fixedAutoRange;\r\n\r\n /**\r\n * Flag that indicates whether or not the tick unit is selected\r\n * automatically.\r\n */\r\n private boolean autoTickUnitSelection;\r\n\r\n /** The standard tick units for the axis. */\r\n private TickUnitSource standardTickUnits;\r\n\r\n /** An index into an array of standard tick values. */\r\n private int autoTickIndex;\r\n\r\n /**\r\n * The number of minor ticks per major tick unit. This is an override\r\n * field, if the value is > 0 it is used, otherwise the axis refers to the\r\n * minorTickCount in the current tickUnit.\r\n */\r\n private int minorTickCount;\r\n\r\n /** A flag indicating whether or not tick labels are rotated to vertical. */\r\n private boolean verticalTickLabels;\r\n\r\n /**\r\n * Constructs a value axis.\r\n *\r\n * @param label the axis label (null permitted).\r\n * @param standardTickUnits the source for standard tick units\r\n * (null permitted).\r\n */\r\n protected ValueAxis(String label, TickUnitSource standardTickUnits) {\r\n\r\n super(label);\r\n\r\n this.positiveArrowVisible = false;\r\n this.negativeArrowVisible = false;\r\n\r\n this.range = DEFAULT_RANGE;\r\n this.autoRange = DEFAULT_AUTO_RANGE;\r\n this.defaultAutoRange = DEFAULT_RANGE;\r\n\r\n this.inverted = DEFAULT_INVERTED;\r\n this.autoRangeMinimumSize = DEFAULT_AUTO_RANGE_MINIMUM_SIZE;\r\n\r\n this.lowerMargin = DEFAULT_LOWER_MARGIN;\r\n this.upperMargin = DEFAULT_UPPER_MARGIN;\r\n\r\n this.fixedAutoRange = 0.0;\r\n\r\n this.autoTickUnitSelection = DEFAULT_AUTO_TICK_UNIT_SELECTION;\r\n this.standardTickUnits = standardTickUnits;\r\n\r\n Polygon p1 = new Polygon();\r\n p1.addPoint(0, 0);\r\n p1.addPoint(-2, 2);\r\n p1.addPoint(2, 2);\r\n\r\n this.upArrow = p1;\r\n\r\n Polygon p2 = new Polygon();\r\n p2.addPoint(0, 0);\r\n p2.addPoint(-2, -2);\r\n p2.addPoint(2, -2);\r\n\r\n this.downArrow = p2;\r\n\r\n Polygon p3 = new Polygon();\r\n p3.addPoint(0, 0);\r\n p3.addPoint(-2, -2);\r\n p3.addPoint(-2, 2);\r\n\r\n this.rightArrow = p3;\r\n\r\n Polygon p4 = new Polygon();\r\n p4.addPoint(0, 0);\r\n p4.addPoint(2, -2);\r\n p4.addPoint(2, 2);\r\n\r\n this.leftArrow = p4;\r\n\r\n this.verticalTickLabels = false;\r\n this.minorTickCount = 0;\r\n\r\n }\r\n\r\n /**\r\n * Returns true if the tick labels should be rotated (to\r\n * vertical), and false otherwise.\r\n *\r\n * @return true or false.\r\n *\r\n * @see #setVerticalTickLabels(boolean)\r\n */\r\n public boolean isVerticalTickLabels() {\r\n return this.verticalTickLabels;\r\n }\r\n\r\n /**\r\n * Sets the flag that controls whether the tick labels are displayed\r\n * vertically (that is, rotated 90 degrees from horizontal). If the flag\r\n * is changed, an {@link AxisChangeEvent} is sent to all registered\r\n * listeners.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isVerticalTickLabels()\r\n */\r\n public void setVerticalTickLabels(boolean flag) {\r\n if (this.verticalTickLabels != flag) {\r\n this.verticalTickLabels = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the positive direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setPositiveArrowVisible(boolean)\r\n */\r\n public boolean isPositiveArrowVisible() {\r\n return this.positiveArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the positive direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #isPositiveArrowVisible()\r\n */\r\n public void setPositiveArrowVisible(boolean visible) {\r\n this.positiveArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether or not the axis line has an arrow\r\n * drawn that points in the negative direction for the axis.\r\n *\r\n * @return A boolean.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public boolean isNegativeArrowVisible() {\r\n return this.negativeArrowVisible;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether or not the axis lines has an arrow\r\n * drawn that points in the negative direction for the axis, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param visible the flag.\r\n *\r\n * @see #setNegativeArrowVisible(boolean)\r\n */\r\n public void setNegativeArrowVisible(boolean visible) {\r\n this.negativeArrowVisible = visible;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never null).\r\n *\r\n * @see #setUpArrow(Shape)\r\n */\r\n public Shape getUpArrow() {\r\n return this.upArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing upwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (null not permitted).\r\n *\r\n * @see #getUpArrow()\r\n */\r\n public void setUpArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.upArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line.\r\n *\r\n * @return A shape (never null).\r\n *\r\n * @see #setDownArrow(Shape)\r\n */\r\n public Shape getDownArrow() {\r\n return this.downArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing downwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (null not permitted).\r\n *\r\n * @see #getDownArrow()\r\n */\r\n public void setDownArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.downArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never null).\r\n *\r\n * @see #setLeftArrow(Shape)\r\n */\r\n public Shape getLeftArrow() {\r\n return this.leftArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing left at the\r\n * end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (null not permitted).\r\n *\r\n * @see #getLeftArrow()\r\n */\r\n public void setLeftArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.leftArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns a shape that can be displayed as an arrow pointing right at the\r\n * end of an axis line.\r\n *\r\n * @return A shape (never null).\r\n *\r\n * @see #setRightArrow(Shape)\r\n */\r\n public Shape getRightArrow() {\r\n return this.rightArrow;\r\n }\r\n\r\n /**\r\n * Sets the shape that can be displayed as an arrow pointing rightwards at\r\n * the end of an axis line and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param arrow the arrow shape (null not permitted).\r\n *\r\n * @see #getRightArrow()\r\n */\r\n public void setRightArrow(Shape arrow) {\r\n ParamChecks.nullNotPermitted(arrow, \"arrow\");\r\n this.rightArrow = arrow;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Draws an axis line at the current cursor position and edge.\r\n *\r\n * @param g2 the graphics device ({@code null} not permitted).\r\n * @param cursor the cursor position.\r\n * @param dataArea the data area.\r\n * @param edge the edge.\r\n */\r\n @Override\r\n protected void drawAxisLine(Graphics2D g2, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n Line2D axisLine = null;\r\n double c = cursor;\r\n if (edge == RectangleEdge.TOP) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n axisLine = new Line2D.Double(dataArea.getX(), c, dataArea.getMaxX(),\r\n c);\r\n } else if (edge == RectangleEdge.LEFT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c, \r\n dataArea.getMaxY());\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n axisLine = new Line2D.Double(c, dataArea.getY(), c,\r\n dataArea.getMaxY());\r\n }\r\n g2.setPaint(getAxisLinePaint());\r\n g2.setStroke(getAxisLineStroke());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n g2.draw(axisLine);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n\r\n boolean drawUpOrRight = false;\r\n boolean drawDownOrLeft = false;\r\n if (this.positiveArrowVisible) {\r\n if (this.inverted) {\r\n drawDownOrLeft = true;\r\n }\r\n else {\r\n drawUpOrRight = true;\r\n }\r\n }\r\n if (this.negativeArrowVisible) {\r\n if (this.inverted) {\r\n drawUpOrRight = true;\r\n } else {\r\n drawDownOrLeft = true;\r\n }\r\n }\r\n if (drawUpOrRight) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMaxX();\r\n y = cursor;\r\n arrow = this.rightArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMinY();\r\n arrow = this.upArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n if (drawDownOrLeft) {\r\n double x = 0.0;\r\n double y = 0.0;\r\n Shape arrow = null;\r\n if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {\r\n x = dataArea.getMinX();\r\n y = cursor;\r\n arrow = this.leftArrow;\r\n } else if (edge == RectangleEdge.LEFT\r\n || edge == RectangleEdge.RIGHT) {\r\n x = cursor;\r\n y = dataArea.getMaxY();\r\n arrow = this.downArrow;\r\n }\r\n\r\n // draw the arrow...\r\n AffineTransform transformer = new AffineTransform();\r\n transformer.setToTranslation(x, y);\r\n Shape shape = transformer.createTransformedShape(arrow);\r\n g2.fill(shape);\r\n g2.draw(shape);\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Calculates the anchor point for a tick label.\r\n *\r\n * @param tick the tick.\r\n * @param cursor the cursor.\r\n * @param dataArea the data area.\r\n * @param edge the edge on which the axis is drawn.\r\n *\r\n * @return The x and y coordinates of the anchor point.\r\n */\r\n protected float[] calculateAnchorPoint(ValueTick tick, double cursor,\r\n Rectangle2D dataArea, RectangleEdge edge) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n float[] result = new float[2];\r\n if (edge == RectangleEdge.TOP) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor - insets.getBottom() - 2.0);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n result[1] = (float) (cursor + insets.getTop() + 2.0);\r\n }\r\n else if (edge == RectangleEdge.LEFT) {\r\n result[0] = (float) (cursor - insets.getLeft() - 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n result[0] = (float) (cursor + insets.getRight() + 2.0);\r\n result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Draws the axis line, tick marks and tick mark labels.\r\n *\r\n * @param g2 the graphics device (null not permitted).\r\n * @param cursor the cursor.\r\n * @param plotArea the plot area (null not permitted).\r\n * @param dataArea the data area (null not permitted).\r\n * @param edge the edge that the axis is aligned with (null \r\n * not permitted).\r\n *\r\n * @return The width or height used to draw the axis.\r\n */\r\n protected AxisState drawTickMarksAndLabels(Graphics2D g2,\r\n double cursor, Rectangle2D plotArea, Rectangle2D dataArea,\r\n RectangleEdge edge) {\r\n\r\n AxisState state = new AxisState(cursor);\r\n if (isAxisLineVisible()) {\r\n drawAxisLine(g2, cursor, dataArea, edge);\r\n }\r\n List ticks = refreshTicks(g2, state, dataArea, edge);\r\n state.setTicks(ticks);\r\n g2.setFont(getTickLabelFont());\r\n Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, \r\n RenderingHints.VALUE_STROKE_NORMALIZE);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n ValueTick tick = (ValueTick) iterator.next();\r\n if (isTickLabelsVisible()) {\r\n g2.setPaint(getTickLabelPaint());\r\n float[] anchorPoint = calculateAnchorPoint(tick, cursor,\r\n dataArea, edge);\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() == null) {\r\n continue;\r\n }\r\n AttrStringUtils.drawRotatedString(lt.getAttributedLabel(), \r\n g2, anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n } else {\r\n if (tick.getText() == null) {\r\n continue;\r\n }\r\n TextUtilities.drawRotatedString(tick.getText(), g2,\r\n anchorPoint[0], anchorPoint[1], \r\n tick.getTextAnchor(), tick.getAngle(), \r\n tick.getRotationAnchor());\r\n }\r\n }\r\n\r\n if ((isTickMarksVisible() && tick.getTickType().equals(\r\n TickType.MAJOR)) || (isMinorTickMarksVisible()\r\n && tick.getTickType().equals(TickType.MINOR))) {\r\n\r\n double ol = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkOutsideLength()\r\n : getTickMarkOutsideLength();\r\n\r\n double il = (tick.getTickType().equals(TickType.MINOR)) \r\n ? getMinorTickMarkInsideLength()\r\n : getTickMarkInsideLength();\r\n\r\n float xx = (float) valueToJava2D(tick.getValue(), dataArea,\r\n edge);\r\n Line2D mark = null;\r\n g2.setStroke(getTickMarkStroke());\r\n g2.setPaint(getTickMarkPaint());\r\n if (edge == RectangleEdge.LEFT) {\r\n mark = new Line2D.Double(cursor - ol, xx, cursor + il, xx);\r\n }\r\n else if (edge == RectangleEdge.RIGHT) {\r\n mark = new Line2D.Double(cursor + ol, xx, cursor - il, xx);\r\n }\r\n else if (edge == RectangleEdge.TOP) {\r\n mark = new Line2D.Double(xx, cursor - ol, xx, cursor + il);\r\n }\r\n else if (edge == RectangleEdge.BOTTOM) {\r\n mark = new Line2D.Double(xx, cursor + ol, xx, cursor - il);\r\n }\r\n g2.draw(mark);\r\n }\r\n }\r\n g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved);\r\n \r\n // need to work out the space used by the tick labels...\r\n // so we can update the cursor...\r\n double used = 0.0;\r\n if (isTickLabelsVisible()) {\r\n if (edge == RectangleEdge.LEFT) {\r\n used += findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorLeft(used);\r\n } else if (edge == RectangleEdge.RIGHT) {\r\n used = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorRight(used);\r\n } else if (edge == RectangleEdge.TOP) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorUp(used);\r\n } else if (edge == RectangleEdge.BOTTOM) {\r\n used = findMaximumTickLabelHeight(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n state.cursorDown(used);\r\n }\r\n }\r\n\r\n return state;\r\n }\r\n\r\n /**\r\n * Returns the space required to draw the axis.\r\n *\r\n * @param g2 the graphics device.\r\n * @param plot the plot that the axis belongs to.\r\n * @param plotArea the area within which the plot should be drawn.\r\n * @param edge the axis location.\r\n * @param space the space already reserved (for other axes).\r\n *\r\n * @return The space required to draw the axis (including pre-reserved\r\n * space).\r\n */\r\n @Override\r\n public AxisSpace reserveSpace(Graphics2D g2, Plot plot, \r\n Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {\r\n\r\n // create a new space object if one wasn't supplied...\r\n if (space == null) {\r\n space = new AxisSpace();\r\n }\r\n\r\n // if the axis is not visible, no additional space is required...\r\n if (!isVisible()) {\r\n return space;\r\n }\r\n\r\n // if the axis has a fixed dimension, return it...\r\n double dimension = getFixedDimension();\r\n if (dimension > 0.0) {\r\n space.add(dimension, edge);\r\n return space;\r\n }\r\n\r\n // calculate the max size of the tick labels (if visible)...\r\n double tickLabelHeight = 0.0;\r\n double tickLabelWidth = 0.0;\r\n if (isTickLabelsVisible()) {\r\n g2.setFont(getTickLabelFont());\r\n List ticks = refreshTicks(g2, new AxisState(), plotArea, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n tickLabelHeight = findMaximumTickLabelHeight(ticks, g2,\r\n plotArea, isVerticalTickLabels());\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n tickLabelWidth = findMaximumTickLabelWidth(ticks, g2, plotArea,\r\n isVerticalTickLabels());\r\n }\r\n }\r\n\r\n // get the axis label size and update the space object...\r\n Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge);\r\n if (RectangleEdge.isTopOrBottom(edge)) {\r\n double labelHeight = labelEnclosure.getHeight();\r\n space.add(labelHeight + tickLabelHeight, edge);\r\n }\r\n else if (RectangleEdge.isLeftOrRight(edge)) {\r\n double labelWidth = labelEnclosure.getWidth();\r\n space.add(labelWidth + tickLabelWidth, edge);\r\n }\r\n\r\n return space;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the height of the tallest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The height of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelHeight(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n g2.setFont(font);\r\n double maxHeight = 0.0;\r\n if (vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(\r\n tick.getText(), g2, fm);\r\n }\r\n if (labelBounds != null && labelBounds.getWidth() \r\n + insets.getTop() + insets.getBottom() > maxHeight) {\r\n maxHeight = labelBounds.getWidth()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxHeight = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxHeight;\r\n\r\n }\r\n\r\n /**\r\n * A utility method for determining the width of the widest tick label.\r\n *\r\n * @param ticks the ticks.\r\n * @param g2 the graphics device.\r\n * @param drawArea the area within which the plot and axes should be drawn.\r\n * @param vertical a flag that indicates whether or not the tick labels\r\n * are 'vertical'.\r\n *\r\n * @return The width of the tallest tick label.\r\n */\r\n protected double findMaximumTickLabelWidth(List ticks, Graphics2D g2,\r\n Rectangle2D drawArea, boolean vertical) {\r\n\r\n RectangleInsets insets = getTickLabelInsets();\r\n Font font = getTickLabelFont();\r\n double maxWidth = 0.0;\r\n if (!vertical) {\r\n FontMetrics fm = g2.getFontMetrics(font);\r\n Iterator iterator = ticks.iterator();\r\n while (iterator.hasNext()) {\r\n Tick tick = (Tick) iterator.next();\r\n Rectangle2D labelBounds = null;\r\n if (tick instanceof LogTick) {\r\n LogTick lt = (LogTick) tick;\r\n if (lt.getAttributedLabel() != null) {\r\n labelBounds = AttrStringUtils.getTextBounds(\r\n lt.getAttributedLabel(), g2);\r\n }\r\n } else if (tick.getText() != null) {\r\n labelBounds = TextUtilities.getTextBounds(tick.getText(), \r\n g2, fm);\r\n }\r\n if (labelBounds != null \r\n && labelBounds.getWidth() + insets.getLeft()\r\n + insets.getRight() > maxWidth) {\r\n maxWidth = labelBounds.getWidth()\r\n + insets.getLeft() + insets.getRight();\r\n }\r\n }\r\n } else {\r\n LineMetrics metrics = font.getLineMetrics(\"ABCxyz\",\r\n g2.getFontRenderContext());\r\n maxWidth = metrics.getHeight()\r\n + insets.getTop() + insets.getBottom();\r\n }\r\n return maxWidth;\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls the direction of values on the axis.\r\n *

\r\n * For a regular axis, values increase from left to right (for a horizontal\r\n * axis) and bottom to top (for a vertical axis). When the axis is\r\n * 'inverted', the values increase in the opposite direction.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setInverted(boolean)\r\n */\r\n public boolean isInverted() {\r\n return this.inverted;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls the direction of values on the axis, and\r\n * notifies registered listeners that the axis has changed.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @see #isInverted()\r\n */\r\n public void setInverted(boolean flag) {\r\n if (this.inverted != flag) {\r\n this.inverted = flag;\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the flag that controls whether or not the axis range is\r\n * automatically adjusted to fit the data values.\r\n *\r\n * @return The flag.\r\n *\r\n * @see #setAutoRange(boolean)\r\n */\r\n public boolean isAutoRange() {\r\n return this.autoRange;\r\n }\r\n\r\n /**\r\n * Sets a flag that determines whether or not the axis range is\r\n * automatically adjusted to fit the data, and notifies registered\r\n * listeners that the axis has been modified.\r\n *\r\n * @param auto the new value of the flag.\r\n *\r\n * @see #isAutoRange()\r\n */\r\n public void setAutoRange(boolean auto) {\r\n setAutoRange(auto, true);\r\n }\r\n\r\n /**\r\n * Sets the auto range attribute. If the notify flag is set,\r\n * an {@link AxisChangeEvent} is sent to registered listeners.\r\n *\r\n * @param auto the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoRange()\r\n */\r\n protected void setAutoRange(boolean auto, boolean notify) {\r\n if (this.autoRange != auto) {\r\n this.autoRange = auto;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n *\r\n * @return The minimum range.\r\n *\r\n * @see #setAutoRangeMinimumSize(double)\r\n */\r\n public double getAutoRangeMinimumSize() {\r\n return this.autoRangeMinimumSize;\r\n }\r\n\r\n /**\r\n * Sets the auto range minimum size and sends an {@link AxisChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param size the size.\r\n *\r\n * @see #getAutoRangeMinimumSize()\r\n */\r\n public void setAutoRangeMinimumSize(double size) {\r\n setAutoRangeMinimumSize(size, true);\r\n }\r\n\r\n /**\r\n * Sets the minimum size allowed for the axis range when it is\r\n * automatically calculated.\r\n *

\r\n * If requested, an {@link AxisChangeEvent} is forwarded to all registered\r\n * listeners.\r\n *\r\n * @param size the new minimum.\r\n * @param notify notify listeners?\r\n */\r\n public void setAutoRangeMinimumSize(double size, boolean notify) {\r\n if (size <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"NumberAxis.setAutoRangeMinimumSize(double): must be > 0.0.\");\r\n }\r\n if (this.autoRangeMinimumSize != size) {\r\n this.autoRangeMinimumSize = size;\r\n if (this.autoRange) {\r\n autoAdjustRange();\r\n }\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Returns the default auto range.\r\n *\r\n * @return The default auto range (never null).\r\n *\r\n * @see #setDefaultAutoRange(Range)\r\n *\r\n * @since 1.0.5\r\n */\r\n public Range getDefaultAutoRange() {\r\n return this.defaultAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the default auto range and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (null not permitted).\r\n *\r\n * @see #getDefaultAutoRange()\r\n *\r\n * @since 1.0.5\r\n */\r\n public void setDefaultAutoRange(Range range) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n this.defaultAutoRange = range;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The lower margin.\r\n *\r\n * @see #setLowerMargin(double)\r\n */\r\n public double getLowerMargin() {\r\n return this.lowerMargin;\r\n }\r\n\r\n /**\r\n * Sets the lower margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setUpperMargin(double)\r\n */\r\n public void setLowerMargin(double margin) {\r\n this.lowerMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the upper margin for the axis, expressed as a percentage of the\r\n * axis range. This controls the space added to the lower end of the axis\r\n * when the axis range is automatically calculated (it is ignored when the\r\n * axis range is set explicitly). The default value is 0.05 (five percent).\r\n *\r\n * @return The upper margin.\r\n *\r\n * @see #setUpperMargin(double)\r\n */\r\n public double getUpperMargin() {\r\n return this.upperMargin;\r\n }\r\n\r\n /**\r\n * Sets the upper margin for the axis (as a percentage of the axis range)\r\n * and sends an {@link AxisChangeEvent} to all registered listeners. This\r\n * margin is added only when the axis range is auto-calculated - if you set\r\n * the axis range manually, the margin is ignored.\r\n *\r\n * @param margin the margin percentage (for example, 0.05 is five percent).\r\n *\r\n * @see #getLowerMargin()\r\n * @see #setLowerMargin(double)\r\n */\r\n public void setUpperMargin(double margin) {\r\n this.upperMargin = margin;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the fixed auto range.\r\n *\r\n * @return The length.\r\n *\r\n * @see #setFixedAutoRange(double)\r\n */\r\n public double getFixedAutoRange() {\r\n return this.fixedAutoRange;\r\n }\r\n\r\n /**\r\n * Sets the fixed auto range for the axis.\r\n *\r\n * @param length the range length.\r\n *\r\n * @see #getFixedAutoRange()\r\n */\r\n public void setFixedAutoRange(double length) {\r\n this.fixedAutoRange = length;\r\n if (isAutoRange()) {\r\n autoAdjustRange();\r\n }\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the lower bound of the axis range.\r\n *\r\n * @return The lower bound.\r\n *\r\n * @see #setLowerBound(double)\r\n */\r\n public double getLowerBound() {\r\n return this.range.getLowerBound();\r\n }\r\n\r\n /**\r\n * Sets the lower bound for the axis range. An {@link AxisChangeEvent} is\r\n * sent to all registered listeners.\r\n *\r\n * @param min the new minimum.\r\n *\r\n * @see #getLowerBound()\r\n */\r\n public void setLowerBound(double min) {\r\n if (this.range.getUpperBound() > min) {\r\n setRange(new Range(min, this.range.getUpperBound()));\r\n }\r\n else {\r\n setRange(new Range(min, min + 1.0));\r\n }\r\n }\r\n\r\n /**\r\n * Returns the upper bound for the axis range.\r\n *\r\n * @return The upper bound.\r\n *\r\n * @see #setUpperBound(double)\r\n */\r\n public double getUpperBound() {\r\n return this.range.getUpperBound();\r\n }\r\n\r\n /**\r\n * Sets the upper bound for the axis range, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param max the new maximum.\r\n *\r\n * @see #getUpperBound()\r\n */\r\n public void setUpperBound(double max) {\r\n if (this.range.getLowerBound() < max) {\r\n setRange(new Range(this.range.getLowerBound(), max));\r\n }\r\n else {\r\n setRange(max - 1.0, max);\r\n }\r\n }\r\n\r\n /**\r\n * Returns the range for the axis.\r\n *\r\n * @return The axis range (never null).\r\n *\r\n * @see #setRange(Range)\r\n */\r\n public Range getRange() {\r\n return this.range;\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * false.\r\n *\r\n * @param range the range (null not permitted).\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range) {\r\n // defer argument checking\r\n setRange(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and, if requested, sends a change event to \r\n * all registered listeners. Furthermore, if turnOffAutoRange\r\n * is true, the auto-range flag is set to false \r\n * (normally when setting the axis range manually the caller expects that\r\n * range to remain in force).\r\n *\r\n * @param range the range (null not permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n *\r\n * @see #getRange()\r\n */\r\n public void setRange(Range range, boolean turnOffAutoRange, \r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n if (range.getLength() <= 0.0) {\r\n throw new IllegalArgumentException(\r\n \"A positive range length is required: \" + range);\r\n }\r\n if (turnOffAutoRange) {\r\n this.autoRange = false;\r\n }\r\n this.range = range;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n\r\n /**\r\n * Sets the range for the axis and sends a change event to all registered \r\n * listeners. As a side-effect, the auto-range flag is set to\r\n * false.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n *\r\n * @see #getRange()\r\n * @see #setRange(Range)\r\n */\r\n public void setRange(double lower, double upper) {\r\n setRange(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the range for the axis (after first adding the current margins to\r\n * the specified range) and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *\r\n * @param range the range (null not permitted).\r\n */\r\n public void setRangeWithMargins(Range range) {\r\n setRangeWithMargins(range, true, true);\r\n }\r\n\r\n /**\r\n * Sets the range for the axis after first adding the current margins to\r\n * the range and, if requested, sends an {@link AxisChangeEvent} to all\r\n * registered listeners. As a side-effect, the auto-range flag is set to\r\n * false (optional).\r\n *\r\n * @param range the range (excluding margins, null not\r\n * permitted).\r\n * @param turnOffAutoRange a flag that controls whether or not the auto\r\n * range is turned off.\r\n * @param notify a flag that controls whether or not listeners are\r\n * notified.\r\n */\r\n public void setRangeWithMargins(Range range, boolean turnOffAutoRange,\r\n boolean notify) {\r\n ParamChecks.nullNotPermitted(range, \"range\");\r\n setRange(Range.expand(range, getLowerMargin(), getUpperMargin()),\r\n turnOffAutoRange, notify);\r\n }\r\n\r\n /**\r\n * Sets the axis range (after first adding the current margins to the\r\n * range) and sends an {@link AxisChangeEvent} to all registered listeners.\r\n * As a side-effect, the auto-range flag is set to false.\r\n *\r\n * @param lower the lower axis limit.\r\n * @param upper the upper axis limit.\r\n */\r\n public void setRangeWithMargins(double lower, double upper) {\r\n setRangeWithMargins(new Range(lower, upper));\r\n }\r\n\r\n /**\r\n * Sets the axis range, where the new range is 'size' in length, and\r\n * centered on 'value'.\r\n *\r\n * @param value the central value.\r\n * @param length the range length.\r\n */\r\n public void setRangeAboutValue(double value, double length) {\r\n setRange(new Range(value - length / 2, value + length / 2));\r\n }\r\n\r\n /**\r\n * Returns a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @return A flag indicating whether or not the tick unit is automatically\r\n * selected.\r\n *\r\n * @see #setAutoTickUnitSelection(boolean)\r\n */\r\n public boolean isAutoTickUnitSelection() {\r\n return this.autoTickUnitSelection;\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units. If the flag is changed,\r\n * registered listeners are notified that the chart has changed.\r\n *\r\n * @param flag the new value of the flag.\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag) {\r\n setAutoTickUnitSelection(flag, true);\r\n }\r\n\r\n /**\r\n * Sets a flag indicating whether or not the tick unit is automatically\r\n * selected from a range of standard tick units.\r\n *\r\n * @param flag the new value of the flag.\r\n * @param notify notify listeners?\r\n *\r\n * @see #isAutoTickUnitSelection()\r\n */\r\n public void setAutoTickUnitSelection(boolean flag, boolean notify) {\r\n\r\n if (this.autoTickUnitSelection != flag) {\r\n this.autoTickUnitSelection = flag;\r\n if (notify) {\r\n fireChangeEvent();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the source for obtaining standard tick units for the axis.\r\n *\r\n * @return The source (possibly null).\r\n *\r\n * @see #setStandardTickUnits(TickUnitSource)\r\n */\r\n public TickUnitSource getStandardTickUnits() {\r\n return this.standardTickUnits;\r\n }\r\n\r\n /**\r\n * Sets the source for obtaining standard tick units for the axis and sends\r\n * an {@link AxisChangeEvent} to all registered listeners. The axis will\r\n * try to select the smallest tick unit from the source that does not cause\r\n * the tick labels to overlap (see also the\r\n * {@link #setAutoTickUnitSelection(boolean)} method.\r\n *\r\n * @param source the source for standard tick units (null\r\n * permitted).\r\n *\r\n * @see #getStandardTickUnits()\r\n */\r\n public void setStandardTickUnits(TickUnitSource source) {\r\n this.standardTickUnits = source;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Returns the number of minor tick marks to display.\r\n *\r\n * @return The number of minor tick marks to display.\r\n *\r\n * @see #setMinorTickCount(int)\r\n *\r\n * @since 1.0.12\r\n */\r\n public int getMinorTickCount() {\r\n return this.minorTickCount;\r\n }\r\n\r\n /**\r\n * Sets the number of minor tick marks to display, and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param count the count.\r\n *\r\n * @see #getMinorTickCount()\r\n *\r\n * @since 1.0.12\r\n */\r\n public void setMinorTickCount(int count) {\r\n this.minorTickCount = count;\r\n fireChangeEvent();\r\n }\r\n\r\n /**\r\n * Converts a data value to a coordinate in Java2D space, assuming that the\r\n * axis runs along one edge of the specified dataArea.\r\n *

\r\n * Note that it is possible for the coordinate to fall outside the area.\r\n *\r\n * @param value the data value.\r\n * @param area the area for plotting the data.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The Java2D coordinate.\r\n *\r\n * @see #java2DToValue(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double valueToJava2D(double value, Rectangle2D area,\r\n RectangleEdge edge);\r\n\r\n /**\r\n * Converts a length in data coordinates into the corresponding length in\r\n * Java2D coordinates.\r\n *\r\n * @param length the length.\r\n * @param area the plot area.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The length in Java2D coordinates.\r\n */\r\n public double lengthToJava2D(double length, Rectangle2D area,\r\n RectangleEdge edge) {\r\n double zero = valueToJava2D(0.0, area, edge);\r\n double l = valueToJava2D(length, area, edge);\r\n return Math.abs(l - zero);\r\n }\r\n\r\n /**\r\n * Converts a coordinate in Java2D space to the corresponding data value,\r\n * assuming that the axis runs along one edge of the specified dataArea.\r\n *\r\n * @param java2DValue the coordinate in Java2D space.\r\n * @param area the area in which the data is plotted.\r\n * @param edge the edge along which the axis lies.\r\n *\r\n * @return The data value.\r\n *\r\n * @see #valueToJava2D(double, Rectangle2D, RectangleEdge)\r\n */\r\n public abstract double java2DToValue(double java2DValue, Rectangle2D area, \r\n RectangleEdge edge);\r\n\r\n /**\r\n * Automatically sets the axis range to fit the range of values in the\r\n * dataset. Sometimes this can depend on the renderer used as well (for\r\n * example, the renderer may \"stack\" values, requiring an axis range\r\n * greater than otherwise necessary).\r\n */\r\n protected abstract void autoAdjustRange();\r\n\r\n /**\r\n * Centers the axis range about the specified value and sends an\r\n * {@link AxisChangeEvent} to all registered listeners.\r\n *\r\n * @param value the center value.\r\n */\r\n public void centerRange(double value) {\r\n double central = this.range.getCentralValue();\r\n Range adjusted = new Range(this.range.getLowerBound() + value - central,\r\n this.range.getUpperBound() + value - central);\r\n setRange(adjusted);\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the central value and sends an {@link AxisChangeEvent} to all registered\r\n * listeners.\r\n *

\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n *\r\n * @see #resizeRange(double, double)\r\n */\r\n public void resizeRange(double percent) {\r\n resizeRange(percent, this.range.getCentralValue());\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *

\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n */\r\n public void resizeRange(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double halfLength = this.range.getLength() * percent / 2;\r\n Range adjusted = new Range(anchorValue - halfLength,\r\n anchorValue + halfLength);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Increases or decreases the axis range by the specified percentage about\r\n * the specified anchor value and sends an {@link AxisChangeEvent} to all\r\n * registered listeners.\r\n *

\r\n * To double the length of the axis range, use 200% (2.0).\r\n * To halve the length of the axis range, use 50% (0.5).\r\n *\r\n * @param percent the resize factor.\r\n * @param anchorValue the new central value after the resize.\r\n *\r\n * @see #resizeRange(double)\r\n *\r\n * @since 1.0.13\r\n */\r\n public void resizeRange2(double percent, double anchorValue) {\r\n if (percent > 0.0) {\r\n double left = anchorValue - getLowerBound();\r\n double right = getUpperBound() - anchorValue;\r\n Range adjusted = new Range(anchorValue - left * percent,\r\n anchorValue + right * percent);\r\n setRange(adjusted);\r\n }\r\n else {\r\n setAutoRange(true);\r\n }\r\n }\r\n\r\n /**\r\n * Zooms in on the current range.\r\n *\r\n * @param lowerPercent the new lower bound.\r\n * @param upperPercent the new upper bound.\r\n */\r\n public void zoomRange(double lowerPercent, double upperPercent) {\r\n double start = this.range.getLowerBound();\r\n double length = this.range.getLength();\r\n double r0, r1;\r\n if (isInverted()) {\r\n r0 = start + (length * (1 - upperPercent));\r\n r1 = start + (length * (1 - lowerPercent));\r\n }\r\n else {\r\n r0 = start + length * lowerPercent;\r\n r1 = start + length * upperPercent;\r\n }\r\n if ((r1 > r0) && !Double.isInfinite(r1 - r0)) {\r\n setRange(new Range(r0, r1));\r\n }\r\n }\r\n\r\n /**\r\n * Slides the axis range by the specified percentage.\r\n *\r\n * @param percent the percentage.\r\n *\r\n * @since 1.0.13\r\n */\r\n public void pan(double percent) {\r\n Range r = getRange();\r\n double length = range.getLength();\r\n double adj = length * percent;\r\n double lower = r.getLowerBound() + adj;\r\n double upper = r.getUpperBound() + adj;\r\n setRange(lower, upper);\r\n }\r\n\r\n /**\r\n * Returns the auto tick index.\r\n *\r\n * @return The auto tick index.\r\n *\r\n * @see #setAutoTickIndex(int)\r\n */\r\n protected int getAutoTickIndex() {\r\n return this.autoTickIndex;\r\n }\r\n\r\n /**\r\n * Sets the auto tick index.\r\n *\r\n * @param index the new value.\r\n *\r\n * @see #getAutoTickIndex()\r\n */\r\n protected void setAutoTickIndex(int index) {\r\n this.autoTickIndex = index;\r\n }\r\n\r\n /**\r\n * Tests the axis for equality with an arbitrary object.\r\n *\r\n * @param obj the object (null permitted).\r\n *\r\n * @return true or false.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof ValueAxis)) {\r\n return false;\r\n }\r\n ValueAxis that = (ValueAxis) obj;\r\n if (this.positiveArrowVisible != that.positiveArrowVisible) {\r\n return false;\r\n }\r\n if (this.negativeArrowVisible != that.negativeArrowVisible) {\r\n return false;\r\n }\r\n if (this.inverted != that.inverted) {\r\n return false;\r\n }\r\n // if autoRange is true, then the current range is irrelevant\r\n if (!this.autoRange && !ObjectUtilities.equal(this.range, that.range)) {\r\n return false;\r\n }\r\n if (this.autoRange != that.autoRange) {\r\n return false;\r\n }\r\n if (this.autoRangeMinimumSize != that.autoRangeMinimumSize) {\r\n return false;\r\n }\r\n if (!this.defaultAutoRange.equals(that.defaultAutoRange)) {\r\n return false;\r\n }\r\n if (this.upperMargin != that.upperMargin) {\r\n return false;\r\n }\r\n if (this.lowerMargin != that.lowerMargin) {\r\n return false;\r\n }\r\n if (this.fixedAutoRange != that.fixedAutoRange) {\r\n return false;\r\n }\r\n if (this.autoTickUnitSelection != that.autoTickUnitSelection) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.standardTickUnits,\r\n that.standardTickUnits)) {\r\n return false;\r\n }\r\n if (this.verticalTickLabels != that.verticalTickLabels) {\r\n return false;\r\n }\r\n if (this.minorTickCount != that.minorTickCount) {\r\n return false;\r\n }\r\n return super.equals(obj);\r\n }\r\n\r\n /**\r\n * Returns a clone of the object.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if some component of the axis does\r\n * not support cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n ValueAxis clone = (ValueAxis) super.clone();\r\n return clone;\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the output stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n */\r\n private void writeObject(ObjectOutputStream stream) throws IOException {\r\n stream.defaultWriteObject();\r\n SerialUtilities.writeShape(this.upArrow, stream);\r\n SerialUtilities.writeShape(this.downArrow, stream);\r\n SerialUtilities.writeShape(this.leftArrow, stream);\r\n SerialUtilities.writeShape(this.rightArrow, stream);\r\n }\r\n\r\n /**\r\n * Provides serialization support.\r\n *\r\n * @param stream the input stream.\r\n *\r\n * @throws IOException if there is an I/O error.\r\n * @throws ClassNotFoundException if there is a classpath problem.\r\n */\r\n private void readObject(ObjectInputStream stream)\r\n throws IOException, ClassNotFoundException {\r\n\r\n stream.defaultReadObject();\r\n this.upArrow = SerialUtilities.readShape(stream);\r\n this.downArrow = SerialUtilities.readShape(stream);\r\n this.leftArrow = SerialUtilities.readShape(stream);\r\n this.rightArrow = SerialUtilities.readShape(stream);\r\n }\r\n\r\n}\r", "answers": [" private int gap = DEFAULT_GAP;\r"], "length": 9119, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "71b745b8-56d1-4a8c-928a-72c1cb076f0f", "reasoning": "The comment just before the placeholder describes the gap between the two outlines that represent the thermometer. In the ThermometerPlot class, after defining the static DEFAULT_GAP constant, the next logical line declares the instance variable that holds the actual gap value, initializing it with the default. Therefore the next line is the declaration of the gap field.", "reasoning_model_answer": "private int gap = DEFAULT_GAP;", "assistant_with_reasoning": "\nThe comment just before the placeholder describes the gap between the two outlines that represent the thermometer. In the ThermometerPlot class, after defining the static DEFAULT_GAP constant, the next logical line declares the instance variable that holds the actual gap value, initializing it with the default. Therefore the next line is the declaration of the gap field.\n\nprivate int gap = DEFAULT_GAP;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.589, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37333, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private int gap = DEFAULT_GAP;", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import json\nimport pytest\nimport torch\nimport torch.nn.functional as F\nfrom mmengine.utils import digit_version\nfrom mmdet.models.losses import (BalancedL1Loss, CrossEntropyLoss, DDQAuxLoss,\n DiceLoss, DistributionFocalLoss, EQLV2Loss,\n FocalLoss, GaussianFocalLoss,\n KnowledgeDistillationKLDivLoss, L1Loss,\n MarginL2Loss, MSELoss, QualityFocalLoss,\n SeesawLoss, SmoothL1Loss, VarifocalLoss)\nfrom mmdet.models.losses.ghm_loss import GHMC, GHMR\nfrom mmdet.models.losses.iou_loss import (BoundedIoULoss, CIoULoss, DIoULoss,\n EIoULoss, GIoULoss, IoULoss,\n SIoULoss)", "context": "tests/test_models/test_losses/test_loss.py\n# Copyright (c) OpenMMLab. All rights reserved.\n\n\n\n\n@pytest.mark.parametrize('loss_class', [\n IoULoss, BoundedIoULoss, GIoULoss, DIoULoss, CIoULoss, EIoULoss, SIoULoss\n])\ndef test_iou_type_loss_zeros_weight(loss_class):\n pred = torch.rand((10, 4))\n target = torch.rand((10, 4))\n weight = torch.zeros(10)\n\n loss = loss_class()(pred, target, weight)\n assert loss == 0.\n\n\n\n\nmmdet/models/losses/kd_loss.py\nclass KnowledgeDistillationKLDivLoss(nn.Module):\n \"\"\"Loss function for knowledge distilling using KL divergence.\n\n Args:\n reduction (str): Options are `'none'`, `'mean'` and `'sum'`.\n loss_weight (float): Loss weight of current loss.\n T (int): Temperature for distillation.\n \"\"\"\n\n def __init__(self,\n reduction: str = 'mean',\n loss_weight: float = 1.0,\n T: int = 10) -> None:\n super().__init__()\n assert T >= 1\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.T = T\n\n def forward(self,\n pred: Tensor,\n soft_label: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): Predicted logits with shape (N, n + 1).\n soft_label (Tensor): Target logits with shape (N, N + 1).\n weight (Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n\n Returns:\n Tensor: Loss tensor.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n\n reduction = (\n reduction_override if reduction_override else self.reduction)\n\n loss_kd = self.loss_weight * knowledge_distillation_kl_div_loss(\n pred,\n soft_label,\n weight,\n reduction=reduction,\n avg_factor=avg_factor,\n T=self.T)\n\n return loss_kd\n\nmmdet/models/losses/smooth_l1_loss.py\nclass L1Loss(nn.Module):\n \"\"\"L1 loss.\n\n Args:\n reduction (str, optional): The method to reduce the loss.\n Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float, optional): The weight of loss.\n \"\"\"\n\n def __init__(self,\n reduction: str = 'mean',\n loss_weight: float = 1.0) -> None:\n super().__init__()\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): The prediction.\n target (Tensor): The learning target of the prediction.\n weight (Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n\n Returns:\n Tensor: Calculated loss\n \"\"\"\n if weight is not None and not torch.any(weight > 0):\n if pred.dim() == weight.dim() + 1:\n weight = weight.unsqueeze(1)\n return (pred * weight).sum()\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n loss_bbox = self.loss_weight * l1_loss(\n pred, target, weight, reduction=reduction, avg_factor=avg_factor)\n return loss_bbox\n\nmmdet/models/losses/smooth_l1_loss.py\nclass SmoothL1Loss(nn.Module):\n \"\"\"Smooth L1 loss.\n\n Args:\n beta (float, optional): The threshold in the piecewise function.\n Defaults to 1.0.\n reduction (str, optional): The method to reduce the loss.\n Options are \"none\", \"mean\" and \"sum\". Defaults to \"mean\".\n loss_weight (float, optional): The weight of loss.\n \"\"\"\n\n def __init__(self,\n beta: float = 1.0,\n reduction: str = 'mean',\n loss_weight: float = 1.0) -> None:\n super().__init__()\n self.beta = beta\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None,\n **kwargs) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): The prediction.\n target (Tensor): The learning target of the prediction.\n weight (Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n\n Returns:\n Tensor: Calculated loss\n \"\"\"\n if weight is not None and not torch.any(weight > 0):\n if pred.dim() == weight.dim() + 1:\n weight = weight.unsqueeze(1)\n return (pred * weight).sum()\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n loss_bbox = self.loss_weight * smooth_l1_loss(\n pred,\n target,\n weight,\n beta=self.beta,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss_bbox\n\nmmdet/models/losses/iou_loss.py\nclass EIoULoss(nn.Module):\n r\"\"\"Implementation of paper `Extended-IoU Loss: A Systematic\n IoU-Related Method: Beyond Simplified Regression for Better\n Localization `_\n\n Code is modified from https://github.com//ShiqiYu/libfacedetection.train.\n\n Args:\n eps (float): Epsilon to avoid log(0).\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float): Weight of loss.\n smooth_point (float): hyperparameter, default is 0.1.\n \"\"\"\n\n def __init__(self,\n eps: float = 1e-6,\n reduction: str = 'mean',\n loss_weight: float = 1.0,\n smooth_point: float = 0.1) -> None:\n super().__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.smooth_point = smooth_point\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None,\n **kwargs) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): The learning target of the prediction,\n shape (n, 4).\n weight (Optional[Tensor], optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (Optional[int], optional): Average factor that is used\n to average the loss. Defaults to None.\n reduction_override (Optional[str], optional): The reduction method\n used to override the original reduction method of the loss.\n Defaults to None. Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor: Loss tensor.\n \"\"\"\n if weight is not None and not torch.any(weight > 0):\n if pred.dim() == weight.dim() + 1:\n weight = weight.unsqueeze(1)\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if weight is not None and weight.dim() > 1:\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * eiou_loss(\n pred,\n target,\n weight,\n smooth_point=self.smooth_point,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\nmmdet/models/losses/varifocal_loss.py\nclass VarifocalLoss(nn.Module):\n\n def __init__(self,\n use_sigmoid: bool = True,\n alpha: float = 0.75,\n gamma: float = 2.0,\n iou_weighted: bool = True,\n reduction: str = 'mean',\n loss_weight: float = 1.0) -> None:\n \"\"\"`Varifocal Loss `_\n\n Args:\n use_sigmoid (bool, optional): Whether the prediction is\n used for sigmoid or softmax. Defaults to True.\n alpha (float, optional): A balance factor for the negative part of\n Varifocal Loss, which is different from the alpha of Focal\n Loss. Defaults to 0.75.\n gamma (float, optional): The gamma for calculating the modulating\n factor. Defaults to 2.0.\n iou_weighted (bool, optional): Whether to weight the loss of the\n positive examples with the iou target. Defaults to True.\n reduction (str, optional): The method used to reduce the loss into\n a scalar. Defaults to 'mean'. Options are \"none\", \"mean\" and\n \"sum\".\n loss_weight (float, optional): Weight of loss. Defaults to 1.0.\n \"\"\"\n super().__init__()\n assert use_sigmoid is True, \\\n 'Only sigmoid varifocal loss supported now.'\n assert alpha >= 0.0\n self.use_sigmoid = use_sigmoid\n self.alpha = alpha\n self.gamma = gamma\n self.iou_weighted = iou_weighted\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): The prediction with shape (N, C), C is the\n number of classes.\n target (Tensor): The learning target of the iou-aware\n classification score with shape (N, C), C is\n the number of classes.\n weight (Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor: The calculated loss\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if self.use_sigmoid:\n loss_cls = self.loss_weight * varifocal_loss(\n pred,\n target,\n weight,\n alpha=self.alpha,\n gamma=self.gamma,\n iou_weighted=self.iou_weighted,\n reduction=reduction,\n avg_factor=avg_factor)\n else:\n raise NotImplementedError\n return loss_cls\n\nmmdet/models/losses/margin_loss.py\nclass MarginL2Loss(BaseModule):\n \"\"\"L2 loss with margin.\n\n Args:\n neg_pos_ub (int, optional): The upper bound of negative to positive\n samples in hard mining. Defaults to -1.\n pos_margin (float, optional): The similarity margin for positive\n samples in hard mining. Defaults to -1.\n neg_margin (float, optional): The similarity margin for negative\n samples in hard mining. Defaults to -1.\n hard_mining (bool, optional): Whether to use hard mining. Defaults to\n False.\n reduction (str, optional): The method to reduce the loss.\n Options are \"none\", \"mean\" and \"sum\". Defaults to \"mean\".\n loss_weight (float, optional): The weight of loss. Defaults to 1.0.\n \"\"\"\n\n def __init__(self,\n neg_pos_ub: int = -1,\n pos_margin: float = -1,\n neg_margin: float = -1,\n hard_mining: bool = False,\n reduction: str = 'mean',\n loss_weight: float = 1.0):\n super(MarginL2Loss, self).__init__()\n self.neg_pos_ub = neg_pos_ub\n self.pos_margin = pos_margin\n self.neg_margin = neg_margin\n self.hard_mining = hard_mining\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[float] = None,\n reduction_override: Optional[str] = None) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning target of the prediction.\n weight (torch.Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (float, optional): Average factor that is used to\n average the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n pred, weight, avg_factor = self.update_weight(pred, target, weight,\n avg_factor)\n loss_bbox = self.loss_weight * mse_loss(\n pred,\n target.float(),\n weight.float(),\n reduction=reduction,\n avg_factor=avg_factor)\n return loss_bbox\n\n def update_weight(self, pred: Tensor, target: Tensor, weight: Tensor,\n avg_factor: float) -> Tuple[Tensor, Tensor, float]:\n \"\"\"Update the weight according to targets.\n\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning target of the prediction.\n weight (torch.Tensor): The weight of loss for each prediction.\n avg_factor (float): Average factor that is used to average the\n loss.\n\n Returns:\n tuple[torch.Tensor]: The updated prediction, weight and average\n factor.\n \"\"\"\n if weight is None:\n weight = target.new_ones(target.size())\n\n invalid_inds = weight <= 0\n target[invalid_inds] = -1\n pos_inds = target == 1\n neg_inds = target == 0\n\n if self.pos_margin > 0:\n pred[pos_inds] -= self.pos_margin\n if self.neg_margin > 0:\n pred[neg_inds] -= self.neg_margin\n pred = torch.clamp(pred, min=0, max=1)\n\n num_pos = int((target == 1).sum())\n num_neg = int((target == 0).sum())\n if self.neg_pos_ub > 0 and num_neg / (num_pos +\n 1e-6) > self.neg_pos_ub:\n num_neg = num_pos * self.neg_pos_ub\n neg_idx = torch.nonzero(target == 0, as_tuple=False)\n\n if self.hard_mining:\n costs = mse_loss(\n pred, target.float(),\n reduction='none')[neg_idx[:, 0], neg_idx[:, 1]].detach()\n neg_idx = neg_idx[costs.topk(num_neg)[1], :]\n else:\n neg_idx = self.random_choice(neg_idx, num_neg)\n\n new_neg_inds = neg_inds.new_zeros(neg_inds.size()).bool()\n new_neg_inds[neg_idx[:, 0], neg_idx[:, 1]] = True\n\n invalid_neg_inds = torch.logical_xor(neg_inds, new_neg_inds)\n weight[invalid_neg_inds] = 0\n\n avg_factor = (weight > 0).sum()\n return pred, weight, avg_factor\n\n @staticmethod\n def random_choice(gallery: Union[list, np.ndarray, Tensor],\n num: int) -> np.ndarray:\n \"\"\"Random select some elements from the gallery.\n\n It seems that Pytorch's implementation is slower than numpy so we use\n numpy to randperm the indices.\n\n Args:\n gallery (list | np.ndarray | torch.Tensor): The gallery from\n which to sample.\n num (int): The number of elements to sample.\n \"\"\"\n assert len(gallery) >= num\n if isinstance(gallery, list):\n gallery = np.array(gallery)\n cands = np.arange(len(gallery))\n np.random.shuffle(cands)\n rand_inds = cands[:num]\n if not isinstance(gallery, np.ndarray):\n rand_inds = torch.from_numpy(rand_inds).long().to(gallery.device)\n return gallery[rand_inds]\n\nmmdet/models/losses/eqlv2_loss.py\nclass EQLV2Loss(nn.Module):\n\n def __init__(self,\n use_sigmoid: bool = True,\n reduction: str = 'mean',\n class_weight: Optional[Tensor] = None,\n loss_weight: float = 1.0,\n num_classes: int = 1203,\n use_distributed: bool = False,\n mu: float = 0.8,\n alpha: float = 4.0,\n gamma: int = 12,\n vis_grad: bool = False,\n test_with_obj: bool = True) -> None:\n \"\"\"`Equalization Loss v2 `_\n\n Args:\n use_sigmoid (bool): EQLv2 uses the sigmoid function to transform\n the predicted logits to an estimated probability distribution.\n reduction (str, optional): The method used to reduce the loss into\n a scalar. Defaults to 'mean'.\n class_weight (Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n loss_weight (float, optional): The weight of the total EQLv2 loss.\n Defaults to 1.0.\n num_classes (int): 1203 for lvis v1.0, 1230 for lvis v0.5.\n use_distributed (bool, float): EQLv2 will calculate the gradients\n on all GPUs if there is any. Change to True if you are using\n distributed training. Default to False.\n mu (float, optional): Defaults to 0.8\n alpha (float, optional): A balance factor for the negative part of\n EQLV2 Loss. Defaults to 4.0.\n gamma (int, optional): The gamma for calculating the modulating\n factor. Defaults to 12.\n vis_grad (bool, optional): Default to False.\n test_with_obj (bool, optional): Default to True.\n\n Returns:\n None.\n \"\"\"\n super().__init__()\n self.use_sigmoid = True\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.class_weight = class_weight\n self.num_classes = num_classes\n self.group = True\n\n # cfg for eqlv2\n self.vis_grad = vis_grad\n self.mu = mu\n self.alpha = alpha\n self.gamma = gamma\n self.use_distributed = use_distributed\n\n # initial variables\n self.register_buffer('pos_grad', torch.zeros(self.num_classes))\n self.register_buffer('neg_grad', torch.zeros(self.num_classes))\n # At the beginning of training, we set a high value (eg. 100)\n # for the initial gradient ratio so that the weight for pos\n # gradients and neg gradients are 1.\n self.register_buffer('pos_neg', torch.ones(self.num_classes) * 100)\n\n self.test_with_obj = test_with_obj\n\n def _func(x, gamma, mu):\n return 1 / (1 + torch.exp(-gamma * (x - mu)))\n\n self.map_func = partial(_func, gamma=self.gamma, mu=self.mu)\n\n print_log(\n f'build EQL v2, gamma: {gamma}, mu: {mu}, alpha: {alpha}',\n logger='current',\n level=logging.DEBUG)\n\n def forward(self,\n cls_score: Tensor,\n label: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[Tensor] = None) -> Tensor:\n \"\"\"`Equalization Loss v2 `_\n\n Args:\n cls_score (Tensor): The prediction with shape (N, C), C is the\n number of classes.\n label (Tensor): The ground truth label of the predicted target with\n shape (N, C), C is the number of classes.\n weight (Tensor, optional): The weight of loss for each prediction.\n Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor: The calculated loss\n \"\"\"\n self.n_i, self.n_c = cls_score.size()\n self.gt_classes = label\n self.pred_class_logits = cls_score\n\n def expand_label(pred, gt_classes):\n target = pred.new_zeros(self.n_i, self.n_c)\n target[torch.arange(self.n_i), gt_classes] = 1\n return target\n\n target = expand_label(cls_score, label)\n\n pos_w, neg_w = self.get_weight(cls_score)\n\n weight = pos_w * target + neg_w * (1 - target)\n\n cls_loss = F.binary_cross_entropy_with_logits(\n cls_score, target, reduction='none')\n cls_loss = torch.sum(cls_loss * weight) / self.n_i\n\n self.collect_grad(cls_score.detach(), target.detach(), weight.detach())\n\n return self.loss_weight * cls_loss\n\n def get_channel_num(self, num_classes):\n num_channel = num_classes + 1\n return num_channel\n\n def get_activation(self, pred):\n pred = torch.sigmoid(pred)\n n_i, n_c = pred.size()\n bg_score = pred[:, -1].view(n_i, 1)\n if self.test_with_obj:\n pred[:, :-1] *= (1 - bg_score)\n return pred\n\n def collect_grad(self, pred, target, weight):\n prob = torch.sigmoid(pred)\n grad = target * (prob - 1) + (1 - target) * prob\n grad = torch.abs(grad)\n\n # do not collect grad for objectiveness branch [:-1]\n pos_grad = torch.sum(grad * target * weight, dim=0)[:-1]\n neg_grad = torch.sum(grad * (1 - target) * weight, dim=0)[:-1]\n\n if self.use_distributed:\n dist.all_reduce(pos_grad)\n dist.all_reduce(neg_grad)\n\n self.pos_grad += pos_grad\n self.neg_grad += neg_grad\n self.pos_neg = self.pos_grad / (self.neg_grad + 1e-10)\n\n def get_weight(self, pred):\n neg_w = torch.cat([self.map_func(self.pos_neg), pred.new_ones(1)])\n pos_w = 1 + self.alpha * (1 - neg_w)\n neg_w = neg_w.view(1, -1).expand(self.n_i, self.n_c)\n pos_w = pos_w.view(1, -1).expand(self.n_i, self.n_c)\n return pos_w, neg_w\n\nmmdet/models/losses/dice_loss.py\nclass DiceLoss(nn.Module):\n\n def __init__(self,\n use_sigmoid=True,\n activate=True,\n reduction='mean',\n naive_dice=False,\n loss_weight=1.0,\n eps=1e-3):\n \"\"\"Compute dice loss.\n\n Args:\n use_sigmoid (bool, optional): Whether to the prediction is\n used for sigmoid or softmax. Defaults to True.\n activate (bool): Whether to activate the predictions inside,\n this will disable the inside sigmoid operation.\n Defaults to True.\n reduction (str, optional): The method used\n to reduce the loss. Options are \"none\",\n \"mean\" and \"sum\". Defaults to 'mean'.\n naive_dice (bool, optional): If false, use the dice\n loss defined in the V-Net paper, otherwise, use the\n naive dice loss in which the power of the number in the\n denominator is the first power instead of the second\n power. Defaults to False.\n loss_weight (float, optional): Weight of loss. Defaults to 1.0.\n eps (float): Avoid dividing by zero. Defaults to 1e-3.\n \"\"\"\n\n super(DiceLoss, self).__init__()\n self.use_sigmoid = use_sigmoid\n self.reduction = reduction\n self.naive_dice = naive_dice\n self.loss_weight = loss_weight\n self.eps = eps\n self.activate = activate\n\n def forward(self,\n pred,\n target,\n weight=None,\n reduction_override=None,\n avg_factor=None):\n \"\"\"Forward function.\n\n Args:\n pred (torch.Tensor): The prediction, has a shape (n, *).\n target (torch.Tensor): The label of the prediction,\n shape (n, *), same shape of pred.\n weight (torch.Tensor, optional): The weight of loss for each\n prediction, has a shape (n,). Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n torch.Tensor: The calculated loss\n \"\"\"\n\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n\n if self.activate:\n if self.use_sigmoid:\n pred = pred.sigmoid()\n else:\n raise NotImplementedError\n\n loss = self.loss_weight * dice_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n naive_dice=self.naive_dice,\n avg_factor=avg_factor)\n\n return loss\n\nmmdet/models/losses/ddq_detr_aux_loss.py\nclass DDQAuxLoss(nn.Module):\n \"\"\"DDQ auxiliary branches loss for dense queries.\n\n Args:\n loss_cls (dict):\n Configuration of classification loss function.\n loss_bbox (dict):\n Configuration of bbox regression loss function.\n train_cfg (dict):\n Configuration of gt targets assigner for each predicted bbox.\n \"\"\"\n\n def __init__(\n self,\n loss_cls=dict(\n type='QualityFocalLoss',\n use_sigmoid=True,\n activated=True, # use probability instead of logit as input\n beta=2.0,\n loss_weight=1.0),\n loss_bbox=dict(type='GIoULoss', loss_weight=2.0),\n train_cfg=dict(\n assigner=dict(type='TopkHungarianAssigner', topk=8),\n alpha=1,\n beta=6),\n ):\n super(DDQAuxLoss, self).__init__()\n self.train_cfg = train_cfg\n self.loss_cls = MODELS.build(loss_cls)\n self.loss_bbox = MODELS.build(loss_bbox)\n self.assigner = TASK_UTILS.build(self.train_cfg['assigner'])\n\n sampler_cfg = dict(type='PseudoSampler')\n self.sampler = TASK_UTILS.build(sampler_cfg)\n\n def loss_single(self, cls_score, bbox_pred, labels, label_weights,\n bbox_targets, alignment_metrics):\n \"\"\"Calculate auxiliary branches loss for dense queries for one image.\n\n Args:\n cls_score (Tensor): Predicted normalized classification\n scores for one image, has shape (num_dense_queries,\n cls_out_channels).\n bbox_pred (Tensor): Predicted unnormalized bbox coordinates\n for one image, has shape (num_dense_queries, 4) with the\n last dimension arranged as (x1, y1, x2, y2).\n labels (Tensor): Labels for one image.\n label_weights (Tensor): Label weights for one image.\n bbox_targets (Tensor): Bbox targets for one image.\n alignment_metrics (Tensor): Normalized alignment metrics for one\n image.\n\n Returns:\n tuple: A tuple of loss components and loss weights.\n \"\"\"\n bbox_targets = bbox_targets.reshape(-1, 4)\n labels = labels.reshape(-1)\n alignment_metrics = alignment_metrics.reshape(-1)\n label_weights = label_weights.reshape(-1)\n targets = (labels, alignment_metrics)\n cls_loss_func = self.loss_cls\n\n loss_cls = cls_loss_func(\n cls_score, targets, label_weights, avg_factor=1.0)\n\n # FG cat_id: [0, num_classes -1], BG cat_id: num_classes\n bg_class_ind = cls_score.size(-1)\n pos_inds = ((labels >= 0)\n & (labels < bg_class_ind)).nonzero().squeeze(1)\n\n if len(pos_inds) > 0:\n pos_bbox_targets = bbox_targets[pos_inds]\n pos_bbox_pred = bbox_pred[pos_inds]\n\n pos_decode_bbox_pred = pos_bbox_pred\n pos_decode_bbox_targets = pos_bbox_targets\n\n # regression loss\n pos_bbox_weight = alignment_metrics[pos_inds]\n\n loss_bbox = self.loss_bbox(\n pos_decode_bbox_pred,\n pos_decode_bbox_targets,\n weight=pos_bbox_weight,\n avg_factor=1.0)\n else:\n loss_bbox = bbox_pred.sum() * 0\n pos_bbox_weight = bbox_targets.new_tensor(0.)\n\n return loss_cls, loss_bbox, alignment_metrics.sum(\n ), pos_bbox_weight.sum()\n\n def loss(self, cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas,\n **kwargs):\n \"\"\"Calculate auxiliary branches loss for dense queries.\n\n Args:\n cls_scores (Tensor): Predicted normalized classification\n scores, has shape (bs, num_dense_queries,\n cls_out_channels).\n bbox_preds (Tensor): Predicted unnormalized bbox coordinates,\n has shape (bs, num_dense_queries, 4) with the last\n dimension arranged as (x1, y1, x2, y2).\n gt_bboxes (list[Tensor]): List of unnormalized ground truth\n bboxes for each image, each has shape (num_gt, 4) with the\n last dimension arranged as (x1, y1, x2, y2).\n NOTE: num_gt is dynamic for each image.\n gt_labels (list[Tensor]): List of ground truth classification\n index for each image, each has shape (num_gt,).\n NOTE: num_gt is dynamic for each image.\n img_metas (list[dict]): Meta information for one image,\n e.g., image size, scaling factor, etc.\n\n Returns:\n dict: A dictionary of loss components.\n \"\"\"\n flatten_cls_scores = cls_scores\n flatten_bbox_preds = bbox_preds\n\n cls_reg_targets = self.get_targets(\n flatten_cls_scores,\n flatten_bbox_preds,\n gt_bboxes,\n img_metas,\n gt_labels_list=gt_labels,\n )\n (labels_list, label_weights_list, bbox_targets_list,\n alignment_metrics_list) = cls_reg_targets\n\n losses_cls, losses_bbox, \\\n cls_avg_factors, bbox_avg_factors = multi_apply(\n self.loss_single,\n flatten_cls_scores,\n flatten_bbox_preds,\n labels_list,\n label_weights_list,\n bbox_targets_list,\n alignment_metrics_list,\n )\n\n cls_avg_factor = reduce_mean(sum(cls_avg_factors)).clamp_(min=1).item()\n losses_cls = list(map(lambda x: x / cls_avg_factor, losses_cls))\n\n bbox_avg_factor = reduce_mean(\n sum(bbox_avg_factors)).clamp_(min=1).item()\n losses_bbox = list(map(lambda x: x / bbox_avg_factor, losses_bbox))\n return dict(aux_loss_cls=losses_cls, aux_loss_bbox=losses_bbox)\n\n def get_targets(self,\n cls_scores,\n bbox_preds,\n gt_bboxes_list,\n img_metas,\n gt_labels_list=None,\n **kwargs):\n \"\"\"Compute regression and classification targets for a batch images.\n\n Args:\n cls_scores (Tensor): Predicted normalized classification\n scores, has shape (bs, num_dense_queries,\n cls_out_channels).\n bbox_preds (Tensor): Predicted unnormalized bbox coordinates,\n has shape (bs, num_dense_queries, 4) with the last\n dimension arranged as (x1, y1, x2, y2).\n gt_bboxes_list (List[Tensor]): List of unnormalized ground truth\n bboxes for each image, each has shape (num_gt, 4) with the\n last dimension arranged as (x1, y1, x2, y2).\n NOTE: num_gt is dynamic for each image.\n img_metas (list[dict]): Meta information for one image,\n e.g., image size, scaling factor, etc.\n gt_labels_list (list[Tensor]): List of ground truth classification\n index for each image, each has shape (num_gt,).\n NOTE: num_gt is dynamic for each image.\n Default: None.\n\n Returns:\n tuple: a tuple containing the following targets.\n\n - all_labels (list[Tensor]): Labels for all images.\n - all_label_weights (list[Tensor]): Label weights for all images.\n - all_bbox_targets (list[Tensor]): Bbox targets for all images.\n - all_assign_metrics (list[Tensor]): Normalized alignment metrics\n for all images.\n \"\"\"\n (all_labels, all_label_weights, all_bbox_targets,\n all_assign_metrics) = multi_apply(self._get_target_single, cls_scores,\n bbox_preds, gt_bboxes_list,\n gt_labels_list, img_metas)\n\n return (all_labels, all_label_weights, all_bbox_targets,\n all_assign_metrics)\n\n def _get_target_single(self, cls_scores, bbox_preds, gt_bboxes, gt_labels,\n img_meta, **kwargs):\n \"\"\"Compute regression and classification targets for one image.\n\n Args:\n cls_scores (Tensor): Predicted normalized classification\n scores for one image, has shape (num_dense_queries,\n cls_out_channels).\n bbox_preds (Tensor): Predicted unnormalized bbox coordinates\n for one image, has shape (num_dense_queries, 4) with the\n last dimension arranged as (x1, y1, x2, y2).\n gt_bboxes (Tensor): Unnormalized ground truth\n bboxes for one image, has shape (num_gt, 4) with the\n last dimension arranged as (x1, y1, x2, y2).\n NOTE: num_gt is dynamic for each image.\n gt_labels (Tensor): Ground truth classification\n index for the image, has shape (num_gt,).\n NOTE: num_gt is dynamic for each image.\n img_meta (dict): Meta information for one image.\n\n Returns:\n tuple[Tensor]: a tuple containing the following for one image.\n\n - labels (Tensor): Labels for one image.\n - label_weights (Tensor): Label weights for one image.\n - bbox_targets (Tensor): Bbox targets for one image.\n - norm_alignment_metrics (Tensor): Normalized alignment\n metrics for one image.\n \"\"\"\n if len(gt_labels) == 0:\n num_valid_anchors = len(cls_scores)\n bbox_targets = torch.zeros_like(bbox_preds)\n labels = bbox_preds.new_full((num_valid_anchors, ),\n cls_scores.size(-1),\n dtype=torch.long)\n label_weights = bbox_preds.new_zeros(\n num_valid_anchors, dtype=torch.float)\n norm_alignment_metrics = bbox_preds.new_zeros(\n num_valid_anchors, dtype=torch.float)\n return (labels, label_weights, bbox_targets,\n norm_alignment_metrics)\n\n assign_result = self.assigner.assign(cls_scores, bbox_preds, gt_bboxes,\n gt_labels, img_meta)\n assign_ious = assign_result.max_overlaps\n assign_metrics = assign_result.assign_metrics\n\n pred_instances = BaseDataElement()\n gt_instances = BaseDataElement()\n\n pred_instances.bboxes = bbox_preds\n gt_instances.bboxes = gt_bboxes\n\n pred_instances.priors = cls_scores\n gt_instances.labels = gt_labels\n\n sampling_result = self.sampler.sample(assign_result, pred_instances,\n gt_instances)\n\n num_valid_anchors = len(cls_scores)\n bbox_targets = torch.zeros_like(bbox_preds)\n labels = bbox_preds.new_full((num_valid_anchors, ),\n cls_scores.size(-1),\n dtype=torch.long)\n label_weights = bbox_preds.new_zeros(\n num_valid_anchors, dtype=torch.float)\n norm_alignment_metrics = bbox_preds.new_zeros(\n num_valid_anchors, dtype=torch.float)\n\n pos_inds = sampling_result.pos_inds\n neg_inds = sampling_result.neg_inds\n if len(pos_inds) > 0:\n # point-based\n pos_bbox_targets = sampling_result.pos_gt_bboxes\n bbox_targets[pos_inds, :] = pos_bbox_targets\n\n if gt_labels is None:\n # Only dense_heads gives gt_labels as None\n # Foreground is the first class since v2.5.0\n labels[pos_inds] = 0\n else:\n labels[pos_inds] = gt_labels[\n sampling_result.pos_assigned_gt_inds]\n\n label_weights[pos_inds] = 1.0\n\n if len(neg_inds) > 0:\n label_weights[neg_inds] = 1.0\n\n class_assigned_gt_inds = torch.unique(\n sampling_result.pos_assigned_gt_inds)\n for gt_inds in class_assigned_gt_inds:\n gt_class_inds = sampling_result.pos_assigned_gt_inds == gt_inds\n pos_alignment_metrics = assign_metrics[gt_class_inds]\n pos_ious = assign_ious[gt_class_inds]\n pos_norm_alignment_metrics = pos_alignment_metrics / (\n pos_alignment_metrics.max() + 10e-8) * pos_ious.max()\n norm_alignment_metrics[\n pos_inds[gt_class_inds]] = pos_norm_alignment_metrics\n\n return (labels, label_weights, bbox_targets, norm_alignment_metrics)\n\nmmdet/models/losses/iou_loss.py\nclass SIoULoss(nn.Module):\n r\"\"\"`Implementation of paper `SIoU Loss: More Powerful Learning\n for Bounding Box Regression `_.\n\n Code is modified from https://github.com/meituan/YOLOv6.\n\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): Corresponding gt bboxes, shape (n, 4).\n eps (float): Eps to avoid log(0).\n neg_gamma (bool): `True` follows original implementation in paper.\n\n Return:\n Tensor: Loss tensor.\n \"\"\"\n\n def __init__(self,\n eps: float = 1e-6,\n reduction: str = 'mean',\n loss_weight: float = 1.0,\n neg_gamma: bool = False) -> None:\n super().__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.neg_gamma = neg_gamma\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None,\n **kwargs) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): The learning target of the prediction,\n shape (n, 4).\n weight (Optional[Tensor], optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (Optional[int], optional): Average factor that is used\n to average the loss. Defaults to None.\n reduction_override (Optional[str], optional): The reduction method\n used to override the original reduction method of the loss.\n Defaults to None. Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor: Loss tensor.\n \"\"\"\n if weight is not None and not torch.any(weight > 0):\n if pred.dim() == weight.dim() + 1:\n weight = weight.unsqueeze(1)\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if weight is not None and weight.dim() > 1:\n # TODO: remove this in the future\n # reduce the weight of shape (n, 4) to (n,) to match the\n # giou_loss of shape (n,)\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * siou_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n neg_gamma=self.neg_gamma,\n **kwargs)\n return loss\n\nmmdet/models/losses/ghm_loss.py\nclass GHMC(nn.Module):\n \"\"\"GHM Classification Loss.\n\n Details of the theorem can be viewed in the paper\n `Gradient Harmonized Single-stage Detector\n `_.\n\n Args:\n bins (int): Number of the unit regions for distribution calculation.\n momentum (float): The parameter for moving average.\n use_sigmoid (bool): Can only be true for BCE based loss now.\n loss_weight (float): The weight of the total GHM-C loss.\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n Defaults to \"mean\"\n \"\"\"\n\n def __init__(self,\n bins=10,\n momentum=0,\n use_sigmoid=True,\n loss_weight=1.0,\n reduction='mean'):\n super(GHMC, self).__init__()\n self.bins = bins\n self.momentum = momentum\n edges = torch.arange(bins + 1).float() / bins\n self.register_buffer('edges', edges)\n self.edges[-1] += 1e-6\n if momentum > 0:\n acc_sum = torch.zeros(bins)\n self.register_buffer('acc_sum', acc_sum)\n self.use_sigmoid = use_sigmoid\n if not self.use_sigmoid:\n raise NotImplementedError\n self.loss_weight = loss_weight\n self.reduction = reduction\n\n def forward(self,\n pred,\n target,\n label_weight,\n reduction_override=None,\n **kwargs):\n \"\"\"Calculate the GHM-C loss.\n\n Args:\n pred (float tensor of size [batch_num, class_num]):\n The direct prediction of classification fc layer.\n target (float tensor of size [batch_num, class_num]):\n Binary class target for each sample.\n label_weight (float tensor of size [batch_num, class_num]):\n the value is 1 if the sample is valid and 0 if ignored.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n Returns:\n The gradient harmonized loss.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n # the target should be binary class label\n if pred.dim() != target.dim():\n target, label_weight = _expand_onehot_labels(\n target, label_weight, pred.size(-1))\n target, label_weight = target.float(), label_weight.float()\n edges = self.edges\n mmt = self.momentum\n weights = torch.zeros_like(pred)\n\n # gradient length\n g = torch.abs(pred.sigmoid().detach() - target)\n\n valid = label_weight > 0\n tot = max(valid.float().sum().item(), 1.0)\n n = 0 # n valid bins\n for i in range(self.bins):\n inds = (g >= edges[i]) & (g < edges[i + 1]) & valid\n num_in_bin = inds.sum().item()\n if num_in_bin > 0:\n if mmt > 0:\n self.acc_sum[i] = mmt * self.acc_sum[i] \\\n + (1 - mmt) * num_in_bin\n weights[inds] = tot / self.acc_sum[i]\n else:\n weights[inds] = tot / num_in_bin\n n += 1\n if n > 0:\n weights = weights / n\n\n loss = F.binary_cross_entropy_with_logits(\n pred, target, reduction='none')\n loss = weight_reduce_loss(\n loss, weights, reduction=reduction, avg_factor=tot)\n return loss * self.loss_weight\n\nmmdet/models/losses/seesaw_loss.py\nclass SeesawLoss(nn.Module):\n \"\"\"\n Seesaw Loss for Long-Tailed Instance Segmentation (CVPR 2021)\n arXiv: https://arxiv.org/abs/2008.10032\n\n Args:\n use_sigmoid (bool, optional): Whether the prediction uses sigmoid\n of softmax. Only False is supported.\n p (float, optional): The ``p`` in the mitigation factor.\n Defaults to 0.8.\n q (float, optional): The ``q`` in the compenstation factor.\n Defaults to 2.0.\n num_classes (int, optional): The number of classes.\n Default to 1203 for LVIS v1 dataset.\n eps (float, optional): The minimal value of divisor to smooth\n the computation of compensation factor\n reduction (str, optional): The method that reduces the loss to a\n scalar. Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float, optional): The weight of the loss. Defaults to 1.0\n return_dict (bool, optional): Whether return the losses as a dict.\n Default to True.\n \"\"\"\n\n def __init__(self,\n use_sigmoid: bool = False,\n p: float = 0.8,\n q: float = 2.0,\n num_classes: int = 1203,\n eps: float = 1e-2,\n reduction: str = 'mean',\n loss_weight: float = 1.0,\n return_dict: bool = True) -> None:\n super().__init__()\n assert not use_sigmoid\n self.use_sigmoid = False\n self.p = p\n self.q = q\n self.num_classes = num_classes\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.return_dict = return_dict\n\n # 0 for pos, 1 for neg\n self.cls_criterion = seesaw_ce_loss\n\n # cumulative samples for each category\n self.register_buffer(\n 'cum_samples',\n torch.zeros(self.num_classes + 1, dtype=torch.float))\n\n # custom output channels of the classifier\n self.custom_cls_channels = True\n # custom activation of cls_score\n self.custom_activation = True\n # custom accuracy of the classsifier\n self.custom_accuracy = True\n\n def _split_cls_score(self, cls_score: Tensor) -> Tuple[Tensor, Tensor]:\n \"\"\"split cls_score.\n\n Args:\n cls_score (Tensor): The prediction with shape (N, C + 2).\n\n Returns:\n Tuple[Tensor, Tensor]: The score for classes and objectness,\n respectively\n \"\"\"\n # split cls_score to cls_score_classes and cls_score_objectness\n assert cls_score.size(-1) == self.num_classes + 2\n cls_score_classes = cls_score[..., :-2]\n cls_score_objectness = cls_score[..., -2:]\n return cls_score_classes, cls_score_objectness\n\n def get_cls_channels(self, num_classes: int) -> int:\n \"\"\"Get custom classification channels.\n\n Args:\n num_classes (int): The number of classes.\n\n Returns:\n int: The custom classification channels.\n \"\"\"\n assert num_classes == self.num_classes\n return num_classes + 2\n\n def get_activation(self, cls_score: Tensor) -> Tensor:\n \"\"\"Get custom activation of cls_score.\n\n Args:\n cls_score (Tensor): The prediction with shape (N, C + 2).\n\n Returns:\n Tensor: The custom activation of cls_score with shape\n (N, C + 1).\n \"\"\"\n cls_score_classes, cls_score_objectness = self._split_cls_score(\n cls_score)\n score_classes = F.softmax(cls_score_classes, dim=-1)\n score_objectness = F.softmax(cls_score_objectness, dim=-1)\n score_pos = score_objectness[..., [0]]\n score_neg = score_objectness[..., [1]]\n score_classes = score_classes * score_pos\n scores = torch.cat([score_classes, score_neg], dim=-1)\n return scores\n\n def get_accuracy(self, cls_score: Tensor,\n labels: Tensor) -> Dict[str, Tensor]:\n \"\"\"Get custom accuracy w.r.t. cls_score and labels.\n\n Args:\n cls_score (Tensor): The prediction with shape (N, C + 2).\n labels (Tensor): The learning label of the prediction.\n\n Returns:\n Dict [str, Tensor]: The accuracy for objectness and classes,\n respectively.\n \"\"\"\n pos_inds = labels < self.num_classes\n obj_labels = (labels == self.num_classes).long()\n cls_score_classes, cls_score_objectness = self._split_cls_score(\n cls_score)\n acc_objectness = accuracy(cls_score_objectness, obj_labels)\n acc_classes = accuracy(cls_score_classes[pos_inds], labels[pos_inds])\n acc = dict()\n acc['acc_objectness'] = acc_objectness\n acc['acc_classes'] = acc_classes\n return acc\n\n def forward(\n self,\n cls_score: Tensor,\n labels: Tensor,\n label_weights: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None\n ) -> Union[Tensor, Dict[str, Tensor]]:\n \"\"\"Forward function.\n\n Args:\n cls_score (Tensor): The prediction with shape (N, C + 2).\n labels (Tensor): The learning label of the prediction.\n label_weights (Tensor, optional): Sample-wise loss weight.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction (str, optional): The method used to reduce the loss.\n Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor | Dict [str, Tensor]:\n if return_dict == False: The calculated loss |\n if return_dict == True: The dict of calculated losses\n for objectness and classes, respectively.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n assert cls_score.size(-1) == self.num_classes + 2\n pos_inds = labels < self.num_classes\n # 0 for pos, 1 for neg\n obj_labels = (labels == self.num_classes).long()\n\n # accumulate the samples for each category\n unique_labels = labels.unique()\n for u_l in unique_labels:\n inds_ = labels == u_l.item()\n self.cum_samples[u_l] += inds_.sum()\n\n if label_weights is not None:\n label_weights = label_weights.float()\n else:\n label_weights = labels.new_ones(labels.size(), dtype=torch.float)\n\n cls_score_classes, cls_score_objectness = self._split_cls_score(\n cls_score)\n # calculate loss_cls_classes (only need pos samples)\n if pos_inds.sum() > 0:\n loss_cls_classes = self.loss_weight * self.cls_criterion(\n cls_score_classes[pos_inds], labels[pos_inds],\n label_weights[pos_inds], self.cum_samples[:self.num_classes],\n self.num_classes, self.p, self.q, self.eps, reduction,\n avg_factor)\n else:\n loss_cls_classes = cls_score_classes[pos_inds].sum()\n # calculate loss_cls_objectness\n loss_cls_objectness = self.loss_weight * cross_entropy(\n cls_score_objectness, obj_labels, label_weights, reduction,\n avg_factor)\n\n if self.return_dict:\n loss_cls = dict()\n loss_cls['loss_cls_objectness'] = loss_cls_objectness\n loss_cls['loss_cls_classes'] = loss_cls_classes\n else:\n loss_cls = loss_cls_classes + loss_cls_objectness\n return loss_cls\n\nmmdet/models/losses/balanced_l1_loss.py\nclass BalancedL1Loss(nn.Module):\n \"\"\"Balanced L1 Loss.\n\n arXiv: https://arxiv.org/pdf/1904.02701.pdf (CVPR 2019)\n\n Args:\n alpha (float): The denominator ``alpha`` in the balanced L1 loss.\n Defaults to 0.5.\n gamma (float): The ``gamma`` in the balanced L1 loss. Defaults to 1.5.\n beta (float, optional): The loss is a piecewise function of prediction\n and target. ``beta`` serves as a threshold for the difference\n between the prediction and target. Defaults to 1.0.\n reduction (str, optional): The method that reduces the loss to a\n scalar. Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float, optional): The weight of the loss. Defaults to 1.0\n \"\"\"\n\n def __init__(self,\n alpha=0.5,\n gamma=1.5,\n beta=1.0,\n reduction='mean',\n loss_weight=1.0):\n super(BalancedL1Loss, self).__init__()\n self.alpha = alpha\n self.gamma = gamma\n self.beta = beta\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n **kwargs):\n \"\"\"Forward function of loss.\n\n Args:\n pred (torch.Tensor): The prediction with shape (N, 4).\n target (torch.Tensor): The learning target of the prediction with\n shape (N, 4).\n weight (torch.Tensor, optional): Sample-wise loss weight with\n shape (N, ).\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n torch.Tensor: The calculated loss\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n loss_bbox = self.loss_weight * balanced_l1_loss(\n pred,\n target,\n weight,\n alpha=self.alpha,\n gamma=self.gamma,\n beta=self.beta,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss_bbox\n\nmmdet/models/losses/iou_loss.py\nclass GIoULoss(nn.Module):\n r\"\"\"`Generalized Intersection over Union: A Metric and A Loss for Bounding\n Box Regression `_.\n\n Args:\n eps (float): Epsilon to avoid log(0).\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float): Weight of loss.\n \"\"\"\n\n def __init__(self,\n eps: float = 1e-6,\n reduction: str = 'mean',\n loss_weight: float = 1.0) -> None:\n super().__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None,\n **kwargs) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): The learning target of the prediction,\n shape (n, 4).\n weight (Optional[Tensor], optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (Optional[int], optional): Average factor that is used\n to average the loss. Defaults to None.\n reduction_override (Optional[str], optional): The reduction method\n used to override the original reduction method of the loss.\n Defaults to None. Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor: Loss tensor.\n \"\"\"\n if weight is not None and not torch.any(weight > 0):\n if pred.dim() == weight.dim() + 1:\n weight = weight.unsqueeze(1)\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if weight is not None and weight.dim() > 1:\n # TODO: remove this in the future\n # reduce the weight of shape (n, 4) to (n,) to match the\n # giou_loss of shape (n,)\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * giou_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\nmmdet/models/losses/ghm_loss.py\nclass GHMR(nn.Module):\n \"\"\"GHM Regression Loss.\n\n Details of the theorem can be viewed in the paper\n `Gradient Harmonized Single-stage Detector\n `_.\n\n Args:\n mu (float): The parameter for the Authentic Smooth L1 loss.\n bins (int): Number of the unit regions for distribution calculation.\n momentum (float): The parameter for moving average.\n loss_weight (float): The weight of the total GHM-R loss.\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n Defaults to \"mean\"\n \"\"\"\n\n def __init__(self,\n mu=0.02,\n bins=10,\n momentum=0,\n loss_weight=1.0,\n reduction='mean'):\n super(GHMR, self).__init__()\n self.mu = mu\n self.bins = bins\n edges = torch.arange(bins + 1).float() / bins\n self.register_buffer('edges', edges)\n self.edges[-1] = 1e3\n self.momentum = momentum\n if momentum > 0:\n acc_sum = torch.zeros(bins)\n self.register_buffer('acc_sum', acc_sum)\n self.loss_weight = loss_weight\n self.reduction = reduction\n\n # TODO: support reduction parameter\n def forward(self,\n pred,\n target,\n label_weight,\n avg_factor=None,\n reduction_override=None):\n \"\"\"Calculate the GHM-R loss.\n\n Args:\n pred (float tensor of size [batch_num, 4 (* class_num)]):\n The prediction of box regression layer. Channel number can be 4\n or 4 * class_num depending on whether it is class-agnostic.\n target (float tensor of size [batch_num, 4 (* class_num)]):\n The target regression values with the same size of pred.\n label_weight (float tensor of size [batch_num, 4 (* class_num)]):\n The weight of each sample, 0 if ignored.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n Returns:\n The gradient harmonized loss.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n mu = self.mu\n edges = self.edges\n mmt = self.momentum\n\n # ASL1 loss\n diff = pred - target\n loss = torch.sqrt(diff * diff + mu * mu) - mu\n\n # gradient length\n g = torch.abs(diff / torch.sqrt(mu * mu + diff * diff)).detach()\n weights = torch.zeros_like(g)\n\n valid = label_weight > 0\n tot = max(label_weight.float().sum().item(), 1.0)\n n = 0 # n: valid bins\n for i in range(self.bins):\n inds = (g >= edges[i]) & (g < edges[i + 1]) & valid\n num_in_bin = inds.sum().item()\n if num_in_bin > 0:\n n += 1\n if mmt > 0:\n self.acc_sum[i] = mmt * self.acc_sum[i] \\\n + (1 - mmt) * num_in_bin\n weights[inds] = tot / self.acc_sum[i]\n else:\n weights[inds] = tot / num_in_bin\n if n > 0:\n weights /= n\n loss = weight_reduce_loss(\n loss, weights, reduction=reduction, avg_factor=tot)\n return loss * self.loss_weight\n\nmmdet/models/losses/focal_loss.py\nclass FocalLoss(nn.Module):\n\n def __init__(self,\n use_sigmoid=True,\n gamma=2.0,\n alpha=0.25,\n reduction='mean',\n loss_weight=1.0,\n activated=False):\n \"\"\"`Focal Loss `_\n\n Args:\n use_sigmoid (bool, optional): Whether to the prediction is\n used for sigmoid or softmax. Defaults to True.\n gamma (float, optional): The gamma for calculating the modulating\n factor. Defaults to 2.0.\n alpha (float, optional): A balanced form for Focal Loss.\n Defaults to 0.25.\n reduction (str, optional): The method used to reduce the loss into\n a scalar. Defaults to 'mean'. Options are \"none\", \"mean\" and\n \"sum\".\n loss_weight (float, optional): Weight of loss. Defaults to 1.0.\n activated (bool, optional): Whether the input is activated.\n If True, it means the input has been activated and can be\n treated as probabilities. Else, it should be treated as logits.\n Defaults to False.\n \"\"\"\n super(FocalLoss, self).__init__()\n assert use_sigmoid is True, 'Only sigmoid focal loss supported now.'\n self.use_sigmoid = use_sigmoid\n self.gamma = gamma\n self.alpha = alpha\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.activated = activated\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None):\n \"\"\"Forward function.\n\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning label of the prediction.\n The target shape support (N,C) or (N,), (N,C) means\n one-hot form.\n weight (torch.Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n torch.Tensor: The calculated loss\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if self.use_sigmoid:\n if self.activated:\n calculate_loss_func = py_focal_loss_with_prob\n else:\n if pred.dim() == target.dim():\n # this means that target is already in One-Hot form.\n calculate_loss_func = py_sigmoid_focal_loss\n elif torch.cuda.is_available() and pred.is_cuda:\n calculate_loss_func = sigmoid_focal_loss\n else:\n num_classes = pred.size(1)\n target = F.one_hot(target, num_classes=num_classes + 1)\n target = target[:, :num_classes]\n calculate_loss_func = py_sigmoid_focal_loss\n\n loss_cls = self.loss_weight * calculate_loss_func(\n pred,\n target,\n weight,\n gamma=self.gamma,\n alpha=self.alpha,\n reduction=reduction,\n avg_factor=avg_factor)\n\n else:\n raise NotImplementedError\n return loss_cls\n\nmmdet/models/losses/iou_loss.py\nclass BoundedIoULoss(nn.Module):\n \"\"\"BIoULoss.\n\n This is an implementation of paper\n `Improving Object Localization with Fitness NMS and Bounded IoU Loss.\n `_.\n\n Args:\n beta (float, optional): Beta parameter in smoothl1.\n eps (float, optional): Epsilon to avoid NaN values.\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float): Weight of loss.\n \"\"\"\n\n def __init__(self,\n beta: float = 0.2,\n eps: float = 1e-3,\n reduction: str = 'mean',\n loss_weight: float = 1.0) -> None:\n super().__init__()\n self.beta = beta\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None,\n **kwargs) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): The learning target of the prediction,\n shape (n, 4).\n weight (Optional[Tensor], optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (Optional[int], optional): Average factor that is used\n to average the loss. Defaults to None.\n reduction_override (Optional[str], optional): The reduction method\n used to override the original reduction method of the loss.\n Defaults to None. Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor: Loss tensor.\n \"\"\"\n if weight is not None and not torch.any(weight > 0):\n if pred.dim() == weight.dim() + 1:\n weight = weight.unsqueeze(1)\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n loss = self.loss_weight * bounded_iou_loss(\n pred,\n target,\n weight,\n beta=self.beta,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\nmmdet/models/losses/cross_entropy_loss.py\nclass CrossEntropyLoss(nn.Module):\n\n def __init__(self,\n use_sigmoid=False,\n use_mask=False,\n reduction='mean',\n class_weight=None,\n ignore_index=None,\n loss_weight=1.0,\n avg_non_ignore=False):\n \"\"\"CrossEntropyLoss.\n\n Args:\n use_sigmoid (bool, optional): Whether the prediction uses sigmoid\n of softmax. Defaults to False.\n use_mask (bool, optional): Whether to use mask cross entropy loss.\n Defaults to False.\n reduction (str, optional): . Defaults to 'mean'.\n Options are \"none\", \"mean\" and \"sum\".\n class_weight (list[float], optional): Weight of each class.\n Defaults to None.\n ignore_index (int | None): The label index to be ignored.\n Defaults to None.\n loss_weight (float, optional): Weight of the loss. Defaults to 1.0.\n avg_non_ignore (bool): The flag decides to whether the loss is\n only averaged over non-ignored targets. Default: False.\n \"\"\"\n super(CrossEntropyLoss, self).__init__()\n assert (use_sigmoid is False) or (use_mask is False)\n self.use_sigmoid = use_sigmoid\n self.use_mask = use_mask\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.class_weight = class_weight\n self.ignore_index = ignore_index\n self.avg_non_ignore = avg_non_ignore\n if ((ignore_index is not None) and not self.avg_non_ignore\n and self.reduction == 'mean'):\n warnings.warn(\n 'Default ``avg_non_ignore`` is False, if you would like to '\n 'ignore the certain label and average loss over non-ignore '\n 'labels, which is the same with PyTorch official '\n 'cross_entropy, set ``avg_non_ignore=True``.')\n\n if self.use_sigmoid:\n self.cls_criterion = binary_cross_entropy\n elif self.use_mask:\n self.cls_criterion = mask_cross_entropy\n else:\n self.cls_criterion = cross_entropy\n\n def extra_repr(self):\n \"\"\"Extra repr.\"\"\"\n s = f'avg_non_ignore={self.avg_non_ignore}'\n return s\n\n def forward(self,\n cls_score,\n label,\n weight=None,\n avg_factor=None,\n reduction_override=None,\n ignore_index=None,\n **kwargs):\n \"\"\"Forward function.\n\n Args:\n cls_score (torch.Tensor): The prediction.\n label (torch.Tensor): The learning label of the prediction.\n weight (torch.Tensor, optional): Sample-wise loss weight.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The method used to reduce the\n loss. Options are \"none\", \"mean\" and \"sum\".\n ignore_index (int | None): The label index to be ignored.\n If not None, it will override the default value. Default: None.\n Returns:\n torch.Tensor: The calculated loss.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if ignore_index is None:\n ignore_index = self.ignore_index\n\n if self.class_weight is not None:\n class_weight = cls_score.new_tensor(\n self.class_weight, device=cls_score.device)\n else:\n class_weight = None\n loss_cls = self.loss_weight * self.cls_criterion(\n cls_score,\n label,\n weight,\n class_weight=class_weight,\n reduction=reduction,\n avg_factor=avg_factor,\n ignore_index=ignore_index,\n avg_non_ignore=self.avg_non_ignore,\n **kwargs)\n return loss_cls\n\nmmdet/models/losses/gfocal_loss.py\nclass QualityFocalLoss(nn.Module):\n r\"\"\"Quality Focal Loss (QFL) is a variant of `Generalized Focal Loss:\n Learning Qualified and Distributed Bounding Boxes for Dense Object\n Detection `_.\n\n Args:\n use_sigmoid (bool): Whether sigmoid operation is conducted in QFL.\n Defaults to True.\n beta (float): The beta parameter for calculating the modulating factor.\n Defaults to 2.0.\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float): Loss weight of current loss.\n activated (bool, optional): Whether the input is activated.\n If True, it means the input has been activated and can be\n treated as probabilities. Else, it should be treated as logits.\n Defaults to False.\n \"\"\"\n\n def __init__(self,\n use_sigmoid=True,\n beta=2.0,\n reduction='mean',\n loss_weight=1.0,\n activated=False):\n super(QualityFocalLoss, self).__init__()\n assert use_sigmoid is True, 'Only sigmoid in QFL supported now.'\n self.use_sigmoid = use_sigmoid\n self.beta = beta\n self.reduction = reduction\n self.loss_weight = loss_weight\n self.activated = activated\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None):\n \"\"\"Forward function.\n\n Args:\n pred (torch.Tensor): Predicted joint representation of\n classification and quality (IoU) estimation with shape (N, C),\n C is the number of classes.\n target (Union(tuple([torch.Tensor]),Torch.Tensor)): The type is\n tuple, it should be included Target category label with\n shape (N,) and target quality label with shape (N,).The type\n is torch.Tensor, the target should be one-hot form with\n soft weights.\n weight (torch.Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if self.use_sigmoid:\n if self.activated:\n calculate_loss_func = quality_focal_loss_with_prob\n else:\n calculate_loss_func = quality_focal_loss\n if isinstance(target, torch.Tensor):\n # the target shape with (N,C) or (N,C,...), which means\n # the target is one-hot form with soft weights.\n calculate_loss_func = partial(\n quality_focal_loss_tensor_target, activated=self.activated)\n\n loss_cls = self.loss_weight * calculate_loss_func(\n pred,\n target,\n weight,\n beta=self.beta,\n reduction=reduction,\n avg_factor=avg_factor)\n else:\n raise NotImplementedError\n return loss_cls\n\nmmdet/models/losses/iou_loss.py\nclass CIoULoss(nn.Module):\n r\"\"\"`Implementation of paper `Enhancing Geometric Factors into\n Model Learning and Inference for Object Detection and Instance\n Segmentation `_.\n\n Code is modified from https://github.com/Zzh-tju/CIoU.\n\n Args:\n eps (float): Epsilon to avoid log(0).\n reduction (str): Options are \"none\", \"mean\" and \"sum\".\n loss_weight (float): Weight of loss.\n \"\"\"\n\n def __init__(self,\n eps: float = 1e-6,\n reduction: str = 'mean',\n loss_weight: float = 1.0) -> None:\n super().__init__()\n self.eps = eps\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred: Tensor,\n target: Tensor,\n weight: Optional[Tensor] = None,\n avg_factor: Optional[int] = None,\n reduction_override: Optional[str] = None,\n **kwargs) -> Tensor:\n \"\"\"Forward function.\n\n Args:\n pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2),\n shape (n, 4).\n target (Tensor): The learning target of the prediction,\n shape (n, 4).\n weight (Optional[Tensor], optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (Optional[int], optional): Average factor that is used\n to average the loss. Defaults to None.\n reduction_override (Optional[str], optional): The reduction method\n used to override the original reduction method of the loss.\n Defaults to None. Options are \"none\", \"mean\" and \"sum\".\n\n Returns:\n Tensor: Loss tensor.\n \"\"\"\n if weight is not None and not torch.any(weight > 0):\n if pred.dim() == weight.dim() + 1:\n weight = weight.unsqueeze(1)\n return (pred * weight).sum() # 0\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n if weight is not None and weight.dim() > 1:\n # TODO: remove this in the future\n # reduce the weight of shape (n, 4) to (n,) to match the\n # giou_loss of shape (n,)\n assert weight.shape == pred.shape\n weight = weight.mean(-1)\n loss = self.loss_weight * ciou_loss(\n pred,\n target,\n weight,\n eps=self.eps,\n reduction=reduction,\n avg_factor=avg_factor,\n **kwargs)\n return loss\n\nmmdet/models/losses/gfocal_loss.py\nclass DistributionFocalLoss(nn.Module):\n r\"\"\"Distribution Focal Loss (DFL) is a variant of `Generalized Focal Loss:\n Learning Qualified and Distributed Bounding Boxes for Dense Object\n Detection `_.\n\n Args:\n reduction (str): Options are `'none'`, `'mean'` and `'sum'`.\n loss_weight (float): Loss weight of current loss.\n \"\"\"\n\n def __init__(self, reduction='mean', loss_weight=1.0):\n super(DistributionFocalLoss, self).__init__()\n self.reduction = reduction\n self.loss_weight = loss_weight\n\n def forward(self,\n pred,\n target,\n weight=None,\n avg_factor=None,\n reduction_override=None):\n \"\"\"Forward function.\n\n Args:\n pred (torch.Tensor): Predicted general distribution of bounding\n boxes (before softmax) with shape (N, n+1), n is the max value\n of the integral set `{0, ..., n}` in paper.\n target (torch.Tensor): Target distance label for bounding boxes\n with shape (N,).\n weight (torch.Tensor, optional): The weight of loss for each\n prediction. Defaults to None.\n avg_factor (int, optional): Average factor that is used to average\n the loss. Defaults to None.\n reduction_override (str, optional): The reduction method used to\n override the original reduction method of the loss.\n Defaults to None.\n \"\"\"\n assert reduction_override in (None, 'none', 'mean', 'sum')\n reduction = (\n reduction_override if reduction_override else self.reduction)\n loss_cls = self.loss_weight * distribution_focal_loss(\n pred, target, weight, reduction=reduction, avg_factor=avg_factor)\n return loss_cls", "answers": ["@pytest.mark.parametrize('loss_class', ["], "length": 7586, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "51e08d0a-a9f3-4b3a-b93d-1cab70735e82", "reasoning": "The import block ends with the last line importing IoU loss classes. In the test file, the next logical code element is the parametrized test decorator that starts the test function for those loss classes. Therefore the next line is the pytest parametrize decorator line.", "reasoning_model_answer": "@pytest.mark.parametrize('loss_class', [", "assistant_with_reasoning": "\nThe import block ends with the last line importing IoU loss classes. In the test file, the next logical code element is the parametrized test decorator that starts the test function for those loss classes. Therefore the next line is the pytest parametrize decorator line.\n\n@pytest.mark.parametrize('loss_class', [", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.809, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36831, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "@pytest.mark.parametrize('loss_class', [", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "import com.flowingcode.vaadin.addons.fontawesome.FontAwesome;\nimport com.nasc.application.data.core.User;\nimport com.nasc.application.security.AuthenticatedUser;\nimport com.nasc.application.views.about.AboutView;\nimport com.nasc.application.views.activeusers.ActiveUsersView;\nimport com.nasc.application.views.address.AddressMasterDetailView;\nimport com.nasc.application.views.auth.create.CreateUsers;\nimport com.nasc.application.views.dashboard.DashboardView;\nimport com.nasc.application.views.forms.adderss.AddressFormView;\nimport com.nasc.application.views.forms.bank.BankDetailsFormView;\nimport com.nasc.application.views.forms.personal.PersonalFormView;\nimport com.nasc.application.views.marks.entry.MarkEntryView;\nimport com.nasc.application.views.marks.table.MarksView;\nimport com.nasc.application.views.password.PasswordChangeView;\nimport com.nasc.application.views.professor.status.ProfessorStatusView;\nimport com.nasc.application.views.student.StudentMasterDetailsView;\nimport com.nasc.application.views.student.status.StudentsStatusView;\nimport com.nasc.application.views.subject.CreateSubjectCrud;\nimport com.nasc.application.views.valuevalut.ValueVaultView;\nimport com.vaadin.flow.component.applayout.AppLayout;\nimport com.vaadin.flow.component.applayout.DrawerToggle;\nimport com.vaadin.flow.component.avatar.Avatar;\nimport com.vaadin.flow.component.contextmenu.MenuItem;\nimport com.vaadin.flow.component.html.*;\nimport com.vaadin.flow.component.icon.Icon;\nimport com.vaadin.flow.component.menubar.MenuBar;\nimport com.vaadin.flow.component.orderedlayout.Scroller;\nimport com.vaadin.flow.component.sidenav.SideNav;\nimport com.vaadin.flow.component.sidenav.SideNavItem;\nimport com.vaadin.flow.router.PageTitle;\nimport com.vaadin.flow.router.PreserveOnRefresh;\nimport com.vaadin.flow.server.auth.AccessAnnotationChecker;\nimport com.vaadin.flow.theme.lumo.LumoUtility;\nimport org.vaadin.lineawesome.LineAwesomeIcon;\nimport java.util.Optional;", "context": "src/main/java/com/nasc/application/views/MainLayout.java\npackage com.nasc.application.views;\n\n\n\n/**\n * The main view is a top-level placeholder for other views.\n */\n@PreserveOnRefresh\npublic class MainLayout extends AppLayout {\n\n private H2 viewTitle;\n\n private final AuthenticatedUser authenticatedUser;\n private final AccessAnnotationChecker accessChecker;\n\n\nsrc/main/java/com/nasc/application/views/marks/entry/MarkEntryView.java\n@Route(value = \"subject-view\", layout = MainLayout.class)\n@PageTitle(\"Subject View\")\n@RolesAllowed({\"HOD\", \"ADMIN\", \"PROFESSOR\"})\npublic class MarkEntryView extends Div {\n\n private final VerticalLayout primaryLayout;\n private final VerticalLayout secondaryLayout;\n private final SplitLayout splitLayout;\n\n // service\n private final ExamService examService;\n private final DepartmentService departmentService;\n private final SubjectService subjectService;\n private final MarksService marksService;\n private final UserService userService;\n private final AcademicYearService academicYearService;\n\n private ComboBox departmentComboBox;\n private ComboBox semesterComboBox;\n private ComboBox subjectComboBox;\n private TextField subjectShortFormTextField;\n private TextField majorTextField;\n private TextField typeOfPaperTextField;\n private TextField subjectCodeTextField;\n private ComboBox academicYearComboBox;\n private ComboBox studentSectionComboBox;\n\n //Exam Fields\n private DatePicker examDateDatePicker;\n private ComboBox examTypeComboBox;\n // Global declaration for current user\n private final User currentUser;\n private NumberField minMarksNumberField;\n private NumberField portionCoveredNumberField;\n private IntegerField examDurationIntegerField;\n private DatePicker examCorrectionDatePicker;\n private MultiSelectComboBox userMultiSelectComboBox;\n private Button createExamButton;\n private Button markEnterButton;\n private NumberField maxMarksNumberField;\n\n //Layouts\n private FormLayout markFormLayout;\n private FormLayout examFormLayout;\n private FormLayout formLayout;\n\n //Exam ComboBoxes\n private ComboBox examComboBox;\n\n @Autowired\n public MarkEntryView(DepartmentService departmentService,\n SubjectService subjectService,\n MarksService marksService,\n UserService userService,\n ExamService examService,\n AuthenticatedUser authenticatedUser,\n AcademicYearService academicYearService\n ) {\n this.departmentService = departmentService;\n this.subjectService = subjectService;\n this.examService = examService;\n this.marksService = marksService;\n this.userService = userService;\n this.academicYearService = academicYearService;\n\n primaryLayout = new VerticalLayout();\n secondaryLayout = new VerticalLayout();\n\n primaryLayout.setMaxHeight(\"90vh\");\n secondaryLayout.setMaxHeight(\"90vh\");\n splitLayout = new SplitLayout(primaryLayout, secondaryLayout);\n\n currentUser = authenticatedUser.get().orElse(null); // If user not exists then it will be null\n\n initMarkForm();\n\n initExamComboBoxes();\n primaryLayout.add(new Divider());\n\n initExamForm();\n\n departmentComboBox.addValueChangeListener(event -> updateSubjectOptions());\n semesterComboBox.addValueChangeListener(event -> updateSubjectOptions());\n markEnterButton.addClickListener(event -> {\n // Fetch the selected exam\n ExamEntity selectedExam = examComboBox.getValue();\n\n // Update the student input fields based on the selected exam\n updateStudentFieldsForExam(selectedExam);\n });\n\n semesterComboBox.addValueChangeListener(event -> updateSubjectOptions());\n subjectComboBox.addValueChangeListener(event -> {\n\n // No need to call updateSubjectOptions again, as it is automatically called when department or semester changes\n DepartmentEntity selectedDepartment = departmentComboBox.getValue();\n Semester selectedSemester = semesterComboBox.getValue();\n\n // Fetch exams based on the selected subject, department, and semester\n updateExamOptions(selectedDepartment, selectedSemester);\n });\n }\n\n private void initMarkForm() {\n\n // Populate department and semester dropdowns\n List departments = departmentService.findAll();\n Semester[] semester = Semester.values();\n List academicYears = academicYearService.findAll();\n StudentSection[] values = StudentSection.values();\n\n //Creating forms\n markFormLayout = new FormLayout();\n\n departmentComboBox = new ComboBox<>(\"Select Department\", departments);\n semesterComboBox = new ComboBox<>(\"Select Semester\");\n semesterComboBox.setItems(semester);\n semesterComboBox.setItemLabelGenerator(Semester::getDisplayName);\n\n // Setup subject dropdown and subject code text-field\n subjectComboBox = new ComboBox<>(\"Select Subject\");\n\n academicYearComboBox = new ComboBox<>(\"Academic Year\");\n academicYearComboBox.setItems(academicYears);\n academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + \"-\" + item.getEndYear());\n\n studentSectionComboBox = new ComboBox<>(\"Select Student Section\");\n studentSectionComboBox.setItems(values);\n studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName);\n\n subjectComboBox.setPlaceholder(\"Select a subject\");\n\n subjectShortFormTextField = new TextField(\"Subject Short Form\");\n subjectShortFormTextField.setReadOnly(true);\n\n majorTextField = new TextField(\"Major\");\n majorTextField.setReadOnly(true);\n\n subjectCodeTextField = new TextField(\"Subject Code\");\n subjectCodeTextField.setReadOnly(true);\n\n typeOfPaperTextField = new TextField(\"Type Of Paper\");\n typeOfPaperTextField.setReadOnly(true);\n\n markEnterButton = new Button(\"Start Entering Mark\");\n markEnterButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n // Add a listener to handle subject selection\n subjectComboBox.addValueChangeListener(event -> handleSubjectSelection());\n\n markFormLayout.add(departmentComboBox,\n semesterComboBox,\n subjectComboBox,\n subjectShortFormTextField,\n majorTextField,\n typeOfPaperTextField,\n subjectCodeTextField,\n academicYearComboBox,\n studentSectionComboBox\n );\n\n primaryLayout.add(markFormLayout);\n\n add(splitLayout);\n }\n\n // HELPER\n private static Checkbox getCheckbox(NumberField studentMarkField) {\n Checkbox absentCheckbox = new Checkbox(\"Absent\");\n absentCheckbox.addValueChangeListener(event -> {\n if (event.getValue()) {\n // If absent, set text field to 0.0 and make it read-only\n studentMarkField.setValue(0.0);\n studentMarkField.setReadOnly(true);\n } else {\n // If not absent, clear the text field and make it editable\n studentMarkField.clear();\n studentMarkField.setReadOnly(false);\n }\n });\n return absentCheckbox;\n }\n\n private void createExam() {\n ExamEntity newExam = createNewExam(); // Implement this method to create a new exam\n examComboBox.setItems(examService.getAllExams()); // Refresh the examComboBox\n examComboBox.setValue(newExam); // Set the newly created exam as the selected exam\n handleExamSelection(); // Trigger the handleExamSelection logic\n }\n\n private void initExamForm() {\n\n //Creating exam form\n examFormLayout = new FormLayout();\n\n Set rolesToFilter = new HashSet<>();\n rolesToFilter.add(Role.PROFESSOR);\n rolesToFilter.add(Role.HOD);\n\n // Removed Current User\n List users = userService.findUsersByRoles(rolesToFilter);\n users.remove(currentUser);\n\n ExamType[] examTypeEnum = ExamType.values();\n\n examDateDatePicker = new DatePicker(\"Exam Date\");\n examTypeComboBox = new ComboBox<>(\"Exam Type\", examTypeEnum);\n examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName);\n\n minMarksNumberField = new NumberField(\"Minimum Marks\");\n minMarksNumberField.setStep(0.50);\n maxMarksNumberField = new NumberField(\"Maximum Marks\");\n maxMarksNumberField.setStep(0.50);\n\n portionCoveredNumberField = new NumberField(\"Portion Covered\");\n\n examDurationIntegerField = new IntegerField(\"Exam Duration (minutes)\");\n examCorrectionDatePicker = new DatePicker(\"Exam Correction Date\");\n\n createExamButton = new Button(\"Create Exam\", event -> createExam());\n createExamButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n userMultiSelectComboBox = new MultiSelectComboBox<>(\"Subject Staffs\");\n userMultiSelectComboBox.setItems(users);\n userMultiSelectComboBox.setPlaceholder(\"Select persons\");\n userMultiSelectComboBox.setAutoExpand(MultiSelectComboBox.AutoExpandMode.BOTH);\n userMultiSelectComboBox.setItemLabelGenerator(item -> item.getUsername() + \" [\" + item.getRegisterNumber() + \"]\");\n\n examFormLayout.add(\n examDateDatePicker,\n examTypeComboBox,\n minMarksNumberField,\n maxMarksNumberField,\n portionCoveredNumberField,\n examDurationIntegerField,\n examCorrectionDatePicker,\n userMultiSelectComboBox,\n createExamButton\n );\n\n primaryLayout.add(examFormLayout);\n }\n\n private void updateSubjectOptions() {\n DepartmentEntity selectedDepartment = departmentComboBox.getValue();\n Semester selectedSemester = semesterComboBox.getValue();\n\n if (selectedDepartment != null && selectedSemester != null) {\n // Fetch subjects based on the selected department and semester\n List subjects = subjectService.getSubjectsByDepartmentAndSemester(\n selectedDepartment,\n selectedSemester\n );\n\n // Update the subject dropdown options\n subjectComboBox.setItems(subjects);\n subjectComboBox.setItemLabelGenerator(\n subject -> subject.getSubjectName() + \" - \" + subject.getSubjectShortForm()\n );\n } else {\n\n // Clear subject dropdown if either department or semester is not selected\n subjectComboBox.setItems();\n }\n }\n\n private void handleSubjectSelection() {\n SubjectEntity selectedSubject = subjectComboBox.getValue();\n\n if (selectedSubject != null) {\n subjectShortFormTextField.setValue(selectedSubject.getSubjectShortForm());\n subjectCodeTextField.setValue(selectedSubject.getSubjectCode());\n\n // Added toSting because value ENUM\n majorTextField.setValue(selectedSubject.getMajorOfPaper().getDisplayName());\n typeOfPaperTextField.setValue(selectedSubject.getPaperType().getDisplayName());\n } else {\n subjectShortFormTextField.clear();\n majorTextField.clear();\n typeOfPaperTextField.clear();\n }\n }\n\n private ExamEntity createNewExam() {\n // Implement the logic to create a new exam\n ExamEntity exam = new ExamEntity();\n exam.setDepartment(departmentComboBox.getValue());\n exam.setSemester(semesterComboBox.getValue());\n exam.setExamType(examTypeComboBox.getValue());\n exam.setExamDate(examDateDatePicker.getValue());\n exam.setSubject(subjectComboBox.getValue());\n exam.setMinMarks(minMarksNumberField.getValue());\n exam.setMaxMarks(maxMarksNumberField.getValue());\n exam.setPortionCovered(portionCoveredNumberField.getValue());\n exam.setExamDuration(examDurationIntegerField.getValue());\n exam.setExamCorrectionDate(examCorrectionDatePicker.getValue());\n\n Set selectedProfessors = userMultiSelectComboBox.getSelectedItems();\n if (!selectedProfessors.isEmpty()) {\n // Add both the current user and selected professors to the responsibleUsers set\n Set responsibleUsers = new HashSet<>(selectedProfessors);\n responsibleUsers.add(currentUser);\n\n exam.setResponsibleUsers(responsibleUsers);\n } else {\n // If no professors are selected, only add the current user\n exam.setResponsibleUsers(Set.of(currentUser));\n }\n\n examService.saveExam(exam); // Save the new exam\n return exam;\n }\n\n private boolean createNewMarks(User student, SubjectEntity subject, ExamEntity exam, Double marksObtained, boolean isAbsent) {\n // Check if the obtained marks are valid\n if (!isAbsent) {\n if (isValidMark(marksObtained, exam)) {\n // Check if a mark already exists for the selected student, subject, and exam\n boolean markExists = marksService.existsByStudentAndSubjectAndExam(student, subject, exam);\n\n if (markExists) {\n // If a mark already exists, update the existing mark\n updateMarks(student, subject, marksObtained, isAbsent, exam);\n } else {\n // Create a new MarksEntity\n MarksEntity marksEntity = new MarksEntity();\n marksEntity.setStudent(student);\n marksEntity.setSubject(subject);\n marksEntity.setExam(exam);\n marksEntity.setMarksObtained(marksObtained);\n\n // Save the marks\n marksService.saveMarks(marksEntity);\n\n NotificationUtils.showSuccessNotification(\"Marks saved successfully\");\n }\n return true;\n } else {\n NotificationUtils.showErrorNotification(\"Please enter valid marks within the specified range\");\n }\n } else {\n // Check if a mark already exists for the selected student, subject, and exam\n boolean markExists = marksService.existsByStudentAndSubjectAndExam(student, subject, exam);\n\n if (!markExists) {\n // If no mark exists, create a new MarksEntity with absent status\n MarksEntity marksEntity = new MarksEntity();\n marksEntity.setStudent(student);\n marksEntity.setSubject(subject);\n marksEntity.setExam(exam);\n marksEntity.setAbsent(true);\n marksEntity.setMarksObtained(0.0);\n marksService.saveMarks(marksEntity);\n\n NotificationUtils.showSuccessNotification(\"Marks saved successfully\");\n return true;\n } else {\n NotificationUtils.showInfoNotification(\"Marks for the selected student, subject, and exam already exist.\");\n }\n }\n return false;\n }\n\n private boolean updateMarks(User student, SubjectEntity subject, Double marksObtained, boolean isAbsent, ExamEntity exam) {\n MarksEntity existingMarks = marksService.findMarkByStudentAndSubject(student, subject, exam).orElse(null);\n if (existingMarks != null) {\n existingMarks.setAbsent(isAbsent);\n if (!isAbsent) {\n if (isValidMark(marksObtained, existingMarks.getExam())) {\n // If marksObtained is not null and within the valid range, update the marks\n existingMarks.setMarksObtained(marksObtained);\n } else {\n // Display an error notification for invalid marks\n NotificationUtils.showErrorNotification(\"Invalid marks. Please enter valid marks within the specified range.\");\n return false;\n }\n } else {\n // If the user is marked as absent, set obtained marks to null\n existingMarks.setMarksObtained(0.00);\n }\n // Save the updated marks\n marksService.saveMarks(existingMarks);\n\n // Display a success notification\n NotificationUtils.showSuccessNotification(\"Marks updated successfully\");\n\n return true;\n } else {\n // If the mark does not exist, you may want to handle this case accordingly\n NotificationUtils.showErrorNotification(\"Marks do not exist for the selected student and subject.\");\n }\n return false;\n }\n\n private void handleExamSelection() {\n ExamEntity selectedExam = examComboBox.getValue();\n\n if (selectedExam != null) {\n // You can add logic here based on the selected exam\n String message = \"Selected exam: \" + selectedExam.getExamType();\n NotificationUtils.showInfoNotification(message);\n } else {\n // Handle the case where no exam is selected\n NotificationUtils.showErrorNotification(\"Please select an exam\");\n }\n }\n\n private void initExamComboBoxes() {\n formLayout = new FormLayout();\n examComboBox = new ComboBox<>(\"Select Exam\");\n examComboBox.setItemLabelGenerator(item ->\n \"DEPT: \" + item.getDepartment().getShortName()\n + \", SUB: \" + item.getSubject().getSubjectShortForm()\n + \", EXAM TYPE: \" + item.getExamType().getDisplayName()\n + \", EXAM DATE: \" + item.getExamDate().format(UIUtils.dateTimeFormatter)\n );\n\n // Add a listener to handle student and exam selection\n examComboBox.addValueChangeListener(event -> handleExamSelection());\n\n formLayout.add(examComboBox, markEnterButton);\n primaryLayout.add(formLayout);\n }\n\n private boolean saveMarksForStudent(User selectedStudent,\n NumberField marksObtainedTextField,\n Checkbox absentCheckbox) {\n SubjectEntity selectedSubject = subjectComboBox.getValue();\n ExamEntity selectedExam = examComboBox.getValue();\n Double marksObtained = marksObtainedTextField.getValue();\n boolean isAbsent = absentCheckbox.getValue();\n\n if (selectedStudent != null && selectedSubject != null && selectedExam != null) {\n try {\n if (marksService.existsByStudentAndSubjectAndExam(\n selectedStudent,\n selectedSubject,\n selectedExam\n )) {\n // The mark already exists, switch to update mode\n return updateMarks(selectedStudent, selectedSubject, marksObtained, isAbsent, selectedExam);\n } else {\n\n // Create a new MarksEntity\n return createNewMarks(selectedStudent, selectedSubject, selectedExam, marksObtained, isAbsent);\n }\n } catch (NumberFormatException e) {\n NotificationUtils.showErrorNotification(\"Please enter a valid number for Marks Obtained\");\n }\n } else {\n NotificationUtils.showErrorNotification(\"Please select a student, subject, and exam before saving marks\");\n }\n\n // Return false if there was an error or marks were not saved/updated\n return false;\n }\n\n private void updateExamOptions(DepartmentEntity department, Semester semester) {\n SubjectEntity selectedSubject = subjectComboBox.getValue();\n\n if (selectedSubject != null) {\n // Fetch exams based on the selected subject, department, and semester\n List exams = examService.getExamsByCriteria(\n currentUser,\n department,\n semester,\n selectedSubject\n );\n\n // Update the examComboBox options\n examComboBox.setItems(exams);\n } else {\n // Clear examComboBox if subject is not selected\n examComboBox.setItems();\n }\n }\n\n private boolean isValidMark(Double obtainedMark, ExamEntity exam) {\n if (obtainedMark == null || exam == null) {\n return false; // Invalid if obtainedMark or exam is null\n }\n\n Double maxMark = exam.getMaxMarks();\n if (maxMark == null) {\n return false; // Invalid if maxMark is null\n }\n\n // Check if obtainedMark is within the valid range\n return obtainedMark >= 0 && obtainedMark <= maxMark;\n }\n\n private void updateStudentFieldsForExam(ExamEntity exam) {\n // Clear the existing components in the secondary layout\n secondaryLayout.removeAll();\n\n // Fetch the students for the selected department, role, and academic year\n AcademicYearEntity academicYear = academicYearComboBox.getValue();\n StudentSection studentSection = studentSectionComboBox.getValue();\n\n List students = userService.findStudentsByDepartmentAndRoleAndAcademicYearAndSection(\n departmentComboBox.getValue(),\n Role.STUDENT,\n academicYear,\n studentSection\n );\n\n // Create a title for the secondary layout\n H3 examTittle = new H3(\"Exam: \" + exam.getExamType() + \" - \" + exam.getSemester());\n String subjectDetails = \"Subject: \" + exam.getSubject().getSubjectName()\n + \" - \" + exam.getSubject().getSubjectShortForm()\n + \" - \" + exam.getSubject().getSubjectCode()\n + \" - \" + exam.getSubject().getMajorOfPaper().getDisplayName()\n + \" - \" + exam.getSubject().getPaperType().getDisplayName();\n H4 subjectTittle = new H4(subjectDetails);\n secondaryLayout.add(examTittle, subjectTittle);\n\n // Update the student input fields based on the selected exam\n students.forEach(student -> {\n String username = student.getUsername();\n String registerNumber = student.getRegisterNumber();\n NumberField studentMarkField = new NumberField(username + \" [\" + registerNumber + \"]\");\n studentMarkField.setStep(0.05);\n studentMarkField.setPlaceholder(\"Enter marks\");\n\n Checkbox absentCheckbox = getCheckbox(studentMarkField);\n\n Button saveButton = new Button(\"Save\");\n saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n // Inside updateStudentFieldsForExam method\n saveButton.addClickListener(event -> {\n boolean marksSaved = saveMarksForStudent(student, studentMarkField, absentCheckbox);\n\n // Update the button text based on whether marks were saved or updated\n if (marksSaved) {\n saveButton.setText(\"Update\");\n } else {\n saveButton.setText(\"Save\");\n }\n });\n\n // Fetch existing marks for the selected exam and student\n MarksEntity existingMarksEntity = marksService.findMarkByStudentAndSubject(student, subjectComboBox.getValue(), exam)\n .orElse(null);\n\n if (existingMarksEntity != null) {\n // Set the initial value of the NumberField to existing marks\n studentMarkField.setValue(existingMarksEntity.getMarksObtained());\n saveButton.setText(\"Update\");\n }\n\n absentCheckbox.setValue(existingMarksEntity != null && existingMarksEntity.isAbsent());\n\n // Set text field to 0.0 and read-only if the student is absent\n if (absentCheckbox.getValue()) {\n studentMarkField.setValue(0.0);\n studentMarkField.setReadOnly(true);\n }\n\n // Create a \"Save\" button for each student\n FormLayout studentLayout = new FormLayout(studentMarkField, absentCheckbox, saveButton);\n\n secondaryLayout.add(studentLayout);\n });\n }\n}\n\nsrc/main/java/com/nasc/application/views/forms/bank/BankDetailsFormView.java\n@PageTitle(\"Bank Details Form\")\n@Route(value = \"bank-details-form\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\", \"PROFESSOR\", \"STUDENT\"})\npublic class BankDetailsFormView extends Div {\n private final TextField accountHolderName = new TextField(\"Account Holder Name\");\n private final TextField bankName = new TextField(\"Bank Name\");\n private final TextField accountNumber = new TextField(\"Account Number\");\n private final TextField ifscCode = new TextField(\"IFSC Code\");\n private final TextField branchName = new TextField(\"Branch Name\");\n private final TextField branchAddress = new TextField(\"Branch Address\");\n private final TextField panNumber = new TextField(\"Permanent Account Number\");\n private final Button saveButton = new Button(\"Save\");\n private final UserService userService;\n private final BeanValidationBinder binder = new BeanValidationBinder<>(BankDetails.class);\n\n @Autowired\n public BankDetailsFormView(UserService userService) {\n this.userService = userService;\n addClassName(\"bank-details-form-view\");\n add(createTitle(), createFormLayout(), createButtonLayout());\n\n binder.bindInstanceFields(this);\n\n saveButton.addClickListener(e -> {\n if (isBankDetailsAlreadySaved()) {\n updateBankDetails();\n } else {\n saveBankDetails();\n }\n });\n\n initFormWithExistingDetails();\n binder.addStatusChangeListener(e -> saveButton.setEnabled(binder.isValid()));\n\n }\n\n private Component createTitle() {\n return new H3(\"Bank Account Details\");\n }\n\n private Component createFormLayout() {\n return new FormLayout(\n accountHolderName, bankName, accountNumber,\n ifscCode, branchName, branchAddress, panNumber\n );\n }\n\n private Component createButtonLayout() {\n saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n HorizontalLayout buttonLayout = new HorizontalLayout(saveButton);\n buttonLayout.addClassName(\"button-layout\");\n return buttonLayout;\n }\n\n private void initFormWithExistingDetails() {\n User currentUser = userService.getCurrentUser();\n BankDetails existingBankDetails = currentUser.getBankDetails();\n\n if (existingBankDetails != null) {\n populateForm(existingBankDetails);\n saveButton.setText(\"Update\");\n }\n }\n\n private void populateForm(BankDetails bankDetails) {\n accountHolderName.setValue(bankDetails.getAccountHolderName());\n bankName.setValue(bankDetails.getBankName());\n accountNumber.setValue(bankDetails.getAccountNumber());\n ifscCode.setValue(bankDetails.getIfscCode());\n branchName.setValue(bankDetails.getBranchName());\n branchAddress.setValue(bankDetails.getBranchAddress());\n panNumber.setValue(bankDetails.getPanNumber());\n }\n\n private boolean isBankDetailsAlreadySaved() {\n return userService.getCurrentUser().getBankDetails() != null;\n }\n\n private void saveBankDetails() {\n User currentUser = userService.getCurrentUser();\n BankDetails newBankDetails = createBankDetailsFromForm();\n\n // Associate bank details with the current user\n newBankDetails.setUser(currentUser);\n\n // Set the new bank details to the current user\n currentUser.setBankDetails(newBankDetails);\n\n // Save the user with bank details\n userService.saveUserWithBankDetails(currentUser, newBankDetails);\n NotificationUtils.createSubmitSuccess(\"Bank details saved successfully\");\n }\n\n private void updateBankDetails() {\n User currentUser = userService.getCurrentUser();\n BankDetails existingBankDetails = currentUser.getBankDetails();\n\n // Print values before update\n System.out.println(\"Before Update: \" + existingBankDetails);\n\n // Update existing bank details\n existingBankDetails.setAccountHolderName(accountHolderName.getValue());\n existingBankDetails.setBankName(bankName.getValue());\n existingBankDetails.setAccountNumber(accountNumber.getValue());\n existingBankDetails.setIfscCode(ifscCode.getValue());\n existingBankDetails.setBranchName(branchName.getValue());\n existingBankDetails.setBranchAddress(branchAddress.getValue());\n existingBankDetails.setPanNumber(panNumber.getValue());\n\n // Save the user with updated bank details\n userService.saveUserWithBankDetails(currentUser, existingBankDetails);\n\n NotificationUtils.createSubmitSuccess(\"Bank details updated successfully\");\n }\n\n private BankDetails createBankDetailsFromForm() {\n BankDetails bankDetails = new BankDetails();\n bankDetails.setAccountHolderName(accountHolderName.getValue());\n bankDetails.setBankName(bankName.getValue());\n bankDetails.setAccountNumber(accountNumber.getValue());\n bankDetails.setIfscCode(ifscCode.getValue());\n bankDetails.setBranchName(branchName.getValue());\n bankDetails.setBranchAddress(branchAddress.getValue());\n bankDetails.setPanNumber(panNumber.getValue());\n return bankDetails;\n }\n}\n\nsrc/main/java/com/nasc/application/data/core/User.java\n@Entity\n@Table(name = \"application_user\")\npublic class User extends AbstractEntity {\n\n @CsvBindByName\n private String username;\n @CsvBindByName\n @Column(unique = true)\n private String registerNumber;\n @CsvBindByName\n private String email;\n @JsonIgnore\n @CsvBindByName\n private String password;\n @Enumerated(EnumType.STRING)\n @ElementCollection(fetch = FetchType.EAGER)\n private Set roles;\n @Enumerated(EnumType.STRING)\n private StudentSection studentSection;\n\n /*\n @Lob\n @Column(length = 1000000)\n private byte[] profilePicture;\n */\n\n private Boolean personalDetailsCompleted;\n private Boolean addressDetailsCompleted;\n private Boolean bankDetailsCompleted;\n\n @ManyToOne\n @JoinColumn(name = \"department_id\")\n private DepartmentEntity department;\n\n @ManyToOne\n @JoinColumn(name = \"academic_year_id\")\n private AcademicYearEntity academicYear;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)\n @JoinColumn(name = \"bank_details_id\")\n private BankDetails bankDetails;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\n @JoinColumn(name = \"address_details_id\")\n private AddressDetails addressDetails;\n\n @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)\n @JoinColumn(name = \"personal_details_id\")\n private PersonalDetails personalDetails;\n\n public User() {\n this.personalDetailsCompleted = Boolean.FALSE;\n this.addressDetailsCompleted = Boolean.FALSE;\n this.bankDetailsCompleted = Boolean.FALSE;\n }\n\n public AcademicYearEntity getAcademicYear() {\n return academicYear;\n }\n\n public void setAcademicYear(AcademicYearEntity academicYear) {\n this.academicYear = academicYear;\n }\n\n public DepartmentEntity getDepartment() {\n return department;\n }\n\n public void setDepartment(DepartmentEntity department) {\n this.department = department;\n }\n\n public StudentSection getStudentSection() {\n return studentSection;\n }\n\n public void setStudentSection(StudentSection studentSection) {\n this.studentSection = studentSection;\n }\n\n public PersonalDetails getPersonalDetails() {\n return personalDetails;\n }\n\n public void setPersonalDetails(PersonalDetails personalDetails) {\n this.personalDetails = personalDetails;\n }\n\n\n public Boolean getPersonalDetailsCompleted() {\n return personalDetailsCompleted;\n }\n\n public void setPersonalDetailsCompleted(Boolean personalDetailsCompleted) {\n this.personalDetailsCompleted = personalDetailsCompleted;\n }\n\n public Boolean getAddressDetailsCompleted() {\n return addressDetailsCompleted;\n }\n\n public void setAddressDetailsCompleted(Boolean addressDetailsCompleted) {\n this.addressDetailsCompleted = addressDetailsCompleted;\n }\n\n public Boolean getBankDetailsCompleted() {\n return bankDetailsCompleted;\n }\n\n public void setBankDetailsCompleted(Boolean bankDetailsCompleted) {\n this.bankDetailsCompleted = bankDetailsCompleted;\n }\n\n public AddressDetails getAddressDetails() {\n return addressDetails;\n }\n\n public void setAddressDetails(AddressDetails addressDetails) {\n this.addressDetails = addressDetails;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getRegisterNumber() {\n return registerNumber;\n }\n\n public void setRegisterNumber(String registerNumber) {\n this.registerNumber = registerNumber;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Set getRoles() {\n return roles;\n }\n\n public void setRoles(Set roles) {\n this.roles = roles;\n }\n\n /*\n public byte[] getProfilePicture() {\n return profilePicture;\n }\n public void setProfilePicture(byte[] profilePicture) {\n this.profilePicture = profilePicture;\n }\n */\n public BankDetails getBankDetails() {\n return bankDetails;\n }\n\n public void setBankDetails(BankDetails bankDetails) {\n this.bankDetails = bankDetails;\n }\n\n //This is ued to indicate user completed all three forms are not.\n public boolean isFormsCompleted() {\n return personalDetailsCompleted && addressDetailsCompleted && bankDetailsCompleted;\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/dashboard/DashboardView.java\n@PageTitle(\"Dashboard\")\n@Route(value = \"dashboard\", layout = MainLayout.class)\n@RouteAlias(value = \"\", layout = MainLayout.class)\n@PermitAll\npublic class DashboardView extends Main {\n\n public DashboardView(UserService userService) {\n addClassName(\"dashboard-view\");\n Board board = new Board();\n board.addRow(\n createHighlight(\"Total Users\", String.valueOf(userService.count())),\n createHighlight(\"Active Users\", String.valueOf(userService.getOnlineUsers().size())));\n add(board);\n }\n\n private Component createHighlight(String title, String value) {\n H2 h2 = new H2(title);\n h2.addClassNames(FontWeight.NORMAL, Margin.NONE, TextColor.SECONDARY, FontSize.SMALL);\n Span span = new Span(value);\n span.addClassNames(FontWeight.SEMIBOLD, FontSize.XXXLARGE);\n VerticalLayout layout = new VerticalLayout(h2, span);\n layout.addClassName(Padding.LARGE);\n layout.setPadding(false);\n layout.setSpacing(false);\n return layout;\n }\n}\n\nsrc/main/java/com/nasc/application/views/student/status/StudentsStatusView.java\n@PageTitle(\"Students Status\")\n@Route(value = \"students-status\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\", \"PROFESSOR\"})\npublic class StudentsStatusView extends VerticalLayout {\n private final UserService userService;\n private final AcademicYearService academicYearService;\n private final DepartmentService departmentService;\n private final Button menuButton = new Button(\"Show/Hide Columns\", FontAwesome.Solid.LIST_CHECK.create());\n private final Anchor downloadLink;\n private final ColumnToggleContextMenu columnToggleContextMenu = new ColumnToggleContextMenu(menuButton);\n private Grid grid;\n private GridListDataView gridListDataView;\n private Grid.Column userColumn;\n private Grid.Column RegisterNumberColumn;\n private final Button searchButton;\n private ComboBox academicYearFilter;\n private ComboBox departmentFilter;\n private ComboBox studentSectionFilter;\n //Layouts\n private HorizontalLayout filterLayout;\n private HorizontalLayout exportAndColumnListLayout;\n\n public StudentsStatusView(UserService userService,\n AcademicYearService academicYearService,\n DepartmentService departmentService\n ) {\n this.userService = userService;\n this.departmentService = departmentService;\n this.academicYearService = academicYearService;\n addClassName(\"students-status-view\");\n setSizeFull();\n createDepartmentFilterComponent();\n createAcademicYearFilterComponent();\n createStudentSectionComboBox();\n createExportAndColumnListLayout();\n downloadLink = createDownloadLink();\n\n menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL);\n\n exportAndColumnListLayout.add(menuButton, downloadLink);\n createGrid();\n createFilterLayout();\n\n searchButton = new Button(\"Search\");\n searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL);\n searchButton.addClickListener(buttonClickEvent -> handleAcademicYearFilterChange());\n\n FlexLayout searchButtonLayout = new FlexLayout(searchButton);\n searchButtonLayout.setJustifyContentMode(JustifyContentMode.END);\n filterLayout.setWidthFull();\n filterLayout.expand(searchButtonLayout);\n filterLayout.add(departmentFilter, academicYearFilter, studentSectionFilter, searchButtonLayout);\n\n add(filterLayout, exportAndColumnListLayout, grid);\n }\n\n private void createFilterLayout() {\n filterLayout = new HorizontalLayout();\n filterLayout.setSpacing(true);\n filterLayout.setAlignItems(Alignment.BASELINE);\n }\n\n private static FontAwesome.Regular.Icon getThumbsUpIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_UP.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private static FontAwesome.Regular.Icon getThumbsDownIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_DOWN.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private void createExportAndColumnListLayout() {\n exportAndColumnListLayout = new HorizontalLayout();\n exportAndColumnListLayout.setWidthFull();\n exportAndColumnListLayout.setJustifyContentMode(JustifyContentMode.END);\n exportAndColumnListLayout.setAlignItems(Alignment.CENTER);\n exportAndColumnListLayout.setSpacing(true);\n }\n\n private Anchor createDownloadLink() {\n Anchor link = new Anchor();\n link.getElement().setAttribute(\"download\", true);\n Button exportButton = new Button(\"Export to CSV\", FontAwesome.Solid.FILE_EXPORT.create());\n exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL, ButtonVariant.LUMO_TERTIARY_INLINE);\n link.add(exportButton);\n return link;\n }\n\n private void createDepartmentFilterComponent() {\n List allDepartment = departmentService.findAll();\n departmentFilter = new ComboBox<>();\n departmentFilter.setLabel(\"Filter by Department\");\n departmentFilter.setItems(allDepartment);\n departmentFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n departmentFilter.setItemLabelGenerator(departmentEntity -> departmentEntity.getName() + \" \" + departmentEntity.getShortName());\n\n }\n\n private void createAcademicYearFilterComponent() {\n List academicYears = academicYearService.findAll();\n academicYearFilter = new ComboBox<>();\n academicYearFilter.setLabel(\"Filter by Academic Year\");\n academicYearFilter.setItems(academicYears);\n academicYearFilter.setItemLabelGenerator(this::generateAcademicYearLabel);\n academicYearFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n }\n\n private void createStudentSectionComboBox() {\n StudentSection[] values = StudentSection.values();\n studentSectionFilter = new ComboBox<>(\"Filter By Student Section\");\n studentSectionFilter.setItems(values);\n studentSectionFilter.setItemLabelGenerator(StudentSection::getDisplayName);\n studentSectionFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n }\n\n private void createGrid() {\n createGridComponent();\n addColumnsToGrid();\n addFiltersToGrid();\n }\n\n private String generateAcademicYearLabel(AcademicYearEntity academicYear) {\n return academicYear.getStartYear() + \" - \" + academicYear.getEndYear();\n }\n\n private void handleAcademicYearFilterChange() {\n refreshGridData();\n }\n\n private static Component createFilterFilter(Consumer filterChangeConsumer) {\n TextField textField = new TextField();\n textField.setValueChangeMode(ValueChangeMode.EAGER);\n textField.setClearButtonVisible(true);\n textField.addThemeVariants(TextFieldVariant.LUMO_SMALL);\n textField.setWidthFull();\n // CASE IN SENSITIVE\n textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase()));\n return textField;\n }\n\n private void addFiltersToGrid() {\n HeaderRow filterRow = grid.appendHeaderRow();\n\n // Username filter\n filterRow.getCell(userColumn)\n .setComponent(createFilterFilter(name -> gridListDataView.setFilter(user -> user\n .getUsername()\n .toLowerCase()\n .contains(name))));\n\n filterRow.getCell(RegisterNumberColumn)\n .setComponent(createFilterFilter(name -> gridListDataView.setFilter(user -> user\n .getRegisterNumber()\n .toLowerCase()\n .contains(name))));\n\n // Status filters\n addStatusFilter(\"Personal Details\", \"personalDetailsCompleted\", filterRow);\n addStatusFilter(\"Address Details\", \"addressDetailsCompleted\", filterRow);\n addStatusFilter(\"Bank Details\", \"bankDetailsCompleted\", filterRow);\n\n ComboBox allFormsFilter = createAllFormsFilter();\n allFormsFilter.addValueChangeListener(this::handleAllFormsFilterChange);\n filterRow.getCell(grid.getColumnByKey(\"allFormsCompleted\")).setComponent(allFormsFilter);\n }\n\n private void addStatusFilter(String columnName, String propertyKey, HeaderRow filterRow) {\n ComboBox statusFilter = createStatusFilter();\n statusFilter.addValueChangeListener(event -> handleStatusFilterChange(event, columnName));\n filterRow.getCell(grid.getColumnByKey(propertyKey)).setComponent(statusFilter);\n }\n\n private ComboBox createStatusFilter() {\n ComboBox statusFilter = new ComboBox<>();\n statusFilter.setItems(Arrays.asList(\"Pending\", \"Success\"));\n statusFilter.setPlaceholder(\"Filter\");\n statusFilter.setClearButtonVisible(true);\n statusFilter.setWidth(\"100%\");\n statusFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n return statusFilter;\n }\n\n private void handleStatusFilterChange(HasValue.ValueChangeEvent event, String columnName) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); //Every Time Drop Down Change, It removes filters from grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areStatusesEqual(user, columnName, filterValue));\n }\n }\n\n private boolean areStatusesEqual(User user, String columnName, String filterValue) {\n switch (columnName) {\n case \"Personal Details\" -> {\n return Boolean.TRUE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Address Details\" -> {\n return Boolean.TRUE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Bank Details\" -> {\n return Boolean.TRUE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n default -> {\n return true;\n }\n }\n }\n\n private ComboBox createAllFormsFilter() {\n ComboBox allFormsFilter = new ComboBox<>();\n allFormsFilter.setItems(Arrays.asList(\"Complete\", \"Incomplete\"));\n allFormsFilter.setPlaceholder(\"Filter\");\n allFormsFilter.setClearButtonVisible(true);\n allFormsFilter.setWidth(\"100%\");\n allFormsFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n return allFormsFilter;\n }\n\n private void handleAllFormsFilterChange(HasValue.ValueChangeEvent event) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); // Every Time Drop Down Change, It removes filters from the grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areAllFormsComplete(user, filterValue));\n }\n }\n\n private boolean areAllFormsComplete(User user, String filterValue) {\n boolean allFormsComplete = user.isFormsCompleted();\n return (allFormsComplete && \"Complete\".equalsIgnoreCase(filterValue)) ||\n (!allFormsComplete && \"Incomplete\".equalsIgnoreCase(filterValue));\n }\n\n private void createGridComponent() {\n grid = new Grid<>();\n grid.setHeight(\"100%\");\n grid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_COLUMN_BORDERS);\n }\n\n private void refreshGridData() {\n AcademicYearEntity academicYearEntity = academicYearFilter.getValue();\n StudentSection studentSection = studentSectionFilter.getValue();\n DepartmentEntity department = departmentFilter.getValue();\n\n if (academicYearEntity != null && studentSection != null && department != null) {\n List users = getStudentsByRoleForLoggedInUserDepartment(department, academicYearEntity, studentSection);\n if (users.isEmpty()) {\n if (users.isEmpty()) {\n NotificationUtils.showWarningNotification(\"No information recorded for the selected academic year\");\n }\n }\n gridListDataView = grid.setItems(users);\n exportToCSV(users);\n }\n }\n\n private void addColumnsToGrid() {\n createUsernameColumn();\n createRegisterNumberColumn();\n createPersonalDetailsColumn();\n createAddressDetailsColumn();\n createBankDetailsColumn();\n createAllFormsCompletedColumn();\n }\n\n private void createUsernameColumn() {\n userColumn = grid.addColumn(User::getUsername)\n .setHeader(\"Username\")\n .setKey(\"username\")\n .setFrozen(true)\n .setComparator((User::getUsername));\n }\n\n private void createRegisterNumberColumn() {\n RegisterNumberColumn = grid.addColumn(User::getRegisterNumber)\n .setHeader(\"Register Number\")\n .setKey(\"Register Number\")\n .setFrozen(true)\n .setComparator((User::getRegisterNumber));\n }\n\n private void createPersonalDetailsColumn() {\n Grid.Column personalDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getPersonalDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getPersonalDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getPersonalDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n }))\n .setHeader(\"Personal Details\")\n .setKey(\"personalDetailsCompleted\")\n .setComparator(User::getUsername);\n\n columnToggleContextMenu.addColumnToggleItem(\"Personal Details Completed\", personalDetailsColumn);\n }\n\n private void createAddressDetailsColumn() {\n Grid.Column addressDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getAddressDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getAddressDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getAddressDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n }))\n .setHeader(\"Address Details\")\n .setKey(\"addressDetailsCompleted\")\n .setComparator(User::getUsername);\n\n\n columnToggleContextMenu.addColumnToggleItem(\"Address Details Completed\", addressDetailsColumn);\n }\n\n private void createBankDetailsColumn() {\n Grid.Column bankDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getBankDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getBankDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getBankDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n }))\n .setHeader(\"Bank Details\")\n .setKey(\"bankDetailsCompleted\")\n .setComparator(User::getUsername);\n\n columnToggleContextMenu.addColumnToggleItem(\"Bank Details\", bankDetailsColumn);\n }\n\n private void createAllFormsCompletedColumn() {\n Grid.Column allFormsCompletedColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n boolean allFormsCompleted = user.isFormsCompleted();\n Span span = new Span(allFormsCompleted ? getThumbsUpIcon() : getThumbsDownIcon(),\n new Span(allFormsCompleted ? \"Complete\" : \"Incomplete\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (allFormsCompleted ? \"success\" : \"error\"));\n return span;\n }))\n .setHeader(\"All Forms Completed\")\n .setKey(\"allFormsCompleted\")\n .setComparator(User::getUsername);\n\n columnToggleContextMenu.addColumnToggleItem(\"All Forms Completed\", allFormsCompletedColumn);\n }\n\n private List getStudentsByRoleForLoggedInUserDepartment(DepartmentEntity department,\n AcademicYearEntity academicYear,\n StudentSection studentSection\n ) {\n return userService.findStudentsByDepartmentAndRoleAndAcademicYearAndSection(\n department,\n Role.STUDENT,\n academicYear,\n studentSection\n );\n }\n\n private Icon createIcon(VaadinIcon vaadinIcon) {\n Icon icon = vaadinIcon.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private void exportToCSV(List users) {\n\n try {\n AcademicYearEntity academicYearEntity = academicYearFilter.getValue();\n // Prepare data for export\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n\n try (CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8))) {\n\n // Write header\n String[] header = {\n \"Username\", \"Register Number\", \"Email\", \"Department\", \"Academic Year\",\n \"Bank Name\", \"Account Holder Name\", \"Account Number\", \"IFSC Code\", \"Branch Name\",\n \"Branch Address\", \"PAN Number\", \"First Name\", \"Last Name\", \"Phone Number\",\n \"Birthday\", \"Gender\", \"Address\", \"Pin code\", \"City\", \"State\", \"Country\"\n };\n csvWriter.writeNext(header);\n\n for (User user : users) {\n List data = new ArrayList<>();\n\n // Common information\n data.add(user.getUsername());\n data.add(user.getRegisterNumber());\n data.add(user.getEmail());\n data.add(user.getDepartment().toString());\n data.add(academicYearEntity.getStartYear() + \" - \" + academicYearEntity.getEndYear());\n\n // Bank details (conditionally added)\n if (Boolean.TRUE.equals(user.getBankDetailsCompleted())) {\n data.add(user.getBankDetails().getBankName());\n data.add(user.getBankDetails().getAccountHolderName());\n data.add(user.getBankDetails().getAccountNumber());\n data.add(user.getBankDetails().getIfscCode());\n data.add(user.getBankDetails().getBranchName());\n data.add(user.getBankDetails().getBranchAddress());\n data.add(user.getBankDetails().getPanNumber());\n } else {\n // Add empty values or placeholders for bank details if not completed\n data.addAll(Collections.nCopies(7, \"\"));\n }\n\n // Personal details\n if (Boolean.TRUE.equals(user.getPersonalDetailsCompleted())) {\n data.add(user.getPersonalDetails().getFirstName());\n data.add(user.getPersonalDetails().getLastName());\n data.add(user.getPersonalDetails().getPhoneNumber());\n data.add(user.getPersonalDetails().getBirthday().toString());\n data.add(user.getPersonalDetails().getGender());\n } else {\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Address details (conditionally added)\n if (Boolean.TRUE.equals(user.getAddressDetailsCompleted())) {\n data.add(user.getAddressDetails().getAddress());\n data.add(user.getAddressDetails().getPinCode());\n data.add(user.getAddressDetails().getCity());\n data.add(user.getAddressDetails().getState());\n data.add(user.getAddressDetails().getCountry());\n } else {\n // Add empty values or placeholders for address details if not completed\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Convert the list to an array and write to CSV`\n csvWriter.writeNext(data.toArray(new String[0]));\n }\n\n String fileName = \"STUDENTS_\"\n + academicYearFilter.getValue().getStartYear()\n + \"_\"\n + academicYearFilter.getValue().getEndYear()\n + \".csv\";\n\n StreamResource resource = new StreamResource(fileName,\n () -> new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));\n\n downloadLink.setHref(resource);\n\n }\n } catch (IOException e) {\n NotificationUtils.showErrorNotification(\"Error exporting data to CSV\");\n }\n }\n\n private static class ColumnToggleContextMenu extends ContextMenu {\n public ColumnToggleContextMenu(Component target) {\n super(target);\n setOpenOnClick(true);\n }\n\n void addColumnToggleItem(String label, Grid.Column column) {\n MenuItem menuItem = this.addItem(label, e -> column.setVisible(e.getSource().isChecked()));\n menuItem.setCheckable(true);\n menuItem.setChecked(column.isVisible());\n menuItem.setKeepOpen(true);\n }\n }\n}\n\nsrc/main/java/com/nasc/application/views/professor/status/ProfessorStatusView.java\n@PageTitle(\"Professor Status\")\n@Route(value = \"professor-status\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\"})\npublic class ProfessorStatusView extends VerticalLayout {\n private final DepartmentService departmentService;\n private final UserService userService;\n private final Anchor downloadLink;\n private final Button menuButton = new Button(\"Show/Hide Columns\", FontAwesome.Solid.LIST_CHECK.create());\n private final ProfessorStatusView.ColumnToggleContextMenu columnToggleContextMenu = new ProfessorStatusView.ColumnToggleContextMenu(menuButton);\n private Grid grid;\n private GridListDataView gridListDataView;\n private Grid.Column userColumn;\n // Layer\n private HorizontalLayout filterLayout;\n private ComboBox departmentFilter;\n private Button searchButton;\n\n public ProfessorStatusView(UserService userService, DepartmentService departmentService) {\n this.userService = userService;\n this.departmentService = departmentService;\n downloadLink = createDownloadLink(); // Add this line to create the download link\n addClassName(\"professor-status-view\");\n setSizeFull();\n createGrid();\n createFilterLayout();\n\n menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL);\n\n HorizontalLayout menuButtonLayout = new HorizontalLayout(menuButton, downloadLink);\n menuButtonLayout.setWidthFull();\n menuButtonLayout.setJustifyContentMode(JustifyContentMode.END);\n menuButtonLayout.setAlignItems(Alignment.CENTER);\n\n createDepartmentFilterComponent();\n\n createSearchButton();\n\n FlexLayout searchButtonLayout = new FlexLayout(searchButton);\n searchButtonLayout.setJustifyContentMode(JustifyContentMode.END);\n filterLayout.setWidthFull();\n filterLayout.expand(searchButtonLayout);\n filterLayout.add(departmentFilter, searchButtonLayout);\n\n add(filterLayout, menuButtonLayout, grid);\n }\n\n private void createSearchButton() {\n searchButton = new Button(\"Search\");\n searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL);\n searchButton.addClickListener(buttonClickEvent -> {\n DepartmentEntity selectedDepartment = departmentFilter.getValue();\n List professors = userService.findUsersByDepartmentAndRole(selectedDepartment, Role.PROFESSOR);\n gridListDataView = grid.setItems(professors);\n exportExport(professors);\n });\n }\n\n\n private void createFilterLayout() {\n filterLayout = new HorizontalLayout();\n filterLayout.setSpacing(true);\n filterLayout.setAlignItems(Alignment.BASELINE);\n }\n\n private void createDepartmentFilterComponent() {\n List allDepartment = departmentService.findAll();\n departmentFilter = new ComboBox<>();\n departmentFilter.setItems(allDepartment);\n departmentFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n departmentFilter.setItemLabelGenerator(departmentEntity -> departmentEntity.getName() + \" \" + departmentEntity.getShortName());\n departmentFilter.setLabel(\"Filter By Department\");\n }\n\n private static FontAwesome.Regular.Icon getThumbsUpIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_UP.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private static FontAwesome.Regular.Icon getThumbsDownIcon() {\n FontAwesome.Regular.Icon icon = FontAwesome.Regular.THUMBS_DOWN.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private Anchor createDownloadLink() {\n Anchor link = new Anchor();\n link.getElement().setAttribute(\"download\", true);\n Button exportButton = new Button(\"Export to CSV\", FontAwesome.Solid.FILE_EXPORT.create());\n exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL, ButtonVariant.LUMO_TERTIARY_INLINE);\n link.add(exportButton);\n return link;\n }\n\n private void createGrid() {\n createGridComponent();\n addColumnsToGrid();\n addFiltersToGrid();\n }\n\n private void addFiltersToGrid() {\n HeaderRow filterRow = grid.appendHeaderRow();\n\n // Username filter\n TextField userFilter = createTextFilter();\n userFilter.addValueChangeListener(event -> gridListDataView\n .addFilter(user -> StringUtils.containsIgnoreCase(user.getUsername(), userFilter.getValue())));\n filterRow.getCell(userColumn).setComponent(userFilter);\n\n // Status filters\n addStatusFilter(\"Personal Details\", \"personalDetailsCompleted\", filterRow);\n addStatusFilter(\"Address Details\", \"addressDetailsCompleted\", filterRow);\n addStatusFilter(\"Bank Details\", \"bankDetailsCompleted\", filterRow);\n\n ComboBox allFormsFilter = createAllFormsFilter();\n allFormsFilter.addValueChangeListener(this::handleAllFormsFilterChange);\n filterRow.getCell(grid.getColumnByKey(\"allFormsCompleted\")).setComponent(allFormsFilter);\n }\n\n private TextField createTextFilter() {\n TextField filter = new TextField();\n filter.setPlaceholder(\"Filter\");\n filter.setClearButtonVisible(true);\n filter.setWidthFull();\n filter.setValueChangeMode(ValueChangeMode.EAGER);\n filter.addThemeVariants(TextFieldVariant.LUMO_SMALL);\n return filter;\n }\n\n private void addStatusFilter(String columnName, String propertyKey, HeaderRow filterRow) {\n ComboBox statusFilter = createStatusFilter();\n statusFilter.addValueChangeListener(event -> handleStatusFilterChange(event, columnName));\n filterRow.getCell(grid.getColumnByKey(propertyKey)).setComponent(statusFilter);\n }\n\n private ComboBox createStatusFilter() {\n ComboBox statusFilter = new ComboBox<>();\n statusFilter.setItems(Arrays.asList(\"Pending\", \"Success\"));\n statusFilter.setPlaceholder(\"Filter\");\n statusFilter.setClearButtonVisible(true);\n statusFilter.setWidth(\"100%\");\n statusFilter.addThemeVariants(ComboBoxVariant.LUMO_SMALL);\n return statusFilter;\n }\n\n private void handleStatusFilterChange(HasValue.ValueChangeEvent event, String columnName) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); //Every Time Drop Down Change, It removes filters from grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areStatusesEqual(user, columnName, filterValue));\n }\n }\n\n private boolean areStatusesEqual(User user, String columnName, String filterValue) {\n switch (columnName) {\n case \"Personal Details\" -> {\n return Boolean.TRUE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getPersonalDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Address Details\" -> {\n return Boolean.TRUE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getAddressDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n case \"Bank Details\" -> {\n return Boolean.TRUE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Success\") || Boolean.FALSE.equals(user.getBankDetailsCompleted()) &&\n filterValue.equals(\"Pending\");\n }\n default -> {\n return true;\n }\n }\n }\n\n private ComboBox createAllFormsFilter() {\n ComboBox allFormsFilter = new ComboBox<>();\n allFormsFilter.setItems(Arrays.asList(\"Complete\", \"Incomplete\"));\n allFormsFilter.setPlaceholder(\"Filter\");\n allFormsFilter.setClearButtonVisible(true);\n allFormsFilter.setWidth(\"100%\");\n return allFormsFilter;\n }\n\n private void handleAllFormsFilterChange(HasValue.ValueChangeEvent event) {\n String filterValue = event.getValue();\n gridListDataView.removeFilters(); // Every Time Drop Down Change, It removes filters from the grid.\n if (StringUtils.isBlank(filterValue)) {\n gridListDataView.removeFilters();\n } else {\n gridListDataView.addFilter(user -> areAllFormsComplete(user, filterValue));\n }\n }\n\n private boolean areAllFormsComplete(User user, String filterValue) {\n boolean allFormsComplete = user.isFormsCompleted();\n return (allFormsComplete && \"Complete\".equalsIgnoreCase(filterValue)) ||\n (!allFormsComplete && \"Incomplete\".equalsIgnoreCase(filterValue));\n }\n\n private void createGridComponent() {\n grid = new Grid<>();\n grid.addThemeVariants(GridVariant.LUMO_COMPACT, GridVariant.LUMO_COLUMN_BORDERS);\n grid.setHeight(\"100%\");\n }\n\n private void addColumnsToGrid() {\n createUsernameColumn();\n createPersonalDetailsColumn();\n createAddressDetailsColumn();\n createBankDetailsColumn();\n createAllFormsCompletedColumn();\n }\n\n private void createUsernameColumn() {\n userColumn = grid.addColumn(User::getUsername).setHeader(\"Username\").setKey(\"username\").setComparator((User::getUsername));\n }\n\n private void createPersonalDetailsColumn() {\n Grid.Column personalDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getPersonalDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getPersonalDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getPersonalDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n })).setHeader(\"Personal Details\").setKey(\"personalDetailsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"Personal Details Completed\", personalDetailsColumn);\n }\n\n private void createAddressDetailsColumn() {\n Grid.Column addressDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getAddressDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getAddressDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getAddressDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n })).setHeader(\"Address Details\").setKey(\"addressDetailsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"Address Details Completed\", addressDetailsColumn);\n }\n\n private void createBankDetailsColumn() {\n Grid.Column bankDetailsColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n Span span = new Span(user.getBankDetailsCompleted() ? createIcon(VaadinIcon.CHECK) : createIcon(VaadinIcon.CLOCK),\n new Span(user.getBankDetailsCompleted() ? \"Success\" : \"Pending\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (user.getBankDetailsCompleted() ? \"success\" : \"pending\"));\n return span;\n })).setHeader(\"Bank Details\").setKey(\"bankDetailsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"Bank Details\", bankDetailsColumn);\n }\n\n private void createAllFormsCompletedColumn() {\n Grid.Column allFormsCompletedColumn = grid.addColumn(new ComponentRenderer<>(user -> {\n boolean allFormsCompleted = user.isFormsCompleted();\n Span span = new Span(allFormsCompleted ? getThumbsUpIcon() : getThumbsDownIcon(),\n new Span(allFormsCompleted ? \"Complete\" : \"Incomplete\"));\n span.getElement().setAttribute(\"theme\", \"badge \" + (allFormsCompleted ? \"success\" : \"error\"));\n return span;\n })).setHeader(\"All Forms Completed\").setKey(\"allFormsCompleted\").setComparator(User::getUsername);\n columnToggleContextMenu.addColumnToggleItem(\"All Forms Completed\", allFormsCompletedColumn);\n }\n\n private Icon createIcon(VaadinIcon vaadinIcon) {\n Icon icon = vaadinIcon.create();\n icon.getStyle().set(\"padding\", \"var(--lumo-space-xs\");\n return icon;\n }\n\n private void exportExport(List users) {\n\n try {\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n\n try (CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8))) {\n\n // Write header\n String[] header = {\n \"Username\", \"Register Number\", \"Email\", \"Department\",\n \"Bank Name\", \"Account Holder Name\", \"Account Number\", \"IFSC Code\", \"Branch Name\",\n \"Branch Address\", \"PAN Number\", \"First Name\", \"Last Name\", \"Phone Number\",\n \"Birthday\", \"Gender\", \"Address\", \"Pin code\", \"City\", \"State\", \"Country\"\n };\n csvWriter.writeNext(header);\n\n for (User user : users) {\n List data = new ArrayList<>();\n\n // Common information\n data.add(user.getUsername());\n data.add(user.getRegisterNumber());\n data.add(user.getEmail());\n data.add(user.getDepartment().toString());\n\n // Bank details (conditionally added)\n if (Boolean.TRUE.equals(user.getBankDetailsCompleted())) {\n data.add(user.getBankDetails().getBankName());\n data.add(user.getBankDetails().getAccountHolderName());\n data.add(user.getBankDetails().getAccountNumber());\n data.add(user.getBankDetails().getIfscCode());\n data.add(user.getBankDetails().getBranchName());\n data.add(user.getBankDetails().getBranchAddress());\n data.add(user.getBankDetails().getPanNumber());\n } else {\n // Add empty values or placeholders for bank details if not completed\n data.addAll(Collections.nCopies(7, \"\"));\n }\n\n // Personal details\n if (Boolean.TRUE.equals(user.getPersonalDetailsCompleted())) {\n data.add(user.getPersonalDetails().getFirstName());\n data.add(user.getPersonalDetails().getLastName());\n data.add(user.getPersonalDetails().getPhoneNumber());\n data.add(user.getPersonalDetails().getBirthday().toString());\n data.add(user.getPersonalDetails().getGender());\n } else {\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Address details (conditionally added)\n if (Boolean.TRUE.equals(user.getAddressDetailsCompleted())) {\n data.add(user.getAddressDetails().getAddress());\n data.add(user.getAddressDetails().getPinCode());\n data.add(user.getAddressDetails().getCity());\n data.add(user.getAddressDetails().getState());\n data.add(user.getAddressDetails().getCountry());\n } else {\n // Add empty values or placeholders for address details if not completed\n data.addAll(Collections.nCopies(5, \"\"));\n }\n\n // Convert the list to an array and write to CSV\n csvWriter.writeNext(data.toArray(new String[0]));\n }\n\n DepartmentEntity department = departmentFilter.getValue();\n\n StringJoiner stringJoiner = new StringJoiner(\"_\");\n stringJoiner.add(department.getName());\n stringJoiner.add(department.getShortName());\n\n String fileName = stringJoiner + \".csv\";\n StreamResource resource = new StreamResource(fileName,\n () -> new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));\n\n downloadLink.setHref(resource);\n }\n } catch (IOException e) {\n NotificationUtils.showErrorNotification(\"Error exporting data to CSV\");\n }\n }\n\n private static class ColumnToggleContextMenu extends ContextMenu {\n public ColumnToggleContextMenu(Component target) {\n super(target);\n setOpenOnClick(true);\n }\n\n void addColumnToggleItem(String label, Grid.Column column) {\n MenuItem menuItem = this.addItem(label, e -> column.setVisible(e.getSource().isChecked()));\n menuItem.setCheckable(true);\n menuItem.setChecked(column.isVisible());\n menuItem.setKeepOpen(true);\n }\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/auth/create/CreateUsers.java\n@PageTitle(\"Create User Account\")\n@Route(value = \"create-user\", layout = MainLayout.class)\n@RolesAllowed({\"EDITOR\", \"ADMIN\"})\n@JsModule(\"./recipe/copytoclipboard/copytoclipboard.js\")\n@Slf4j\npublic class CreateUsers extends VerticalLayout {\n\n private final DepartmentService departmentService;\n private final AcademicYearService academicYearService;\n private final UserService userService;\n private final PasswordEncoder passwordEncoder;\n private final Upload upload;\n private final Grid userGrid;\n private final Checkbox verifyCheckbox;\n private final Button createUserButton;\n private ComboBox roleComboBox;\n private ComboBox departmentComboBox;\n private ComboBox academicYearComboBox;\n private ComboBox studentSectionComboBox;\n\n public CreateUsers(UserService userService,\n PasswordEncoder passwordEncoder,\n DepartmentService departmentService,\n AcademicYearService academicYearService) {\n this.userService = userService;\n this.passwordEncoder = passwordEncoder;\n this.departmentService = departmentService;\n this.academicYearService = academicYearService;\n\n // Title for the view\n add(new H3(\"Create Users\"));\n\n // Helper text for upload\n add(new H3(\"Upload CSV with user details\"));\n add(new H3(\"Columns: username, registerNumber, email, password\"));\n\n MemoryBuffer buffer = new MemoryBuffer();\n upload = new Upload(buffer);\n upload.setAcceptedFileTypes(\"text/csv\");\n upload.addSucceededListener(event -> handleFileUpload(event, buffer.getInputStream()));\n\n userGrid = new Grid<>(User.class);\n userGrid.removeAllColumns();\n\n //This theme has a compact interface\n userGrid.addThemeVariants(GridVariant.LUMO_COMPACT);\n\n userGrid.addColumn(User::getUsername).setHeader(\"Username\").setSortable(true).setComparator(User::getUsername);\n userGrid.addColumn(User::getRegisterNumber).setHeader(\"Register Number\").setSortable(true).setComparator(User::getRegisterNumber);\n userGrid.addColumn(User::getEmail).setHeader(\"Email\").setSortable(true).setComparator(User::getEmail);\n userGrid.addColumn(User::getPassword).setHeader(\"Password\").setSortable(true).setComparator(User::getPassword);\n\n verifyCheckbox = new Checkbox(\"Verified\");\n verifyCheckbox.addValueChangeListener(this::verifyCheckboxChanged);\n\n createUserButton = new Button(\"Create Users\", event -> {\n try {\n if (buffer.getInputStream() == null || buffer.getInputStream().available() == 0) {\n NotificationUtils.showInfoNotification(\"Please upload a CSV file before processing.\");\n return;\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n createUserButtonClicked(buffer.getInputStream());\n });\n createUserButton.setEnabled(verifyCheckbox.getValue());\n\n createRoleComboBox();\n createDepartmentComboBox();\n createAcademicYearComboBox();\n createStudentSectionComboBox();\n downloadSampleCsv();\n\n academicYearComboBox.setVisible(false);\n studentSectionComboBox.setVisible(false);\n HorizontalLayout horizontalLayout = new HorizontalLayout(roleComboBox, departmentComboBox, academicYearComboBox, studentSectionComboBox);\n\n // Horizontal layout for checkbox and button\n HorizontalLayout checkboxButtonLayout = new HorizontalLayout(verifyCheckbox, createUserButton);\n checkboxButtonLayout.setWidthFull();\n checkboxButtonLayout.setJustifyContentMode(JustifyContentMode.END);\n checkboxButtonLayout.setAlignItems(Alignment.CENTER);\n\n // Initialize the state of the \"Create Users\" button based on the initial value of the verifyCheckbox\n createUserButton.setEnabled(verifyCheckbox.getValue());\n\n add(upload, horizontalLayout, checkboxButtonLayout, userGrid);\n }\n\n private void handleFileUpload(SucceededEvent event, InputStream stream) {\n String mimeType = event.getMIMEType();\n if (\"text/csv\".equals(mimeType)) {\n try (Reader reader = new InputStreamReader(stream)) {\n // Parse CSV file and process data\n List users = readCSV(reader);\n\n // Use DataProvider to set items in the grid\n userGrid.setDataProvider(DataProvider.fromStream(users.stream()));\n NotificationUtils.createUploadSuccess(\"File uploaded successfully\", event.getFileName());\n } catch (Exception e) {\n NotificationUtils.showErrorNotification(\"Error processing the CSV file\");\n }\n } else {\n NotificationUtils.showErrorNotification(\"Please select a valid CSV file\");\n }\n }\n\n private List readCSV(Reader reader) throws IOException, CsvException {\n // Use OpenCSV to parse the CSV file\n try (CSVReader csvReader = new CSVReader(reader)) {\n HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy<>();\n strategy.setType(User.class);\n return new CsvToBeanBuilder(csvReader)\n .withMappingStrategy(strategy)\n .build()\n .parse();\n }\n }\n\n private void verifyCheckboxChanged(HasValue.ValueChangeEvent event) {\n boolean isVerified = verifyCheckbox.getValue();\n createUserButton.setEnabled(isVerified);\n }\n\n private void createUserButtonClicked(InputStream inputStream) {\n\n try (Reader reader = new InputStreamReader(inputStream)) {\n List users = readCSV(reader);\n\n Role selectedRole = roleComboBox.getValue();\n DepartmentEntity selectedDepartmentEntity = departmentComboBox.getValue();\n AcademicYearEntity selectedAcademicYearEntity = academicYearComboBox.getValue();\n StudentSection studentSection = studentSectionComboBox.getValue();\n\n // Clear previous error messages\n clearErrorMessages();\n\n // Validate the selected values\n boolean isValid = true;\n\n if (selectedRole == null) {\n setComboBoxError(roleComboBox, \"Please select a role\");\n isValid = false;\n }\n\n if (selectedDepartmentEntity == null) {\n setComboBoxError(departmentComboBox, \"Please select a department\");\n isValid = false;\n }\n\n if (selectedRole == Role.STUDENT) {\n if (selectedAcademicYearEntity == null) {\n setComboBoxError(academicYearComboBox, \"Please select an academic year\");\n isValid = false;\n }\n\n if (studentSection == null) {\n setComboBoxError(studentSectionComboBox, \"Please select an student section\");\n isValid = false;\n }\n }\n\n if (!isValid) {\n // Show a common error message or handle the invalid state as needed\n NotificationUtils.showInfoNotification(\"Please correct the highlighted fields\");\n return;\n }\n\n // Check for duplicate register numbers\n List existingRegisterNumbers = userService.findExistingRegisterNumbers(users.stream()\n .map(User::getRegisterNumber)\n .collect(Collectors.toList()));\n\n List duplicateRegisterNumbers = existingRegisterNumbers.stream()\n .filter(registerNumber -> users.stream().anyMatch(user -> user.getRegisterNumber().equals(registerNumber)))\n .toList();\n\n if (!duplicateRegisterNumbers.isEmpty()) {\n // Display a dialog with information about duplicate register numbers\n showDuplicateDialog(duplicateRegisterNumbers);\n return;\n }\n\n users.forEach(user -> {\n user.setRoles(Set.of(selectedRole));\n user.setPassword(passwordEncoder.encode(user.getPassword()));\n user.setDepartment(departmentComboBox.getValue());\n\n // Set academic year only for students\n if (selectedRole == Role.STUDENT) {\n user.setAcademicYear(selectedAcademicYearEntity);\n user.setStudentSection(studentSection);\n }\n\n });\n\n userService.saveAll(users);\n NotificationUtils.showSuccessNotification(\"Users created successfully\");\n } catch (IOException | CsvException e) {\n throw new RuntimeException(e);\n }\n }\n\n private void createDepartmentComboBox() {\n departmentComboBox = new ComboBox<>(\"Select Department\");\n departmentComboBox.setItemLabelGenerator(DepartmentEntity::getName);\n departmentComboBox.setItems(departmentService.findAll());\n departmentComboBox.setRequired(true);\n }\n\n private void createRoleComboBox() {\n roleComboBox = new ComboBox<>(\"Select Role\");\n\n // Filter out excluded roles (EDITOR and ADMIN)\n roleComboBox.setItems(Arrays.stream(Role.values())\n .filter(role -> !Arrays.asList(Role.EDITOR, Role.ADMIN).contains(role))\n .collect(Collectors.toList()));\n roleComboBox.setItemLabelGenerator(Role::getDisplayName);\n roleComboBox.setRequired(true);\n roleComboBox.addValueChangeListener(event -> {\n Role selectedRole = event.getValue();\n if (selectedRole == Role.STUDENT) {\n // If student role is selected, enable the academic year ComboBox\n academicYearComboBox.setVisible(true);\n academicYearComboBox.setRequired(true);\n\n studentSectionComboBox.setVisible(true);\n studentSectionComboBox.setRequired(true);\n } else {\n // If any other role is selected, disable the academic year ComboBox and clear its value\n academicYearComboBox.setVisible(false);\n academicYearComboBox.setRequired(false);\n academicYearComboBox.clear();\n\n studentSectionComboBox.setVisible(false);\n studentSectionComboBox.setRequired(false);\n studentSectionComboBox.clear();\n }\n });\n }\n\n //Utility\n private String generateAcademicYearLabel(AcademicYearEntity academicYear) {\n return academicYear.getStartYear() + \" - \" + academicYear.getEndYear();\n }\n\n private void createAcademicYearComboBox() {\n academicYearComboBox = new ComboBox<>(\"Select Academic Year\");\n academicYearComboBox.setItemLabelGenerator(this::generateAcademicYearLabel);\n academicYearComboBox.setItems(academicYearService.findAll());\n }\n\n private void createStudentSectionComboBox() {\n StudentSection[] values = StudentSection.values();\n studentSectionComboBox = new ComboBox<>(\"Select Student Section\");\n studentSectionComboBox.setItems(values);\n studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName);\n }\n\n private void downloadSampleCsv() {\n String sampleCsvContent = \"username,registerNumber,email,password\\nganesh,2122k1466,ganesh@mail.com,password123\";\n Button button = new Button(\"Download Sample CSV\", LumoIcon.DOWNLOAD.create());\n FileDownloadWrapper buttonWrapper = new FileDownloadWrapper(\n new StreamResource(\"sample.csv\", () -> new ByteArrayInputStream(sampleCsvContent.getBytes())));\n buttonWrapper.wrapComponent(button);\n add(buttonWrapper);\n }\n\n private void showDuplicateDialog(List duplicateRegisterNumbers) {\n Dialog dialog = new Dialog();\n dialog.setModal(true);\n dialog.setCloseOnEsc(false);\n dialog.setCloseOnOutsideClick(false);\n\n Button copyBtn = new Button(\"Copy\", FontAwesome.Regular.CLIPBOARD.create());\n copyBtn.addClickListener(event ->\n {\n UI.getCurrent().getPage().executeJs(\"window.copyToClipboard($0)\",\n duplicateRegisterNumbers\n .stream()\n .collect(Collectors.joining(\"\\n\", \"\", \"\\n\")));\n NotificationUtils.showInfoNotification(\"Register numbers copied to clipboard\");\n }\n );\n\n dialog.getFooter().add(copyBtn);\n\n Button cancelBtn = new Button(\"Close\", event -> dialog.close());\n cancelBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n dialog.getFooter().add(cancelBtn);\n\n dialog.setHeaderTitle(\"Duplicate Account's Detected\");\n\n Grid grid = new Grid<>();\n grid.setItems(duplicateRegisterNumbers);\n\n grid.addColumn(String::valueOf).setHeader(\"Register Number\");\n\n dialog.add(grid);\n dialog.open();\n }\n\n // Helpers\n private void clearErrorMessages() {\n departmentComboBox.setErrorMessage(null);\n roleComboBox.setErrorMessage(null);\n academicYearComboBox.setErrorMessage(null);\n studentSectionComboBox.setErrorMessage(null);\n }\n\n private void setComboBoxError(ComboBox comboBox, String errorMessage) {\n comboBox.setInvalid(true);\n comboBox.setErrorMessage(errorMessage);\n }\n}\n\nsrc/main/java/com/nasc/application/views/address/AddressMasterDetailView.java\n@PageTitle(\"Address Master Detail\")\n@Route(value = \"student-master-detail/:sampleAddressID?/:action?(edit)\", layout = MainLayout.class)\n@RolesAllowed(\"HOD\")\n@Slf4j\npublic class AddressMasterDetailView extends Div implements BeforeEnterObserver, BeforeLeaveObserver {\n\n private final String SAMPLEADDRESS_ID = \"sampleAddressID\";\n private final String SAMPLEADDRESS_EDIT_ROUTE_TEMPLATE = \"student-master-detail/%s/edit\";\n private final Grid grid = new Grid<>(AddressDetails.class, false);\n private final BeanValidationBinder binder;\n private final CountryService countryService;\n private final StateService stateService;\n private TextField username;\n private TextField city;\n private TextField registerNumber;\n private TextField address;\n private final Button cancel = new Button(\"Cancel\");\n private final Button save = new Button(\"Save\");\n private TextField pinCode;\n private Select state;\n private final SampleAddressService sampleAddressService;\n private Select country;\n private AddressDetails addressDetails;\n\n public AddressMasterDetailView(SampleAddressService sampleAddressService,\n CountryService countryService,\n StateService stateService) {\n this.sampleAddressService = sampleAddressService;\n this.countryService = countryService;\n this.stateService = stateService;\n addClassNames(\"address-master-detail-view\");\n\n // Create UI\n SplitLayout splitLayout = new SplitLayout();\n\n createGridLayout(splitLayout);\n createEditorLayout(splitLayout);\n\n add(splitLayout);\n\n // Configure Grid\n grid.addColumn(AddressDetails -> AddressDetails.getUser().getUsername())\n .setHeader(\"User Name\")\n .setAutoWidth(true)\n .setComparator(Comparator.comparing(addressDetails -> addressDetails.getUser().getUsername()));\n\n grid.addColumn(AddressDetails -> AddressDetails.getUser().getRegisterNumber())\n .setHeader(\"Register Number\")\n .setAutoWidth(true)\n .setComparator(Comparator.comparing(addressDetails1 -> addressDetails1.getUser().getRegisterNumber()));\n\n\n grid.addColumn(\"address\").setAutoWidth(true);\n grid.addColumn(\"pinCode\").setAutoWidth(true);\n grid.addColumn(\"city\").setAutoWidth(true);\n grid.addColumn(\"state\").setAutoWidth(true);\n grid.addColumn(\"country\").setAutoWidth(true);\n grid.setItems(query -> sampleAddressService.list(\n PageRequest.of(query.getPage(), query.getPageSize(), VaadinSpringDataHelpers.toSpringDataSort(query)))\n .stream());\n grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);\n\n // when a row is selected or deselected, populate form\n grid.asSingleSelect().addValueChangeListener(event -> {\n if (event.getValue() != null) {\n UI.getCurrent().navigate(String.format(SAMPLEADDRESS_EDIT_ROUTE_TEMPLATE, event.getValue().getId()));\n } else {\n clearForm();\n UI.getCurrent().navigate(AddressMasterDetailView.class);\n }\n });\n\n // Configure Form\n binder = new BeanValidationBinder<>(AddressDetails.class);\n\n // Bind fields. This is where you'd define e.g. validation rules\n binder.bindInstanceFields(this);\n\n binder.forField(state)\n .bind(AddressDetails::getState, AddressDetails::setState);\n\n binder.forField(country)\n .bind(AddressDetails::getCountry, AddressDetails::setCountry);\n\n cancel.addClickListener(e -> {\n clearForm();\n refreshGrid();\n });\n\n save.addClickListener(e -> {\n try {\n binder.writeBean(this.addressDetails);\n sampleAddressService.update(this.addressDetails);\n\n UI.getCurrent().navigate(AddressMasterDetailView.class);\n\n refreshGrid();\n NotificationUtils.showSuccessNotification(\"Data updated\");\n clearForm();\n } catch (ObjectOptimisticLockingFailureException exception) {\n NotificationUtils.showErrorNotification(\"Error updating the data. Somebody else has updated the record while you were making changes.\");\n } catch (ValidationException validationException) {\n NotificationUtils.showErrorNotification(\"Failed to update the data. Check again that all values are valid\");\n }\n });\n }\n\n @Override\n public void beforeEnter(BeforeEnterEvent event) {\n Optional sampleAddressId = event.getRouteParameters().get(SAMPLEADDRESS_ID).map(Long::parseLong);\n if (sampleAddressId.isPresent()) {\n Optional sampleAddressFromBackend = sampleAddressService.get(sampleAddressId.get());\n if (sampleAddressFromBackend.isPresent()) {\n populateForm(sampleAddressFromBackend.get());\n } else {\n String message = String.format(\"The requested sampleAddress was not found, ID = %s\", sampleAddressId.get());\n NotificationUtils.showErrorNotification(message);\n refreshGrid();\n event.forwardTo(AddressMasterDetailView.class);\n }\n }\n }\n\n private void createEditorLayout(SplitLayout splitLayout) {\n Div editorLayoutDiv = new Div();\n editorLayoutDiv.setClassName(\"editor-layout\");\n\n Div editorDiv = new Div();\n editorDiv.setClassName(\"editor\");\n editorLayoutDiv.add(editorDiv);\n\n FormLayout formLayout = new FormLayout();\n username = new TextField(\"User Name\");\n registerNumber = new TextField(\"Register Number\");\n address = new TextField(\"address\");\n pinCode = new TextField(\"Postal Code\");\n city = new TextField(\"City\");\n\n state = new Select<>();\n state.setLabel(\"State\");\n state.setItems(stateService.getAllStates());\n state.setPlaceholder(\"Select State\");\n state.setRequiredIndicatorVisible(true);\n\n country = new Select<>();\n country.setLabel(\"Country\");\n country.setItems(countryService.getAllCountries());\n country.setPlaceholder(\"Select Country\");\n country.setRequiredIndicatorVisible(true);\n\n username.setEnabled(false);\n registerNumber.setEnabled(false);\n\n formLayout.add(username, registerNumber, address, pinCode, city, state, country);\n\n editorDiv.add(formLayout);\n createButtonLayout(editorLayoutDiv);\n\n splitLayout.addToSecondary(editorLayoutDiv);\n }\n\n private void createButtonLayout(Div editorLayoutDiv) {\n HorizontalLayout buttonLayout = new HorizontalLayout();\n buttonLayout.setClassName(\"button-layout\");\n cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);\n save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n buttonLayout.add(save, cancel);\n editorLayoutDiv.add(buttonLayout);\n }\n\n private void createGridLayout(SplitLayout splitLayout) {\n Div wrapper = new Div();\n wrapper.setClassName(\"grid-wrapper\");\n splitLayout.addToPrimary(wrapper);\n wrapper.add(grid);\n }\n\n private void refreshGrid() {\n grid.select(null);\n grid.getDataProvider().refreshAll();\n }\n\n private void clearForm() {\n populateForm(null);\n }\n\n private void populateForm(AddressDetails value) {\n this.addressDetails = value;\n\n // Bind the rest of the fields\n binder.readBean(this.addressDetails);\n\n // Set values for disabled fields\n if (value != null && value.getUser() != null) {\n username.setValue(value.getUser().getUsername());\n registerNumber.setValue(value.getUser().getRegisterNumber());\n } else {\n // Clear values if no addressDetails provided\n username.clear();\n registerNumber.clear();\n }\n }\n\n @Override\n public void beforeLeave(BeforeLeaveEvent event) {\n // only prevent if certain condition is met. In my example I prevent navigation if binder has changes.\n if (binder.hasChanges()) {\n\n // prevents navigation\n BeforeLeaveEvent.ContinueNavigationAction action = event.postpone();\n\n // after you prevented the navigation, you are still able to proceed with the navigation, by using action.proceed();\n // it is good practice IMO to give the user the choice to navigate away anyway, if they wish so.\n ConfirmDialog dialog = new ConfirmDialog(\n \"Unsaved Changes\",\n \"You have unsaved changes. Are you sure you want to leave this anyway?\",\n \"Yes\", confirmEvent -> {\n // do the navigation anyway\n action.proceed();\n },\n \"No\", cancelEvent -> {\n // navigation was already prevented with event.postpone() so nothing has to be done here\n }\n );\n dialog.open();\n }\n }\n}\n\nsrc/main/java/com/nasc/application/views/valuevalut/ValueVaultView.java\n@PageTitle(\"Value Vault\")\n@Route(value = \"value-vault\", layout = MainLayout.class)\n@RolesAllowed(\"EDITOR\")\n@UIScope\n@Component\npublic class ValueVaultView extends Div {\n\n public ValueVaultView(\n CreateStateCrud createStateCrud,\n CreateDistrictCrud createDistrictCrud,\n CreateCountryCrud createCountryCrud,\n CreateBloodGroupCrud createBloodGroupCrud,\n CreateDepartmentCrud createDepartmentCrud,\n CreateAcademicYearCrud createAcademicYearCrud\n ) {\n TabSheet tabSheet = new TabSheet();\n tabSheet.add(\"State\", createStateCrud);\n tabSheet.add(\"District\", createDistrictCrud);\n tabSheet.add(\"Country\", createCountryCrud);\n tabSheet.add(\"Blood Group\", createBloodGroupCrud);\n tabSheet.add(\"Department\", createDepartmentCrud);\n tabSheet.add(\"Academic Year\", createAcademicYearCrud);\n tabSheet.setSizeFull();\n setSizeFull();\n add(tabSheet);\n }\n}\n\nsrc/main/java/com/nasc/application/views/forms/adderss/AddressFormView.java\n@PageTitle(\"Address Form\")\n@Route(value = \"address-form\", layout = MainLayout.class)\n@RolesAllowed({\"STUDENT\", \"PROFESSOR\", \"HOD\"})\npublic class AddressFormView extends Composite {\n private final VerticalLayout layoutColumn2 = new VerticalLayout();\n private final FormLayout formLayout2Col = new FormLayout();\n private final HorizontalLayout layoutRow = new HorizontalLayout();\n private final TextArea address = new TextArea();\n private final TextField pinCode = new TextField();\n private final TextField city = new TextField();\n private final Select state = new Select<>();\n private final Select country = new Select<>();\n private final UserService userService;\n private final BeanValidationBinder binder = new BeanValidationBinder<>(AddressDetails.class);\n Button saveButtonPrimary = new Button();\n\n public AddressFormView(CountryService countryService, StateService stateService, UserService userService) {\n this.userService = userService;\n binder.bindInstanceFields(this);\n initLayout(countryService, stateService);\n initFormWithExistingDetails();\n }\n\n private void initLayout(CountryService countryService, StateService stateService) {\n\n List allCountries = countryService.getAllCountries();\n List allStates = stateService.getAllStates();\n\n H3 h3 = new H3(\"Address Form\");\n\n address.setLabel(\"Address\");\n address.setRequiredIndicatorVisible(true);\n\n pinCode.setLabel(\"Pin Code\");\n pinCode.setRequiredIndicatorVisible(true);\n\n city.setLabel(\"City\");\n city.setRequiredIndicatorVisible(true);\n\n // Set up styles and layout properties\n getContent().setWidthFull();\n getContent().getStyle().set(\"flex-grow\", \"1\");\n getContent().setJustifyContentMode(JustifyContentMode.START);\n getContent().setAlignItems(Alignment.CENTER);\n layoutColumn2.setWidthFull();\n layoutColumn2.setMaxWidth(\"800px\");\n layoutColumn2.setSpacing(true);\n\n // Set up components\n h3.getStyle().set(\"margin-bottom\", \"20px\");\n address.setWidth(\"100%\");\n formLayout2Col.setWidth(\"100%\");\n pinCode.setWidth(\"100%\");\n\n country.setLabel(\"Country\");\n country.setItems(allCountries);\n country.setPlaceholder(\"Select Country\");\n country.setRequiredIndicatorVisible(true);\n country.getStyle().setWidth(\"100%\");\n\n state.setLabel(\"State\");\n state.setPlaceholder(\"Select State\");\n state.setItems(allStates);\n state.setRequiredIndicatorVisible(true);\n state.getStyle().setWidth(\"100%\");\n\n layoutRow.setSpacing(true);\n\n // Customize button styles\n saveButtonPrimary.setText(\"Save\");\n saveButtonPrimary.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n binder.addStatusChangeListener(e -> saveButtonPrimary.setEnabled(binder.isValid()));\n\n saveButtonPrimary.addClickListener(\n event -> {\n try {\n binder.writeBean(createAddressDetailsFromForm());\n if (isAddressDetailsAlreadySaved()) {\n updateAddressDetails();\n } else {\n saveAddressDetails();\n }\n } catch (ValidationException e) {\n Notification.show(e.getMessage());\n }\n });\n\n // Build the layout hierarchy\n getContent().add(layoutColumn2);\n layoutColumn2.add(h3, address, formLayout2Col, layoutRow);\n formLayout2Col.add(pinCode, city, country, state);\n layoutRow.add(saveButtonPrimary);\n }\n\n private void initFormWithExistingDetails() {\n User currentUser = userService.getCurrentUser();\n AddressDetails existingAddressDetails = currentUser.getAddressDetails();\n\n if (existingAddressDetails != null) {\n populateForm(existingAddressDetails);\n saveButtonPrimary.setText(\"Update\");\n }\n }\n\n private void populateForm(AddressDetails existingAddress) {\n address.setValue(existingAddress.getAddress());\n pinCode.setValue(existingAddress.getPinCode());\n city.setValue(existingAddress.getCity());\n country.setValue(existingAddress.getCountry());\n state.setValue(existingAddress.getState());\n }\n\n private boolean isAddressDetailsAlreadySaved() {\n return userService.getCurrentUser().getBankDetails() != null;\n }\n\n private void updateAddressDetails() {\n User currentUser = userService.getCurrentUser();\n AddressDetails existingAddressDetails = currentUser.getAddressDetails();\n existingAddressDetails.setAddress(address.getValue());\n existingAddressDetails.setPinCode(pinCode.getValue());\n existingAddressDetails.setCity(city.getValue());\n existingAddressDetails.setState(state.getValue());\n existingAddressDetails.setCountry(country.getValue());\n userService.saveUserWithAddressDetails(currentUser, existingAddressDetails);\n NotificationUtils.createSubmitSuccess(\"Address details updated successfully\");\n }\n\n private void saveAddressDetails() {\n User currentUser = userService.getCurrentUser();\n AddressDetails addressDetailsFromForm = createAddressDetailsFromForm();\n addressDetailsFromForm.setUser(currentUser);\n currentUser.setAddressDetails(addressDetailsFromForm);\n userService.saveUserWithAddressDetails(currentUser, addressDetailsFromForm);\n NotificationUtils.createSubmitSuccess(\"Address details saved successfully\");\n }\n\n private AddressDetails createAddressDetailsFromForm() {\n AddressDetails addressDetails = new AddressDetails();\n addressDetails.setAddress(address.getValue());\n addressDetails.setPinCode(pinCode.getValue());\n addressDetails.setCity(city.getValue());\n addressDetails.setState(state.getValue());\n addressDetails.setCountry(country.getValue());\n return addressDetails;\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/password/PasswordChangeView.java\n@PageTitle(\"Change Password\")\n@Route(value = \"password-change\", layout = MainLayout.class)\n@PermitAll\npublic class PasswordChangeView extends VerticalLayout {\n\n private final TextField oldPassword;\n private final PasswordField newPassword;\n private final PasswordField confirmPassword;\n private final UserService userService;\n\n public PasswordChangeView(UserService userService) {\n oldPassword = new TextField(\"Old Password\");\n newPassword = new PasswordField(\"New Password\");\n confirmPassword = new PasswordField(\"Confirm Password\");\n\n this.userService = userService;\n Button changeButton = new Button(\"Change Password\");\n changeButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n changeButton.addClickListener(event -> handleChangeButtonClick());\n\n FormLayout formLayout2Col = new FormLayout();\n formLayout2Col.add(oldPassword, newPassword, confirmPassword);\n HorizontalLayout layoutRow = new HorizontalLayout();\n layoutRow.add(changeButton);\n add(formLayout2Col, layoutRow);\n }\n\n private void handleChangeButtonClick() {\n try {\n String oldPasswordValue = oldPassword.getValue();\n String newPasswordValue = newPassword.getValue();\n String confirmPasswordValue = confirmPassword.getValue();\n userService.changePassword(oldPasswordValue, newPasswordValue, confirmPasswordValue);\n NotificationUtils.createSubmitSuccess(\"Password changed successfully\");\n } catch (Exception e) {\n String message = e.getMessage();\n NotificationUtils.showErrorNotification(message);\n }\n }\n}\n\nsrc/main/java/com/nasc/application/views/forms/personal/PersonalFormView.java\n@PageTitle(\"Personal Information Form\")\n@Route(value = \"personal-information-form\", layout = MainLayout.class)\n@RolesAllowed({\"HOD\", \"PROFESSOR\", \"STUDENT\"})\n@Uses(Icon.class)\npublic class PersonalFormView extends Composite {\n\n private final UserService userService;\n private final VerticalLayout mainLayout = new VerticalLayout();\n private final H3 title = new H3();\n private final FormLayout formLayout = new FormLayout();\n private final TextField firstName = new TextField();\n private final TextField lastName = new TextField();\n private final DatePicker birthday = new DatePicker();\n private final TextField phoneNumber = new TextField();\n private final EmailField email = new EmailField();\n private final ComboBox gender = new ComboBox<>();\n private final HorizontalLayout buttonLayout = new HorizontalLayout();\n private final Button saveButton = new Button();\n private final BeanValidationBinder binder = new BeanValidationBinder<>(PersonalDetails.class);\n\n public PersonalFormView(UserService userService) {\n this.userService = userService;\n configureLayout();\n initFormWithExistingDetails(); // Initialize the form with existing personal details\n }\n\n private void configureLayout() {\n mainLayout.setWidth(\"100%\");\n mainLayout.getStyle().set(\"flex-grow\", \"1\");\n mainLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.START);\n mainLayout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n title.setText(\"Personal Information\");\n title.setWidth(\"100%\");\n\n formLayout.setWidth(\"100%\");\n firstName.setLabel(\"First Name\");\n lastName.setLabel(\"Last Name\");\n birthday.setLabel(\"Birthday\");\n phoneNumber.setLabel(\"Phone Number\");\n email.setLabel(\"Email\");\n\n buttonLayout.addClassName(Gap.MEDIUM);\n buttonLayout.setWidth(\"100%\");\n buttonLayout.getStyle().set(\"flex-grow\", \"1\");\n\n saveButton.setText(\"Save\");\n saveButton.setWidth(\"min-content\");\n saveButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n mainLayout.add(title, formLayout, buttonLayout);\n formLayout.add(firstName,\n lastName,\n birthday,\n phoneNumber,\n email,\n gender);\n gender.setLabel(\"Gender\");\n gender.setItems(\"Male\", \"Female\", \"Other\");\n\n saveButton.addClickListener(e -> {\n if (isPersonalDetailsAlreadySaved()) {\n updatePersonalDetails();\n } else {\n savePersonalDetails();\n }\n });\n\n binder.addStatusChangeListener(e -> saveButton.setEnabled(binder.isValid()));\n\n buttonLayout.add(saveButton);\n\n getContent().add(mainLayout);\n }\n\n private void initFormWithExistingDetails() {\n User currentUser = userService.getCurrentUser();\n binder.bindInstanceFields(this);\n PersonalDetails existingPersonalDetails = currentUser.getPersonalDetails();\n if (existingPersonalDetails != null) {\n populateForm(existingPersonalDetails);\n saveButton.setText(\"Update\");\n }\n }\n\n private void populateForm(PersonalDetails existingPersonalDetails) {\n firstName.setValue(existingPersonalDetails.getFirstName());\n lastName.setValue(existingPersonalDetails.getLastName());\n birthday.setValue(existingPersonalDetails.getBirthday());\n phoneNumber.setValue(existingPersonalDetails.getPhoneNumber());\n email.setValue(existingPersonalDetails.getEmail());\n gender.setValue(existingPersonalDetails.getGender());\n }\n\n private boolean isPersonalDetailsAlreadySaved() {\n return userService.getCurrentUser().getPersonalDetails() != null;\n }\n\n private void updatePersonalDetails() {\n User currentUser = userService.getCurrentUser();\n PersonalDetails existingPersonalDetails = currentUser.getPersonalDetails();\n existingPersonalDetails.setFirstName(firstName.getValue());\n existingPersonalDetails.setLastName(lastName.getValue());\n existingPersonalDetails.setBirthday(birthday.getValue());\n existingPersonalDetails.setPhoneNumber(phoneNumber.getValue());\n existingPersonalDetails.setEmail(email.getValue());\n existingPersonalDetails.setGender(gender.getValue());\n userService.saveUserWithPersonalDetails(currentUser, existingPersonalDetails);\n NotificationUtils.createSubmitSuccess(\"Personal Form Updated Successfully.\");\n }\n\n private void savePersonalDetails() {\n User currentUser = userService.getCurrentUser();\n PersonalDetails personalDetailsFromForm = createPersonalDetailsFromForm();\n personalDetailsFromForm.setUser(currentUser);\n currentUser.setPersonalDetails(personalDetailsFromForm);\n userService.saveUserWithPersonalDetails(currentUser, personalDetailsFromForm);\n NotificationUtils.createSubmitSuccess(\"Personal Form Saved Successfully.\");\n }\n\n private PersonalDetails createPersonalDetailsFromForm() {\n PersonalDetails personalDetails = new PersonalDetails();\n personalDetails.setFirstName(firstName.getValue());\n personalDetails.setLastName(lastName.getValue());\n personalDetails.setBirthday(birthday.getValue());\n personalDetails.setPhoneNumber(phoneNumber.getValue());\n personalDetails.setEmail(email.getValue());\n personalDetails.setGender(gender.getValue());\n return personalDetails;\n }\n}\n\nsrc/main/java/com/nasc/application/views/activeusers/ActiveUsersView.java\n@Route(value = \"get-online-users\", layout = MainLayout.class)\n@RolesAllowed(\"ADMIN\")\npublic class ActiveUsersView extends Div {\n public ActiveUsersView(UserService userService) {\n add(createActiveUserGrid(userService));\n }\n\n private Component createActiveUserGrid(UserService userService) {\n // Header\n HorizontalLayout header = createHeader(\"Active Users\", \"Online\");\n\n // Grid\n Grid grid = new Grid<>();\n grid.addThemeVariants(GridVariant.MATERIAL_COLUMN_DIVIDERS);\n grid.setAllRowsVisible(true);\n\n // Columns\n grid.addColumn(UserDetails::getUsername)\n .setHeader(\"User Name\")\n .setAutoWidth(true)\n .setSortable(true);\n\n/* grid.addColumn(userDetails -> userDetails.getAuthorities().stream()\n .map(Object::toString)\n .collect(Collectors.joining(\", \")))\n .setHeader(\"User Roles\")\n .setAutoWidth(true)\n .setSortable(true);*/\n\n grid.addComponentColumn(userDetails -> {\n List roleNames = userDetails.getAuthorities().stream()\n .map(Object::toString)\n .collect(Collectors.toList());\n return createBadgeList(roleNames);\n }).setHeader(\"User Roles\").setAutoWidth(true).setSortable(true);\n\n\n // Set items\n grid.setItems(userService.getOnlineUsers());\n\n // Add it all together\n VerticalLayout activeUsersLayout = new VerticalLayout(header, grid);\n activeUsersLayout.addClassName(LumoUtility.Padding.LARGE);\n activeUsersLayout.setPadding(false);\n activeUsersLayout.setSpacing(false);\n activeUsersLayout.getElement().getThemeList().add(\"spacing-l\");\n return activeUsersLayout;\n }\n\n\n private HorizontalLayout createHeader(String title, String subtitle) {\n H2 h2 = new H2(title);\n h2.addClassNames(LumoUtility.FontSize.XLARGE, LumoUtility.Margin.NONE);\n\n Span span = new Span(subtitle);\n span.addClassNames(LumoUtility.TextColor.SECONDARY, LumoUtility.FontSize.XSMALL);\n\n VerticalLayout column = new VerticalLayout(h2, span);\n column.setPadding(false);\n column.setSpacing(false);\n\n HorizontalLayout header = new HorizontalLayout(column);\n header.setJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN);\n header.setSpacing(false);\n header.setWidthFull();\n return header;\n }\n\n private BadgeList createBadgeList(List roles) {\n List badges = new ArrayList<>();\n roles.forEach(role -> badges.add(new Badge(role)));\n return new BadgeList(badges);\n }\n}\n\nsrc/main/java/com/nasc/application/views/about/AboutView.java\n@PageTitle(\"About\")\n@Route(value = \"about\", layout = MainLayout.class)\n@AnonymousAllowed\npublic class AboutView extends VerticalLayout {\n\n public AboutView() {\n setSpacing(false);\n\n Image img = new Image(\"images/NASC_LOGO.jpg\", \"NASC LOGO\");\n img.setWidth(\"200px\");\n add(img);\n\n H2 header = new H2(\"\\\"Automate the Future\\\"\");\n header.addClassNames(Margin.Top.XLARGE, Margin.Bottom.MEDIUM);\n add(header);\n add(new Paragraph(\"NASC PORTAL WAS DESIGNED AND DEVELOPED BY DEPARTMENT OF COMPUTER SCIENCE\"));\n\n setSizeFull();\n setJustifyContentMode(JustifyContentMode.CENTER);\n setDefaultHorizontalComponentAlignment(Alignment.CENTER);\n getStyle().set(\"text-align\", \"center\");\n }\n\n}\n\nsrc/main/java/com/nasc/application/security/AuthenticatedUser.java\n@Component\npublic class AuthenticatedUser {\n\n private final UserRepository userRepository;\n private final AuthenticationContext authenticationContext;\n\n private final SessionRegistry sessionRegistry;\n\n public AuthenticatedUser(AuthenticationContext authenticationContext, UserRepository userRepository, SessionRegistry sessionRegistry) {\n this.userRepository = userRepository;\n this.authenticationContext = authenticationContext;\n this.sessionRegistry = sessionRegistry;\n }\n\n @Transactional\n public Optional get() {\n return authenticationContext.getAuthenticatedUser(UserDetails.class)\n .map(userDetails -> userRepository.findByUsername(userDetails.getUsername()));\n }\n\n @Transactional\n public void logout() {\n // Get the current authentication\n UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n\n // Manually expire the session in the SessionRegistry\n expireUserSessions(userDetails);\n\n // Perform the Vaadin logout\n authenticationContext.logout();\n }\n\n private void expireUserSessions(UserDetails userDetails) {\n // Obtain the list of sessions for the user\n List userSessions = sessionRegistry.getAllSessions(userDetails, false);\n\n // Expire all sessions for the user\n userSessions.forEach(SessionInformation::expireNow);\n }\n\n}\n\nsrc/main/java/com/nasc/application/views/subject/CreateSubjectCrud.java\n@Component\n@UIScope\n@Route(value = \"create-subject\", layout = MainLayout.class)\n@RolesAllowed(\"HOD\")\n@PageTitle(\"Create Subject\")\npublic class CreateSubjectCrud extends VerticalLayout {\n public static final String EDIT_COLUMN = \"vaadin-crud-edit-column\";\n private final SubjectService service;\n private final Crud crud;\n\n @Autowired\n public CreateSubjectCrud(SubjectService service) {\n this.service = service;\n crud = new Crud<>(SubjectEntity.class, createEditor());\n createGrid();\n setupDataProvider();\n HorizontalLayout horizontalLayout = new HorizontalLayout();\n Button exportButton = new Button(\n \"Export\",\n FontAwesome.Solid.FILE_EXPORT.create(),\n e -> {\n int size = crud.getGrid().getDataProvider().size(new Query<>());\n if (size > 0) {\n String fileName = \"Department Subjects\";\n GridExporter.newWithDefaults(crud.getGrid())\n //Removing Edit Column For Export\n .withColumnFilter(stateEntityColumn -> !stateEntityColumn.getKey().equals(EDIT_COLUMN))\n .withFileName(fileName)\n .withColumnConfigurationBuilder(new ColumnConfigurationBuilder())\n .open();\n }\n }\n );\n exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);\n horizontalLayout.add(exportButton);\n horizontalLayout.setWidthFull();\n horizontalLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.END);\n horizontalLayout.setAlignItems(FlexComponent.Alignment.CENTER);\n\n Button newItemBtn = new Button(\"Create New Subject\", LumoIcon.PLUS.create());\n newItemBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n crud.setNewButton(newItemBtn);\n\n setAlignItems(Alignment.STRETCH);\n expand(crud);\n setSizeFull();\n\n add(horizontalLayout, crud);\n }\n\n private CrudEditor createEditor() {\n MajorOfPaper[] majorOfPaperEnum = MajorOfPaper.values();\n PaperType[] paperTypeEnum = PaperType.values();\n Semester[] semesterEnum = Semester.values();\n\n TextField subjectNameField = new TextField(\"Subject Name\");\n TextField subjectShortNameField = new TextField(\"Subject Short Name\");\n TextField subjectCodeField = new TextField(\"Subject Code\");\n\n ComboBox typeOfPaperComboBox = new ComboBox<>(\"Type of Paper\");\n typeOfPaperComboBox.setItems(paperTypeEnum);\n typeOfPaperComboBox.setItemLabelGenerator(PaperType::getDisplayName);\n\n ComboBox majorOfPaperComboBox = new ComboBox<>(\"Major of Paper\");\n majorOfPaperComboBox.setItems(majorOfPaperEnum);\n majorOfPaperComboBox.setItemLabelGenerator(MajorOfPaper::getDisplayName);\n\n ComboBox semesterComboBox = new ComboBox<>(\"Semester\");\n semesterComboBox.setItems(semesterEnum);\n semesterComboBox.setItemLabelGenerator(Semester::getDisplayName);\n\n FormLayout form = new FormLayout(subjectNameField, subjectShortNameField, subjectCodeField,\n typeOfPaperComboBox, majorOfPaperComboBox, semesterComboBox);\n form.setMaxWidth(\"480px\");\n form.setResponsiveSteps(new FormLayout.ResponsiveStep(\"0\", 1),\n new FormLayout.ResponsiveStep(\"30em\", 2));\n\n Binder binder = new Binder<>(SubjectEntity.class);\n binder.forField(subjectNameField).asRequired().bind(SubjectEntity::getSubjectName, SubjectEntity::setSubjectName);\n binder.forField(subjectCodeField).bind(SubjectEntity::getSubjectCode, SubjectEntity::setSubjectCode);\n binder.forField(subjectShortNameField).asRequired().bind(SubjectEntity::getSubjectShortForm, SubjectEntity::setSubjectShortForm);\n binder.forField(typeOfPaperComboBox).bind(SubjectEntity::getPaperType, SubjectEntity::setPaperType);\n binder.forField(majorOfPaperComboBox).bind(SubjectEntity::getMajorOfPaper, SubjectEntity::setMajorOfPaper);\n binder.forField(semesterComboBox).bind(SubjectEntity::getSemester, SubjectEntity::setSemester);\n\n // Add bindings for other fields as needed\n return new BinderCrudEditor<>(binder, form);\n }\n\n private void createGrid() {\n Grid grid = crud.getGrid();\n\n grid.removeColumnByKey(\"id\");\n grid.removeColumnByKey(\"department\");\n\n String[] columns = {\"subjectName\", \"subjectShortForm\", \"subjectCode\", \"paperType\", \"majorOfPaper\", \"semester\", EDIT_COLUMN};\n List> list = Arrays.stream(columns).map(grid::getColumnByKey).toList();\n grid.setColumnOrder(list);\n\n grid.getColumnByKey(EDIT_COLUMN).setHeader(\"Edit\");\n grid.getColumnByKey(EDIT_COLUMN).setWidth(\"100px\");\n grid.getColumnByKey(EDIT_COLUMN).setResizable(false);\n\n grid.getColumnByKey(\"paperType\").setRenderer(new TextRenderer<>(item -> item.getPaperType().getDisplayName()));\n grid.getColumnByKey(\"majorOfPaper\").setRenderer(new TextRenderer<>(item -> item.getMajorOfPaper().getDisplayName()));\n grid.getColumnByKey(\"semester\").setRenderer(new TextRenderer<>(item -> item.getSemester().getDisplayName()));\n }\n\n private void setupDataProvider() {\n GenericDataProvider genericDataProvider =\n new GenericDataProvider<>(SubjectEntity.class, service);\n crud.setDataProvider(genericDataProvider);\n crud.addDeleteListener(deleteEvent -> {\n genericDataProvider.delete(deleteEvent.getItem());\n NotificationUtils.showSuccessNotification(\"Subject deleted successfully\");\n });\n crud.addSaveListener(saveEvent -> {\n genericDataProvider.persist(saveEvent.getItem());\n NotificationUtils.showSuccessNotification(\"Subject saved successfully\");\n });\n }\n}", "answers": [" public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {"], "length": 7647, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "58c462f7-a18c-4e92-98b5-ee9071394f87", "reasoning": "The MainLayout class declares two final fields: authenticatedUser and accessChecker. The next logical step is to provide a constructor that receives these dependencies and assigns them, which is standard in Vaadin layouts. Therefore, the next line should be the constructor signature.", "reasoning_model_answer": "public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {", "assistant_with_reasoning": "\nThe MainLayout class declares two final fields: authenticatedUser and accessChecker. The next logical step is to provide a constructor that receives these dependencies and assigns them, which is standard in Vaadin layouts. Therefore, the next line should be the constructor signature.\n\npublic MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.249, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37978, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.fasterxml.jackson.annotation.JsonPropertyOrder;\nimport com.fasterxml.jackson.annotation.JsonTypeName;\nimport com.fasterxml.jackson.annotation.JsonValue;\nimport com.fasterxml.jackson.dataformat.xml.annotation.*;\nimport com.hubsante.model.emsi.Context;\nimport com.hubsante.model.emsi.Event;\nimport com.hubsante.model.emsi.Mission;\nimport com.hubsante.model.emsi.Resource;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Objects;\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;", "context": "src/main/java/com/hubsante/model/emsi/Emsi.java\n/**\n * Copyright © 2023-2024 Agence du Numerique en Sante (ANS)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n *\n *\n *\n *\n *\n *\n * NOTE: This class is auto generated by OpenAPI Generator\n * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit\n * the class manually.\n */\n\npackage com.hubsante.model.emsi;\n\n\n/**\n * Emsi\n */\n@JsonPropertyOrder(\n {Emsi.JSON_PROPERTY_C_O_N_T_E_X_T, Emsi.JSON_PROPERTY_E_V_E_N_T,\n Emsi.JSON_PROPERTY_M_I_S_S_I_O_N, Emsi.JSON_PROPERTY_R_E_S_O_U_R_C_E})\n@JsonTypeName(\"emsi\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Emsi {\n public static final String JSON_PROPERTY_C_O_N_T_E_X_T = \"CONTEXT\";\n private Context CONTEXT;\n\n public static final String JSON_PROPERTY_E_V_E_N_T = \"EVENT\";\n private Event EVENT;\n\n public static final String JSON_PROPERTY_M_I_S_S_I_O_N = \"MISSION\";\n private List MISSION;\n\n public static final String JSON_PROPERTY_R_E_S_O_U_R_C_E = \"RESOURCE\";\n private List RESOURCE;\n\n public Emsi() {}\n\n public Emsi CONTEXT(Context CONTEXT) {\n\n this.CONTEXT = CONTEXT;\n return this;\n }\n\n /**\n * Get CONTEXT\n * @return CONTEXT\n **/\n @JsonProperty(JSON_PROPERTY_C_O_N_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public Context getCONTEXT() {\n return CONTEXT;\n }\n\n @JsonProperty(JSON_PROPERTY_C_O_N_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setCONTEXT(Context CONTEXT) {\n this.CONTEXT = CONTEXT;\n }\n\n public Emsi EVENT(Event EVENT) {\n\n this.EVENT = EVENT;\n return this;\n }\n\n /**\n * Get EVENT\n * @return EVENT\n **/\n @JsonProperty(JSON_PROPERTY_E_V_E_N_T)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public Event getEVENT() {\n return EVENT;\n }\n\n @JsonProperty(JSON_PROPERTY_E_V_E_N_T)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setEVENT(Event EVENT) {\n\nsrc/main/java/com/hubsante/model/emsi/Resource.java\n@JsonPropertyOrder(\n {Resource.JSON_PROPERTY_R_T_Y_P_E, Resource.JSON_PROPERTY_I_D,\n Resource.JSON_PROPERTY_O_R_G_I_D, Resource.JSON_PROPERTY_N_A_M_E,\n Resource.JSON_PROPERTY_F_R_E_E_T_E_X_T, Resource.JSON_PROPERTY_R_G_E_O,\n Resource.JSON_PROPERTY_Q_U_A_N_T_I_T_Y, Resource.JSON_PROPERTY_U_M,\n Resource.JSON_PROPERTY_S_T_A_T_U_S,\n Resource.JSON_PROPERTY_N_A_T_I_O_N_A_L_I_T_Y,\n Resource.JSON_PROPERTY_C_O_N_T_A_C_T_S})\n@JsonTypeName(\"resource\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Resource {\n public static final String JSON_PROPERTY_R_T_Y_P_E = \"RTYPE\";\n private Rtype RTYPE;\n\n public static final String JSON_PROPERTY_I_D = \"ID\";\n private String ID;\n\n public static final String JSON_PROPERTY_O_R_G_I_D = \"ORG_ID\";\n private String ORG_ID;\n\n public static final String JSON_PROPERTY_N_A_M_E = \"NAME\";\n private String NAME;\n\n public static final String JSON_PROPERTY_F_R_E_E_T_E_X_T = \"FREETEXT\";\n private String FREETEXT;\n\n public static final String JSON_PROPERTY_R_G_E_O = \"RGEO\";\n private List RGEO;\n\n public static final String JSON_PROPERTY_Q_U_A_N_T_I_T_Y = \"QUANTITY\";\n private BigDecimal QUANTITY;\n\n /**\n * Dans le cadre d'un échange d'opération, optionnel. Unité de mesure\n * pour des ressources consommables\n */\n public enum UMEnum {\n LSV(\"LSV\"),\n\n OTH(\"OTH\"),\n\n PKG(\"PKG\"),\n\n TIM(\"TIM\"),\n\n WGT(\"WGT\"),\n\n LSV_CM(\"LSV/CM\"),\n\n LSV_CMH(\"LSV/CMH\"),\n\n LSV_CNTLTR(\"LSV/CNTLTR\"),\n\n LSV_DEG(\"LSV/DEG\"),\n\n LSV_HCTLTR(\"LSV/HCTLTR\"),\n\n LSV_HCTMTR(\"LSV/HCTMTR\"),\n\n LSV_KM(\"LSV/KM\"),\n\n LSV_KPH(\"LSV/KPH\"),\n\n LSV_LI(\"LSV/LI\"),\n\n LSV_LTPRHR(\"LSV/LTPRHR\"),\n\n LSV_LTPRMN(\"LSV/LTPRMN\"),\n\n LSV_METRE(\"LSV/METRE\"),\n\n LSV_MILLTR(\"LSV/MILLTR\"),\n\n LSV_MILMTR(\"LSV/MILMTR\"),\n\n LSV_SMH(\"LSV/SMH\"),\n\n LSV_SQM(\"LSV/SQM\"),\n\n OTH_COIL(\"OTH/COIL\"),\n\n OTH_DOZEN(\"OTH/DOZEN\"),\n\n OTH_EA(\"OTH/EA\"),\n\n OTH_GROSS(\"OTH/GROSS\"),\n\n OTH_MANHUR(\"OTH/MANHUR\"),\n\n OTH_MHPRHR(\"OTH/MHPRHR\"),\n\n PKG_BALE(\"PKG/BALE\"),\n\n PKG_BARREL(\"PKG/BARREL\"),\n\n PKG_BLK(\"PKG/BLK\"),\n\n PKG_BOX(\"PKG/BOX\"),\n\n PKG_CASE(\"PKG/CASE\"),\n\n PKG_CONTNR(\"PKG/CONTNR\"),\n\n PKG_CRATE(\"PKG/CRATE\"),\n\n PKG_DRM(\"PKG/DRM\"),\n\n PKG_JERCAN(\"PKG/JERCAN\"),\n\n PKG_PAK(\"PKG/PAK\"),\n\n PKG_PAL(\"PKG/PAL\"),\n\n PKG_RATION(\"PKG/RATION\"),\n\n TIM_DAY(\"TIM/DAY\"),\n\n TIM_HR(\"TIM/HR\"),\n\n TIM_MINUTE(\"TIM/MINUTE\"),\n\n TIM_MON(\"TIM/MON\"),\n\n TIM_SECOND(\"TIM/SECOND\"),\n\n TIM_WEK(\"TIM/WEK\"),\n\n TIM_YEA(\"TIM/YEA\"),\n\n WGT_CNTGRM(\"WGT/CNTGRM\"),\n\n WGT_GRAM(\"WGT/GRAM\"),\n\n WGT_KG(\"WGT/KG\"),\n\n WGT_KGH(\"WGT/KGH\");\n\n private String value;\n\n UMEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static UMEnum fromValue(String value) {\n for (UMEnum b : UMEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_U_M = \"UM\";\n private UMEnum UM;\n\n /**\n * Définit le statut de disponibilité d'une ressource. - AVAILB :\n * Lorsqu'une mission est terminée, une ressource redevient disponible -\n * RESRVD : Lorsque la ressource est réservée pour intervenir sur\n * l'affaire mais pas encore engagée dans l'opération. Par exemple :\n * un SMUR termine un autre transfert patient/victime avant de rejoindre une\n * autre intervention : il est alors RESRVD - IN_USE/MOBILE : à utiliser pour\n * les véhicules et le personnel lorsqu'ils se déplaces - IN_USE/ON_SCENE\n * : à utiliser pour les véhicules et le personnel lorsqu'ils sont sur les\n * lieux de l'affaire\n */\n public enum STATUSEnum {\n AVAILB(\"AVAILB\"),\n\n UNAV(\"UNAV\"),\n\n MAINTC(\"MAINTC\"),\n\n RESRVD(\"RESRVD\"),\n\n VIRTUAL(\"VIRTUAL\"),\n\n IN_USE_MOBILE(\"IN_USE/MOBILE\"),\n\n IN_USE_ON_SCENE(\"IN_USE/ON_SCENE\");\n\n private String value;\n\n STATUSEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static STATUSEnum fromValue(String value) {\n for (STATUSEnum b : STATUSEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_S_T_A_T_U_S = \"STATUS\";\n private STATUSEnum STATUS;\n\n public static final String JSON_PROPERTY_N_A_T_I_O_N_A_L_I_T_Y =\n \"NATIONALITY\";\n private String NATIONALITY;\n\n public static final String JSON_PROPERTY_C_O_N_T_A_C_T_S = \"CONTACTS\";\n private List CONTACTS;\n\n public Resource() {}\n\n public Resource RTYPE(Rtype RTYPE) {\n\n this.RTYPE = RTYPE;\n return this;\n }\n\n /**\n * Get RTYPE\n * @return RTYPE\n **/\n @JsonProperty(JSON_PROPERTY_R_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public Rtype getRTYPE() {\n return RTYPE;\n }\n\n @JsonProperty(JSON_PROPERTY_R_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setRTYPE(Rtype RTYPE) {\n this.RTYPE = RTYPE;\n }\n\n public Resource ID(String ID) {\n\n this.ID = ID;\n return this;\n }\n\n /**\n * Identifiant unique de la ressource dans le système du partenaire\n *propriétaire. Les systèmes sont garants de l'unicité et de\n *l'invariablité des ids de véhicule dans le temps. Ils peuvent se servir\n *des ids dans les référentiels existants si ils sont uniques et stables. Dans\n *le cas d'un véhicule agrégé par un LRM (comme un SMUR), l'ID doit\n *être valorisé avec son immatriculation. Dans le cas d'un véhicule agrégé\n *par NexSIS, l'ID fournit peut ne pas correspondre à une immatriculation.\n * @return ID\n **/\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getID() {\n return ID;\n }\n\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setID(String ID) {\n this.ID = ID;\n }\n\n public Resource ORG_ID(String ORG_ID) {\n\n this.ORG_ID = ORG_ID;\n return this;\n }\n\n /**\n * Identifiant de l'organisation à laquelle la ressource est rattachée\n *(caserne, SAMU etc). Se référer au DSF pour la structure normée des\n *organisations Le format est le suivant {pays}.{domaine}.{code\n *département}.{organisation}.{structure interne}*.{unité fonctionnelle}*.\n *Dans le cas où le LRM/NexSIS sert d'aggrégateur pour des véhicules\n *appartenant à un partenaire tiers (type ambulance privée), l'identifiant\n *d'organisation permet d'identifier ce tiers A constituer par le\n *rédacteur du présent EMSI pour être unique, identique à\n *<CONTEXT><ORIGIN><ORG_ID>\n * @return ORG_ID\n **/\n @JsonProperty(JSON_PROPERTY_O_R_G_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getORGID() {\n return ORG_ID;\n }\n\n @JsonProperty(JSON_PROPERTY_O_R_G_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setORGID(String ORG_ID) {\n this.ORG_ID = ORG_ID;\n }\n\n public Resource NAME(String NAME) {\n\n this.NAME = NAME;\n return this;\n }\n\n /**\n * Nom donné à la ressource par le partenaire. L'immatriculation peut être\n *utilisée dans le nom courant des véhicules. Dans le cas pompier, les\n *véhicules sont nommés Dans le cas d'équipier, cela peut être leur nom\n * @return NAME\n **/\n @JsonProperty(JSON_PROPERTY_N_A_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getNAME() {\n return NAME;\n }\n\n @JsonProperty(JSON_PROPERTY_N_A_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setNAME(String NAME) {\n this.NAME = NAME;\n }\n\n public Resource FREETEXT(String FREETEXT) {\n\n this.FREETEXT = FREETEXT;\n return this;\n }\n\n /**\n * Texte libre permettant de décrire la ressource où d'ajouter des\n *précisions sur son engagement. Permet aussi notamment de décrire des\n *attributs librement pour la ressource. Par exemple, pour un véhicule, sa\n *plaque d'immatriculation.\n * @return FREETEXT\n **/\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getFREETEXT() {\n return FREETEXT;\n }\n\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setFREETEXT(String FREETEXT) {\n this.FREETEXT = FREETEXT;\n }\n\n public Resource RGEO(List RGEO) {\n\n this.RGEO = RGEO;\n return this;\n }\n\n public Resource addRGEOItem(Rgeo RGEOItem) {\n if (this.RGEO == null) {\n this.RGEO = new ArrayList<>();\n }\n this.RGEO.add(RGEOItem);\n return this;\n }\n\n /**\n * Get RGEO\n * @return RGEO\n **/\n @JsonProperty(JSON_PROPERTY_R_G_E_O)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getRGEO() {\n return RGEO;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_R_G_E_O)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setRGEO(List RGEO) {\n if (RGEO == null) {\n return;\n }\n if (this.RGEO == null) {\n this.RGEO = new ArrayList<>();\n }\n this.RGEO.addAll(RGEO);\n }\n\n public Resource QUANTITY(BigDecimal QUANTITY) {\n\n this.QUANTITY = QUANTITY;\n return this;\n }\n\n /**\n * Dans le cadre d'un échange d'opération, optionnel. Permet de\n *quantifier une ressource : - à ne pas utiliser pour les véhicules ni le\n *personnel - utilisable pour du matériel - utilisable pour des consommables\n *(dans le cas de consommable, à compléter avec le champ UM)\n * @return QUANTITY\n **/\n @JsonProperty(JSON_PROPERTY_Q_U_A_N_T_I_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public BigDecimal getQUANTITY() {\n return QUANTITY;\n }\n\n @JsonProperty(JSON_PROPERTY_Q_U_A_N_T_I_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setQUANTITY(BigDecimal QUANTITY) {\n this.QUANTITY = QUANTITY;\n }\n\n public Resource UM(UMEnum UM) {\n\n this.UM = UM;\n return this;\n }\n\n /**\n * Dans le cadre d'un échange d'opération, optionnel. Unité de mesure\n *pour des ressources consommables\n * @return UM\n **/\n @JsonProperty(JSON_PROPERTY_U_M)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public UMEnum getUM() {\n return UM;\n }\n\n @JsonProperty(JSON_PROPERTY_U_M)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setUM(UMEnum UM) {\n this.UM = UM;\n }\n\n public Resource STATUS(STATUSEnum STATUS) {\n\n this.STATUS = STATUS;\n return this;\n }\n\n /**\n * Définit le statut de disponibilité d'une ressource. - AVAILB :\n *Lorsqu'une mission est terminée, une ressource redevient disponible -\n *RESRVD : Lorsque la ressource est réservée pour intervenir sur l'affaire\n *mais pas encore engagée dans l'opération. Par exemple : un SMUR termine\n *un autre transfert patient/victime avant de rejoindre une autre intervention\n *: il est alors RESRVD - IN_USE/MOBILE : à utiliser pour les véhicules et le\n *personnel lorsqu'ils se déplaces - IN_USE/ON_SCENE : à utiliser pour les\n *véhicules et le personnel lorsqu'ils sont sur les lieux de l'affaire\n * @return STATUS\n **/\n @JsonProperty(JSON_PROPERTY_S_T_A_T_U_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public STATUSEnum getSTATUS() {\n return STATUS;\n }\n\n @JsonProperty(JSON_PROPERTY_S_T_A_T_U_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSTATUS(STATUSEnum STATUS) {\n this.STATUS = STATUS;\n }\n\n public Resource NATIONALITY(String NATIONALITY) {\n\n this.NATIONALITY = NATIONALITY;\n return this;\n }\n\n /**\n * Nationalité d'une ressource, réemployer ISO 3166-1-alpha-2 code\n *elements.\n * @return NATIONALITY\n **/\n @JsonProperty(JSON_PROPERTY_N_A_T_I_O_N_A_L_I_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getNATIONALITY() {\n return NATIONALITY;\n }\n\n @JsonProperty(JSON_PROPERTY_N_A_T_I_O_N_A_L_I_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setNATIONALITY(String NATIONALITY) {\n this.NATIONALITY = NATIONALITY;\n }\n\n public Resource CONTACTS(List CONTACTS) {\n\n this.CONTACTS = CONTACTS;\n return this;\n }\n\n public Resource addCONTACTSItem(Contact CONTACTSItem) {\n if (this.CONTACTS == null) {\n this.CONTACTS = new ArrayList<>();\n }\n this.CONTACTS.add(CONTACTSItem);\n return this;\n }\n\n /**\n * Get CONTACTS\n * @return CONTACTS\n **/\n @JsonProperty(JSON_PROPERTY_C_O_N_T_A_C_T_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getCONTACTS() {\n return CONTACTS;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_C_O_N_T_A_C_T_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCONTACTS(List CONTACTS) {\n if (CONTACTS == null) {\n return;\n }\n if (this.CONTACTS == null) {\n this.CONTACTS = new ArrayList<>();\n }\n this.CONTACTS.addAll(CONTACTS);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Resource resource = (Resource)o;\n return Objects.equals(this.RTYPE, resource.RTYPE) &&\n Objects.equals(this.ID, resource.ID) &&\n Objects.equals(this.ORG_ID, resource.ORG_ID) &&\n Objects.equals(this.NAME, resource.NAME) &&\n Objects.equals(this.FREETEXT, resource.FREETEXT) &&\n Objects.equals(this.RGEO, resource.RGEO) &&\n Objects.equals(this.QUANTITY, resource.QUANTITY) &&\n Objects.equals(this.UM, resource.UM) &&\n Objects.equals(this.STATUS, resource.STATUS) &&\n Objects.equals(this.NATIONALITY, resource.NATIONALITY) &&\n Objects.equals(this.CONTACTS, resource.CONTACTS);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(RTYPE, ID, ORG_ID, NAME, FREETEXT, RGEO, QUANTITY, UM,\n STATUS, NATIONALITY, CONTACTS);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class Resource {\\n\");\n sb.append(\" RTYPE: \").append(toIndentedString(RTYPE)).append(\"\\n\");\n sb.append(\" ID: \").append(toIndentedString(ID)).append(\"\\n\");\n sb.append(\" ORG_ID: \").append(toIndentedString(ORG_ID)).append(\"\\n\");\n sb.append(\" NAME: \").append(toIndentedString(NAME)).append(\"\\n\");\n sb.append(\" FREETEXT: \").append(toIndentedString(FREETEXT)).append(\"\\n\");\n sb.append(\" RGEO: \").append(toIndentedString(RGEO)).append(\"\\n\");\n sb.append(\" QUANTITY: \").append(toIndentedString(QUANTITY)).append(\"\\n\");\n sb.append(\" UM: \").append(toIndentedString(UM)).append(\"\\n\");\n sb.append(\" STATUS: \").append(toIndentedString(STATUS)).append(\"\\n\");\n sb.append(\" NATIONALITY: \")\n .append(toIndentedString(NATIONALITY))\n .append(\"\\n\");\n sb.append(\" CONTACTS: \").append(toIndentedString(CONTACTS)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n\nsrc/main/java/com/hubsante/model/emsi/Event.java\n@JsonPropertyOrder(\n {Event.JSON_PROPERTY_I_D, Event.JSON_PROPERTY_N_A_M_E,\n Event.JSON_PROPERTY_M_A_I_N_E_V_E_N_T_I_D, Event.JSON_PROPERTY_E_T_Y_P_E,\n Event.JSON_PROPERTY_S_O_U_R_C_E, Event.JSON_PROPERTY_S_C_A_L_E,\n Event.JSON_PROPERTY_C_E_R_T_A_I_N_T_Y,\n Event.JSON_PROPERTY_D_E_C_L_D_A_T_I_M_E,\n Event.JSON_PROPERTY_O_C_C_D_A_T_I_M_E,\n Event.JSON_PROPERTY_O_B_S_D_A_T_I_M_E, Event.JSON_PROPERTY_S_T_A_T_U_S,\n Event.JSON_PROPERTY_R_I_S_K_A_S_S_E_S_M_E_N_T,\n Event.JSON_PROPERTY_R_E_F_E_R_E_N_C_E,\n Event.JSON_PROPERTY_C_A_S_U_A_L_T_I_E_S, Event.JSON_PROPERTY_E_V_A_C,\n Event.JSON_PROPERTY_E_G_E_O, Event.JSON_PROPERTY_C_A_U_S_E,\n Event.JSON_PROPERTY_F_R_E_E_T_E_X_T})\n@JsonTypeName(\"event\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Event {\n public static final String JSON_PROPERTY_I_D = \"ID\";\n private String ID;\n\n public static final String JSON_PROPERTY_N_A_M_E = \"NAME\";\n private String NAME;\n\n public static final String JSON_PROPERTY_M_A_I_N_E_V_E_N_T_I_D =\n \"MAIN_EVENT_ID\";\n private String MAIN_EVENT_ID;\n\n public static final String JSON_PROPERTY_E_T_Y_P_E = \"ETYPE\";\n private Etype ETYPE;\n\n /**\n * Optionnel\n */\n public enum SOURCEEnum {\n COMFOR(\"COMFOR\"),\n\n HUMDED(\"HUMDED\"),\n\n HUMOBS(\"HUMOBS\"),\n\n SENSOR(\"SENSOR\");\n\n private String value;\n\n SOURCEEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static SOURCEEnum fromValue(String value) {\n for (SOURCEEnum b : SOURCEEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_S_O_U_R_C_E = \"SOURCE\";\n private SOURCEEnum SOURCE;\n\n /**\n * Optionnel, Niveau de criticité de l'opération\n */\n public enum SCALEEnum {\n _1(\"1\"),\n\n _2(\"2\"),\n\n _3(\"3\"),\n\n _4(\"4\"),\n\n _5(\"5\");\n\n private String value;\n\n SCALEEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static SCALEEnum fromValue(String value) {\n for (SCALEEnum b : SCALEEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_S_C_A_L_E = \"SCALE\";\n private SCALEEnum SCALE;\n\n public static final String JSON_PROPERTY_C_E_R_T_A_I_N_T_Y = \"CERTAINTY\";\n private Integer CERTAINTY;\n\n public static final String JSON_PROPERTY_D_E_C_L_D_A_T_I_M_E = \"DECL_DATIME\";\n private OffsetDateTime DECL_DATIME;\n\n public static final String JSON_PROPERTY_O_C_C_D_A_T_I_M_E = \"OCC_DATIME\";\n private OffsetDateTime OCC_DATIME;\n\n public static final String JSON_PROPERTY_O_B_S_D_A_T_I_M_E = \"OBS_DATIME\";\n private OffsetDateTime OBS_DATIME;\n\n /**\n * Permet de décrire le status de l'affaire en cours. Ce champ suit une\n * nomenclature EMSI. (COM = event complete, IPR = event in\n * progress, NST = event not started, STOP = STOP = event under\n * control, no need for additional resource) Dans le cadre d'une opération\n * : - si l'opération est encore en cours : rensigner 'IPR', - si\n * le dispatching de moyens est encore en cours ou que seulement des\n * qualifications d'alertes ont été échangées sans aucune décision de\n * régulation 'NST', - si l'opération est en pause/veille :\n * 'STOP' - si le message d'échange opérationnel décrit une fin\n * d'opération, à renseigner avec 'COM' Un message EMSI-EO sans\n * RESSOURCE ni\n */\n public enum STATUSEnum {\n COM(\"COM\"),\n\n IPR(\"IPR\"),\n\n NST(\"NST\"),\n\n STOP(\"STOP\");\n\n private String value;\n\n STATUSEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static STATUSEnum fromValue(String value) {\n for (STATUSEnum b : STATUSEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_S_T_A_T_U_S = \"STATUS\";\n private STATUSEnum STATUS;\n\n /**\n * Optionnel\n */\n public enum RISKASSESMENTEnum {\n NCREA(\"NCREA\"),\n\n DECREA(\"DECREA\"),\n\n STABLE(\"STABLE\");\n\n private String value;\n\n RISKASSESMENTEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static RISKASSESMENTEnum fromValue(String value) {\n for (RISKASSESMENTEnum b : RISKASSESMENTEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_R_I_S_K_A_S_S_E_S_M_E_N_T =\n \"RISK_ASSESMENT\";\n private RISKASSESMENTEnum RISK_ASSESMENT;\n\n public static final String JSON_PROPERTY_R_E_F_E_R_E_N_C_E = \"REFERENCE\";\n private List REFERENCE;\n\n public static final String JSON_PROPERTY_C_A_S_U_A_L_T_I_E_S = \"CASUALTIES\";\n private List CASUALTIES;\n\n public static final String JSON_PROPERTY_E_V_A_C = \"EVAC\";\n private List EVAC;\n\n public static final String JSON_PROPERTY_E_G_E_O = \"EGEO\";\n private List EGEO;\n\n /**\n * Optionnel\n */\n public enum CAUSEEnum {\n ACC(\"ACC\"),\n\n DEL(\"DEL\"),\n\n NAT(\"NAT\");\n\n private String value;\n\n CAUSEEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static CAUSEEnum fromValue(String value) {\n for (CAUSEEnum b : CAUSEEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_C_A_U_S_E = \"CAUSE\";\n private CAUSEEnum CAUSE;\n\n public static final String JSON_PROPERTY_F_R_E_E_T_E_X_T = \"FREETEXT\";\n private String FREETEXT;\n\n public Event() {}\n\n public Event ID(String ID) {\n\n this.ID = ID;\n return this;\n }\n\n /**\n * Identifiant local de l'affaire dans le système du partenaire emetteur\n * @return ID\n **/\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public String getID() {\n return ID;\n }\n\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setID(String ID) {\n this.ID = ID;\n }\n\n public Event NAME(String NAME) {\n\n this.NAME = NAME;\n return this;\n }\n\n /**\n * Optionnel Dans nexSIS; [libelle NF 1 métier] & \\" - \\" &\n *[libelle TL 1 métier] & \\" - \\" & [libellé commune]\n * @return NAME\n **/\n @JsonProperty(JSON_PROPERTY_N_A_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getNAME() {\n return NAME;\n }\n\n @JsonProperty(JSON_PROPERTY_N_A_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setNAME(String NAME) {\n this.NAME = NAME;\n }\n\n public Event MAIN_EVENT_ID(String MAIN_EVENT_ID) {\n\n this.MAIN_EVENT_ID = MAIN_EVENT_ID;\n return this;\n }\n\n /**\n * Identifiant d’affaire partagé issu du message RC-EDA transmis en amont NB :\n *Dans le cas d’un partage initié par un SAMU, on peut avoir EVENT.ID =\n *EVENT.MAIN_EVENT_ID\n * @return MAIN_EVENT_ID\n **/\n @JsonProperty(JSON_PROPERTY_M_A_I_N_E_V_E_N_T_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getMAINEVENTID() {\n return MAIN_EVENT_ID;\n }\n\n @JsonProperty(JSON_PROPERTY_M_A_I_N_E_V_E_N_T_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setMAINEVENTID(String MAIN_EVENT_ID) {\n this.MAIN_EVENT_ID = MAIN_EVENT_ID;\n }\n\n public Event ETYPE(Etype ETYPE) {\n\n this.ETYPE = ETYPE;\n return this;\n }\n\n /**\n * Get ETYPE\n * @return ETYPE\n **/\n @JsonProperty(JSON_PROPERTY_E_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public Etype getETYPE() {\n return ETYPE;\n }\n\n @JsonProperty(JSON_PROPERTY_E_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setETYPE(Etype ETYPE) {\n this.ETYPE = ETYPE;\n }\n\n public Event SOURCE(SOURCEEnum SOURCE) {\n\n this.SOURCE = SOURCE;\n return this;\n }\n\n /**\n * Optionnel\n * @return SOURCE\n **/\n @JsonProperty(JSON_PROPERTY_S_O_U_R_C_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public SOURCEEnum getSOURCE() {\n return SOURCE;\n }\n\n @JsonProperty(JSON_PROPERTY_S_O_U_R_C_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSOURCE(SOURCEEnum SOURCE) {\n this.SOURCE = SOURCE;\n }\n\n public Event SCALE(SCALEEnum SCALE) {\n\n this.SCALE = SCALE;\n return this;\n }\n\n /**\n * Optionnel, Niveau de criticité de l'opération\n * @return SCALE\n **/\n @JsonProperty(JSON_PROPERTY_S_C_A_L_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public SCALEEnum getSCALE() {\n return SCALE;\n }\n\n @JsonProperty(JSON_PROPERTY_S_C_A_L_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSCALE(SCALEEnum SCALE) {\n this.SCALE = SCALE;\n }\n\n public Event CERTAINTY(Integer CERTAINTY) {\n\n this.CERTAINTY = CERTAINTY;\n return this;\n }\n\n /**\n * Prend une valeur entière entre 0 et 100, et décrit à quel point\n *l'alerte associée à l'événement est fiable Optionnel\n * @return CERTAINTY\n **/\n @JsonProperty(JSON_PROPERTY_C_E_R_T_A_I_N_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public Integer getCERTAINTY() {\n return CERTAINTY;\n }\n\n @JsonProperty(JSON_PROPERTY_C_E_R_T_A_I_N_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCERTAINTY(Integer CERTAINTY) {\n this.CERTAINTY = CERTAINTY;\n }\n\n public Event DECL_DATIME(OffsetDateTime DECL_DATIME) {\n\n this.DECL_DATIME = DECL_DATIME;\n return this;\n }\n\n /**\n * Dans le cadre d'une demande de concours, ce champ est valorisé avec la\n *date/heure de création de l'affaire ou de l'opération. NexSIS\n *transmettra la date/heure de création de l'opération dans ses systèmes\n *(qui peut diverger de la date/heure de création de l'affaire)\n * @return DECL_DATIME\n **/\n @JsonProperty(JSON_PROPERTY_D_E_C_L_D_A_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public OffsetDateTime getDECLDATIME() {\n return DECL_DATIME;\n }\n\n @JsonProperty(JSON_PROPERTY_D_E_C_L_D_A_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setDECLDATIME(OffsetDateTime DECL_DATIME) {\n this.DECL_DATIME = DECL_DATIME;\n }\n\n public Event OCC_DATIME(OffsetDateTime OCC_DATIME) {\n\n this.OCC_DATIME = OCC_DATIME;\n return this;\n }\n\n /**\n * Dans le cadre d'une demande de concours, ce champ est valorisé avec la\n *date de la première alerte ou la date évaluée de début de la situation\n *d'urgence. Par exemple : Si un incendie est déclaré est 9h02, il a pu\n *démarré à 8h55 par exemple. NB : temporairement, NexSIS renseignera ce champ\n *avec la date de réception de l'alerte initiale\n * @return OCC_DATIME\n **/\n @JsonProperty(JSON_PROPERTY_O_C_C_D_A_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public OffsetDateTime getOCCDATIME() {\n return OCC_DATIME;\n }\n\n @JsonProperty(JSON_PROPERTY_O_C_C_D_A_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setOCCDATIME(OffsetDateTime OCC_DATIME) {\n this.OCC_DATIME = OCC_DATIME;\n }\n\n public Event OBS_DATIME(OffsetDateTime OBS_DATIME) {\n\n this.OBS_DATIME = OBS_DATIME;\n return this;\n }\n\n /**\n * Ce champ est idéalement à valoriser avec la date/heure à laquelle\n *l'observation de la situation d'urgence de l'affaire la plus\n *récente a été réalisée. NexSIS transmettra la date/heure d'envoi de la\n *demande de concours dans son système. NB : temporairement, NexSIS\n *renseignera ce champ avec la date de réception de l'alerte initiale\n * @return OBS_DATIME\n **/\n @JsonProperty(JSON_PROPERTY_O_B_S_D_A_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public OffsetDateTime getOBSDATIME() {\n return OBS_DATIME;\n }\n\n @JsonProperty(JSON_PROPERTY_O_B_S_D_A_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setOBSDATIME(OffsetDateTime OBS_DATIME) {\n this.OBS_DATIME = OBS_DATIME;\n }\n\n public Event STATUS(STATUSEnum STATUS) {\n\n this.STATUS = STATUS;\n return this;\n }\n\n /**\n * Permet de décrire le status de l'affaire en cours. Ce champ suit une\n *nomenclature EMSI. (COM = event complete, IPR = event in progress,\n *NST = event not started, STOP = STOP = event under control,\n *no need for additional resource) Dans le cadre d'une opération : - si\n *l'opération est encore en cours : rensigner 'IPR', - si le\n *dispatching de moyens est encore en cours ou que seulement des\n *qualifications d'alertes ont été échangées sans aucune décision de\n *régulation 'NST', - si l'opération est en pause/veille :\n *'STOP' - si le message d'échange opérationnel décrit une fin\n *d'opération, à renseigner avec 'COM' Un message EMSI-EO sans\n *RESSOURCE ni\n * @return STATUS\n **/\n @JsonProperty(JSON_PROPERTY_S_T_A_T_U_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public STATUSEnum getSTATUS() {\n return STATUS;\n }\n\n @JsonProperty(JSON_PROPERTY_S_T_A_T_U_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSTATUS(STATUSEnum STATUS) {\n this.STATUS = STATUS;\n }\n\n public Event RISK_ASSESMENT(RISKASSESMENTEnum RISK_ASSESMENT) {\n\n this.RISK_ASSESMENT = RISK_ASSESMENT;\n return this;\n }\n\n /**\n * Optionnel\n * @return RISK_ASSESMENT\n **/\n @JsonProperty(JSON_PROPERTY_R_I_S_K_A_S_S_E_S_M_E_N_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public RISKASSESMENTEnum getRISKASSESMENT() {\n return RISK_ASSESMENT;\n }\n\n @JsonProperty(JSON_PROPERTY_R_I_S_K_A_S_S_E_S_M_E_N_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setRISKASSESMENT(RISKASSESMENTEnum RISK_ASSESMENT) {\n this.RISK_ASSESMENT = RISK_ASSESMENT;\n }\n\n public Event REFERENCE(List REFERENCE) {\n\n this.REFERENCE = REFERENCE;\n return this;\n }\n\n public Event addREFERENCEItem(Reference REFERENCEItem) {\n if (this.REFERENCE == null) {\n this.REFERENCE = new ArrayList<>();\n }\n this.REFERENCE.add(REFERENCEItem);\n return this;\n }\n\n /**\n * Get REFERENCE\n * @return REFERENCE\n **/\n @JsonProperty(JSON_PROPERTY_R_E_F_E_R_E_N_C_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getREFERENCE() {\n return REFERENCE;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_R_E_F_E_R_E_N_C_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setREFERENCE(List REFERENCE) {\n if (REFERENCE == null) {\n return;\n }\n if (this.REFERENCE == null) {\n this.REFERENCE = new ArrayList<>();\n }\n this.REFERENCE.addAll(REFERENCE);\n }\n\n public Event CASUALTIES(List CASUALTIES) {\n\n this.CASUALTIES = CASUALTIES;\n return this;\n }\n\n public Event addCASUALTIESItem(Casualties CASUALTIESItem) {\n if (this.CASUALTIES == null) {\n this.CASUALTIES = new ArrayList<>();\n }\n this.CASUALTIES.add(CASUALTIESItem);\n return this;\n }\n\n /**\n * Get CASUALTIES\n * @return CASUALTIES\n **/\n @JsonProperty(JSON_PROPERTY_C_A_S_U_A_L_T_I_E_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getCASUALTIES() {\n return CASUALTIES;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_C_A_S_U_A_L_T_I_E_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCASUALTIES(List CASUALTIES) {\n if (CASUALTIES == null) {\n return;\n }\n if (this.CASUALTIES == null) {\n this.CASUALTIES = new ArrayList<>();\n }\n this.CASUALTIES.addAll(CASUALTIES);\n }\n\n public Event EVAC(List EVAC) {\n\n this.EVAC = EVAC;\n return this;\n }\n\n public Event addEVACItem(Evac EVACItem) {\n if (this.EVAC == null) {\n this.EVAC = new ArrayList<>();\n }\n this.EVAC.add(EVACItem);\n return this;\n }\n\n /**\n * Get EVAC\n * @return EVAC\n **/\n @JsonProperty(JSON_PROPERTY_E_V_A_C)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getEVAC() {\n return EVAC;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_E_V_A_C)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setEVAC(List EVAC) {\n if (EVAC == null) {\n return;\n }\n if (this.EVAC == null) {\n this.EVAC = new ArrayList<>();\n }\n this.EVAC.addAll(EVAC);\n }\n\n public Event EGEO(List EGEO) {\n\n this.EGEO = EGEO;\n return this;\n }\n\n public Event addEGEOItem(Egeo EGEOItem) {\n if (this.EGEO == null) {\n this.EGEO = new ArrayList<>();\n }\n this.EGEO.add(EGEOItem);\n return this;\n }\n\n /**\n * Get EGEO\n * @return EGEO\n **/\n @JsonProperty(JSON_PROPERTY_E_G_E_O)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getEGEO() {\n return EGEO;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_E_G_E_O)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setEGEO(List EGEO) {\n if (EGEO == null) {\n return;\n }\n if (this.EGEO == null) {\n this.EGEO = new ArrayList<>();\n }\n this.EGEO.addAll(EGEO);\n }\n\n public Event CAUSE(CAUSEEnum CAUSE) {\n\n this.CAUSE = CAUSE;\n return this;\n }\n\n /**\n * Optionnel\n * @return CAUSE\n **/\n @JsonProperty(JSON_PROPERTY_C_A_U_S_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public CAUSEEnum getCAUSE() {\n return CAUSE;\n }\n\n @JsonProperty(JSON_PROPERTY_C_A_U_S_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCAUSE(CAUSEEnum CAUSE) {\n this.CAUSE = CAUSE;\n }\n\n public Event FREETEXT(String FREETEXT) {\n\n this.FREETEXT = FREETEXT;\n return this;\n }\n\n /**\n * Optionnel\n * @return FREETEXT\n **/\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getFREETEXT() {\n return FREETEXT;\n }\n\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setFREETEXT(String FREETEXT) {\n this.FREETEXT = FREETEXT;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Event event = (Event)o;\n return Objects.equals(this.ID, event.ID) &&\n Objects.equals(this.NAME, event.NAME) &&\n Objects.equals(this.MAIN_EVENT_ID, event.MAIN_EVENT_ID) &&\n Objects.equals(this.ETYPE, event.ETYPE) &&\n Objects.equals(this.SOURCE, event.SOURCE) &&\n Objects.equals(this.SCALE, event.SCALE) &&\n Objects.equals(this.CERTAINTY, event.CERTAINTY) &&\n Objects.equals(this.DECL_DATIME, event.DECL_DATIME) &&\n Objects.equals(this.OCC_DATIME, event.OCC_DATIME) &&\n Objects.equals(this.OBS_DATIME, event.OBS_DATIME) &&\n Objects.equals(this.STATUS, event.STATUS) &&\n Objects.equals(this.RISK_ASSESMENT, event.RISK_ASSESMENT) &&\n Objects.equals(this.REFERENCE, event.REFERENCE) &&\n Objects.equals(this.CASUALTIES, event.CASUALTIES) &&\n Objects.equals(this.EVAC, event.EVAC) &&\n Objects.equals(this.EGEO, event.EGEO) &&\n Objects.equals(this.CAUSE, event.CAUSE) &&\n Objects.equals(this.FREETEXT, event.FREETEXT);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(ID, NAME, MAIN_EVENT_ID, ETYPE, SOURCE, SCALE,\n CERTAINTY, DECL_DATIME, OCC_DATIME, OBS_DATIME, STATUS,\n RISK_ASSESMENT, REFERENCE, CASUALTIES, EVAC, EGEO,\n CAUSE, FREETEXT);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class Event {\\n\");\n sb.append(\" ID: \").append(toIndentedString(ID)).append(\"\\n\");\n sb.append(\" NAME: \").append(toIndentedString(NAME)).append(\"\\n\");\n sb.append(\" MAIN_EVENT_ID: \")\n .append(toIndentedString(MAIN_EVENT_ID))\n .append(\"\\n\");\n sb.append(\" ETYPE: \").append(toIndentedString(ETYPE)).append(\"\\n\");\n sb.append(\" SOURCE: \").append(toIndentedString(SOURCE)).append(\"\\n\");\n sb.append(\" SCALE: \").append(toIndentedString(SCALE)).append(\"\\n\");\n sb.append(\" CERTAINTY: \")\n .append(toIndentedString(CERTAINTY))\n .append(\"\\n\");\n sb.append(\" DECL_DATIME: \")\n .append(toIndentedString(DECL_DATIME))\n .append(\"\\n\");\n sb.append(\" OCC_DATIME: \")\n .append(toIndentedString(OCC_DATIME))\n .append(\"\\n\");\n sb.append(\" OBS_DATIME: \")\n .append(toIndentedString(OBS_DATIME))\n .append(\"\\n\");\n sb.append(\" STATUS: \").append(toIndentedString(STATUS)).append(\"\\n\");\n sb.append(\" RISK_ASSESMENT: \")\n .append(toIndentedString(RISK_ASSESMENT))\n .append(\"\\n\");\n sb.append(\" REFERENCE: \")\n .append(toIndentedString(REFERENCE))\n .append(\"\\n\");\n sb.append(\" CASUALTIES: \")\n .append(toIndentedString(CASUALTIES))\n .append(\"\\n\");\n sb.append(\" EVAC: \").append(toIndentedString(EVAC)).append(\"\\n\");\n sb.append(\" EGEO: \").append(toIndentedString(EGEO)).append(\"\\n\");\n sb.append(\" CAUSE: \").append(toIndentedString(CAUSE)).append(\"\\n\");\n sb.append(\" FREETEXT: \").append(toIndentedString(FREETEXT)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n\nsrc/main/java/com/hubsante/model/emsi/Context.java\n@JsonPropertyOrder(\n {Context.JSON_PROPERTY_I_D, Context.JSON_PROPERTY_M_O_D_E,\n Context.JSON_PROPERTY_M_S_G_T_Y_P_E, Context.JSON_PROPERTY_C_R_E_A_T_I_O_N,\n Context.JSON_PROPERTY_L_I_N_K, Context.JSON_PROPERTY_L_E_V_E_L,\n Context.JSON_PROPERTY_S_E_C_L_A_S_S, Context.JSON_PROPERTY_F_R_E_E_T_E_X_T,\n Context.JSON_PROPERTY_O_R_I_G_I_N,\n Context.JSON_PROPERTY_E_X_T_E_R_N_A_L_I_N_F_O,\n Context.JSON_PROPERTY_U_R_G_E_N_C_Y})\n@JsonTypeName(\"context\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Context {\n public static final String JSON_PROPERTY_I_D = \"ID\";\n private String ID;\n\n /**\n * Valeur constante dans le cadre des échanges LRM-NexSIS : ACTUAL\n */\n public enum MODEEnum {\n ACTUAL(\"ACTUAL\"),\n\n EXERCS(\"EXERCS\"),\n\n SYSTEM(\"SYSTEM\"),\n\n TEST(\"TEST\");\n\n private String value;\n\n MODEEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static MODEEnum fromValue(String value) {\n for (MODEEnum b : MODEEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_M_O_D_E = \"MODE\";\n private MODEEnum MODE;\n\n /**\n * - A valoriser avec la valeur \\"ALERT\\" lors du premier échange\n * entre systèmes. - A valoriser avec la valeur constante \\"UPDATE\\"\n * ensuite. Peut ne pas être interprété par les LRM.\n */\n public enum MSGTYPEEnum {\n ACK(\"ACK\"),\n\n ALERT(\"ALERT\"),\n\n CANCEL(\"CANCEL\"),\n\n ERROR(\"ERROR\"),\n\n UPDATE(\"UPDATE\");\n\n private String value;\n\n MSGTYPEEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static MSGTYPEEnum fromValue(String value) {\n for (MSGTYPEEnum b : MSGTYPEEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_M_S_G_T_Y_P_E = \"MSGTYPE\";\n private MSGTYPEEnum MSGTYPE;\n\n public static final String JSON_PROPERTY_C_R_E_A_T_I_O_N = \"CREATION\";\n private OffsetDateTime CREATION;\n\n public static final String JSON_PROPERTY_L_I_N_K = \"LINK\";\n private List LINK;\n\n /**\n * A valoriser avec la valeur constante \\"OPR\\" dans le cadre du\n * message EMSI-EO\n */\n public enum LEVELEnum {\n STRTGC(\"STRTGC\"),\n\n OPR(\"OPR\"),\n\n TACTCL(\"TACTCL\");\n\n private String value;\n\n LEVELEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static LEVELEnum fromValue(String value) {\n for (LEVELEnum b : LEVELEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_L_E_V_E_L = \"LEVEL\";\n private LEVELEnum LEVEL;\n\n /**\n * Optionnel Dans NexSIS ; Les messages transmis par NexSIS auront un champ\n * valorisé avec systématiquement le même code:\n * \\"RESTRC\\"=restricted Les LRM doivent également renseigner\n * la valeur \\"RESTRC\\"\n */\n public enum SECLASSEnum {\n CONFID(\"CONFID\"),\n\n RESTRC(\"RESTRC\"),\n\n SECRET(\"SECRET\"),\n\n TOPSRT(\"TOPSRT\"),\n\n UNCLAS(\"UNCLAS\"),\n\n UNMARK(\"UNMARK\");\n\n private String value;\n\n SECLASSEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static SECLASSEnum fromValue(String value) {\n for (SECLASSEnum b : SECLASSEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_S_E_C_L_A_S_S = \"SECLASS\";\n private SECLASSEnum SECLASS;\n\n public static final String JSON_PROPERTY_F_R_E_E_T_E_X_T = \"FREETEXT\";\n private String FREETEXT;\n\n public static final String JSON_PROPERTY_O_R_I_G_I_N = \"ORIGIN\";\n private Origin ORIGIN;\n\n public static final String JSON_PROPERTY_E_X_T_E_R_N_A_L_I_N_F_O =\n \"EXTERNAL_INFO\";\n private List EXTERNAL_INFO;\n\n /**\n * Niveau d'urgence pour l'affaire en cours Dans le cadre des échanges\n * LRM-NexSIS, optionnel\n */\n public enum URGENCYEnum {\n URGENT(\"URGENT\"),\n\n NOT_URGENT(\"NOT_URGENT\");\n\n private String value;\n\n URGENCYEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static URGENCYEnum fromValue(String value) {\n for (URGENCYEnum b : URGENCYEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_U_R_G_E_N_C_Y = \"URGENCY\";\n private URGENCYEnum URGENCY;\n\n public Context() {}\n\n public Context ID(String ID) {\n\n this.ID = ID;\n return this;\n }\n\n /**\n * A constituer par le rédacteur du présent EMSI pour être unique, il est\n *préconisé de reprendre la valeur du champ messageId de l'entête RC-DE.\n * @return ID\n **/\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public String getID() {\n return ID;\n }\n\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setID(String ID) {\n this.ID = ID;\n }\n\n public Context MODE(MODEEnum MODE) {\n\n this.MODE = MODE;\n return this;\n }\n\n /**\n * Valeur constante dans le cadre des échanges LRM-NexSIS : ACTUAL\n * @return MODE\n **/\n @JsonProperty(JSON_PROPERTY_M_O_D_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public MODEEnum getMODE() {\n return MODE;\n }\n\n @JsonProperty(JSON_PROPERTY_M_O_D_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setMODE(MODEEnum MODE) {\n this.MODE = MODE;\n }\n\n public Context MSGTYPE(MSGTYPEEnum MSGTYPE) {\n\n this.MSGTYPE = MSGTYPE;\n return this;\n }\n\n /**\n * - A valoriser avec la valeur \\"ALERT\\" lors du premier échange\n *entre systèmes. - A valoriser avec la valeur constante \\"UPDATE\\"\n *ensuite. Peut ne pas être interprété par les LRM.\n * @return MSGTYPE\n **/\n @JsonProperty(JSON_PROPERTY_M_S_G_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public MSGTYPEEnum getMSGTYPE() {\n return MSGTYPE;\n }\n\n @JsonProperty(JSON_PROPERTY_M_S_G_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setMSGTYPE(MSGTYPEEnum MSGTYPE) {\n this.MSGTYPE = MSGTYPE;\n }\n\n public Context CREATION(OffsetDateTime CREATION) {\n\n this.CREATION = CREATION;\n return this;\n }\n\n /**\n * Obligatoire dans le cadre d'une demande de concours, contient la date\n *de création de la demande de concours dans le système du partenaire\n *requérant. A valoriser avec le même horaire que dateTimeSent dans le message\n *RC-DE associé. Dans le cadre d'une demande de concours, obligatoire. Ce\n *champ est valorisée avec l'heure de création de la demande de concours\n *chez le partenaire emetteur. L'heure d'envoi du message peut être\n *obtenue via l'enveloppe EDXL-DE (se référer au DST)\n * @return CREATION\n **/\n @JsonProperty(JSON_PROPERTY_C_R_E_A_T_I_O_N)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public OffsetDateTime getCREATION() {\n return CREATION;\n }\n\n @JsonProperty(JSON_PROPERTY_C_R_E_A_T_I_O_N)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCREATION(OffsetDateTime CREATION) {\n this.CREATION = CREATION;\n }\n\n public Context LINK(List LINK) {\n\n this.LINK = LINK;\n return this;\n }\n\n public Context addLINKItem(Link LINKItem) {\n if (this.LINK == null) {\n this.LINK = new ArrayList<>();\n }\n this.LINK.add(LINKItem);\n return this;\n }\n\n /**\n * Get LINK\n * @return LINK\n **/\n @JsonProperty(JSON_PROPERTY_L_I_N_K)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getLINK() {\n return LINK;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_L_I_N_K)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setLINK(List LINK) {\n if (LINK == null) {\n return;\n }\n if (this.LINK == null) {\n this.LINK = new ArrayList<>();\n }\n this.LINK.addAll(LINK);\n }\n\n public Context LEVEL(LEVELEnum LEVEL) {\n\n this.LEVEL = LEVEL;\n return this;\n }\n\n /**\n * A valoriser avec la valeur constante \\"OPR\\" dans le cadre du\n *message EMSI-EO\n * @return LEVEL\n **/\n @JsonProperty(JSON_PROPERTY_L_E_V_E_L)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public LEVELEnum getLEVEL() {\n return LEVEL;\n }\n\n @JsonProperty(JSON_PROPERTY_L_E_V_E_L)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setLEVEL(LEVELEnum LEVEL) {\n this.LEVEL = LEVEL;\n }\n\n public Context SECLASS(SECLASSEnum SECLASS) {\n\n this.SECLASS = SECLASS;\n return this;\n }\n\n /**\n * Optionnel Dans NexSIS ; Les messages transmis par NexSIS auront un champ\n *valorisé avec systématiquement le même code:\n *\\"RESTRC\\"=restricted Les LRM doivent également renseigner la\n *valeur \\"RESTRC\\"\n * @return SECLASS\n **/\n @JsonProperty(JSON_PROPERTY_S_E_C_L_A_S_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public SECLASSEnum getSECLASS() {\n return SECLASS;\n }\n\n @JsonProperty(JSON_PROPERTY_S_E_C_L_A_S_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSECLASS(SECLASSEnum SECLASS) {\n this.SECLASS = SECLASS;\n }\n\n public Context FREETEXT(String FREETEXT) {\n\n this.FREETEXT = FREETEXT;\n return this;\n }\n\n /**\n * Texte libre, optionnel Dans NexSIS; Fonction de l'événement\n *générateur RG 1 : la valeur de <context><freetext> reste à\n *'Création d'un événement opérationnel EMSI' & version &\n *'suite à réception d'une affaire*' dans le cadre de la création\n *d'une opération commune (conforme RG 2 de NEXSIS-6618) RG 3 : les\n *événements générateurs sont ceux définis au sein de NEXSIS-6619 RG 1 de\n *traçabilité ( input = <Evenement à l'origine> =\n *CREATION_OPERATION / MAJ_MODIFICATION_ETAT_OPERATION / AJOUT_RESSOURCE /\n *RETRAIT_RESSOURCE / MAJ_ETAT_SITUATION_RESSOURCE / MAJ_LOCALISATION_ADRESSE)\n *auxquels seront ajoutés les éventuels événements à venir.\n * @return FREETEXT\n **/\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getFREETEXT() {\n return FREETEXT;\n }\n\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setFREETEXT(String FREETEXT) {\n this.FREETEXT = FREETEXT;\n }\n\n public Context ORIGIN(Origin ORIGIN) {\n\n this.ORIGIN = ORIGIN;\n return this;\n }\n\n /**\n * Get ORIGIN\n * @return ORIGIN\n **/\n @JsonProperty(JSON_PROPERTY_O_R_I_G_I_N)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public Origin getORIGIN() {\n return ORIGIN;\n }\n\n @JsonProperty(JSON_PROPERTY_O_R_I_G_I_N)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setORIGIN(Origin ORIGIN) {\n this.ORIGIN = ORIGIN;\n }\n\n public Context EXTERNAL_INFO(List EXTERNAL_INFO) {\n\n this.EXTERNAL_INFO = EXTERNAL_INFO;\n return this;\n }\n\n public Context addEXTERNALINFOItem(ExternalInfo EXTERNAL_INFOItem) {\n if (this.EXTERNAL_INFO == null) {\n this.EXTERNAL_INFO = new ArrayList<>();\n }\n this.EXTERNAL_INFO.add(EXTERNAL_INFOItem);\n return this;\n }\n\n /**\n * Get EXTERNAL_INFO\n * @return EXTERNAL_INFO\n **/\n @JsonProperty(JSON_PROPERTY_E_X_T_E_R_N_A_L_I_N_F_O)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getEXTERNALINFO() {\n return EXTERNAL_INFO;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_E_X_T_E_R_N_A_L_I_N_F_O)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setEXTERNALINFO(List EXTERNAL_INFO) {\n if (EXTERNAL_INFO == null) {\n return;\n }\n if (this.EXTERNAL_INFO == null) {\n this.EXTERNAL_INFO = new ArrayList<>();\n }\n this.EXTERNAL_INFO.addAll(EXTERNAL_INFO);\n }\n\n public Context URGENCY(URGENCYEnum URGENCY) {\n\n this.URGENCY = URGENCY;\n return this;\n }\n\n /**\n * Niveau d'urgence pour l'affaire en cours Dans le cadre des échanges\n *LRM-NexSIS, optionnel\n * @return URGENCY\n **/\n @JsonProperty(JSON_PROPERTY_U_R_G_E_N_C_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public URGENCYEnum getURGENCY() {\n return URGENCY;\n }\n\n @JsonProperty(JSON_PROPERTY_U_R_G_E_N_C_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setURGENCY(URGENCYEnum URGENCY) {\n this.URGENCY = URGENCY;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Context context = (Context)o;\n return Objects.equals(this.ID, context.ID) &&\n Objects.equals(this.MODE, context.MODE) &&\n Objects.equals(this.MSGTYPE, context.MSGTYPE) &&\n Objects.equals(this.CREATION, context.CREATION) &&\n Objects.equals(this.LINK, context.LINK) &&\n Objects.equals(this.LEVEL, context.LEVEL) &&\n Objects.equals(this.SECLASS, context.SECLASS) &&\n Objects.equals(this.FREETEXT, context.FREETEXT) &&\n Objects.equals(this.ORIGIN, context.ORIGIN) &&\n Objects.equals(this.EXTERNAL_INFO, context.EXTERNAL_INFO) &&\n Objects.equals(this.URGENCY, context.URGENCY);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(ID, MODE, MSGTYPE, CREATION, LINK, LEVEL, SECLASS,\n FREETEXT, ORIGIN, EXTERNAL_INFO, URGENCY);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class Context {\\n\");\n sb.append(\" ID: \").append(toIndentedString(ID)).append(\"\\n\");\n sb.append(\" MODE: \").append(toIndentedString(MODE)).append(\"\\n\");\n sb.append(\" MSGTYPE: \").append(toIndentedString(MSGTYPE)).append(\"\\n\");\n sb.append(\" CREATION: \").append(toIndentedString(CREATION)).append(\"\\n\");\n sb.append(\" LINK: \").append(toIndentedString(LINK)).append(\"\\n\");\n sb.append(\" LEVEL: \").append(toIndentedString(LEVEL)).append(\"\\n\");\n sb.append(\" SECLASS: \").append(toIndentedString(SECLASS)).append(\"\\n\");\n sb.append(\" FREETEXT: \").append(toIndentedString(FREETEXT)).append(\"\\n\");\n sb.append(\" ORIGIN: \").append(toIndentedString(ORIGIN)).append(\"\\n\");\n sb.append(\" EXTERNAL_INFO: \")\n .append(toIndentedString(EXTERNAL_INFO))\n .append(\"\\n\");\n sb.append(\" URGENCY: \").append(toIndentedString(URGENCY)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}\n\nsrc/main/java/com/hubsante/model/emsi/Mission.java\n@JsonPropertyOrder(\n {Mission.JSON_PROPERTY_T_Y_P_E, Mission.JSON_PROPERTY_F_R_E_E_T_E_X_T,\n Mission.JSON_PROPERTY_I_D, Mission.JSON_PROPERTY_O_R_G_I_D,\n Mission.JSON_PROPERTY_N_A_M_E, Mission.JSON_PROPERTY_S_T_A_T_U_S,\n Mission.JSON_PROPERTY_S_T_A_R_T_T_I_M_E,\n Mission.JSON_PROPERTY_E_N_D_T_I_M_E,\n Mission.JSON_PROPERTY_R_E_S_O_U_R_C_E_I_D,\n Mission.JSON_PROPERTY_P_A_R_E_N_T_M_I_S_S_I_O_N_I_D,\n Mission.JSON_PROPERTY_C_H_I_L_D_M_I_S_S_I_O_N_I_D,\n Mission.JSON_PROPERTY_M_A_I_N_M_I_S_S_I_O_N_I_D,\n Mission.JSON_PROPERTY_P_O_S_I_T_I_O_N,\n Mission.JSON_PROPERTY_P_R_I_O_R_I_T_Y})\n@JsonTypeName(\"mission\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Mission {\n\n /**\n * Le champ MISSION TYPE permet d'identifier l'effet à obtenir\n * souhaité à partir de la combinaison du code ACTOR et du code TYPE.\n * => La table de transcodage permettant d'identifier les\n * concourants et les effets à obtenir à partir d'un code EMSI est fournie\n * en annexe \\"Référentiel Effets à Obtenir - correspondance EMSI\\".\n * Dans le cadre d'une réponse à DC : - reprendre le type de la DC si le\n * code réponse choisi est vien \\"VALIDE\\" Dans le cadre d'une\n * mission décrivant les opérations en cours : - reprendre la nomenclature\n * EMSI pour caractériser la mission en cours.\n */\n public enum TYPEEnum {\n C2(\"C2\"),\n\n CBRN(\"CBRN\"),\n\n FF(\"FF\"),\n\n FSTT(\"FSTT\"),\n\n GEN(\"GEN\"),\n\n INT(\"INT\"),\n\n MAC(\"MAC\"),\n\n MIL(\"MIL\"),\n\n NET(\"NET\"),\n\n OPR(\"OPR\"),\n\n POL(\"POL\"),\n\n REC(\"REC\"),\n\n RSC(\"RSC\"),\n\n SAV(\"SAV\"),\n\n SCS(\"SCS\"),\n\n SOC(\"SOC\"),\n\n C2_DEBRIF(\"C2/DEBRIF\"),\n\n C2_DNRSKA(\"C2/DNRSKA\"),\n\n C2_INASSM(\"C2/INASSM\"),\n\n C2_OIC(\"C2/OIC\"),\n\n C2_POA(\"C2/POA\"),\n\n C2_THRTAS(\"C2/THRTAS\"),\n\n CBRN_CBRNCH(\"CBRN/CBRNCH\"),\n\n CBRN_CBRNDC(\"CBRN/CBRNDC\"),\n\n CBRN_NTRCH(\"CBRN/NTRCH\"),\n\n CBRN_NUCWS(\"CBRN/NUCWS\"),\n\n FF_IN(\"FF/IN\"),\n\n FF_OA(\"FF/OA\"),\n\n FF_SALVAG(\"FF/SALVAG\"),\n\n FF_STR(\"FF/STR\"),\n\n FF_TRP(\"FF/TRP\"),\n\n FSTT_DI(\"FSTT/DI\"),\n\n FSTT_RRHAZ(\"FSTT/RRHAZ\"),\n\n FSTT_TA(\"FSTT/TA\"),\n\n GEN_AIRLAU(\"GEN/AIRLAU\"),\n\n GEN_ASSMBL(\"GEN/ASSMBL\"),\n\n GEN_CRWDCT(\"GEN/CRWDCT\"),\n\n GEN_DEMO(\"GEN/DEMO\"),\n\n GEN_DEPLOY(\"GEN/DEPLOY\"),\n\n GEN_DSTRBT(\"GEN/DSTRBT\"),\n\n GEN_FINANC(\"GEN/FINANC\"),\n\n GEN_MARKNG(\"GEN/MARKNG\"),\n\n GEN_MOVE(\"GEN/MOVE\"),\n\n GEN_RECVRN(\"GEN/RECVRN\"),\n\n GEN_RECVRY(\"GEN/RECVRY\"),\n\n GEN_REDPLN(\"GEN/REDPLN\"),\n\n GEN_REORGN(\"GEN/REORGN\"),\n\n GEN_REPAIR(\"GEN/REPAIR\"),\n\n GEN_RESPLN(\"GEN/RESPLN\"),\n\n GEN_RESTNG(\"GEN/RESTNG\"),\n\n GEN_RETIRE(\"GEN/RETIRE\"),\n\n GEN_RLFPLC(\"GEN/RLFPLC\"),\n\n GEN_RNDZVS(\"GEN/RNDZVS\"),\n\n GEN_SCNMNG(\"GEN/SCNMNG\"),\n\n GEN_SECRNG(\"GEN/SECRNG\"),\n\n GEN_STNGUP(\"GEN/STNGUP\"),\n\n GEN_SUPRTN(\"GEN/SUPRTN\"),\n\n GEN_TRNSPN(\"GEN/TRNSPN\"),\n\n INT_BIOSMP(\"INT/BIOSMP\"),\n\n INT_CHMSMP(\"INT/CHMSMP\"),\n\n INT_IDENT(\"INT/IDENT\"),\n\n INT_ILLUMN(\"INT/ILLUMN\"),\n\n INT_LOCTNG(\"INT/LOCTNG\"),\n\n INT_NUCSMP(\"INT/NUCSMP\"),\n\n INT_OBSRNG(\"INT/OBSRNG\"),\n\n INT_PLUMOD(\"INT/PLUMOD\"),\n\n INT_PTRLNG(\"INT/PTRLNG\"),\n\n INT_RECCE(\"INT/RECCE\"),\n\n INT_SRVMET(\"INT/SRVMET\"),\n\n INT_SRVSEN(\"INT/SRVSEN\"),\n\n INT_WITNSN(\"INT/WITNSN\"),\n\n MAC_AII(\"MAC/AII\"),\n\n MAC_COL(\"MAC/COL\"),\n\n MIL_BCESC(\"MIL/BCESC\"),\n\n MIL_BLOCKN(\"MIL/BLOCKN\"),\n\n MIL_BOMBNG(\"MIL/BOMBNG\"),\n\n MIL_CAPTUR(\"MIL/CAPTUR\"),\n\n MIL_CTRATK(\"MIL/CTRATK\"),\n\n MIL_DEFEND(\"MIL/DEFEND\"),\n\n MIL_DISENG(\"MIL/DISENG\"),\n\n MIL_DIVRSN(\"MIL/DIVRSN\"),\n\n MIL_DLBATK(\"MIL/DLBATK\"),\n\n MIL_DSRPTN(\"MIL/DSRPTN\"),\n\n MIL_ENVLPN(\"MIL/ENVLPN\"),\n\n MIL_FIX(\"MIL/FIX\"),\n\n MIL_HARASS(\"MIL/HARASS\"),\n\n MIL_HIDE(\"MIL/HIDE\"),\n\n MIL_HLDDEF(\"MIL/HLDDEF\"),\n\n MIL_HLDOFF(\"MIL/HLDOFF\"),\n\n MIL_INFLTN(\"MIL/INFLTN\"),\n\n MIL_INTCPN(\"MIL/INTCPN\"),\n\n MIL_INTDCT(\"MIL/INTDCT\"),\n\n MIL_MASFOR(\"MIL/MASFOR\"),\n\n MIL_MIL(\"MIL/MIL\"),\n\n MIL_WPNFIR(\"MIL/WPNFIR\"),\n\n NET_COMDEA(\"NET/COMDEA\"),\n\n NET_DATTRF(\"NET/DATTRF\"),\n\n NET_NETJAM(\"NET/NETJAM\"),\n\n NET_NETSEI(\"NET/NETSEI\"),\n\n NET_SGNC(\"NET/SGNC\"),\n\n NET_SGNLE(\"NET/SGNLE\"),\n\n POL_NTRCOM(\"POL/NTRCOM\"),\n\n POL_NTREXP(\"POL/NTREXP\"),\n\n POL_SCNMNG(\"POL/SCNMNG\"),\n\n POL_SCNPRS(\"POL/SCNPRS\"),\n\n POL_SHELTR(\"POL/SHELTR\"),\n\n POL_SUSHOS(\"POL/SUSHOS\"),\n\n POL_WITDRL(\"POL/WITDRL\"),\n\n REC_CLROBS(\"REC/CLROBS\"),\n\n REC_COMACT(\"REC/COMACT\"),\n\n REC_COMRES(\"REC/COMRES\"),\n\n REC_CONSTN(\"REC/CONSTN\"),\n\n REC_ENGCN(\"REC/ENGCN\"),\n\n REC_ENGCNN(\"REC/ENGCNN\"),\n\n REC_PROCUR(\"REC/PROCUR\"),\n\n REC_PRVACC(\"REC/PRVACC\"),\n\n REC_PRVAGR(\"REC/PRVAGR\"),\n\n REC_PRVBDD(\"REC/PRVBDD\"),\n\n REC_PRVCMP(\"REC/PRVCMP\"),\n\n REC_PRVCNS(\"REC/PRVCNS\"),\n\n REC_PRVDCN(\"REC/PRVDCN\"),\n\n REC_PRVEDU(\"REC/PRVEDU\"),\n\n REC_PRVHLT(\"REC/PRVHLT\"),\n\n REC_PRVHSN(\"REC/PRVHSN\"),\n\n REC_PRVINF(\"REC/PRVINF\"),\n\n REC_PRVLND(\"REC/PRVLND\"),\n\n REC_PRVRPR(\"REC/PRVRPR\"),\n\n REC_PRVSCY(\"REC/PRVSCY\"),\n\n REC_PRVSHL(\"REC/PRVSHL\"),\n\n REC_PRVSTG(\"REC/PRVSTG\"),\n\n REC_PRVTRS(\"REC/PRVTRS\"),\n\n REC_PSO(\"REC/PSO\"),\n\n REC_SPLLDB(\"REC/SPLLDB\"),\n\n REC_SPLWAT(\"REC/SPLWAT\"),\n\n REC_UTILTY(\"REC/UTILTY\"),\n\n REC_WATER(\"REC/WATER\"),\n\n RSC_COVERN(\"RSC/COVERN\"),\n\n RSC_FRFGTN(\"RSC/FRFGTN\"),\n\n RSC_MEDEVC(\"RSC/MEDEVC\"),\n\n RSC_SAR(\"RSC/SAR\"),\n\n SAV_AR(\"SAV/AR\"),\n\n SAV_ASC(\"SAV/ASC\"),\n\n SAV_RHD(\"SAV/RHD\"),\n\n SAV_RTA(\"SAV/RTA\"),\n\n SAV_SARCSL(\"SAV/SARCSL\"),\n\n SAV_SARHHA(\"SAV/SARHHA\"),\n\n SAV_SRW(\"SAV/SRW\"),\n\n SAV_USAR(\"SAV/USAR\"),\n\n SAV_UW(\"SAV/UW\"),\n\n SCS_EDU(\"SCS/EDU\"),\n\n SOC_CNDCNF(\"SOC/CNDCNF\"),\n\n SOC_CNDMED(\"SOC/CNDMED\"),\n\n SOC_CNDRCR(\"SOC/CNDRCR\"),\n\n SOC_CNDSCL(\"SOC/CNDSCL\"),\n\n SOC_CNDSPT(\"SOC/CNDSPT\"),\n\n SOC_ISSMDA(\"SOC/ISSMDA\"),\n\n SOC_ISSMDD(\"SOC/ISSMDD\"),\n\n SOC_ISSPRS(\"SOC/ISSPRS\"),\n\n SOC_MN(\"SOC/MN\"),\n\n SOC_PUBMDA(\"SOC/PUBMDA\"),\n\n SOC_PUBMDD(\"SOC/PUBMDD\"),\n\n SOC_PUBPRS(\"SOC/PUBPRS\");\n\n private String value;\n\n TYPEEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static TYPEEnum fromValue(String value) {\n for (TYPEEnum b : TYPEEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_T_Y_P_E = \"TYPE\";\n private TYPEEnum TYPE;\n\n public static final String JSON_PROPERTY_F_R_E_E_T_E_X_T = \"FREETEXT\";\n private String FREETEXT;\n\n public static final String JSON_PROPERTY_I_D = \"ID\";\n private String ID;\n\n public static final String JSON_PROPERTY_O_R_G_I_D = \"ORG_ID\";\n private String ORG_ID;\n\n public static final String JSON_PROPERTY_N_A_M_E = \"NAME\";\n private String NAME;\n\n /**\n * Les valeurs possibles avec lesquelles valoriser ce champ sont détaillées au\n * sein d'une nomenclature EMSI - ABO : mission refusée (ABOrted) - CANCLD\n * : mission annulée (CANCeLeD)** - NST : mission non débuté pour le métier\n * (Not STarted) - IPR : mission débuté pour le métier (In PRogress). la\n * valeur IPR peut être suivi d'une valeur numérique de 00 à 100 (IPRnn)\n * spécifiant le degré d'avancement de la mission. Ce principe n'est\n * pas retenu au sein de NexSIS qui ne transmettra pas d'indication sur le\n * degré d'avancement de la mission via ce champ. - PAU : événement\n * arrêté, en pause pour métier, pas de besoin supplémentaire - COM :\n * événement terminé pour le métier (COMplete) Le status de la mission et\n * celui des RESSOURCE associées doit être cohérent et transcodable avec un\n * status ANTARES (voir DSF) Dans le cas d'un objet MISSION générique de\n * réponse à demande de concours, le champ doit être valorisé à\n * \\"NST\\"\n */\n public enum STATUSEnum {\n ABO(\"ABO\"),\n\n NST(\"NST\"),\n\n CANCLD(\"CANCLD\"),\n\n COM(\"COM\"),\n\n IPR(\"IPR\"),\n\n PAU(\"PAU\");\n\n private String value;\n\n STATUSEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static STATUSEnum fromValue(String value) {\n for (STATUSEnum b : STATUSEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_S_T_A_T_U_S = \"STATUS\";\n private STATUSEnum STATUS;\n\n public static final String JSON_PROPERTY_S_T_A_R_T_T_I_M_E = \"START_TIME\";\n private OffsetDateTime START_TIME;\n\n public static final String JSON_PROPERTY_E_N_D_T_I_M_E = \"END_TIME\";\n private OffsetDateTime END_TIME;\n\n public static final String JSON_PROPERTY_R_E_S_O_U_R_C_E_I_D = \"RESOURCE_ID\";\n private List RESOURCE_ID;\n\n public static final String JSON_PROPERTY_P_A_R_E_N_T_M_I_S_S_I_O_N_I_D =\n \"PARENT_MISSION_ID\";\n private List PARENT_MISSION_ID;\n\n public static final String JSON_PROPERTY_C_H_I_L_D_M_I_S_S_I_O_N_I_D =\n \"CHILD_MISSION_ID\";\n private List CHILD_MISSION_ID;\n\n public static final String JSON_PROPERTY_M_A_I_N_M_I_S_S_I_O_N_I_D =\n \"MAIN_MISSION_ID\";\n private String MAIN_MISSION_ID;\n\n public static final String JSON_PROPERTY_P_O_S_I_T_I_O_N = \"POSITION\";\n private Position POSITION;\n\n /**\n * Indique une échelle de priorité pour la demande de concours. Dans le cadre\n * du standard EMSI, cette échelle doit être comprise entre 0 et 5. Ce champ\n * peut ne pas être interprété ni alimenté par les LRMs. Dans le cadre\n * d'un échange des opérations, optionnel. Le champ peut ne pas être émis\n * ni interprété.\n */\n public enum PRIORITYEnum {\n _0(\"0\"),\n\n _1(\"1\"),\n\n _2(\"2\"),\n\n _3(\"3\"),\n\n _4(\"4\"),\n\n _5(\"5\");\n\n private String value;\n\n PRIORITYEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static PRIORITYEnum fromValue(String value) {\n for (PRIORITYEnum b : PRIORITYEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_P_R_I_O_R_I_T_Y = \"PRIORITY\";\n private PRIORITYEnum PRIORITY;\n\n public Mission() {}\n\n public Mission TYPE(TYPEEnum TYPE) {\n\n this.TYPE = TYPE;\n return this;\n }\n\n /**\n * Le champ MISSION TYPE permet d'identifier l'effet à obtenir\n *souhaité à partir de la combinaison du code ACTOR et du code TYPE.\n *=> La table de transcodage permettant d'identifier les\n *concourants et les effets à obtenir à partir d'un code EMSI est fournie\n *en annexe \\"Référentiel Effets à Obtenir - correspondance EMSI\\".\n *Dans le cadre d'une réponse à DC : - reprendre le type de la DC si le\n *code réponse choisi est vien \\"VALIDE\\" Dans le cadre d'une\n *mission décrivant les opérations en cours : - reprendre la nomenclature EMSI\n *pour caractériser la mission en cours.\n * @return TYPE\n **/\n @JsonProperty(JSON_PROPERTY_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public TYPEEnum getTYPE() {\n return TYPE;\n }\n\n @JsonProperty(JSON_PROPERTY_T_Y_P_E)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setTYPE(TYPEEnum TYPE) {\n this.TYPE = TYPE;\n }\n\n public Mission FREETEXT(String FREETEXT) {\n\n this.FREETEXT = FREETEXT;\n return this;\n }\n\n /**\n * Contient des commentaires relatifs aux objectifs et moyens sollicités dans\n *le cadre de la demande de concours. Les équipements supplémentaires\n *souhaités ou le nom/ prénom des patients à prendre en charge peuvent être\n *explicitement indiqués ici.\n * @return FREETEXT\n **/\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getFREETEXT() {\n return FREETEXT;\n }\n\n @JsonProperty(JSON_PROPERTY_F_R_E_E_T_E_X_T)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setFREETEXT(String FREETEXT) {\n this.FREETEXT = FREETEXT;\n }\n\n public Mission ID(String ID) {\n\n this.ID = ID;\n return this;\n }\n\n /**\n * Contient un identifiant de demande de concours unique. Cet identifiant sera\n *réutilisable par le partenaire pour répondre à cette demande. Identifiant\n *unique de la mission dans le système du partenaire la conduisant.\n * @return ID\n **/\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getID() {\n return ID;\n }\n\n @JsonProperty(JSON_PROPERTY_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setID(String ID) {\n this.ID = ID;\n }\n\n public Mission ORG_ID(String ORG_ID) {\n\n this.ORG_ID = ORG_ID;\n return this;\n }\n\n /**\n * Indique l'organisation du partenaire concerné par la Demande de\n *Concours (voir DSF 8.4). Le code CRRA ou le code du SIS peut être utilisé.\n *Indique l'organisation du service réalisant la mission. Dans le cas\n *d'une réponse, c'est l'organisation du concourant qui doit être\n *indiquée. Se référer au DSF pour la structure normée des organisations Le\n *format est le suivant {pays}:{domaine}:{code\n *département}:{organisation}:{structure interne}*:{unité fonctionnelle}*.\n *identique à <CONTEXT><ORIGIN><ORG_ID>\n * @return ORG_ID\n **/\n @JsonProperty(JSON_PROPERTY_O_R_G_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getORGID() {\n return ORG_ID;\n }\n\n @JsonProperty(JSON_PROPERTY_O_R_G_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setORGID(String ORG_ID) {\n this.ORG_ID = ORG_ID;\n }\n\n public Mission NAME(String NAME) {\n\n this.NAME = NAME;\n return this;\n }\n\n /**\n * Le nom de la mission est construit à partir de l'expression régulière\n *suivante :\n *\\"#DEMANDE_CONCOURS#\\"{libelle_cadre_conventionnel}\\"#\\"{code_cadre_conventionnel}\\"#\\"\n *où le code_cadre_conventionnel est issue d'une nomenclature CISU-Cadre\n *Conventionnel (A Venir) NB : ce champ est détourné par rapport au standard\n *EMSI pour permettre l'expression d'une demande de concours et\n *indiquer le cadre conventionnel dans lequel elle est effectuée. Pour une\n *réponse à demande de concours : - Le nom de la mission est construit à\n *partir de l'expression régulière suivante :\n *\\"#REPONSE_DEMANDE_CONCOURS#\\"{code_reponse}\\"#\\" où le\n *code_reponse peut prendre les valeurs ACCEPTE, REFUS, PARTIELLE, DIVERGENTE\n *- sinon libre\n * @return NAME\n **/\n @JsonProperty(JSON_PROPERTY_N_A_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getNAME() {\n return NAME;\n }\n\n @JsonProperty(JSON_PROPERTY_N_A_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setNAME(String NAME) {\n this.NAME = NAME;\n }\n\n public Mission STATUS(STATUSEnum STATUS) {\n\n this.STATUS = STATUS;\n return this;\n }\n\n /**\n * Les valeurs possibles avec lesquelles valoriser ce champ sont détaillées au\n *sein d'une nomenclature EMSI - ABO : mission refusée (ABOrted) - CANCLD\n *: mission annulée (CANCeLeD)** - NST : mission non débuté pour le métier\n *(Not STarted) - IPR : mission débuté pour le métier (In PRogress). la\n *valeur IPR peut être suivi d'une valeur numérique de 00 à 100 (IPRnn)\n *spécifiant le degré d'avancement de la mission. Ce principe n'est\n *pas retenu au sein de NexSIS qui ne transmettra pas d'indication sur le\n *degré d'avancement de la mission via ce champ. - PAU : événement arrêté,\n *en pause pour métier, pas de besoin supplémentaire - COM : événement terminé\n *pour le métier (COMplete) Le status de la mission et celui des RESSOURCE\n *associées doit être cohérent et transcodable avec un status ANTARES (voir\n *DSF) Dans le cas d'un objet MISSION générique de réponse à demande de\n *concours, le champ doit être valorisé à \\"NST\\"\n * @return STATUS\n **/\n @JsonProperty(JSON_PROPERTY_S_T_A_T_U_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public STATUSEnum getSTATUS() {\n return STATUS;\n }\n\n @JsonProperty(JSON_PROPERTY_S_T_A_T_U_S)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSTATUS(STATUSEnum STATUS) {\n this.STATUS = STATUS;\n }\n\n public Mission START_TIME(OffsetDateTime START_TIME) {\n\n this.START_TIME = START_TIME;\n return this;\n }\n\n /**\n * - Dans le cadre d'une réponse à Demande de Concours Horraire cible pour\n *l'arrivée sur les lieux décrites (peut diverger de l'horaire\n *demandé) - Dans le cadre d'une mission décrivant les opérations en cours\n *: Horaire effectif de début de la mission\n * @return START_TIME\n **/\n @JsonProperty(JSON_PROPERTY_S_T_A_R_T_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public OffsetDateTime getSTARTTIME() {\n return START_TIME;\n }\n\n @JsonProperty(JSON_PROPERTY_S_T_A_R_T_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSTARTTIME(OffsetDateTime START_TIME) {\n this.START_TIME = START_TIME;\n }\n\n public Mission END_TIME(OffsetDateTime END_TIME) {\n\n this.END_TIME = END_TIME;\n return this;\n }\n\n /**\n * A valoriser selon la catégorie de mission : - Dans le cadre d'une\n *mission de réponse à demande de concours : ne pas renseigner - Dans le cadre\n *d'une mission décrivant les opérations en cours : Si c'est un\n *déplacement, l'heure d'arrivée, si c'est une prise en charge\n *patient/victime, la fin de la prise en charge.\n * @return END_TIME\n **/\n @JsonProperty(JSON_PROPERTY_E_N_D_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public OffsetDateTime getENDTIME() {\n return END_TIME;\n }\n\n @JsonProperty(JSON_PROPERTY_E_N_D_T_I_M_E)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setENDTIME(OffsetDateTime END_TIME) {\n this.END_TIME = END_TIME;\n }\n\n public Mission RESOURCE_ID(List RESOURCE_ID) {\n\n this.RESOURCE_ID = RESOURCE_ID;\n return this;\n }\n\n public Mission addRESOURCEIDItem(String RESOURCE_IDItem) {\n if (this.RESOURCE_ID == null) {\n this.RESOURCE_ID = new ArrayList<>();\n }\n this.RESOURCE_ID.add(RESOURCE_IDItem);\n return this;\n }\n\n /**\n * Get RESOURCE_ID\n * @return RESOURCE_ID\n **/\n @JsonProperty(JSON_PROPERTY_R_E_S_O_U_R_C_E_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getRESOURCEID() {\n return RESOURCE_ID;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_R_E_S_O_U_R_C_E_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setRESOURCEID(List RESOURCE_ID) {\n if (RESOURCE_ID == null) {\n return;\n }\n if (this.RESOURCE_ID == null) {\n this.RESOURCE_ID = new ArrayList<>();\n }\n this.RESOURCE_ID.addAll(RESOURCE_ID);\n }\n\n public Mission PARENT_MISSION_ID(List PARENT_MISSION_ID) {\n\n this.PARENT_MISSION_ID = PARENT_MISSION_ID;\n return this;\n }\n\n public Mission addPARENTMISSIONIDItem(String PARENT_MISSION_IDItem) {\n if (this.PARENT_MISSION_ID == null) {\n this.PARENT_MISSION_ID = new ArrayList<>();\n }\n this.PARENT_MISSION_ID.add(PARENT_MISSION_IDItem);\n return this;\n }\n\n /**\n * Get PARENT_MISSION_ID\n * @return PARENT_MISSION_ID\n **/\n @JsonProperty(JSON_PROPERTY_P_A_R_E_N_T_M_I_S_S_I_O_N_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getPARENTMISSIONID() {\n return PARENT_MISSION_ID;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_P_A_R_E_N_T_M_I_S_S_I_O_N_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setPARENTMISSIONID(List PARENT_MISSION_ID) {\n if (PARENT_MISSION_ID == null) {\n return;\n }\n if (this.PARENT_MISSION_ID == null) {\n this.PARENT_MISSION_ID = new ArrayList<>();\n }\n this.PARENT_MISSION_ID.addAll(PARENT_MISSION_ID);\n }\n\n public Mission CHILD_MISSION_ID(List CHILD_MISSION_ID) {\n\n this.CHILD_MISSION_ID = CHILD_MISSION_ID;\n return this;\n }\n\n public Mission addCHILDMISSIONIDItem(String CHILD_MISSION_IDItem) {\n if (this.CHILD_MISSION_ID == null) {\n this.CHILD_MISSION_ID = new ArrayList<>();\n }\n this.CHILD_MISSION_ID.add(CHILD_MISSION_IDItem);\n return this;\n }\n\n /**\n * Get CHILD_MISSION_ID\n * @return CHILD_MISSION_ID\n **/\n @JsonProperty(JSON_PROPERTY_C_H_I_L_D_M_I_S_S_I_O_N_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public List getCHILDMISSIONID() {\n return CHILD_MISSION_ID;\n }\n\n @JacksonXmlElementWrapper(useWrapping = false)\n\n @JsonProperty(JSON_PROPERTY_C_H_I_L_D_M_I_S_S_I_O_N_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCHILDMISSIONID(List CHILD_MISSION_ID) {\n if (CHILD_MISSION_ID == null) {\n return;\n }\n if (this.CHILD_MISSION_ID == null) {\n this.CHILD_MISSION_ID = new ArrayList<>();\n }\n this.CHILD_MISSION_ID.addAll(CHILD_MISSION_ID);\n }\n\n public Mission MAIN_MISSION_ID(String MAIN_MISSION_ID) {\n\n this.MAIN_MISSION_ID = MAIN_MISSION_ID;\n return this;\n }\n\n /**\n * - Dans le cas d'une mission générique de réponse à demande de concours,\n *indiquer l'ID de la mission générique utilisée pour modéliser la demande\n *de concours - Dans le cas d'une mission déclenchée dans le cadre\n *d'une réponse à demande de concours, l'ID de la mission générique de\n *réponse peut être utilisée dans ce champ pour indiquer qu'elle est liée\n *à une réponse\n * @return MAIN_MISSION_ID\n **/\n @JsonProperty(JSON_PROPERTY_M_A_I_N_M_I_S_S_I_O_N_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public String getMAINMISSIONID() {\n return MAIN_MISSION_ID;\n }\n\n @JsonProperty(JSON_PROPERTY_M_A_I_N_M_I_S_S_I_O_N_I_D)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setMAINMISSIONID(String MAIN_MISSION_ID) {\n this.MAIN_MISSION_ID = MAIN_MISSION_ID;\n }\n\n public Mission POSITION(Position POSITION) {\n\n this.POSITION = POSITION;\n return this;\n }\n\n /**\n * Get POSITION\n * @return POSITION\n **/\n @JsonProperty(JSON_PROPERTY_P_O_S_I_T_I_O_N)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public Position getPOSITION() {\n return POSITION;\n }\n\n @JsonProperty(JSON_PROPERTY_P_O_S_I_T_I_O_N)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setPOSITION(Position POSITION) {\n this.POSITION = POSITION;\n }\n\n public Mission PRIORITY(PRIORITYEnum PRIORITY) {\n\n this.PRIORITY = PRIORITY;\n return this;\n }\n\n /**\n * Indique une échelle de priorité pour la demande de concours. Dans le cadre\n *du standard EMSI, cette échelle doit être comprise entre 0 et 5. Ce champ\n *peut ne pas être interprété ni alimenté par les LRMs. Dans le cadre d'un\n *échange des opérations, optionnel. Le champ peut ne pas être émis ni\n *interprété.\n * @return PRIORITY\n **/\n @JsonProperty(JSON_PROPERTY_P_R_I_O_R_I_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public PRIORITYEnum getPRIORITY() {\n return PRIORITY;\n }\n\n @JsonProperty(JSON_PROPERTY_P_R_I_O_R_I_T_Y)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setPRIORITY(PRIORITYEnum PRIORITY) {\n this.PRIORITY = PRIORITY;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Mission mission = (Mission)o;\n return Objects.equals(this.TYPE, mission.TYPE) &&\n Objects.equals(this.FREETEXT, mission.FREETEXT) &&\n Objects.equals(this.ID, mission.ID) &&\n Objects.equals(this.ORG_ID, mission.ORG_ID) &&\n Objects.equals(this.NAME, mission.NAME) &&\n Objects.equals(this.STATUS, mission.STATUS) &&\n Objects.equals(this.START_TIME, mission.START_TIME) &&\n Objects.equals(this.END_TIME, mission.END_TIME) &&\n Objects.equals(this.RESOURCE_ID, mission.RESOURCE_ID) &&\n Objects.equals(this.PARENT_MISSION_ID, mission.PARENT_MISSION_ID) &&\n Objects.equals(this.CHILD_MISSION_ID, mission.CHILD_MISSION_ID) &&\n Objects.equals(this.MAIN_MISSION_ID, mission.MAIN_MISSION_ID) &&\n Objects.equals(this.POSITION, mission.POSITION) &&\n Objects.equals(this.PRIORITY, mission.PRIORITY);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(TYPE, FREETEXT, ID, ORG_ID, NAME, STATUS, START_TIME,\n END_TIME, RESOURCE_ID, PARENT_MISSION_ID,\n CHILD_MISSION_ID, MAIN_MISSION_ID, POSITION, PRIORITY);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class Mission {\\n\");\n sb.append(\" TYPE: \").append(toIndentedString(TYPE)).append(\"\\n\");\n sb.append(\" FREETEXT: \").append(toIndentedString(FREETEXT)).append(\"\\n\");\n sb.append(\" ID: \").append(toIndentedString(ID)).append(\"\\n\");\n sb.append(\" ORG_ID: \").append(toIndentedString(ORG_ID)).append(\"\\n\");\n sb.append(\" NAME: \").append(toIndentedString(NAME)).append(\"\\n\");\n sb.append(\" STATUS: \").append(toIndentedString(STATUS)).append(\"\\n\");\n sb.append(\" START_TIME: \")\n .append(toIndentedString(START_TIME))\n .append(\"\\n\");\n sb.append(\" END_TIME: \").append(toIndentedString(END_TIME)).append(\"\\n\");\n sb.append(\" RESOURCE_ID: \")\n .append(toIndentedString(RESOURCE_ID))\n .append(\"\\n\");\n sb.append(\" PARENT_MISSION_ID: \")\n .append(toIndentedString(PARENT_MISSION_ID))\n .append(\"\\n\");\n sb.append(\" CHILD_MISSION_ID: \")\n .append(toIndentedString(CHILD_MISSION_ID))\n .append(\"\\n\");\n sb.append(\" MAIN_MISSION_ID: \")\n .append(toIndentedString(MAIN_MISSION_ID))\n .append(\"\\n\");\n sb.append(\" POSITION: \").append(toIndentedString(POSITION)).append(\"\\n\");\n sb.append(\" PRIORITY: \").append(toIndentedString(PRIORITY)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}", "answers": [" this.EVENT = EVENT;"], "length": 7992, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "3d4a6d3d-13c4-499e-9639-d624d4a6adda", "reasoning": "The Emsi class follows a consistent pattern for its setter methods. For CONTEXT, the setter is defined as `public void setCONTEXT(Context CONTEXT) { this.CONTEXT = CONTEXT; }`. The snippet ends right after the opening brace of the `setEVENT` method. Following the same pattern, the next line should assign the passed parameter to the class field, i.e., `this.EVENT = EVENT;`.", "reasoning_model_answer": "this.EVENT = EVENT;", "assistant_with_reasoning": "\nThe Emsi class follows a consistent pattern for its setter methods. For CONTEXT, the setter is defined as `public void setCONTEXT(Context CONTEXT) { this.CONTEXT = CONTEXT; }`. The snippet ends right after the opening brace of the `setEVENT` method. Following the same pattern, the next line should assign the passed parameter to the class field, i.e., `this.EVENT = EVENT;`.\n\nthis.EVENT = EVENT;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.609, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36694, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "this.EVENT = EVENT;", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "import android.util.Log;\nimport android.util.SparseIntArray;\nimport android.view.InputDevice;\nimport android.view.KeyEvent;\nimport android.view.MotionEvent;\nimport android.widget.Toast;\nimport com.seleuco.mame4droid.Emulator;\nimport com.seleuco.mame4droid.MAME4droid;\nimport com.seleuco.mame4droid.helpers.DialogHelper;\nimport com.seleuco.mame4droid.helpers.MainHelper;\nimport com.seleuco.mame4droid.helpers.PrefsHelper;\nimport java.util.Arrays;", "context": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/GameController.java\n\n\t\tresetAutodetected();\n }\n\n\tpublic static void resetAutodetected() {\n\t\t//id = 0;\n\t\tArrays.fill(deviceIDs, -1);\n\t\tbanDev.clear();\n\t}\n\n\tpublic static int getGamePadId(InputDevice id) {\n\t\tint iDeviceId = 0;\n\t\tint iControllerNumber = 0;\n\n\t\ttry {\n\t\t\tif (!fakeID)\n\t\t\t\tiDeviceId = id.getId();\n\t\t\telse\n\t\t\t\tiDeviceId = 0;\n\t\t} catch (Exception ignored) {\n\t\t}\n\n\t\tif (!fakeID) {\n\t\t\tiControllerNumber = id.getControllerNumber();\n\t\t\tif (iControllerNumber > 0)\n\t\t\t\tiDeviceId = iControllerNumber;\n\t\t}\n\t\treturn iDeviceId;\n\t}\n\n\tpublic static int makeKeyCodeWithDeviceID(InputDevice id, int iKeyCode) {\n\t\tint padid = 0;\n\t\ttry {\n\t\t\tpadid = getGamePadId(id);\n\t\t} catch (Exception ignored) {\n\t\t}\n\n\t\treturn makeKeyCodeWithDeviceID(padid, iKeyCode);\n\t}\n\n\tpublic static int makeKeyCodeWithDeviceID(int iDeviceId, int iKeyCode) {\n\t\tint iRet = 0;\n\n\t\t//iRet = ((iDeviceId * 1000) + iKeyCode);//type 1\n\n\t\t//type 2\n\t\tiRet = iDeviceId;\n\t\tiRet = iRet << 16;\n\t\tiRet |= iKeyCode;\n\t\t//type 2 end\n\n\t\treturn iRet;\n\t}\n\n\tpublic static void getInfoFromKeyCodeWithDeviceID(int iKeyCode, int[] iArrRet) {\n\t\tint iDeviceIdRet = 0;\n\t\tint iKeyCodeRet = 0;\n\n\t\t//type 1\n\t\t/*iDeviceIdRet = iKeyCode / 1000;\n\t\tiKeyCodeRet = iKeyCode % 1000;\n\t\t*/\n\t\t//type 1 end\n\n\t\t//type 2\n\t\tiDeviceIdRet = iKeyCode >> 16;\n\t\tiKeyCodeRet = iKeyCode & 0xFFFF;\n\t\t//type 2 end\n\n\t\tiArrRet[0] = iDeviceIdRet;\n\t\tiArrRet[1] = iKeyCodeRet;\n\t}\n\n\tpublic static int getDeviceIdFromKeyCodeWithDeviceID(int iKeyCode) {\n\t\t//return iKeyCode / 1000; //type 1\n\t\treturn iKeyCode >> 16; //type 2\n\t}\n\n\tpublic static int getKeyCodeFromKeyCodeWithDeviceID(int iKeyCode) {\n\t\t//return iKeyCode % 1000; //type 1\n\t\treturn iKeyCode & 0xFFFF; //type 2\n\t}\n\n\tprotected void setContollerData(int i, KeyEvent event, int data, int[]digital_data) {\n\t\tint action = event.getAction();\n\t\tif (action == KeyEvent.ACTION_DOWN)\n\t\t\tdigital_data[i] |= data;\n\t\telse if (action == KeyEvent.ACTION_UP)\n\t\t\tdigital_data[i] &= ~data;\n\t}\n\n\tprotected boolean handleControllerKey(int value, KeyEvent event, int []digital_data) {\n\n\t\tint v = emulatorInputValues[value % emulatorInputValues.length];\n\n\t\tif (v == EXIT_VALUE) {\n\t\t\tif (event.getAction() == KeyEvent.ACTION_UP) {\n\t\t\t\t/*\n\t\t\t\tif (Emulator.isInMenu()) {\n\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 1);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.sleep(InputHandler.PRESS_WAIT);\n\t\t\t\t\t} catch (InterruptedException ignored) {\n\t\t\t\t\t}\n\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 0);\n\t\t\t\t} else if (!Emulator.isInGame()) {\n\t\t\t\t\tmm.showDialog(DialogHelper.DIALOG_EXIT);\n\t\t\t\t} else {\n\t\t\t\t*/\n\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 1);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.sleep(InputHandler.PRESS_WAIT);\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t}\n\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 0);\n\t\t\t\t//}\n\t\t\t}\n\t\t} else if (v == OPTION_VALUE ) {\n\t\t\tif (event.getAction() == KeyEvent.ACTION_UP && !Emulator.isInOptions()) {\n\t\t\t\tEmulator.setInOptions(true);\n\nandroid-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java\npublic class Emulator {\n\n\t//gets\n\tfinal static public int IN_MENU = 1;\n\tfinal static public int IN_GAME = 2;\n\tfinal static public int NUMBTNS = 3;\n\tfinal static public int NUMWAYS = 4;\n\tfinal static public int IS_LIGHTGUN = 5;\n\n\t//sets\n\tfinal static public int EXIT_GAME = 1;\n\n\tfinal static public int EXIT_PAUSE = 2;\n final static public int SHOW_FPS = 3;\n\n\tfinal static public int AUTO_FRAMESKIP = 4;\n\tfinal static public int CHEATS = 5;\n\tfinal static public int SKIP_GAMEINFO = 6;\n\n\tfinal static public int DISABLE_DRC = 7;\n\n\tfinal static public int DRC_USE_C = 8;\n\n\tfinal static public int SIMPLE_UI = 9;\n\n final static public int PAUSE = 11;\n final static public int SOUND_VALUE = 13;\n\n final static public int AUTOSAVE = 16;\n final static public int SAVESTATE = 17;\n final static public int LOADSTATE = 18;\n\n\tfinal static public int OSD_RESOLUTION = 20;\n final static public int EMU_RESOLUTION = 21;\n\n\tfinal static public int ZOOM_TO_WINDOW = 22;\n\n final static public int DOUBLE_BUFFER = 23;\n final static public int PXASP1 = 24;\n\n final static public int VBEAM2X = 34;\n final static public int VFLICKER = 36;\n final static public int SOUND_OPTIMAL_FRAMES = 48;\n final static public int SOUND_OPTIMAL_SAMPLERATE = 49;\n final static public int SOUND_ENGINE = 50;\n\n final static public int MOUSE = 60;\n final static public int REFRESH = 61;\n final static public int USING_SAF = 62;\n final static public int SAVESATES_IN_ROM_PATH = 63;\n\n\tfinal static public int WARN_ON_EXIT = 64;\n\n\tfinal static public int IS_MOUSE = 65;\n\n\tfinal static public int KEYBOARD = 66;\n\n\tfinal static public int ONE_PROCESSOR = 67;\n\tfinal static public int NODEADZONEANDSAT = 68;\n\tfinal static public int MAMEINI = 69;\n\n\t//set str\n final static public int SAF_PATH = 1;\n final static public int ROM_NAME = 2;\n final static public int VERSION = 3;\n\tfinal static public int OVERLAY_EFECT = 4;\n\n\t//get str\n\tfinal static public int MAME_VERSION = 1;\n\n\t//KEYS ACTIONS\n\tfinal static public int KEY_DOWN = 1;\n\tfinal static public int KEY_UP = 2;\n\n\t//MOUSE ACTIONS\n\tfinal static public int MOUSE_MOVE = 1;\n\tfinal static public int MOUSE_BTN_DOWN = 2;\n\tfinal static public int MOUSE_BTN_UP = 3;\n\n\n private static MAME4droid mm = null;\n\n private static boolean isEmulating = false;\n\n public static boolean isEmulating() {\n return isEmulating;\n }\n\n private static Object lock1 = new Object();\n\n private static ByteBuffer screenBuff = null;\n\n private static boolean emuFiltering = false;\n\n public static boolean isEmuFiltering() {\n return emuFiltering;\n }\n\n\tpublic static void setEmuFiltering(boolean value) {\n\t\temuFiltering = value;\n\t}\n\n\tprivate static Paint debugPaint = new Paint();\n\n private static Matrix mtx = new Matrix();\n\n private static int window_width = 320;\n\n public static int getWindow_width() {\n return window_width;\n }\n\n private static int window_height = 240;\n\n public static int getWindow_height() {\n return window_height;\n }\n\n private static int emu_width = 320;\n private static int emu_height = 240;\n\n\n private static AudioTrack audioTrack = null;\n\n private static boolean isDebug = false;\n private static int videoRenderMode = PrefsHelper.PREF_RENDER_GL;\n\n private static boolean inMenu = false;\n private static boolean oldInMenu = false;\n\n public static boolean isInGame() {\n return Emulator.getValue(Emulator.IN_GAME) == 1;\n }\n\n public static boolean isInMenu() {\n return inMenu;\n }\n\n\tpublic static boolean isInGameButNotInMenu() {\n\t\treturn isInGame() && !isInMenu();\n\t}\n\n\tprivate static boolean saveorload = false;\n\tpublic static void setSaveorload(boolean value){saveorload=value;}\n\tpublic static boolean isSaveorload(){return saveorload;};\n\n\tprivate static boolean inOptions = false;\n\tpublic static void setInOptions(boolean value){\n\t\tinOptions =value;}\n\tpublic static boolean isInOptions(){return inOptions;};\n\n private static boolean needsRestart = false;\n\n public static void setNeedRestart(boolean value) {\n needsRestart = value;\n }\n\n public static boolean isRestartNeeded() {\n return needsRestart;\n }\n\n private static boolean warnResChanged = false;\n\n public static boolean isWarnResChanged() {\n return warnResChanged;\n }\n\n public static void setWarnResChanged(boolean warnResChanged) {\n Emulator.warnResChanged = warnResChanged;\n }\n\n private static boolean paused = true;\n\n public static boolean isPaused() {\n return paused;\n }\n\n private static boolean portraitFull = false;\n\n public static boolean isPortraitFull() {\n return portraitFull;\n }\n\n public static void setPortraitFull(boolean portraitFull) {\n Emulator.portraitFull = portraitFull;\n }\n\n static {\n try {\n System.loadLibrary(\"mame4droid-jni\");\n } catch (java.lang.Error e) {\n e.printStackTrace();\n }\n\n debugPaint.setARGB(255, 255, 255, 255);\n debugPaint.setStyle(Style.STROKE);\n debugPaint.setTextSize(16);\n }\n\n public static int getEmulatedWidth() {\n return emu_width;\n }\n\n public static int getEmulatedHeight() {\n return emu_height;\n }\n\n public static boolean isDebug() {\n return isDebug;\n }\n\n public static void setDebug(boolean isDebug) {\n Emulator.isDebug = isDebug;\n }\n\n public static int getVideoRenderMode() {\n return Emulator.videoRenderMode;\n }\n\n public static void setVideoRenderMode(int videoRenderMode) {\n Emulator.videoRenderMode = videoRenderMode;\n }\n\n public static Paint getDebugPaint() {\n return debugPaint;\n }\n\n public static Matrix getMatrix() {\n return mtx;\n }\n\n //synchronized\n public static ByteBuffer getScreenBuffer() {\n return screenBuff;\n }\n\n public static void setMAME4droid(MAME4droid mm) {\n Emulator.mm = mm;\n }\n\n //VIDEO\n public static void setWindowSize(int w, int h) {\n\n //System.out.println(\"window size \"+w+\" \"+h);\n\n window_width = w;\n window_height = h;\n\n if (videoRenderMode == PrefsHelper.PREF_RENDER_GL)\n return;\n\n mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height));\n }\n\n //synchronized\n static void bitblt(ByteBuffer sScreenBuff) {\n\n //Log.d(\"Thread Video\", \"fuera lock\");\n synchronized (lock1) {\n try {\n //Log.d(\"Thread Video\", \"dentro lock\");\n screenBuff = sScreenBuff;\n Emulator.inMenu = Emulator.getValue(Emulator.IN_MENU) == 1;\n\n if (inMenu != oldInMenu) {\n\n\t\t\t\t\tif(!inMenu && isSaveorload())\n\t\t\t\t\t\tsetSaveorload(false);\n\n final View v = mm.getInputView();\n if (v != null) {\n mm.runOnUiThread(new Runnable() {\n public void run() {\n v.invalidate();\n }\n });\n }\n }\n oldInMenu = inMenu;\n\n if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) {\n ((EmulatorViewGL) mm.getEmuView()).requestRender();\n } else {\n Log.e(\"Thread Video\", \"Renderer not supported.\");\n }\n //Log.d(\"Thread Video\", \"fin lock\");\n\n } catch (/*Throwable*/NullPointerException t) {\n Log.getStackTraceString(t);\n t.printStackTrace();\n }\n }\n }\n\n //synchronized\n static public void changeVideo(final int newWidth, final int newHeight) {\n\n\t\tLog.d(\"Thread Video\", \"changeVideo emu_width:\"+emu_width+\" emu_height: \"+emu_height+\" newWidth:\"+newWidth+\" newHeight: \"+newHeight);\n synchronized (lock1) {\n\n mm.getInputHandler().resetInput();\n\n warnResChanged = emu_width != newWidth || emu_height != newHeight;\n\n //if(emu_width!=newWidth || emu_height!=newHeight)\n //{\n emu_width = newWidth;\n emu_height = newHeight;\n\n mtx.setScale((float) (window_width / (float) emu_width), (float) (window_height / (float) emu_height));\n\n if (videoRenderMode == PrefsHelper.PREF_RENDER_GL) {\n GLRenderer r = (GLRenderer) ((EmulatorViewGL) mm.getEmuView()).getRender();\n if (r != null) r.changedEmulatedSize();\n } else {\n\t\t\t\tLog.e(\"Thread Video\", \"Error renderer not supported\");\n }\n\n mm.getMainHelper().updateEmuValues();\n\n mm.runOnUiThread(new Runnable() {\n public void run() {\n\n //Toast.makeText(mm, \"changeVideo newWidth:\"+newWidth+\" newHeight:\"+newHeight+\" newVisWidth:\"+newVisWidth+\" newVisHeight:\"+newVisHeight,Toast.LENGTH_SHORT).show();\n mm.overridePendingTransition(0, 0);\n\t\t\t\t\t/*\n if (warnResChanged && videoRenderMode == PrefsHelper.PREF_RENDER_GL && Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1)\n mm.getEmuView().setVisibility(View.INVISIBLE);\n\t\t\t\t\t*/\n\n mm.getMainHelper().updateMAME4droid();\n if (mm.getEmuView().getVisibility() != View.VISIBLE)\n mm.getEmuView().setVisibility(View.VISIBLE);\n }\n });\n //}\n }\n\n }\n\n\tstatic public void initInput() {\n\t\tLog.d(\"initInput\",\"initInput isInGame:\"+isInGame()+\" isInMenu:\"+isInMenu());\n\t\tmm.runOnUiThread(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(100);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t\tif ( /*Emulator.getValue(Emulator.IN_GAME) == 1 && Emulator.getValue(Emulator.IN_MENU) == 0\n\t\t\t\t\t&&*/ (((mm.getPrefsHelper().isTouchLightgun() || mm.getPrefsHelper().isTouchGameMouse())\n\t\t\t\t\t&& mm.getInputHandler()\n\t\t\t\t\t.getTouchController().getState() != TouchController.STATE_SHOWING_NONE) || mm\n\t\t\t\t\t.getPrefsHelper().isTiltSensorEnabled())) {\n\n\t\t\t\t\tCharSequence text = \"\";\n\t\t\t\t\tif(mm.getPrefsHelper().isTiltSensorEnabled())\n\t\t\t\t\t\ttext = \"Tilt sensor is enabled!\";\n\t\t\t\t\telse if(mm.getPrefsHelper().isTouchLightgun())\n\t\t\t\t\t\ttext = \"Touch lightgun is enabled!\";\n\t\t\t\t\telse if(mm.getPrefsHelper().isTouchGameMouse())\n\t\t\t\t\t\ttext = \"Touch mouse is enabled!\";\n\n\t\t\t\t\tint duration = Toast.LENGTH_SHORT;\n\t\t\t\t\tToast toast = Toast.makeText(mm, text, duration);\n\t\t\t\t\ttoast.show();\n\t\t\t\t\tLog.d(\"initInput\",\"virtual device: \"+text);\n\t\t\t\t}\n\n\t\t\t\tmm.getMainHelper().updateMAME4droid();\n\t\t\t}\n\t\t});\n\t}\n\n //SOUND\n static public void initAudio(int freq, boolean stereo) {\n int sampleFreq = freq;\n\n int channelConfig = stereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;\n int audioFormat = AudioFormat.ENCODING_PCM_16BIT;\n\n int bufferSize = AudioTrack.getMinBufferSize(sampleFreq, channelConfig, audioFormat);\n\n if (mm.getPrefsHelper().getSoundEngine() == PrefsHelper.PREF_SNDENG_AUDIOTRACK_HIGH)\n bufferSize += bufferSize / 4;\n\n //System.out.println(\"Buffer Size \"+bufferSize);\n\n audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,\n sampleFreq,\n channelConfig,\n audioFormat,\n bufferSize,\n AudioTrack.MODE_STREAM);\n\n audioTrack.play();\n }\n\n public static void endAudio() {\n if (audioTrack != null) {\n audioTrack.stop();\n audioTrack.release();\n }\n audioTrack = null;\n }\n\n public static void writeAudio(byte[] b, int sz) {\n //System.out.println(\"Envio \"+sz+\" \"+audioTrack);\n if (audioTrack != null) {\n\t\t\taudioTrack.write(b, 0, sz);\n }\n }\n\n //LIVE CYCLE\n public static void pause() {\n //Log.d(\"EMULATOR\", \"PAUSE\");\n\n if (isEmulating) {\n //pauseEmulation(true);\n Emulator.setValue(Emulator.PAUSE, 1);\n paused = true;\n }\n\n if (audioTrack != null) {\n try {\n audioTrack.pause();\n } catch (Throwable e) {\n }\n }\n/*\n try {\n Thread.sleep(60);//ensure threads stop\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n*/\n }\n\n public static void resume() {\n //Log.d(\"EMULATOR\", \"RESUME\");\n\n if (isRestartNeeded())\n return;\n\n if (audioTrack != null)\n audioTrack.play();\n\n if (isEmulating) {\n Emulator.setValue(Emulator.PAUSE, 0);\n Emulator.setValue(Emulator.EXIT_PAUSE, 1);\n paused = false;\n }\n }\n\n //EMULATOR\n public static void emulate(final String libPath, final String resPath) {\n\n //Thread.currentThread().setPriority(Thread.MAX_PRIORITY);\n\n if (isEmulating) return;\n\n Thread t = new Thread(new Runnable() {\n\n public void run() {\n\n boolean extROM = false;\n isEmulating = true;\n\t\t\t\tSize sz = mm.getMainHelper().getWindowSize();\n init(libPath, resPath, Math.max(sz.getWidth(),sz.getHeight()), Math.min(sz.getWidth(),sz.getHeight()));\n final String versionName = mm.getMainHelper().getVersion();\n Emulator.setValueStr(Emulator.VERSION, versionName);\n\n\t\t\t\tboolean isUsingSaf = mm.getPrefsHelper().getROMsDIR() != null && mm.getPrefsHelper().getROMsDIR().length() != 0;\n\t\t\t\tif(isUsingSaf) {\n\t\t\t\t\tEmulator.setValue(Emulator.USING_SAF, 1);\n\t\t\t\t\tEmulator.setValueStr(Emulator.SAF_PATH, mm.getPrefsHelper().getROMsDIR());\n\t\t\t\t\tmm.getSAFHelper().listUriFiles(true);\n\t\t\t\t}\n\n Intent intent = mm.getIntent();\n String action = intent.getAction();\n //Uri pkg = null;\n String fileName = null;\n String path = null;\n boolean delete = false;\n if (Intent.ACTION_VIEW.equals(action)) {\n //android.os.Debug.waitForDebugger();\n //pkg = mm.getReferrer();\n //System.out.println(\"PKG: \"+pkg.getHost());\n\n Uri _uri = intent.getData();\n //System.out.println(\"URI: \"+_uri.toString());\n boolean error = false;\n\n //String filePath = null;\n\n //android.os.Debug.waitForDebugger();\n Log.d(\"\", \"URI = \" + _uri);\n try {\n if (_uri != null && \"content\".equalsIgnoreCase(_uri.getScheme())) {\n //mm.safHelper.setURI(null);//disable SAF.\n\t\t\t\t\t\t\t//Log.d(\"SAF\",\"Disabling SAF\");\n fileName = mm.getMainHelper().getFileName(_uri);\n String state = Environment.getExternalStorageState();\n\n if (Environment.MEDIA_MOUNTED.equals(state)) {\n //path = mm.getExternalCacheDir().getPath();\n path = mm.getPrefsHelper().getInstallationDIR()+\"roms\";\n File f = new File(path+\"/\"+fileName);\n if(!f.exists()) {\n java.io.InputStream input = mm.getContentResolver().openInputStream(_uri);\n error = mm.getMainHelper().copyFile(input, path, fileName);\n delete = true;\n }\n } else\n error = true;\n } else {\n String filePath = _uri.getPath();\n java.io.File f = new java.io.File(filePath);\n fileName = f.getName();\n path = f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(File.separator));\n }\n } catch (Exception e) {\n error = true;\n }\n\n if (error) {\n mm.runOnUiThread(new Runnable() {\n public void run() {\n mm.getDialogHelper().setInfoMsg(\"Error opening file...\");\n mm.showDialog(DialogHelper.DIALOG_INFO);\n }\n });\n } else {\n\n Emulator.setValueStr(Emulator.ROM_NAME, fileName);\n System.out.println(\"XX name: \" + fileName);\n System.out.println(\"XX path: \" + path);\n extROM = true;\n final String name = fileName;\n mm.runOnUiThread(new Runnable() {\n public void run() {\n //Toast.makeText(mm, Html.fromHtml(\"\" + \"MAME4droid (0.139) \" + versionName + \".
Launching: \" + name + \"
\"), Toast.LENGTH_LONG).show();\n Toast.makeText(mm, \"Launching: \" + name + \"\\nMAME4droid 2024 \" + versionName, Toast.LENGTH_LONG).show();\n }\n });\n }\n }\n\n mm.getMainHelper().updateEmuValues();\n\n\t\t\t\trunT();\n\n if (extROM) {\n\t\t\t\t\t/*\n\t\t\t\t\tif (pkg != null && \"com.digdroid.alman.dig\".equals(pkg.getHost())) {\n\t\t\t\t\t\tPackageManager pm = mm.getPackageManager();\n\t\t\t\t\t\tIntent intent2 = pm.getLaunchIntentForPackage(\"com.digdroid.alman.dig\");\n\t\t\t\t\t\tmm.startActivity(intent2);\n\t\t\t\t\t}*/\n if (delete) {\n java.io.File f = new java.io.File(path, fileName);\n f.delete();\n }\n }\n\t\t\t\tmm.runOnUiThread(new Runnable() {\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tif (android.os.Build.VERSION.SDK_INT >= 21) {\n\t\t\t\t\t\t\tmm.finishAndRemoveTask();\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tmm.finish();\n\t\t\t\t\t\tandroid.os.Process.killProcess(android.os.Process.myPid());\n\t\t\t\t\t}\n\t\t\t\t});\n }\n }, \"emulatorNativeMain-Thread\");\n\n\n if (mm.getPrefsHelper().getMainThreadPriority() == PrefsHelper.LOW) {\n t.setPriority(Thread.MIN_PRIORITY);\n } else if (mm.getPrefsHelper().getMainThreadPriority() == PrefsHelper.NORMAL) {\n t.setPriority(Thread.NORM_PRIORITY);\n } else\n t.setPriority(Thread.MAX_PRIORITY);\n\n t.start();\n }\n\n public static int getValue(int key) {\n return getValue(key, 0);\n }\n\n public static String getValueStr(int key) {\n return getValueStr(key, 0);\n }\n\n public static void setValue(int key, int value) {\n setValue(key, 0, value);\n }\n\n public static void setValueStr(int key, String value) {\n setValueStr(key, 0, value);\n }\n\n static int safOpenFile(String pathName, String mode) {\n //System.out.println(\"-->Llaman a safOpenFile en java \"+pathName+\" \"+mode);\n\n String file = \"\";\n\n String romPath = mm.getPrefsHelper().getROMsDIR();\n if (pathName.startsWith(romPath))\n file = pathName.substring(romPath.length() + 1, pathName.length());\n\n if(file.equals(\"\"))\n return -1;\n\n //System.out.println(\"File with path \"+file);\n\n return mm.getSAFHelper().openUriFd(\"/\" + file, mode);\n }\n\n static int safReadDir(String dirName, int reload) {\n //System.out.println(\"Llaman a safReadDir en java \"+dirName);\n\n //boolean res = mm.getSAFHelper().listUriFiles(reload == 1);\n\n\t\tString dirSAF = \"\";\n\n\t\tString romPath = mm.getPrefsHelper().getROMsDIR();\n\t\tif (dirName.startsWith(romPath)) {\n\t\t\tdirSAF = dirName.substring(romPath.length(), dirName.length());\n\t\t\tif(!dirSAF.startsWith(\"/\")) dirSAF = \"/\"+dirSAF;\n\t\t\tif(!dirSAF.endsWith(\"/\")) dirSAF = dirSAF +\"/\";\n\t\t}\n\n\t\treturn mm.getSAFHelper().readDir(dirSAF);\n }\n\n static String safGetNextDirEntry(int dirId) {\n //System.out.println(\"Llaman a safGetNextDirEntry en java \"+dirId);\n\n return mm.getSAFHelper().getNextDirName(dirId);\n }\n\n static void safCloseDir(int dirId) {\n //System.out.println(\"Llaman a safCloseDir en java \"+dirId);\n\n\t\tmm.getSAFHelper().closeDir(dirId);\n }\n\n //native\n protected static native void init(String libPath, String resPath, int nativeWidth, int nativeHeight);\n\n protected static native void runT();\n\n //protected static native void runVideoT();\n\n synchronized public static native void setDigitalData(int i, long data);\n\n synchronized public static native void setAnalogData(int i, float v1, float v2);\n\n public static native int getValue(int key, int i);\n\n public static native String getValueStr(int key, int i);\n\n public static native void setValue(int key, int i, int value);\n\n public static native void setValueStr(int key, int i, String value);\n\n\tpublic static native int setKeyData(int keyCode, int keyAction, char keyChar);\n\n\tpublic static native int setMouseData(int i, int mouseAction,int button, float cx, float cy);\n\n}\n\nandroid-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/PrefsHelper.java\npublic class PrefsHelper implements OnSharedPreferenceChangeListener {\n final static public String PREF_ROMsDIR = \"PREF_ROMsDIR_2\";\n final static public String PREF_SAF_URI = \"PREF_SAF_URI\";\n final static public String PREF_INSTALLATION_DIR = \"PREF_INSTALLATION_DIR\";\n final static public String PREF_OLD_INSTALLATION_DIR = \"PREF_OLD_INSTALLATION_DIR\";\n\n\n final static public String PREF_GLOBAL_VIDEO_RENDER_MODE = \"PREF_GLOBAL_VIDEO_RENDER_MODE\";\n\n final static public String PREF_EMU_RESOLUTION = \"PREF_EMU_RESOLUTION_2\";\n\tfinal static public String PREF_EMU_RESOLUTION_OSD = \"PREF_EMU_RESOLUTION_OSD\";\n final static public String PREF_EMU_SOUND = \"PREF_EMU_SOUND\";\n final static public String PREF_EMU_SHOW_FPS = \"PREF_EMU_SHOW_FPS\";\n\tfinal static public String PREF_ZOOM_TO_WINDOW = \"PREF_ZOOM_TO_WINDOW\";\n\tfinal static public String PREF_EMU_AUTO_FRAMESKIP = \"PREF_EMU_AUTO_FRAMESKIP\";\n\tfinal static public String CHEATS = \"CHEATS\";\n\tfinal static public String SKIP_GAMEINFO = \"SKIP_GAMEINFO\";\n\tfinal static public String PREF_EMU_DISABLE_DRC = \"PREF_EMU_DISABLE_DRC_2\";\n\tfinal static public String PREF_EMU_DRC_USR_C = \"PREF_EMU_DRC_USR_C\";\n\tfinal static public String PREF_EMU_ONE_PROCESSOR = \"PREF_EMU_ONE_PROCESSOR\";\n\tfinal static public String PREF_MAMEINI = \"PREF_MAMEINI\";\n\n final static public String PREF_GLOBAL_AUTOSAVE = \"PREF_GLOBAL_AUTOSAVE\";\n final static public String PREF_GLOBAL_DEBUG = \"PREF_GLOBAL_DEBUG\";\n\n final static public String PREF_GLOBAL_WARN_ON_EXIT = \"PREF_GLOBAL_WARN_ON_EXIT\";\n\n final static public String PREF_PORTRAIT_SCALING_MODE = \"PREF_PORTRAIT_SCALING_MODE\";\n final static public String PREF_PORTRAIT_TOUCH_CONTROLLER = \"PREF_PORTRAIT_TOUCH_CONTROLLER\";\n final static public String PREF_PORTRAIT_BITMAP_FILTERING = \"PREF_PORTRAIT_BITMAP_FILTERING\";\n final static public String PREF_PORTRAIT_FULLSCREEN = \"PREF_PORTRAIT_FULLSCREEN\";\n\n final static public String PREF_LANDSCAPE_SCALING_MODE = \"PREF_LANDSCAPE_SCALING_MODE\";\n final static public String PREF_LANDSCAPE_TOUCH_CONTROLLER = \"PREF_LANDSCAPE_TOUCH_CONTROLLER\";\n final static public String PREF_LANDSCAPE_BITMAP_FILTERING = \"PREF_LANDSCAPE_BITMAP_FILTERING\";\n final static public String PREF_LANDSCAPE_CONTROLLER_TYPE = \"PREF_LANDSCAPE_CONTROLLER_TYPE\";\n\n final static public String PREF_DEFINED_KEYS = \"PREF_DEFINED_KEYS\";\n\n final static public String PREF_DEFINED_CONTROL_LAYOUT = \"PREF_DEFINED_CONTROL_LAYOUT\";\n final static public String PREF_DEFINED_CONTROL_LAYOUT_P = \"PREF_DEFINED_CONTROL_LAYOUT_P\";\n\n final static public String PREF_DISABLE_RIGHT_STICK = \"PREF_DISABLE_RIGHT_STICK\";\n final static public String PREF_ANIMATED_INPUT = \"PREF_ANIMATED_INPUT\";\n final static public String PREF_TOUCH_LIGHTGUN = \"PREF_TOUCH_LIGHTGUN\";\n\tfinal static public String PREF_TOUCH_LIGHTGUN_FORCE = \"PREF_TOUCH_LIGHTGUN_FORCE\";\n final static public String PREF_TOUCH_DZ = \"PREF_TOUCH_DZ\";\n final static public String PREF_CONTROLLER_TYPE = \"PREF_CONTROLLER_TYPE\";\n final static public String PREF_STICK_TYPE = \"PREF_STICK_TYPE\";\n final static public String PREF_NUMBUTTONS = \"PREF_NUMBUTTONS\";\n final static public String PREF_CONTROLLER_AUTODETECT = \"PREF_CONTROLLER_AUTODETECT\";\n final static public String PREF_ANALOG_DZ = \"PREF_ANALOG_DZ\";\n final static public String PREF_GAMEPAD_DZ = \"PREF_GAMEPAD_DZ\";\n final static public String PREF_VIBRATE = \"PREF_VIBRATE\";\n final static public String PREF_MOUSE = \"PREF_MOUSE\";\n\tfinal static public String PREF_TOUCH_MOUSE = \"PREF_TOUCH_MOUSE\";\n\tfinal static public String PREF_TOUCH_GAME_MOUSE = \"PREF_TOUCH_GAME_MOUSE\";\n\tfinal static public String PREF_TOUCH_GAME_MOUSE_FORCE = \"PREF_TOUCH_GAME_MOUSE_FORCE\";\n\tfinal static public String PREF_KEYBOARD = \"PREF_KEYBOARD\";\n\tfinal static public String PREF_KEYBOARD_HIDE_CONTROLLER = \"PREF_KEYBOARD_HIDE_CONTROLLER\";\n\tfinal static public String PREF_VIRTUAL_KEYBOARD = \"PREF_VIRTUAL_KEYBOARD\";\n final static public String PREF_INPUT_FAKE_ID = \"PREF_INPUT_FAKE_ID\";\n\n final static public String PREF_TILT_SENSOR = \"PREF_TILT_SENSOR\";\n final static public String PREF_TILT_DZ = \"PREF_TILT_DZ\";\n final static public String PREF_TILT_SENSITIVITY = \"PREF_TILT_SENSITIVITY\";\n final static public String PREF_TILT_NEUTRAL = \"PREF_TILT_NEUTRAL\";\n final static public String PREF_TILT_ANALOG = \"PREF_TILT_ANALOG\";\n final static public String PREF_TILT_TOUCH = \"PREF_TILT_TOUCH\";\n final static public String PREF_TILT_SWAP_YZ = \"PREF_TILT_SWAP_YZ\";\n final static public String PREF_TILT_INVERT_X = \"PREF_TILT_INVERT_X\";\n\n final static public String PREF_HIDE_STICK = \"PREF_HIDE_STICK\";\n final static public String PREF_BUTTONS_SIZE = \"PREF_BUTTONS_SIZE\";\n final static public String PREF_STICK_SIZE = \"PREF_STICK_SIZE\";\n final static public String PREF_MAIN_THREAD_PRIORITY = \"PREF_MAIN_THREAD_PRIORITY\";\n final static public String PREF_SOUND_ENGINE = \"PREF_SOUND_ENGINE\";\n\n final static public String PREF_DOUBLE_BUFFER = \"PREF_DOUBLE_BUFFER\";\n\n final static public String PREF_FORCE_ALTGLPATH = \"PREF_FORCE_ALTGLPATH\";\n final static public String PREF_PXASP1 = \"PREF_PXASP1\";\n\tfinal static public String PREF_NODEADZONEANDSAT = \"PREF_NODEADZONEANDSAT\";\n final static public String SAVESATES_IN_ROM_PATH = \"SAVESATES_IN_ROM_PATH\";\n\n final static public String PREF_BEAM2X = \"PREF_BEAM2X\";\n final static public String PREF_FLICKER = \"PREF_FLICKER\";\n\n final static public String PREF_GLOBAL_NAVBAR_MODE = \"PREF_GLOBAL_NAVBAR_MODE\";\n final static public String PREF_GLOBAL_SCALE_BEYOND = \"PREF_GLOBAL_SCALE_BEYOND\";\n final static public String PREF_GLOBAL_OVERSCAN = \"PREF_GLOBAL_OVERSCAN\";\n final static public String PREF_GLOBAL_USE_NOTCH = \"PREF_GLOBAL_USE_NOTCH\";\n\tfinal static public String PREF_GLOBAL_SIMPLE_UI = \"PREF_GLOBAL_SIMPLE_UI\";\n\tfinal static public String PREF_OVERLAY = \"PREF_OVERLAY\";\n\tfinal static public String PREF_ORIENTATION = \"PREF_ORIENTATION\";\n\n final static public String PREF_MAME_DEFAULTS = \"PREF_MAME_DEFAULTS\";\n\tfinal static public String PREF_LIGHTGUN_LONGPRESS = \"PREF_LIGHTGUN_LONGPRESS\";\n final static public String PREF_BOTTOM_RELOAD = \"PREF_BOTTOM_RELOAD\";\n\n final static public int LOW = 1;\n final static public int NORMAL = 2;\n final static public int HIGHT = 2;\n\n final static public int PREF_RENDER_GL = 1;\n\n final static public int PREF_DIGITAL_DPAD = 1;\n final static public int PREF_DIGITAL_STICK = 2;\n final static public int PREF_ANALOG_STICK = 3;\n\n final static public int PREF_INPUT_NO_DETECT_CONTROLLER = 1;\n final static public int PREF_INPUT_DETECT_CONTROLLER = 2;\n\n\n final public static int PREF_ORIGINAL = 3;\n final public static int PREF_15X = 4;\n final public static int PREF_20X = 5;\n final public static int PREF_SCALE = 1;\n final public static int PREF_STRETCH = 2;\n final public static int PREF_SCALE_INTEGER = 14;\n final public static int PREF_SCALE_INTEGER_BEYOND = 15;\n\n final public static String PREF_OVERLAY_NONE = \"none\";\n\n final public static int PREF_AUTOMAP_THUMBS_DISABLED_L2R2_AS_L1R2 = 1;\n final public static int PREF_AUTOMAP_THUMBS_AS_COINSTART_L2R2_AS_L1R2 = 2;\n final public static int PREF_AUTOMAP_THUMBS_AS_COINSTART_L2R2_DISABLED = 3;\n final public static int PREF_AUTOMAP_THUMBS_DISABLED_L2R2_AS_COINSTART = 4;\n final public static int PREF_AUTOMAP_L1R1_AS_COINSTART_L2R2_AS_L1R1 = 5;\n final public static int PREF_AUTOMAP_L1R1_AS_EXITMENU_L2R2_AS_L1R1 = 6;\n\n final public static int PREF_SNDENG_AUDIOTRACK = 1;\n final public static int PREF_SNDENG_AUDIOTRACK_HIGH = 2;\n final public static int PREF_SNDENG_OPENSL = 3;\n final public static int PREF_SNDENG_OPENSL_LOW = 4;\n\n final public static int PREF_NAVBAR_VISIBLE = 0;\n final public static int PREF_NAVBAR_DIMM_OR_HIDE = 1;\n final public static int PREF_NAVBAR_IMMERSIVE = 2;\n\n protected MAME4droid mm = null;\n\n public PrefsHelper(MAME4droid value) {\n mm = value;\n }\n\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,\n String key) {\n }\n\n public void resume() {\n Context context = mm.getApplicationContext();\n SharedPreferences prefs =\n PreferenceManager.getDefaultSharedPreferences(context);\n prefs.registerOnSharedPreferenceChangeListener(this);\n }\n\n public void pause() {\n\n Context context = mm.getApplicationContext();\n SharedPreferences prefs =\n PreferenceManager.getDefaultSharedPreferences(context);\n prefs.unregisterOnSharedPreferenceChangeListener(this);\n }\n\n public SharedPreferences getSharedPreferences() {\n Context context = mm.getApplicationContext();\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n public int getPortraitScaleMode() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_PORTRAIT_SCALING_MODE, \"1\")).intValue();\n }\n\n public int getLandscapeScaleMode() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_LANDSCAPE_SCALING_MODE, \"1\")).intValue();\n }\n\n\tpublic String getOverlayFilterValue() {\n\t\treturn getSharedPreferences().getString(PREF_OVERLAY, PrefsHelper.PREF_OVERLAY_NONE);\n\t}\n\n\tpublic int getOrientationMode() {\n\t\treturn Integer.valueOf(getSharedPreferences().getString(PREF_ORIENTATION, \"0\")).intValue();\n\t}\n\n\tpublic boolean isPortraitTouchController() {\n return getSharedPreferences().getBoolean(PREF_PORTRAIT_TOUCH_CONTROLLER, true);\n }\n\n public boolean isPortraitBitmapFiltering() {\n return getSharedPreferences().getBoolean(PREF_PORTRAIT_BITMAP_FILTERING, true);\n }\n\n public boolean isPortraitFullscreen() {\n return getSharedPreferences().getBoolean(PREF_PORTRAIT_FULLSCREEN, false);\n }\n\n public boolean isLandscapeTouchController() {\n return getSharedPreferences().getBoolean(PREF_LANDSCAPE_TOUCH_CONTROLLER, true);\n }\n\n public boolean isLandscapeBitmapFiltering() {\n return getSharedPreferences().getBoolean(PREF_LANDSCAPE_BITMAP_FILTERING, true);\n }\n\n public String getDefinedKeys() {\n\n SharedPreferences p = getSharedPreferences();\n\n StringBuffer defaultKeys = new StringBuffer();\n\n for (int i = 0; i < GameController.defaultKeyMapping.length; i++)\n defaultKeys.append(GameController.defaultKeyMapping[i] + \":\");\n\n return p.getString(PREF_DEFINED_KEYS, defaultKeys.toString());\n\n }\n\n public int getVideoRenderMode() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_GLOBAL_VIDEO_RENDER_MODE, \"1\")).intValue();\n }\n\n public int getEmulatedResolution() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_EMU_RESOLUTION, \"1\")).intValue();\n }\n\n\tpublic int getOSDResolution() {\n\t\treturn Integer.valueOf(getSharedPreferences().getString(PREF_EMU_RESOLUTION_OSD, \"0\")).intValue();\n\t}\n\n public boolean isWarnOnExit() {\n return getSharedPreferences().getBoolean(PREF_GLOBAL_WARN_ON_EXIT, true);\n }\n\n public int getSoundValue() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_EMU_SOUND, \"44100\")).intValue();\n }\n\n public boolean isFPSShowed() {\n return getSharedPreferences().getBoolean(PREF_EMU_SHOW_FPS, false);\n }\n\n\tpublic boolean isZoomToWindow() {\n\t\treturn getSharedPreferences().getBoolean(PREF_ZOOM_TO_WINDOW, true);\n\t}\n\n\tpublic boolean isAutoFrameSkip() {\n\t\treturn getSharedPreferences().getBoolean(PREF_EMU_AUTO_FRAMESKIP, false);\n\t}\n\n\tpublic boolean isCheats() {\n\t\treturn getSharedPreferences().getBoolean(CHEATS, false);\n\t}\n\n\tpublic boolean isSkipGameInfo() {\n\t\treturn getSharedPreferences().getBoolean(SKIP_GAMEINFO, false);\n\t}\n\n\tpublic boolean isDisabledDRC() {\n\t\treturn getSharedPreferences().getBoolean(PREF_EMU_DISABLE_DRC, true);\n\t}\n\n\tpublic boolean isDRCUseC() {\n\t\treturn getSharedPreferences().getBoolean(PREF_EMU_DRC_USR_C, true);\n\t}\n\n\tpublic boolean isOneProcessor() {\n\t\treturn getSharedPreferences().getBoolean(PREF_EMU_ONE_PROCESSOR, true);\n\t}\n\n public boolean isAutosave() {\n return getSharedPreferences().getBoolean(PREF_GLOBAL_AUTOSAVE, false);\n }\n\n public boolean isDebugEnabled() {\n return getSharedPreferences().getBoolean(PREF_GLOBAL_DEBUG, false);\n }\n\n public boolean isHideStick() {\n return getSharedPreferences().getBoolean(PREF_HIDE_STICK, false);\n }\n\n public boolean isDisabledRightStick() {\n return getSharedPreferences().getBoolean(PREF_DISABLE_RIGHT_STICK, false);\n }\n\n public boolean isAnimatedInput() {\n return getSharedPreferences().getBoolean(PREF_ANIMATED_INPUT, true);\n }\n\n public boolean isTouchDZ() {\n return getSharedPreferences().getBoolean(PREF_TOUCH_DZ, true);\n }\n\n public int getControllerType() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_CONTROLLER_TYPE, \"1\")).intValue();\n }\n\n public boolean isTouchLightgun() {\n\n\t\tif(!Emulator.isInGame())\n\t\t\treturn false;\n\n boolean enabled = getSharedPreferences().getBoolean(PREF_TOUCH_LIGHTGUN, true);\n\n if (enabled &&\n\n\t\t\t(Emulator.getValue(Emulator.IS_LIGHTGUN) == 1 || getSharedPreferences().getBoolean(PREF_TOUCH_LIGHTGUN_FORCE, false))\n\n\t\t\t&& !this.isTiltSensorEnabled() && !mm.getInputHandler().getMouse().isEnabled())\n return true;\n\n return false;\n }\n\n public boolean isMouseEnabled() {\n return getSharedPreferences().getBoolean(PREF_MOUSE, true);\n }\n\n\tpublic boolean isTouchMouseEnabled() {\n\t\tif(mm.getInputHandler().getMouse().isEnabled())\n\t\t\treturn false;\n\n\t\treturn getSharedPreferences().getBoolean(PREF_TOUCH_MOUSE, true);\n\t}\n\n\tpublic boolean isTouchGameMouse() {\n\n\t\tif(!isTouchMouseEnabled())\n\t\t\treturn false;\n\n\t\tif(!getSharedPreferences().getBoolean(PREF_TOUCH_GAME_MOUSE, true))\n\t\t\treturn false;\n\n\t\tif(!Emulator.isInGame() && Emulator.isInMenu())\n\t\t\treturn false;\n\n\t\tif(mm.getInputHandler().getTiltSensor().isEnabled())\n\t\t\treturn false;\n\n\t\tif(mm.getInputHandler().getGameController().isEnabled())\n\t\t\treturn false;\n\n\t\tif(mm.getInputHandler().getMouse().isEnabled())\n\t\t\treturn false;\n\n\t\tif(isTouchLightgun())\n\t\t\treturn false;\n\n\t\treturn Emulator.getValue(Emulator.IS_MOUSE)==1 || getSharedPreferences().getBoolean(PREF_TOUCH_GAME_MOUSE_FORCE, false);\n\n\t}\n\n\tpublic boolean isKeyboardEnabled() {\n\t\treturn getSharedPreferences().getBoolean(PREF_KEYBOARD, true);\n\t}\n\n\tpublic boolean isKeyboardHideController() {\n\t\treturn getSharedPreferences().getBoolean(PREF_KEYBOARD_HIDE_CONTROLLER, true);\n\t}\n\n\tpublic boolean isVirtualKeyboardEnabled() {\n\t\treturn getSharedPreferences().getBoolean(PREF_VIRTUAL_KEYBOARD, true);\n\t}\n\n public int getStickWays() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_STICK_TYPE, \"-1\")).intValue();\n }\n\n public int getNumButtons() {\n int n = Integer.valueOf(getSharedPreferences().getString(PREF_NUMBUTTONS, \"-1\")).intValue();\n if (n == 33) n = 3;\n return n;\n }\n\n public boolean isBplusX() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_NUMBUTTONS, \"-1\")).intValue() == 33;\n }\n\n public boolean isContollerAutodetect() {\n\t\treturn getSharedPreferences().getBoolean(PREF_CONTROLLER_AUTODETECT, true);\n }\n\n public int getAnalogDZ() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_ANALOG_DZ, \"2\")).intValue();\n }\n\n public int getGamepadDZ() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_GAMEPAD_DZ, \"3\")).intValue();\n }\n\n public boolean isVibrate() {\n return getSharedPreferences().getBoolean(PREF_VIBRATE, false);\n }\n\n public String getROMsDIR() {\n return getSharedPreferences().getString(PREF_ROMsDIR, null);\n }\n\n public void setROMsDIR(String value) {\n //PreferenceManager.getDefaultSharedPreferences(this);\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(PREF_ROMsDIR, value);\n editor.commit();\n }\n\n public String getSAF_Uri() {\n return getSharedPreferences().getString(PREF_SAF_URI, null);\n }\n\n public void setSAF_Uri(String value) {\n //PreferenceManager.getDefaultSharedPreferences(this);\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(PREF_SAF_URI, value);\n editor.commit();\n }\n\n public String getInstallationDIR() {\n return getSharedPreferences().getString(PREF_INSTALLATION_DIR, null);\n }\n\n public void setInstallationDIR(String value) {\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(PREF_INSTALLATION_DIR, value);\n editor.commit();\n }\n\n public String getOldInstallationDIR() {\n return getSharedPreferences().getString(PREF_OLD_INSTALLATION_DIR, null);\n }\n\n public void setOldInstallationDIR(String value) {\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(PREF_OLD_INSTALLATION_DIR, value);\n editor.commit();\n }\n\n\n public String getDefinedControlLayoutLand() {\n return getSharedPreferences().getString(PREF_DEFINED_CONTROL_LAYOUT, null);\n }\n\n public void setDefinedControlLayoutLand(String value) {\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(PREF_DEFINED_CONTROL_LAYOUT, value);\n editor.commit();\n }\n\n public String getDefinedControlLayoutPortrait() {\n return getSharedPreferences().getString(PREF_DEFINED_CONTROL_LAYOUT_P, null);\n }\n\n public void setDefinedControlLayoutPortrait(String value) {\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(PREF_DEFINED_CONTROL_LAYOUT_P, value);\n editor.commit();\n }\n\n public boolean isTiltSensorEnabled() {\n\n\t\tif(mm.getInputHandler().getGameController().isEnabled())\n\t\t\treturn false;\n\n\t\tif(mm.getInputHandler().getMouse().isEnabled())\n\t\t\treturn false;\n\n return getSharedPreferences().getBoolean(PREF_TILT_SENSOR, false);\n }\n\n public int getTiltSensitivity() {\n return getSharedPreferences().getInt(PREF_TILT_SENSITIVITY, 6);\n }\n\n public int getTiltVerticalNeutralPos() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_TILT_NEUTRAL, \"5\")).intValue();\n }\n\n public int getTiltDZ() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_TILT_DZ, \"3\")).intValue();\n }\n\n public boolean isTiltAnalog() {\n return getSharedPreferences().getBoolean(PREF_TILT_ANALOG, true);\n }\n\n public boolean isTiltTouch() {\n return getSharedPreferences().getBoolean(PREF_TILT_TOUCH, false);\n }\n\n public boolean isTiltSwappedYZ() {\n return getSharedPreferences().getBoolean(PREF_TILT_SWAP_YZ, false);\n }\n\n public boolean isTiltInvertedX() {\n return getSharedPreferences().getBoolean(PREF_TILT_INVERT_X, false);\n }\n\n public int getButtonsSize() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_BUTTONS_SIZE, \"3\")).intValue();\n }\n\n public int getStickSize() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_STICK_SIZE, \"3\")).intValue();\n }\n\n public int getMainThreadPriority() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_MAIN_THREAD_PRIORITY, \"2\")).intValue();\n }\n\n public int getSoundEngine() {\n return Integer.valueOf(getSharedPreferences().getString(PREF_SOUND_ENGINE, \"1\")).intValue();\n }\n\n public boolean isDoubleBuffer() {\n return getSharedPreferences().getBoolean(PREF_DOUBLE_BUFFER, true);\n }\n\n public boolean isAltGLPath() {\n return getSharedPreferences().getBoolean(PREF_FORCE_ALTGLPATH, false);\n }\n\n public boolean areSavesInRomPath() {\n return getSharedPreferences().getBoolean(SAVESATES_IN_ROM_PATH, false);\n }\n\n public boolean isPlayerXasPlayer1() {\n return getSharedPreferences().getBoolean(PREF_PXASP1, false);\n }\n\n\tpublic boolean isOverrideDZandSAT() {\n\t\treturn getSharedPreferences().getBoolean(PREF_NODEADZONEANDSAT, true);\n\t}\n\n\tpublic boolean isUsedMAMEini() {\n\t\treturn getSharedPreferences().getBoolean(PREF_MAMEINI, false);\n\t}\n\n public boolean isVectorBeam2x() {\n return getSharedPreferences().getBoolean(PREF_BEAM2X, true);\n }\n\n public boolean isVectorFlicker() {\n return getSharedPreferences().getBoolean(PREF_FLICKER, false);\n }\n\n\t/*public int getEffectOverlayIntensity(){\n\t\treturn Integer.valueOf(getSharedPreferences().getString(PREF_OVERLAY_INTENSITY,\"3\")).intValue();\n\t}*/\n\n public int getNavBarMode() {\n\n if (getSharedPreferences().getString(PREF_GLOBAL_NAVBAR_MODE, \"\").equals(\"\")) {\n String value = PREF_NAVBAR_IMMERSIVE + \"\";\n SharedPreferences.Editor edit = getSharedPreferences().edit();\n edit.putString(PREF_GLOBAL_NAVBAR_MODE, value);\n edit.commit();\n }\n\n return Integer.valueOf(getSharedPreferences().getString(PREF_GLOBAL_NAVBAR_MODE, \"1\")).intValue();\n }\n\n public boolean isDefaultData() {\n\n boolean v = getSharedPreferences().getBoolean(PrefsHelper.PREF_MAME_DEFAULTS, false);\n\n if (v) {\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putBoolean(PrefsHelper.PREF_MAME_DEFAULTS, false);\n editor.commit();\n }\n\n return v;\n }\n\n public boolean isScaleBeyondBoundaries() {\n return getSharedPreferences().getBoolean(PREF_GLOBAL_SCALE_BEYOND, true);\n }\n\n public boolean isOverscan() {\n return getSharedPreferences().getBoolean(\"PREF_GLOBAL_OVERSCAN\", false);\n }\n\n public boolean isNotchUsed() {\n return getSharedPreferences().getBoolean(PREF_GLOBAL_USE_NOTCH, false);\n }\n\n\tpublic boolean isSimpleUI() {\n\t\treturn getSharedPreferences().getBoolean(PREF_GLOBAL_SIMPLE_UI, false);\n\t}\n\n public boolean isBottomReload() {\n return getSharedPreferences().getBoolean(\"PREF_BOTTOM_RELOAD\", true);\n }\n\n\tpublic boolean isLightgunLongPress() {\n\t\treturn getSharedPreferences().getBoolean(\"PREF_LIGHTGUN_LONGPRESS\", true);\n\t}\n\n public boolean isFakeID() {\n return getSharedPreferences().getBoolean(PREF_INPUT_FAKE_ID, false);\n }\n}\n\nandroid-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java\npublic class DialogHelper {\n\n\tpublic static int savedDialog = DialogHelper.DIALOG_NONE;\n\n\tpublic final static int DIALOG_NONE = -1;\n\tpublic final static int DIALOG_EXIT = 1;\n\tpublic final static int DIALOG_ERROR_WRITING = 2;\n\tpublic final static int DIALOG_INFO = 3;\n\tpublic final static int DIALOG_OPTIONS = 5;\n\tpublic final static int DIALOG_FULLSCREEN = 7;\n\tpublic final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10;\n\tpublic final static int DIALOG_EMU_RESTART = 11;\n\tpublic final static int DIALOG_NO_PERMISSIONS = 12;\n\tpublic final static int DIALOG_ROMs = 13;\n\n\tprotected MAME4droid mm = null;\n\n\tstatic protected String errorMsg;\n\tstatic protected String infoMsg;\n\n\tpublic void setErrorMsg(String errorMsg) {\n\t\tDialogHelper.errorMsg = errorMsg;\n\t}\n\n\tpublic void setInfoMsg(String infoMsg) {\n\t\tDialogHelper.infoMsg = infoMsg;\n\t}\n\n\tpublic DialogHelper(MAME4droid value) {\n\t\tmm = value;\n\t}\n\n\tpublic Dialog createDialog(int id) {\n\n\t\tDialog dialog;\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(mm);\n\t\tswitch (id) {\n\t\t\tcase DIALOG_FINISH_CUSTOM_LAYOUT:\n\n\t\t\t\tbuilder.setMessage(\"Do you want to save changes?\")\n\t\t\t\t\t.setCancelable(false)\n\t\t\t\t\t.setPositiveButton(\"Yes\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);\n\t\t\t\t\t\t\tControlCustomizer.setEnabled(false);\n\t\t\t\t\t\t\tmm.getInputHandler().getControlCustomizer().saveDefinedControlLayout();\n\t\t\t\t\t\t\tmm.getEmuView().setVisibility(View.VISIBLE);\n\t\t\t\t\t\t\tmm.getEmuView().requestFocus();\n\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\tmm.getInputView().invalidate();\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.setNegativeButton(\"No\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);\n\t\t\t\t\t\t\tControlCustomizer.setEnabled(false);\n\t\t\t\t\t\t\tmm.getInputHandler().getControlCustomizer().discardDefinedControlLayout();\n\t\t\t\t\t\t\tmm.getEmuView().setVisibility(View.VISIBLE);\n\t\t\t\t\t\t\tmm.getEmuView().requestFocus();\n\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\tmm.getInputView().invalidate();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\n\t\t\tcase DIALOG_ROMs:\n\n\t\t\t\tString message = \"\";\n\n\t\t\t\tmessage += \"Where do you have stored or want to store your ROM files?\\n\\n\" +\n\t\t\t\t\t\"By default, an empty internal folder will be used (but you should manually copy your ROMs files there using a PC). You can also select a folder with ROMs files from your external storage which will \"\n\t\t\t\t\t+ \"need to be authorized in the next step so MAME4droid can read the ROMS from it.\\n\\n\" +\n\t\t\t\t\t\"Also, if you select an external storage folder, your ROMs files will not be deleted when the app is uninstalled and you can use an Android file manager to move your ROMs there without needing a PC.\";\n\n\t\t\t\tbuilder.setMessage(message)\n\t\t\t\t\t.setCancelable(false)\n\t\t\t\t\t.setPositiveButton(\"Internal\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_ROMs);\n\t\t\t\t\t\t\tif (mm.getMainHelper().isAndroidTV())\n\t\t\t\t\t\t\t\tmm.getMainHelper().setInstallationDirType(MainHelper.INSTALLATION_DIR_MEDIA_FOLDER);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tmm.getMainHelper().setInstallationDirType(MainHelper.INSTALLATION_DIR_FILES_DIR);\n\t\t\t\t\t\t\tmm.getPrefsHelper().setROMsDIR(\"\");\n\t\t\t\t\t\t\tmm.getPrefsHelper().setSAF_Uri(null);\n\n\t\t\t\t\t\t\tThread t = new Thread(new Runnable() { public void run() {\n\t\t\t\t\t\t\t\tmm.runMAME4droid();\n\t\t\t\t\t\t\t}});\n\t\t\t\t\t\t\tt.start();\n\n\t\t\t\t\t\t\t//mm.runMAME4droid();\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.setNegativeButton(\"External Storage\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_ROMs);\n\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tIntent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);\n\t\t\t\t\t\t\t\tmm.startActivityForResult(intent, MainHelper.REQUEST_CODE_OPEN_DIRECTORY);\n\t\t\t\t\t\t\t\t//throw new ActivityNotFoundException(\"TEST\");\n\t\t\t\t\t\t\t} catch (ActivityNotFoundException e) {\n\n\t\t\t\t\t\t\t\tString msg = \"Your device doesn't have the native android file manager needed to authorize external storage reading.\";\n\t\t\t\t\t\t\t\tif (mm.getMainHelper().isAndroidTV())\n\t\t\t\t\t\t\t\t\tmsg += \"\\n\\nSome Android TV devices don't include the OS document picker which is needed to grant folder permissions for the apps on Android 11+. As an alternative, select default which use the App Media Folder which is supported on all devices and is created at Android/media/[app package name]. Move any emulator files into that folder with a file manager so the app can access them without any special permissions.\";\n\n\t\t\t\t\t\t\t\tmm.getDialogHelper().showMessage(msg,\n\t\t\t\t\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\t\t\t\t\tandroid.os.Process.killProcess(android.os.Process.myPid());\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\t\t\tcase DIALOG_EXIT:\n\n\t\t\t\tbuilder.setMessage(\"Are you sure you want to exit from app?\")\n\t\t\t\t\t.setCancelable(false)\n\t\t\t\t\t.setPositiveButton(\"Yes\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\t//System.exit(0);\n\t\t\t\t\t\t\tmm.finishAndRemoveTask();\n\t\t\t\t\t\t\tandroid.os.Process.killProcess(android.os.Process.myPid());\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.setNegativeButton(\"No\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_EXIT);\n\t\t\t\t\t\t\t//dialog.cancel();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\t\t\tcase DIALOG_ERROR_WRITING:\n\t\t\t\tbuilder.setMessage(\"Error\")\n\t\t\t\t\t.setCancelable(false)\n\t\t\t\t\t.setPositiveButton(\"OK\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\t//System.exit(0);\n\t\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_ERROR_WRITING);\n\t\t\t\t\t\t\tmm.getMainHelper().restartApp();\n\t\t\t\t\t\t\t//mm.showDialog(DialogHelper.DIALOG_LOAD_FILE_EXPLORER);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\t\t\tcase DIALOG_INFO:\n\t\t\t\tbuilder.setMessage(\"Info\")\n\t\t\t\t\t.setCancelable(false)\n\t\t\t\t\t.setPositiveButton(\"OK\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_INFO);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\t\t\tcase DIALOG_OPTIONS:\n\t\t\tcase DIALOG_FULLSCREEN:\n\t\t\t\tCharSequence[] items1 = {\"Load State\", \"Save State\", \"Help\", \"Settings\", \"Keyboard\"};\n\t\t\t\tCharSequence[] items2 = {\"Help\", \"Settings\", \"Keyboard\"};\n\t\t\t\tCharSequence[] items3 = {\"Exit\", \"Load State\", \"Save State\", \"Help\", \"Settings\", \"Keyboard\"};\n\t\t\t\tCharSequence[] items4 = {\"Exit\", \"Help\", \"Settings\", \"Keyboard\"};\n\n\t\t\t\tboolean saveload = Emulator.isInGameButNotInMenu() && Emulator.getValue(Emulator.PAUSE)!=1;\n\n\t\t\t\tfinal int a = id == DIALOG_FULLSCREEN ? 0 : 1;\n\t\t\t\tfinal int b = saveload ? 0 : 2;\n\n\t\t\t\tif (a == 1)\n\t\t\t\t\tbuilder.setTitle(\"Choose an option from the menu.\");\n\n\t\t\t\tCharSequence[] items = saveload ? (id == DIALOG_OPTIONS ? items1 : items3) : (id == DIALOG_OPTIONS ? items2 : items4);\n\n\t\t\t\tboolean notKeyboard = !mm.getPrefsHelper().isVirtualKeyboardEnabled() || mm.getInputHandler().getKeyboard().isKeyboardConnected() || mm.getMainHelper().isAndroidTV();\n\n\t\t\t\tif(notKeyboard)\n\t\t\t\t\titems = Arrays.copyOf(items, items.length-1);\n\n\t\t\t\tbuilder.setCancelable(true);\n\t\t\t\tbuilder.setItems(items, new DialogInterface.OnClickListener() {\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int item) {\n\n\t\t\t\t\t\tif (item == 0 && a == 0) {\n\n\t\t\t\t\t\t\tmm.showDialog(DialogHelper.DIALOG_EXIT);\n\n\t\t\t\t\t\t\t//if (Emulator.isInMenu()) {\n\t\t\t\t\t\t\t /*\n\t\t\t\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 1);\n\t\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tThread.sleep(PRESS_WAIT);\n\t\t\t\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 0);\n\t\t\t\t\t\t\t\t*/\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t} else if (!Emulator.isInGame())\n\t\t\t\t\t\t\t\tmm.showDialog(DialogHelper.DIALOG_EXIT);\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 1);\n\t\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tThread.sleep(PRESS_WAIT);\n\t\t\t\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tEmulator.setValue(Emulator.EXIT_GAME, 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t} else if (item == 1 - a && b == 0) {\n\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\tEmulator.setValue(Emulator.LOADSTATE, 1);\n\t\t\t\t\t\t\tEmulator.setSaveorload(true);\n\t\t\t\t\t\t\t//Emulator.resume();\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tThread.sleep(PRESS_WAIT);\n\t\t\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tEmulator.setValue(Emulator.LOADSTATE, 0);\n\t\t\t\t\t\t} else if (item == 2 - a && b == 0) {\n\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t\tEmulator.setValue(Emulator.SAVESTATE, 1);\n\t\t\t\t\t\t\tEmulator.setSaveorload(true);\n\t\t\t\t\t\t\t//Emulator.resume();\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tThread.sleep(PRESS_WAIT);\n\t\t\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tEmulator.setValue(Emulator.SAVESTATE, 0);\n\t\t\t\t\t\t} else if (item == 3 - a - b) {\n\t\t\t\t\t\t\tmm.getMainHelper().showHelp();\n\t\t\t\t\t\t} else if (item == 4 - a - b) {\n\t\t\t\t\t\t\tmm.getMainHelper().showSettings();\n\t\t\t\t\t\t} else if (item == 5 - a - b) {\n\t\t\t\t\t\t\t((IEmuView) mm.getEmuView()).showSoftKeyboard();\n\t\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tEmulator.setInOptions(false);\n\n\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\tmm.removeDialog(DIALOG_OPTIONS);\n\t\t\t\t\t\tmm.removeDialog(DIALOG_FULLSCREEN);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onCancel(DialogInterface dialog) {\n\n\t\t\t\t\t\tEmulator.resume();\n\t\t\t\t\t\tEmulator.setInOptions(false);\n\n\t\t\t\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t\t\t\t\tif (a != 0)\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_OPTIONS);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmm.removeDialog(DIALOG_FULLSCREEN);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\t\t\tcase DIALOG_EMU_RESTART:\n\t\t\t\tbuilder.setTitle(\"Restart needed!\")\n\t\t\t\t\t.setMessage(\"MAME4droid needs to restart for the changes to take effect.\")\n\t\t\t\t\t.setCancelable(false)\n\t\t\t\t\t.setPositiveButton(\"Dismiss\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tmm.getMainHelper().restartApp();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\t\t\tcase DIALOG_NO_PERMISSIONS:\n\t\t\t\tbuilder.setTitle(\"No permissions!\")\n\t\t\t\t\t.setMessage(\"You don't have permission to read from external storage. Please, allow storage permission on Android applications settings.\")\n\t\t\t\t\t.setCancelable(false)\n\t\t\t\t\t.setPositiveButton(\"Dismiss\", new DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\t\t\tandroid.os.Process.killProcess(android.os.Process.myPid());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\tdialog = builder.create();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tdialog = null;\n\t\t}\n\t /*\n\t if(dialog!=null)\n\t {\n\t \tdialog.setCanceledOnTouchOutside(false);\n\t }*/\n\t\treturn dialog;\n\n\t}\n\n\tpublic void prepareDialog(int id, Dialog dialog) {\n\n\t\tif (id == DIALOG_ERROR_WRITING) {\n\t\t\t((AlertDialog) dialog).setMessage(errorMsg);\n\t\t\tDialogHelper.savedDialog = DIALOG_ERROR_WRITING;\n\t\t} else if (id == DIALOG_INFO) {\n\t\t\t((AlertDialog) dialog).setMessage(infoMsg);\n\t\t\tEmulator.pause();\n\t\t\tDialogHelper.savedDialog = DIALOG_INFO;\n\t\t} else if (id == DIALOG_EXIT) {\n\t\t\tEmulator.pause();\n\t\t\tDialogHelper.savedDialog = DIALOG_EXIT;\n\t\t} else if (id == DIALOG_OPTIONS) {\n\t\t\tEmulator.pause();\n\t\t\tDialogHelper.savedDialog = DIALOG_OPTIONS;\n\t\t} else if (id == DIALOG_FULLSCREEN) {\n\t\t\tEmulator.pause();\n\t\t\tDialogHelper.savedDialog = DIALOG_FULLSCREEN;\n\t\t} else if (id == DIALOG_ROMs) {\n\t\t\tDialogHelper.savedDialog = DIALOG_ROMs;\n\t\t} else if (id == DIALOG_FINISH_CUSTOM_LAYOUT) {\n\t\t\tDialogHelper.savedDialog = DIALOG_FINISH_CUSTOM_LAYOUT;\n\t\t} else if (id == DIALOG_EMU_RESTART) {\n\t\t\tEmulator.pause();\n\t\t} else if (id == DIALOG_NO_PERMISSIONS) {\n\t\t\tDialogHelper.savedDialog = DIALOG_NO_PERMISSIONS;\n\t\t}\n\n\t}\n\n\tpublic void removeDialogs() {\n\t\tif (savedDialog == DIALOG_FINISH_CUSTOM_LAYOUT) {\n\t\t\tmm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT);\n\t\t\tDialogHelper.savedDialog = DIALOG_NONE;\n\t\t}\n\t}\n\n\tpublic void showMessage(String message, DialogInterface.OnClickListener okListener) {\n\t\tnew AlertDialog.Builder(mm)\n\t\t\t.setMessage(message)\n\t\t\t.setCancelable(false)\n\t\t\t.setPositiveButton(\"OK\", okListener)\n\t\t\t.create()\n\t\t\t.show();\n\t}\n\n}\n\nandroid-MAME4droid/app/src/main/java/com/seleuco/mame4droid/MAME4droid.java\npublic class MAME4droid extends Activity {\n\n protected View emuView = null;\n\n protected InputView inputView = null;\n\n protected MainHelper mainHelper = null;\n protected PrefsHelper prefsHelper = null;\n protected DialogHelper dialogHelper = null;\n protected SAFHelper safHelper = null;\n\n protected InputHandler inputHandler = null;\n\n public PrefsHelper getPrefsHelper() {\n return prefsHelper;\n }\n\n public MainHelper getMainHelper() {\n return mainHelper;\n }\n\n public DialogHelper getDialogHelper() {\n return dialogHelper;\n }\n\n public SAFHelper getSAFHelper() {\n return safHelper;\n }\n\n public View getEmuView() {\n return emuView;\n }\n\n public InputView getInputView() {\n return inputView;\n }\n\n public InputHandler getInputHandler() {\n return inputHandler;\n }\n\n /**\n * Called when the activity is first created.\n */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n //android.os.Debug.waitForDebugger();\n\n Log.d(\"EMULATOR\", \"onCreate \" + this);\n System.out.println(\"onCreate intent:\" + getIntent().getAction());\n\n overridePendingTransition(0, 0);\n getWindow().setWindowAnimations(0);\n\n prefsHelper = new PrefsHelper(this);\n\n dialogHelper = new DialogHelper(this);\n\n mainHelper = new MainHelper(this);\n\n safHelper = new SAFHelper(this);\n\n inputHandler = new InputHandler(this);\n\n mainHelper.detectDevice();\n\n inflateViews();\n\n Emulator.setMAME4droid(this);\n\n mainHelper.updateMAME4droid();\n\n\t\tString uri = getPrefsHelper().getSAF_Uri();\n\t\tif (uri != null) {\n\t\t\tsafHelper.setURI(uri);\n\t\t}\n\n initMame4droid();\n }\n\n protected void initMame4droid() {\n if (!Emulator.isEmulating()) {\n\n if (getPrefsHelper().getInstallationDIR()==null || prefsHelper.getROMsDIR() == null ) {\n if (DialogHelper.savedDialog == DialogHelper.DIALOG_NONE) {\n\t\t\t\t\t showDialog(DialogHelper.DIALOG_ROMs);\n\t\t\t\t}\n } else { //roms dir no es null es que previamente hemos puesto \"\" o un path especifico. Venimos del recreate y si ha cambiado el installation path hay que actuzalizarlo\n\n boolean res = getMainHelper().ensureInstallationDIR(mainHelper.getInstallationDIR());\n if (res == false) {\n this.getPrefsHelper().setInstallationDIR(this.getPrefsHelper().getOldInstallationDIR());//revert\n } else {\n runMAME4droid();//MAIN ENTRY POINT\n }\n }\n }\n }\n\n\n public void inflateViews() {\n\n\t\tif(getPrefsHelper().getOrientationMode()!=0) {\n\t\t\tint mode = getMainHelper().getScreenOrientation();\n\t\t\tthis.setRequestedOrientation(mode);\n\t\t}\n\n if (getPrefsHelper().isNotchUsed()) {\n getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;\n }\n inputHandler.unsetInputListeners();\n\n Emulator.setPortraitFull(getPrefsHelper().isPortraitFullscreen());\n\n boolean full = false;\n if (prefsHelper.isPortraitFullscreen() && mainHelper.getscrOrientation() == Configuration.ORIENTATION_PORTRAIT) {\n setContentView(R.layout.main_fullscreen);\n full = true;\n } else {\n setContentView(R.layout.main);\n }\n\n FrameLayout fl = (FrameLayout) this.findViewById(R.id.EmulatorFrame);\n\n Emulator.setVideoRenderMode(getPrefsHelper().getVideoRenderMode());\n\n if (prefsHelper.getVideoRenderMode() == PrefsHelper.PREF_RENDER_GL) {\n\n if (prefsHelper.getNavBarMode() != PrefsHelper.PREF_NAVBAR_VISIBLE)\n this.getLayoutInflater().inflate(R.layout.emuview_gl_ext, fl);\n else\n this.getLayoutInflater().inflate(R.layout.emuview_gl, fl);\n\n emuView = this.findViewById(R.id.EmulatorViewGL);\n }\n\n if (full && prefsHelper.isPortraitTouchController()) {\n FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) emuView.getLayoutParams();\n lp.gravity = Gravity.TOP | Gravity.CENTER;\n }\n\n inputView = (InputView) this.findViewById(R.id.InputView);\n\n ((IEmuView) emuView).setMAME4droid(this);\n\n inputView.setMAME4droid(this);\n\n View frame = this.findViewById(R.id.EmulatorFrame);\n frame.setOnTouchListener(inputHandler);\n\n\n inputHandler.setInputListeners();\n }\n\n public void runMAME4droid() {\n\n getMainHelper().copyFiles();\n getMainHelper().removeFiles();\n\n Emulator.emulate(mainHelper.getLibDir(), mainHelper.getInstallationDIR());\n }\n\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n\t\tLog.d(\"EMULATOR\", \"onConfigurationChanged \" + this);\n\n super.onConfigurationChanged(newConfig);\n\n overridePendingTransition(0, 0);\n\n inflateViews();\n\n getMainHelper().updateMAME4droid();\n\n overridePendingTransition(0, 0);\n }\n\n\n //ACTIVITY\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (mainHelper != null)\n mainHelper.activityResult(requestCode, resultCode, data);\n }\n\n //LIVE CYCLE\n @Override\n protected void onResume() {\n Log.d(\"EMULATOR\", \"onResume \" + this);\n super.onResume();\n\n if (prefsHelper != null)\n prefsHelper.resume();\n\n if (DialogHelper.savedDialog != -1)\n showDialog(DialogHelper.savedDialog);\n else if (!ControlCustomizer.isEnabled())\n Emulator.resume();\n\n if (inputHandler != null) {\n if (inputHandler.getTiltSensor() != null)\n inputHandler.getTiltSensor().enable();\n }\n\n //System.out.println(\"OnResume\");\n }\n\n @Override\n protected void onPause() {\n Log.d(\"EMULATOR\", \"onPause \" + this);\n super.onPause();\n if (prefsHelper != null)\n prefsHelper.pause();\n if (!ControlCustomizer.isEnabled())\n Emulator.pause();\n if (inputHandler != null) {\n if (inputHandler.getTiltSensor() != null)\n inputHandler.getTiltSensor().disable();\n }\n\n if (dialogHelper != null) {\n dialogHelper.removeDialogs();\n }\n\n //System.out.println(\"OnPause\");\n }\n\n @Override\n protected void onStart() {\n Log.d(\"EMULATOR\", \"onStart \" + this);\n super.onStart();\n try {\n GameController.resetAutodetected();\n } catch (Throwable e) {\n }\n ;\n //System.out.println(\"OnStart\");\n }\n\n @Override\n protected void onStop() {\n Log.d(\"EMULATOR\", \"onStop \" + this);\n super.onStop();\n //System.out.println(\"OnStop\");\n }\n\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n Log.d(\"EMULATOR\", \"onNewIntent \" + this);\n System.out.println(\"onNewIntent action:\" + intent.getAction());\n mainHelper.checkNewViewIntent(intent);\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n Log.d(\"EMULATOR\", \"onDestroy \" + this);\n\n View frame = this.findViewById(R.id.EmulatorFrame);\n if (frame != null)\n frame.setOnTouchListener(null);\n\n if (inputHandler != null) {\n inputHandler.unsetInputListeners();\n\n if (inputHandler.getTiltSensor() != null)\n inputHandler.getTiltSensor().disable();\n }\n\n if (emuView != null)\n ((IEmuView) emuView).setMAME4droid(null);\n\n /*\n if(inputView!=null)\n inputView.setMAME4droid(null);\n\n if(filterView!=null)\n filterView.setMAME4droid(null);\n\n prefsHelper = null;\n\n dialogHelper = null;\n\n mainHelper = null;\n\n inputHandler = null;\n\n inputView = null;\n\n emuView = null;\n\n filterView = null; */\n }\n\n\n //Dialog Stuff\n @Override\n protected Dialog onCreateDialog(int id) {\n\n if (dialogHelper != null) {\n Dialog d = dialogHelper.createDialog(id);\n if (d != null) return d;\n }\n return super.onCreateDialog(id);\n }\n\n @Override\n protected void onPrepareDialog(int id, Dialog dialog) {\n if (dialogHelper != null)\n dialogHelper.prepareDialog(id, dialog);\n }\n\n @Override\n public boolean dispatchGenericMotionEvent(MotionEvent event) {\n if (inputHandler != null)\n return inputHandler.genericMotion(event);\n return false;\n }\n\n\t@Override\n\tpublic void onPointerCaptureChanged(boolean hasCapture) {\n\t\tsuper.onPointerCaptureChanged(hasCapture);\n\t}\n\n\t@Override\n public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case 1:\n if (grantResults == null || grantResults.length == 0) {\n //this.showDialog(DialogHelper.DIALOG_NO_PERMISSIONS);\n System.out.println(\"***1\");\n } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n System.out.println(\"***2\");\n initMame4droid();\n } else {\n System.out.println(\"***3\");\n this.showDialog(DialogHelper.DIALOG_NO_PERMISSIONS);\n }\n break;\n default:\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n }\n }\n\n}", "answers": ["\t\t\t\tmm.showDialog(DialogHelper.DIALOG_OPTIONS);"], "length": 5745, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "50a2367d-3837-4e34-8cdf-bff4ab627328", "reasoning": "The code is handling the OPTION_VALUE case inside handleControllerKey. After detecting the option button release and confirming the emulator is not already in the options menu, it sets the in‑options flag to true. The next logical step is to actually display the options dialog, which elsewhere in the project is done via mm.showDialog with the DIALOG_OPTIONS constant.", "reasoning_model_answer": "mm.showDialog(DialogHelper.DIALOG_OPTIONS);", "assistant_with_reasoning": "\nThe code is handling the OPTION_VALUE case inside handleControllerKey. After detecting the option button release and confirming the emulator is not already in the options menu, it sets the in‑options flag to true. The next logical step is to actually display the options dialog, which elsewhere in the project is done via mm.showDialog with the DIALOG_OPTIONS constant.\n\nmm.showDialog(DialogHelper.DIALOG_OPTIONS);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.717, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36472, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "mm.showDialog(DialogHelper.DIALOG_OPTIONS);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.HashSet;\nimport java.util.Set;\nimport java.util.function.Function;\nimport edu.uky.cs.nil.sabre.Character;\nimport edu.uky.cs.nil.sabre.FiniteState;\nimport edu.uky.cs.nil.sabre.graph.StateGraph;\nimport edu.uky.cs.nil.sabre.hg.ActionNode;\nimport edu.uky.cs.nil.sabre.hg.CostSet;\nimport edu.uky.cs.nil.sabre.hg.EffectNode;\nimport edu.uky.cs.nil.sabre.hg.FluentNode;\nimport edu.uky.cs.nil.sabre.hg.HeuristicGraph;\nimport edu.uky.cs.nil.sabre.hg.MaxGraph;\nimport edu.uky.cs.nil.sabre.hg.PreconditionNode;\nimport edu.uky.cs.nil.sabre.logic.Effect;\nimport edu.uky.cs.nil.sabre.logic.False;\nimport edu.uky.cs.nil.sabre.logic.Precondition;\nimport edu.uky.cs.nil.sabre.logic.True;\nimport edu.uky.cs.nil.sabre.logic.Value;\nimport edu.uky.cs.nil.sabre.util.Worker;", "context": "src/edu/uky/cs/nil/sabre/comp/Reachable.java\npackage edu.uky.cs.nil.sabre.comp;\n\n\n\n/**\n * A {@link Function function} which maps some {@link\n * edu.uky.cs.nil.sabre.logic.Expression logical expressions} to simpler\n * expressions based on a leveled off {@link HeuristicGraph heuristic graph}.\n * A proposition is said to be reachable if it can ever be true and unreachable\n * if it can never be true.\n *

\n * This function initializes a heuristic graph to {@link CompiledProblem#start\n * a compiled problem's initial state} and then extends it until it has leveled\n * off, also accounting for beliefs during that process. A heuristic graph\n * provides a necessary but not sufficient way to detect which values a {@link\n * edu.uky.cs.nil.sabre.Fluent fluent} can have (that is, it cannot reliably\n * detect if a fluent can have a value, but it can reliably detect when a\n * fluent cannot have a value).\n *

\n * This function maps expressions in the following ways:\n *

    \n *
  • If the expression is a {@link CompiledFluent compiled fluent} and that\n * fluent can only have one possible value, this function returns that value.\n *
  • \n *
  • If the expression is {@link Precondition an atomic precondition}, and\n * that precondition cannot every possible be true, this function returns\n * {@link False#FALSE false}.
  • \n *
  • If the expression is {@link Effect an atomic effect}, and {@link\n * edu.uky.cs.nil.sabre.logic.Assignment#fluent the effect's fluent} is one\n * which can only have one possible value, this function returns {@link\n * True#TRUE true}.
  • \n *
\n * \n * @author Stephen G. Ware\n */\npublic class Reachable implements Function {\n\t\n\tprivate final HeuristicGraph graph;\n\t\n\t/**\n\t * Constructs a new reachable mapping.\n\t * \n\t * @param problem a compiled problem whose initial state will be used to\n\t * determine which propositions are reachable and unreachable\n\t * @param status a status to update while the compiler runs\n\t */\n\nsrc/edu/uky/cs/nil/sabre/graph/StateGraph.java\npublic class StateGraph implements Serializable {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * The set of all fluents tracked by the state nodes in this graph (with\n\t * all {@link Fluent#characters} removed). This set contains only\n\t * non-espitemic fluents; to check the value of an epistemic fluent at a\n\t * node, follow {@link EpistemicEdge epistemic edges} for the characters in\n\t * order from that node and check the value of the fluent minus all\n\t * characters in the final destination node.\n\t */\n\tpublic final ImmutableSet fluents;\n\t\n\t/** The set of all characters whose beliefs are represented in this graph */\n\tpublic final ImmutableSet characters;\n\t\n\t/**\n\t * The set of all ground triggers which can occur in the states represented\n\t * in this graph\n\t */\n\tpublic final EventSet triggers;\n\t\n\t/**\n\t * The first state represented by this graph (usually a problem's initial\n\t * state)\n\t */\n\tpublic final StateNode root;\n\t\n\t/**\n\t * A mapping of each {@link #fluents fluent} to its integer index in the set\n\t * of fluents\n\t */\n\tfinal HashMap index = new HashMap<>();\n\t\n\t/**\n\t * A hashtable containing every unique combination of fluents values used in\n\t * the nodes of this graph\n\t */\n\tfinal HashMap values = new HashMap<>();\n\t\n\t/**\n\t * A hashtable for storing all state nodes in the graph which uses a hash\n\t * function which can detect when nodes are duplicates\n\t */\n\tfinal HashMap states = new HashMap<>();\n\t\n\t/**\n\t * A reusable list of node pairs used when checking whether two nodes are\n\t * duplicates\n\t */\n\tfinal ArrayList pairs = new ArrayList<>();\n\t\n\t/**\n\t * Constructs a new state graph that tracks a given set of fluents,\n\t * characters, and triggers, and which starts with a given state.\n\t * \n\t * @param fluents the set of all fluents to be tracked by the state nodes\n\t * in this graph\n\t * @param characters the set of all characters whose beliefs are to be\n\t * represented in this graph\n\t * @param triggers the set of all ground triggers which can occur in the\n\t * states represented by this graph\n\t * @param root the first state to be represented by this graph (usually but\n\t * not necessarily the {@link edu.uky.cs.nil.sabre.InitialState initial\n\t * state} of a {@link edu.uky.cs.nil.sabre.Problem planning problem}\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic StateGraph(ImmutableSet fluents, ImmutableSet characters, EventSet triggers, FiniteState root) {\n\t\tthis.fluents = fluents.apply(object -> {\n\t\t\tFluent fluent = (Fluent) object;\n\t\t\twhile(fluent.characters.size() > 0)\n\t\t\t\tfluent = fluent.removeFirstCharacter();\n\t\t\treturn fluent;\n\t\t}).cast(Fluent.class);\n\t\tfor(int i=0; i) triggers;\n\t\tthis.root = new InitialNode(this, root, new HashMap<>()).resolve();\n\t}\n\t\n\t/**\n\t * Constructs a new state graph based on a compiled planning problem.\n\t * The fluent tracked in this graph will be {@link CompiledProblem#fluents\n\t * all fluent defined by the problem}. The characters tracked in this graph\n\t * will be {@link edu.uky.cs.nil.sabre.Problem#universe all characters\n\t * defined by the problem's universe}. The triggers tracked will be {@link\n\t * CompiledProblem#triggers all trigger defined by the problem}. The root\n\t * state will be the {@link CompiledProblem#initial problem's initial\n\t * state}.\n\t * \n\t * @param problem the compiled planning problem\n\t */\n\tpublic StateGraph(CompiledProblem problem) {\n\t\tthis(problem.fluents, problem.universe.characters, problem.triggers, problem.start);\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[\" + getClass().getSimpleName() + \": \" + states.size() + \" nodes]\";\n\t}\n\t\n\t/**\n\t * Interns a combination of values for the fluents tracked in this graph.\n\t * \n\t * @param values an array of values\n\t * @return the first such array of these values ever interned by this graph\n\t */\n\tValue[] resolve(Value[] values) {\n\t\tValuesKey key = new ValuesKey(values);\n\t\tvalues = this.values.get(key);\n\t\tif(values == null) {\n\t\t\tvalues = key.values;\n\t\t\tthis.values.put(key, values);\n\t\t}\n\t\treturn values;\n\t}\n\t\n\t/**\n\t * Interns a state node in the graph. If a state that is a duplicate of the\n\t * given node exists, the earlier existing node will be returned.\n\t * Otherwise, a new permanent state node will be constructed and added to\n\t * the graph. If this method is called with {@link a permanent StateNode\n\t * state node}, it will always return that node, but when this method is\n\t * called with a {@link TemporaryNode temporary state node}, it will\n\t * return a permanent state node that is equivalent to the temporary node.\n\t * This method is used to detect and avoid duplicate state nodes.\n\t * \n\t * @param state a state node which will be interned in the graph\n\t * @return a permanent state node in the graph\n\t */\n\tStateNode resolve(StateNode state) {\n\t\tStateKey key = new StateKey(state);\n\t\tstate = states.get(key);\n\t\tif(state == null)\n\t\t\tstate = new StateNode(key.node);\n\t\treturn state;\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/hg/HeuristicGraph.java\npublic abstract class HeuristicGraph implements Serializable {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * Nodes representing all {@link edu.uky.cs.nil.sabre.comp.CompiledFluent\n\t * fluents} in the graph\n\t */\n\tpublic final List fluents = new List<>();\n\n\t/**\n\t * Nodes representing all {@link edu.uky.cs.nil.sabre.comp.CompiledAction\n\t * actions} in the graph\n\t */\n\tpublic final List actions = new List<>();\n\t\n\t/** Maps the labels of nodes to their corresponding nodes */\n\tprotected final HashMap nodes = new HashMap<>();\n\t\n\t/**\n\t * A node representing the {@link edu.uky.cs.nil.sabre.Problem#utility\n\t * author's utility}\n\t */\n\tprotected UtilityNode utility = null;\n\t\n\t/**\n\t * Nodes representing each {@link edu.uky.cs.nil.sabre.Problem#utilities\n\t * character's utility}\n\t */\n\tprotected final HashMap utilities = new HashMap<>();\n\t\n\t/**\n\t * A node representing the constant {@link False#FALSE}. This field is\n\t * necessary because false is both a {@link Value value} and an empty\n\t * {@link Disjunction disjunction}, so the same label can map to two\n\t * different nodes. This field points to the {@link ConstantNode constant}\n\t * for false; the mapping in {@link #nodes} will be to the {@link\n\t * DisjunctionNode disjunction} for false.\n\t */\n\tfinal ConstantNode falseValueNode;\n\t\n\t/**\n\t * A node representing the constant {@link True#TRUE}. This field is\n\t * necessary because true is both a {@link Value value} and a {@link\n\t * Disjunction disjunction} of {@link Clause#EMPTY the empty clause}, so\n\t * the same label can map to two different nodes. This field points to the\n\t * {@link ConstantNode constant} for true; the mapping in {@link #nodes}\n\t * will be to the {@link DisjunctionNode disjunction} for true.\n\t */\n\tfinal ConstantNode trueValueNode;\n\t\n\t/** A node representing {@link Clause#EMPTY the empty clause} */\n\tfinal ClauseNode emptyClauseNode;\n\t\n\t/**\n\t * A list of {@link ActionNode actions} whose preconditions have a finite\n\t * cost but which have not yet been added to the graph\n\t */\n\tfinal List next = new List<>();\n\t\n\t/**\n\t * A sentinel node that represents the end of the list of nodes that need to\n\t * be {@link #reset() reset}\n\t */\n\tprivate final Node lastToReset = new Node(this, null) {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1L;\n\t};\n\t\n\t/**\n\t * The start of a linked list of nodes that need to be {@link #reset()\n\t * reset}\n\t */\n\tNode firstToReset = lastToReset;\n\t\n\t/**\n\t * Constructs a heuristic graph which contains only the nodes representing\n\t * {@link False#FALSE false}, {@link True#TRUE true}, and {@link\n\t * Clause#EMPTY the empty clause}.\n\t * \n\t * @param status a status to update while building the graph\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic HeuristicGraph(Status status) {\n\t\tstatus.setMessage(\"Building empty heuristic graph...\");\n\t\tthis.falseValueNode = makeConstantNode(False.FALSE);\n\t\tthis.trueValueNode = makeConstantNode(True.TRUE);\n\t\tthis.emptyClauseNode = getClause((Clause) (Clause) Clause.EMPTY);\n\t\tmakeDisjunctionNode(False.FALSE.toPrecondition());\n\t\tmakeDisjunctionNode(True.TRUE.toPrecondition());\n\t}\n\t\n\t/**\n\t * Constructs a heuristic graph which contains nodes for every fluent,\n\t * event, and utility in a given problem.\n\t * \n\t * @param problem the problem whose fluents, events, and utilities will be\n\t * represented in the graph\n\t * @param status a status to update while building the graph\n\t */\n\tpublic HeuristicGraph(CompiledProblem problem, Status status) {\n\t\tthis(status);\n\t\tstatus.setMessage(\"Building heuristic graph for \\\"\" + problem.name + \"\\\"...\");\n\t\tfor(Fluent fluent : problem.fluents)\n\t\t\tgetFluent(fluent);\n\t\tfor(Event event : problem.events)\n\t\t\tgetEvent(event);\n\t\tsetUtility(null, problem.utility);\n\t\tfor(Character character : problem.universe.characters)\n\t\t\tsetUtility(character, problem.utilities.get(character));\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn Utilities.DEFAULT_PRINTER.toString(this);\n\t}\n\t\n\t/**\n\t * Returns the {@link Node heuristic graph node} associated with the given\n\t * {@link Logical logical expression}. If the node does not exist, it will\n\t * be created.\n\t * \n\t * @param logical the logical expression to represent in the graph\n\t * @return a node representing that logical expression (which will have\n\t * that expression as its {@link Node#label its label})\n\t * @throws IllegalArgumentException if the graph cannot create a node for\n\t * the given expression\n\t * @throws edu.uky.cs.nil.sabre.FormatException if the logical expression\n\t * is not ground\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Node getNode(Logical logical) {\n\t\tif(logical instanceof Value)\n\t\t\treturn getConstant((Value) logical);\n\t\tif(logical instanceof Fluent)\n\t\t\treturn getFluent((Fluent) logical);\n\t\telse if(logical instanceof Arithmetic)\n\t\t\treturn getArithmetic((Arithmetic) logical);\n\t\telse if(logical instanceof Precondition)\n\t\t\treturn getPrecondition((Precondition) logical);\n\t\telse if(isClause(logical))\n\t\t\treturn getClause((Clause) logical);\n\t\telse if(isDNF(logical))\n\t\t\treturn getDisjunction((Disjunction>) logical);\n\t\telse if(logical instanceof Event)\n\t\t\treturn getEvent((Event) logical);\n\t\telse if(logical instanceof Effect)\n\t\t\treturn getEffect((Effect) logical);\n\t\telse if(logical instanceof Expression)\n\t\t\treturn getDisjunction(((Expression) logical).toPrecondition());\n\t\telse\n\t\t\tthrow Exceptions.noHeuristicGraphNode(logical);\n\t}\n\t\n\tprivate static final boolean isClause(Logical logical) {\n\t\tif(!(logical instanceof Clause))\n\t\t\treturn false;\n\t\tClause clause = (Clause) logical;\n\t\tfor(int i=0; i disjunction = (Disjunction) logical;\n\t\tfor(int i=0; i clause) {\n\t\tClauseNode node = (ClauseNode) nodes.get(clause);\n\t\tif(node == null)\n\t\t\tnode = makeClauseNode(clause);\n\t\treturn node;\n\t}\n\t\n\t/**\n\t * This method is used to create all {@link ClauseNode clause nodes} so\n\t * that subclasses of {@link HeuristicGraph} have the option to\n\t * return subclasses of {@link ClauseNode} to modify the graph's behavior.\n\t * \n\t * @param clause the conjunctive clause to represent in the graph\n\t * @return a new clause node\n\t */\n\tprotected ClauseNode makeClauseNode(Clause clause) {\n\t\treturn new ClauseNode(this, clause);\n\t}\n\t\n\t/**\n\t * Defines the {@link CostNode#getCost() cost} of a {@link ClauseNode\n\t * clause node} being {@link True#TRUE true}. The {@link\n\t * ClauseNode#preconditions preconditions} that make up the clause and\n\t * their costs can be accessed from the node itself. This method will be\n\t * called after {@link ClauseNode#notify(Node, Value, double)} has been\n\t * called as many times as it has preconditions. Usually, this implies\n\t * this method will not be called until all preconditions in the clause\n\t * have a finite cost, but this cannot be guaranteed.\n\t * \n\t * @param node the clause node for which the cost of bring true is being\n\t * calculated\n\t * @return the cost of a clause being true\n\t */\n\tprotected abstract double cost(ClauseNode node);\n\t\n\t/**\n\t * Returns the {@link DisjunctionNode disjunction node} associated with the\n\t * given {@link Expression#toPrecondition() disjunctive normal form\n\t * expression}. If the node does not exist, it will be created.\n\t * \n\t * @param disjunction the disjunctive normal form expression to represent\n\t * in the graph\n\t * @return the disjunction node representing the expression\n\t * @throws edu.uky.cs.nil.sabre.FormatException if the disjunction is not\n\t * ground\n\t */\n\tpublic DisjunctionNode getDisjunction(Disjunction> disjunction) {\n\t\tDisjunctionNode node = (DisjunctionNode) nodes.get(disjunction);\n\t\tif(node == null)\n\t\t\tnode = makeDisjunctionNode(disjunction);\n\t\treturn node;\n\t}\n\t\n\t/**\n\t * This method is used to create all {@link DisjunctionNode disjunction\n\t * nodes} so that subclasses of {@link HeuristicGraph} have the option to\n\t * return subclasses of {@link DisjunctionNode} to modify the graph's\n\t * behavior.\n\t * \n\t * @param disjunction the disjunctive normal form expression to represent\n\t * in the graph\n\t * @return a new disjunction node\n\t */\n\tprotected DisjunctionNode makeDisjunctionNode(Disjunction> disjunction) {\n\t\treturn new DisjunctionNode(this, disjunction);\n\t}\n\t\n\t/**\n\t * Returns the {@link EventNode event node} associated with the given\n\t * {@link Event event}. If the node does not exist, it will be created.\n\t * \n\t * @param event the event to represent in the graph\n\t * @return the event node representing the event\n\t * @throws edu.uky.cs.nil.sabre.FormatException if the event is not ground\n\t */\n\tpublic EventNode getEvent(Event event) {\n\t\tif(event instanceof Action)\n\t\t\treturn getAction((Action) event);\n\t\telse\n\t\t\treturn getTrigger((Trigger) event);\n\t}\n\t\n\t/**\n\t * Returns the {@link ActionNode action node} associated with the given\n\t * {@link Action action}. If the node does not exist, it will be created.\n\t * \n\t * @param action the action to represent in the graph\n\t * @return the action node representing the action\n\t * @throws edu.uky.cs.nil.sabre.FormatException if the action is not ground\n\t */\n\tpublic ActionNode getAction(Action action) {\n\t\tActionNode node = (ActionNode) nodes.get(action);\n\t\tif(node == null)\n\t\t\tnode = makeActionNode(action);\n\t\treturn node;\n\t}\n\t\n\t/**\n\t * This method is used to create all {@link ActionNode action nodes} so\n\t * that subclasses of {@link HeuristicGraph} have the option to return\n\t * subclasses of {@link ActionNode} to modify the graph's behavior.\n\t * \n\t * @param action the action to represent in the graph\n\t * @return a new action node\n\t */\n\tprotected ActionNode makeActionNode(Action action) {\n\t\treturn new ActionNode(this, action);\n\t}\n\t\n\t/**\n\t * Returns the {@link TriggerNode trigger node} associated with the given\n\t * {@link Trigger trigger}. If the node does not exist, it will be created.\n\t * \n\t * @param trigger the trigger to represent in the graph\n\t * @return the node representing the trigger\n\t * @throws edu.uky.cs.nil.sabre.FormatException if the trigger is not\n\t * ground\n\t */\n\tpublic TriggerNode getTrigger(Trigger trigger) {\n\t\tTriggerNode node = (TriggerNode) nodes.get(trigger);\n\t\tif(node == null)\n\t\t\tnode = makeTriggerNode(trigger);\n\t\treturn node;\n\t}\n\t\n\t/**\n\t * This method is used to create all {@link TriggerNode trigger nodes} so\n\t * that subclasses of {@link HeuristicGraph} have the option to return\n\t * subclasses of {@link TriggerNode} to modify the graph's behavior.\n\t * \n\t * @param trigger the trigger to represent in the graph\n\t * @return a new trigger node\n\t */\n\tprotected TriggerNode makeTriggerNode(Trigger trigger) {\n\t\treturn new TriggerNode(this, trigger);\n\t}\n\t\n\t/**\n\t * Returns the {@link EffectNode effect node} associated with the given\n\t * {@link Effect atomic effect}. If the node does not exist, it will be\n\t * created.\n\t * \n\t * @param effect the effect to represent in the graph\n\t * @return an effect node representing the effect\n\t * @throws edu.uky.cs.nil.sabre.FormatException if the effect is not ground\n\t */\n\tpublic EffectNode getEffect(Effect effect) {\n\t\tEffectNode node = (EffectNode) nodes.get(effect);\n\t\tif(node == null)\n\t\t\tnode = makeEffectNode(effect);\n\t\treturn node;\n\t}\n\t\n\t/**\n\t * This method is used to create all {@link EffectNode effect nodes} so\n\t * that subclasses of {@link HeuristicGraph} have the option to return\n\t * subclasses of {@link EffectNode} to modify the graph's behavior.\n\t * \n\t * @param effect the effect to represent in the graph\n\t * @return a new effect node\n\t */\n\tprotected EffectNode makeEffectNode(Effect effect) {\n\t\treturn new EffectNode(this, effect);\n\t}\n\t\n\t/**\n\t * Defines the {@link CostNode#getCost() cost} of an {@link EffectNode\n\t * effect node} being included in the graph, which means that at least\n\t * one of {@link EffectNode#events the events that has this effect} has\n\t * a finite cost and {@link EffectNode#condition the effect's condition}\n\t * also has a finite cost. The events that have this effect and the\n\t * condition can be accessed from the node itself. This method may be\n\t * called before some event has a finite cost and before the condition\n\t * has a finite cost.\n\t * \n\t * @param node the effect node for which the cost of being true is being\n\t * calculated\n\t * @return the cost of the effect being true\n\t */\n\tprotected abstract double cost(EffectNode node);\n\t\n\t/**\n\t * Defines the {@link CostSet#getCost(Value) cost} of {@link\n\t * EffectNode#fluent an effect node's fluent} having a given {@link Value\n\t * value} from the {@link EffectNode#value right hand side of an effect\n\t * node's assignment} based on the value and cost of the right hand side.\n\t * \n\t * @param node the effect node which is assigning the value to its fluent\n\t * @param value the value being assigned to the fluent\n\t * @param cost the cost of the value being assigned to the fluent\n\t * @return the cost of the fluent having that value\n\t */\n\tprotected abstract double cost(EffectNode node, Value value, double cost);\n\t\n\t/**\n\t * Returns the {@link Character characters} which have {@link UtilityNode\n\t * utility nodes} represented in the graph. The resulting collection will\n\t * not include {@code null}, even if {@link #getUtility() the author's\n\t * utility} is represented.\n\t * \n\t * @return a collection of characters whose utilities are defined in the\n\t * graph\n\t */\n\tpublic Iterable getCharacters() {\n\t\treturn utilities.keySet();\n\t}\n\t\n\t/**\n\t * Returns the {@link UtilityNode utility node} representing {@link \n\t * edu.uky.cs.nil.sabre.Problem#utility the author's utility} if it {@link\n\t * #setUtility(Character, Conditional) has been defined}.\n\t * \n\t * @return a utility node representing the author's utility, or null if the\n\t * author's utility has not been represented in this graph yet\n\t */\n\tpublic UtilityNode getUtility() {\n\t\treturn getUtility(null);\n\t}\n\t\n\t/**\n\t * Returns the {@link UtilityNode utility node} representing {@link\n\t * edu.uky.cs.nil.sabre.Problem#utilities an character's utility} if it\n\t * {@link #setUtility(Character, Conditional) has been defined}.\n\t * \n\t * @param character the character whose utility representation is desired\n\t * @return a utility node representing the character's utility, or null if\n\t * the character's utility has not been represented in this graph yet\n\t */\n\tpublic UtilityNode getUtility(Character character) {\n\t\tif(character == null)\n\t\t\treturn utility;\n\t\telse\n\t\t\treturn utilities.get(character);\n\t}\n\t\n\t/**\n\t * Defines a {@link UtilityNode utility node} for the given character using\n\t * the given utility expression. To define the author's utility, the\n\t * character argument should be {@code null}. This method should only be\n\t * called once per character; calling it more than once per character will\n\t * cause an {@link IllegalStateException}. To access an already defined\n\t * utility node, use {@link #getUtility()}.\n\t * \n\t * @param character the character whose utility is being represented\n\t * @param utility a numeric expression which can be evaluated to determine\n\t * how satisfied the character is with a given situation\n\t * @return a utility node for that character representing the utility\n\t * expression\n\t * @throws IllegalStateException if a utility node has already been defined\n\t * for the character\n\t */\n\tpublic UtilityNode setUtility(Character character, Conditional>> utility) {\n\t\tUtilityNode node = getUtility(character);\n\t\tif(node != null)\n\t\t\tthrow Exceptions.utilityNodeAlreadyDefined(character);\n\t\tnode = makeUtilityNode(character, utility);\n\t\tif(character == null)\n\t\t\tthis.utility = node;\n\t\telse\n\t\t\tutilities.put(character, node);\n\t\treturn node;\n\t}\n\t\n\t/**\n\t * This method is used to create all {@link UtilityNode utility nodes} so\n\t * that subclasses of {@link HeuristicGraph} have the option to return\n\t * subclasses of {@link UtilityNode} to modify the graph's behavior.\n\t * \n\t * @param character the character whose utility is being defined\n\t * @param conditional a numeric expression which can be evaluated to\n\t * determine how satisfied the character is with a given situation\n\t * @return a new utility node\n\t */\n\tprotected UtilityNode makeUtilityNode(Character character, Conditional>> conditional) {\n\t\treturn new UtilityNode(this, character, conditional);\n\t}\n\n\t/**\n\t * This method is used to create all {@link GoalNode goal nodes} so that\n\t * subclasses of {@link HeuristicGraph} have the option to return\n\t * subclasses of {@link GoalNode} to modify the graph's behavior.\n\t * \n\t * @param utility the utility node for which this goal represents a branch\n\t * @param label a conditional expression where the first condition and\n\t * branch (and only the first condition and branch) will be used as the\n\t * condition and value expressions for one branch of a utility node\n\t * @return a goal node for the given utility node with the given condition\n\t */\n\tprotected GoalNode makeGoalNode(UtilityNode utility, Conditional>> label) {\n\t\treturn new GoalNode(utility, label);\n\t}\n\t\n\t/**\n\t * Defines the {@link CostSet#getCost(Value) cost} of a {@link UtilityNode\n\t * utility node} having a given {@link Value value} based on the cost of\n\t * the {@link GoalNode goal condition} that was met and the value and cost\n\t * of the {@link GoalNode#value branch of the utility expression that was\n\t * evaluated}. A utility node has {@link UtilityNode#goals has many goals},\n\t * which represent the conditions and branches of a {@link Conditional\n\t * conditional utility expression}. When a {@link GoalNode#condition goal\n\t * node's condition} becomes finite, it becomes possible for {@link\n\t * GoalNode#utility the goal's utility node} to take on every value that\n\t * the {@link GoalNode#value goal node's value expression can have}.\n\t * This method will only be called after the goal node has a finite {@link\n\t * CostNode#getCost() cost}.\n\t * \n\t * @param node the goal node which represents a {@link GoalNode#condition\n\t * condition} of the utility expression that has a finite cost\n\t * @param value a value that the {@link GoalNode#value goal node's value\n\t * expression} can have\n\t * @param cost the cost of the goal node's value expression having that\n\t * value\n\t * @return the cost of the goal node's utility node having that value\n\t */\n\tprotected abstract double cost(GoalNode node, Value value, double cost);\n\t\n\t/**\n\t * {@link Node#reset() Resets} event node in the graph so that all costs\n\t * are {@link Double#POSITIVE_INFINITY positive infinity}, except for costs\n\t * which are trivially 0 (the {@link ConstantNode constant node}\n\t * representing true and the {@link ClauseNode clause node} representing\n\t * {@link Clause#EMPTY the empty clause}).\n\t */\n\tpublic void reset() {\n\t\tNode current = null;\n\t\tNode next = firstToReset;\n\t\twhile(next != lastToReset) {\n\t\t\tcurrent = next;\n\t\t\tnext = current.nextToReset;\n\t\t\tcurrent.reset();\n\t\t}\n\t\tfirstToReset = lastToReset;\n\t\temptyClauseNode.setCost(0);\n\t}\n\t\n\t/**\n\t * Returns an array of all finite costs that appear anywhere in the graph\n\t * (that is, the cost of any {@link CostNode cost nodes} with a finite\n\t * {@link CostNode#getCost() cost} and the costs of any {@link CostSet cost\n\t * sets} that have {@link CostSet#getCost(Value) values with finite\n\t * costs}).\n\t * \n\t * @return a sorted array of finite costs that appear in this graph\n\t */\n\tpublic double[] getLevels() {\n\t\tHashSet costs = new HashSet<>();\n\t\tfor(FluentNode fluent : fluents)\n\t\t\tfor(CostSet.Entry entry : fluent)\n\t\t\t\tcosts.add(entry.cost);\n\t\tfor(ActionNode action : actions)\n\t\t\tcosts.add(action.getCost());\n\t\tcosts.remove(Double.POSITIVE_INFINITY);\n\t\tdouble[] levels = new double[costs.size()];\n\t\tint index = 0;\n\t\tfor(Double cost : costs)\n\t\t\tlevels[index++] = cost;\n\t\tArrays.sort(levels);\n\t\treturn levels;\n\t}\n\t\n\t/**\n\t * {@link #reset() Resets} all nodes in the graph and then initializes all\n\t * {@link FluentNode fluent nodes} by setting the cost of the value that\n\t * fluent has in the given state to 0. After initialization, {@link\n\t * CostNode nodes that represent Boolean propositions} will have a cost of\n\t * 0 if they are true in the given state or {@link Double#POSITIVE_INFINITY\n\t * positive infinity} otherwise. Numeric nodes like {@link ArithmeticNode\n\t * arithmetic nodes} and {@link UtilityNode utility nodes} will have the\n\t * cost of their value in the given state set of 0, and the cost of all\n\t * other values set to positive infinity.\n\t * \n\t * @param state the state that defines the initial value of each fluent\n\t */\n\tpublic void initialize(State state) {\n\t\treset();\n\t\tfor(int i=0; i= 0) {\n\t\t\tActionNode node = next.get(index);\n\t\t\textend(index - 1);\n\t\t\tnode.setCost(node.precondition.getCost() + 1);\n\t\t}\n\t\telse\n\t\t\tnext.clear();\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/hg/EffectNode.java\npublic class EffectNode extends CostNode {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\n\t/** The atomic effect this node represents */\n\tpublic final Effect label;\n\t\n\t/**\n\t * The node representing the fluent on {@link\n\t * edu.uky.cs.nil.sabre.logic.Assignment#fluent the left side of the\n\t * assignment}\n\t */\n\tpublic final FluentNode fluent;\n\t\n\t/**\n\t * The node representing the value expression on the {@link\n\t * edu.uky.cs.nil.sabre.logic.Assignment#value right side of the assignment}\n\t */\n\tpublic final FormulaNode value;\n\t\n\t/** A list of {@link EventNode event nodes} that have this effect */\n\tpublic final List events = new List<>();\n\t\n\t/**\n\t * The node representing the {@link Effect#condition condition} under which\n\t * the effect can happen\n\t */\n\tpublic final DisjunctionNode condition;\n\t\n\t/**\n\t * A list of all {@link PreconditionNode precondition nodes} whose fluent\n\t * this effect might assign values to\n\t */\n\tpublic final List preconditions;\n\t\n\t/**\n\t * Constructs a new effect node that belongs to a given graph and\n\t * represents a given atomic effect.\n\t * \n\t * @param graph the graph this node belongs to\n\t * @param label the atomic effect this node represents\n\t */\n\tprotected EffectNode(HeuristicGraph graph, Effect label) {\n\t\tsuper(graph, label);\n\t\tthis.label = label;\n\t\tthis.fluent = graph.getFluent(label.fluent);\n\t\tthis.value = (FormulaNode) graph.getNode(label.value);\n\t\tthis.value.formulas.add(this);\n\t\tthis.condition = graph.getDisjunction(label.condition);\n\t\tthis.condition.conditionals.add(this);\n\t\tif(label.fluent.isNumber())\n\t\t\tthis.preconditions = this.fluent.preconditions;\n\t\telse\n\t\t\tthis.preconditions = ((NominalFluentNode) this.fluent).getGroup((Value) label.value);\n\t\tthis.fluent.register(this);\n\t}\n\t\n\t@Override\n\tprotected boolean setCost(double cost) {\n\t\tif(super.setCost(cost)) {\n\t\t\tfor(int i=0; i\nThe comment ends with the description of the constructor parameters. The next logical line is the constructor declaration for Reachable, taking a CompiledProblem and a Status, matching the comment.\n\npublic Reachable(CompiledProblem problem, Status status) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.901, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36795, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public Reachable(CompiledProblem problem, Status status) {", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import emu.lunarcore.server.game.GameSession;\nimport emu.lunarcore.server.packet.CmdId;\nimport emu.lunarcore.server.packet.Opcodes;\nimport emu.lunarcore.server.packet.PacketHandler;\nimport emu.lunarcore.server.packet.send.PacketGetAvatarDataScRsp;", "context": "src/main/java/emu/lunarcore/server/packet/recv/HandlerGetAvatarDataCsReq.java\npackage emu.lunarcore.server.packet.recv;\n\n\n@Opcodes(CmdId.GetAvatarDataCsReq)\npublic class HandlerGetAvatarDataCsReq extends PacketHandler {\n\n @Override\n public void handle(GameSession session, byte[] data) throws Exception {\n\nsrc/main/java/emu/lunarcore/server/packet/PacketHandler.java\npublic abstract class PacketHandler {\n public abstract void handle(GameSession session, byte[] data) throws Exception;\n}\n\nsrc/main/java/emu/lunarcore/server/packet/send/PacketGetAvatarDataScRsp.java\npublic class PacketGetAvatarDataScRsp extends BasePacket {\n \n public PacketGetAvatarDataScRsp(Player player) {\n super(CmdId.GetAvatarDataScRsp);\n\n var data = GetAvatarDataScRsp.newInstance()\n .setIsGetAll(true);\n\n for (GameAvatar avatar : player.getAvatars()) {\n data.addAvatarList(avatar.toProto());\n }\n\n this.setData(data);\n }\n \n}\n\nsrc/main/java/emu/lunarcore/server/packet/CmdId.java\npublic class CmdId {\n // Empty\n public static final int NONE = 0;\n\n // Cmd Ids\n public static final int SpringRecoverCsReq = 1471;\n public static final int TakeTrainVisitorUntakenBehaviorRewardScRsp = 3738;\n public static final int SelectChatBubbleScRsp = 5184;\n public static final int GetEnhanceCommonRogueBuffInfoCsReq = 5659;\n public static final int SubmitMonsterResearchActivityMaterialCsReq = 2620;\n public static final int EnterAetherDivideSceneCsReq = 4883;\n public static final int HeliobusActivityDataCsReq = 5883;\n public static final int CommonRogueQueryScRsp = 5686;\n public static final int GetRogueShopMiracleInfoCsReq = 5684;\n public static final int ApplyFriendCsReq = 2942;\n public static final int ComposeLimitNumUpdateNotify = 506;\n public static final int GetCurAssistCsReq = 2977;\n public static final int ChangeLineupLeaderCsReq = 764;\n public static final int TrialActivityDataChangeScNotify = 2679;\n public static final int AlleyGuaranteedFundsCsReq = 4777;\n public static final int UpdateFeatureSwitchScNotify = 43;\n public static final int FinishQuestCsReq = 938;\n public static final int ChessRogueRollDiceScRsp = 5485;\n public static final int GetAuthkeyScRsp = 73;\n public static final int ActivateFarmElementCsReq = 1470;\n public static final int StartAetherDivideChallengeBattleScRsp = 4819;\n public static final int SetAetherDivideLineUpCsReq = 4855;\n public static final int StartRogueScRsp = 1884;\n public static final int UnlockAvatarSkinScNotify = 333;\n public static final int SellItemCsReq = 520;\n public static final int SwapLineupScRsp = 738;\n public static final int TakeAllApRewardCsReq = 3360;\n public static final int GetChallengeGroupStatisticsCsReq = 1773;\n public static final int RetcodeNotify = 86;\n public static final int FinishPerformSectionIdScRsp = 2738;\n public static final int AetherDivideFinishChallengeScNotify = 4865;\n public static final int SyncLineupNotify = 749;\n public static final int UseItemScRsp = 519;\n public static final int GetFarmStageGachaInfoCsReq = 1304;\n public static final int UseTreasureDungeonItemScRsp = 4480;\n public static final int AcceptMainMissionCsReq = 1224;\n public static final int JoinLineupCsReq = 782;\n public static final int DelSaveRaidScNotify = 2220;\n public static final int InteractPropScRsp = 1484;\n public static final int EnableRogueTalentCsReq = 1823;\n public static final int CurTrialActivityScNotify = 2611;\n public static final int UnlockPhoneThemeScNotify = 5119;\n public static final int UpdateRogueAdventureRoomScoreScRsp = 5676;\n public static final int NewAssistHistoryNotify = 2927;\n public static final int AlleyShipUsedCountScNotify = 4778;\n public static final int RecoverAllLineupCsReq = 1477;\n public static final int HeliobusSnsPostScRsp = 5860;\n public static final int SetNicknameCsReq = 92;\n public static final int SharePunkLordMonsterCsReq = 3282;\n public static final int GetChessRogueBuffEnhanceInfoScRsp = 5570;\n public static final int AlleyPlacingGameCsReq = 4755;\n public static final int TakeRogueEventHandbookRewardCsReq = 5618;\n public static final int GetPlayerReturnMultiDropInfoScRsp = 4682;\n public static final int MuseumTakeCollectRewardCsReq = 4365;\n public static final int GetActivityScheduleConfigCsReq = 2682;\n public static final int DeleteSummonUnitCsReq = 1447;\n public static final int RefreshAlleyOrderScRsp = 4745;\n public static final int FinishChessRogueSubStoryScRsp = 5406;\n public static final int GetCurSceneInfoScRsp = 1419;\n public static final int GetFightActivityDataScRsp = 3661;\n public static final int QuitBattleCsReq = 104;\n public static final int FinishFirstTalkNpcScRsp = 2119;\n public static final int StartCocoonStageScRsp = 1427;\n public static final int BattleLogReportScRsp = 149;\n public static final int TreasureDungeonFinishScNotify = 4461;\n public static final int ChessRogueEnterScRsp = 5595;\n public static final int SetMissionEventProgressCsReq = 1246;\n public static final int TreasureDungeonDataScNotify = 4483;\n public static final int StrongChallengeActivityBattleEndScNotify = 6682;\n public static final int StartAlleyEventCsReq = 4742;\n public static final int ChessRogueCellUpdateNotify = 5469;\n public static final int QuestRecordScNotify = 997;\n public static final int BuyRogueShopMiracleCsReq = 5619;\n public static final int EnterRogueEndlessActivityStageScRsp = 6084;\n public static final int StartAetherDivideStageBattleCsReq = 4859;\n public static final int GetLoginActivityCsReq = 2683;\n public static final int UpdateServerPrefsDataCsReq = 6182;\n public static final int StartBoxingClubBattleScRsp = 4260;\n public static final int ChessRogueUpdateReviveInfoScNotify = 5562;\n public static final int GetWaypointCsReq = 483;\n public static final int ReturnLastTownScRsp = 1480;\n public static final int LeaveRogueScRsp = 1819;\n public static final int FinishTutorialGuideCsReq = 1649;\n public static final int SpaceZooExchangeItemScRsp = 6755;\n public static final int SetSpringRecoverConfigScRsp = 1444;\n public static final int GetAlleyInfoCsReq = 4783;\n public static final int GetAllSaveRaidScRsp = 2245;\n public static final int FightTreasureDungeonMonsterScRsp = 4445;\n public static final int FinishCosumeItemMissionCsReq = 1255;\n public static final int ExchangeStaminaScRsp = 40;\n public static final int ChessRogueNousDiceSurfaceUnlockNotify = 5520;\n public static final int FinishChapterScNotify = 4904;\n public static final int GetPunkLordBattleRecordScRsp = 3277;\n public static final int GetShopListScRsp = 1561;\n public static final int LogisticsScoreRewardSyncInfoScNotify = 4756;\n public static final int GetStageLineupScRsp = 761;\n public static final int LockRelicCsReq = 573;\n public static final int EnterSceneCsReq = 1417;\n public static final int SetClientPausedCsReq = 1422;\n public static final int PlayerLogoutCsReq = 4;\n public static final int SpaceZooMutateCsReq = 6782;\n public static final int BattlePassInfoNotify = 3083;\n public static final int ReserveStaminaExchangeScRsp = 81;\n public static final int MarkItemCsReq = 553;\n public static final int StartFinishMainMissionScNotify = 1206;\n public static final int FinishAeonDialogueGroupCsReq = 1821;\n public static final int HeliobusSnsUpdateScNotify = 5849;\n public static final int UpdateFloorSavedValueNotify = 1491;\n public static final int TrainVisitorBehaviorFinishScRsp = 3761;\n public static final int LockEquipmentCsReq = 582;\n public static final int AetherDivideTainerInfoScNotify = 4887;\n public static final int TextJoinBatchSaveCsReq = 3882;\n public static final int ExpUpRelicScRsp = 552;\n public static final int AlleyShipUnlockScNotify = 4708;\n public static final int DeactivateFarmElementScRsp = 1425;\n public static final int ChessRogueEnterNextLayerScRsp = 5448;\n public static final int SyncRogueFinishScNotify = 1840;\n public static final int HeliobusSnsReadCsReq = 5804;\n public static final int ChessRogueNousEditDiceCsReq = 5437;\n public static final int LeaveTrialActivityScRsp = 2658;\n public static final int SetGameplayBirthdayScRsp = 71;\n public static final int GroupStateChangeScNotify = 1466;\n public static final int SetSignatureCsReq = 2838;\n public static final int EquipAetherDividePassiveSkillCsReq = 4840;\n public static final int GetLevelRewardTakenListCsReq = 80;\n public static final int SetLanguageScRsp = 87;\n public static final int InteractTreasureDungeonGridScRsp = 4492;\n public static final int GetRndOptionCsReq = 3483;\n public static final int ChessRogueNousDiceUpdateNotify = 5537;\n public static final int TakeQuestRewardCsReq = 904;\n public static final int ChessRoguePickAvatarScRsp = 5453;\n public static final int LeaveAetherDivideSceneScRsp = 4884;\n public static final int MuseumRandomEventStartScNotify = 4320;\n public static final int RemoveStuffFromAreaScRsp = 4319;\n public static final int SetGenderScRsp = 56;\n public static final int BoxingClubChallengeUpdateScNotify = 4238;\n public static final int SyncRogueCommonVirtualItemInfoScNotify = 5667;\n public static final int GetBasicInfoScRsp = 67;\n public static final int AetherDivideSpiritExpUpCsReq = 4890;\n public static final int GetFirstTalkByPerformanceNpcScRsp = 2109;\n public static final int TrainRefreshTimeNotify = 3782;\n public static final int ChooseBoxingClubStageOptionalBuffScRsp = 4252;\n public static final int TakeCityShopRewardScRsp = 1560;\n public static final int ChessRogueUpdateUnlockLevelScNotify = 5592;\n public static final int ReviveRogueAvatarCsReq = 1820;\n public static final int SetTurnFoodSwitchScRsp = 522;\n public static final int SceneEntityMoveScNotify = 1449;\n public static final int TakeTrialActivityRewardScRsp = 2651;\n public static final int ClientObjDownloadDataScNotify = 10;\n public static final int ExchangeHcoinScRsp = 590;\n public static final int DressAvatarSkinCsReq = 380;\n public static final int QueryProductInfoCsReq = 16;\n public static final int TakeChallengeRaidRewardScRsp = 2297;\n public static final int GetReplayTokenCsReq = 3583;\n public static final int ChessRogueNousEnableRogueTalentScRsp = 5580;\n public static final int EnhanceCommonRogueBuffCsReq = 5690;\n public static final int EnterStrongChallengeActivityStageScRsp = 6684;\n public static final int PromoteEquipmentScRsp = 584;\n public static final int RankUpAvatarScRsp = 340;\n public static final int SceneEntityMoveScRsp = 1461;\n public static final int AlleyEventEffectNotify = 4738;\n public static final int GetCurBattleInfoScRsp = 160;\n public static final int TriggerVoiceCsReq = 4155;\n public static final int GameplayCounterUpdateScNotify = 1454;\n public static final int ChessRogueUpdateDicePassiveAccumulateValueScNotify = 5567;\n public static final int GiveUpBoxingClubChallengeScRsp = 4219;\n public static final int AcceptedPamMissionExpireScRsp = 4061;\n public static final int RegionStopScNotify = 45;\n public static final int TakeRogueEndlessActivityPointRewardScRsp = 6042;\n public static final int GetChessRogueStoryAeonTalkInfoCsReq = 5472;\n public static final int DailyTaskDataScNotify = 1219;\n public static final int BuyNpcStuffScRsp = 4384;\n public static final int GetMissionDataCsReq = 1283;\n public static final int GetFriendApplyListInfoCsReq = 2982;\n public static final int GetUnlockTeleportCsReq = 1481;\n public static final int ChessRogueFinishCurRoomNotify = 5587;\n public static final int TextJoinQueryCsReq = 3804;\n public static final int LeaveChallengeScRsp = 1760;\n public static final int TakeRogueAeonLevelRewardCsReq = 1874;\n public static final int SummonPunkLordMonsterScRsp = 3219;\n public static final int SetGroupCustomSaveDataScRsp = 1413;\n public static final int SwitchLineupIndexCsReq = 752;\n public static final int FinishItemIdCsReq = 2782;\n public static final int MuseumRandomEventSelectCsReq = 4380;\n public static final int PlayerGetTokenScRsp = 60;\n public static final int RefreshTriggerByClientCsReq = 1407;\n public static final int EnterTreasureDungeonScRsp = 4464;\n public static final int GetQuestRecordScRsp = 919;\n public static final int RogueModifierUpdateNotify = 5319;\n public static final int CommonRogueUpdateScNotify = 5651;\n public static final int MissionGroupWarnScNotify = 1209;\n public static final int GetEnteredSceneScRsp = 1421;\n public static final int SyncTaskScRsp = 1242;\n public static final int PlayerReturnTakeRewardScRsp = 4519;\n public static final int PickRogueAvatarScRsp = 1873;\n public static final int ComposeItemCsReq = 555;\n public static final int SyncRogueRewardInfoScNotify = 1829;\n public static final int UnlockHeadIconScNotify = 2897;\n public static final int SyncHandleFriendScNotify = 2909;\n public static final int GetGachaInfoCsReq = 1983;\n public static final int RogueModifierSelectCellScRsp = 5382;\n public static final int HeliobusUpgradeLevelScRsp = 5864;\n public static final int TakeLoginActivityRewardScRsp = 2684;\n public static final int PVEBattleResultCsReq = 183;\n public static final int QuitBattleScNotify = 197;\n public static final int TakeOffRelicCsReq = 345;\n public static final int StartRaidScRsp = 2261;\n public static final int RogueModifierStageStartNotify = 5338;\n public static final int SetHeroBasicTypeCsReq = 24;\n public static final int ComposeSelectedRelicCsReq = 546;\n public static final int GetTutorialGuideScRsp = 1684;\n public static final int GetTreasureDungeonActivityDataScRsp = 4409;\n public static final int GetPlayerBoardDataScRsp = 2861;\n public static final int EntityBindPropScRsp = 1456;\n public static final int GetExpeditionDataCsReq = 2583;\n public static final int AlleyTakeEventRewardScRsp = 4703;\n public static final int TakeMailAttachmentScRsp = 819;\n public static final int SetDisplayAvatarCsReq = 2882;\n public static final int ChessRogueQueryAeonDimensionsScRsp = 5523;\n public static final int HeliobusSnsLikeCsReq = 5842;\n public static final int ScenePlaneEventScNotify = 1462;\n public static final int MatchBoxingClubOpponentScRsp = 4284;\n public static final int CurAssistChangedNotify = 2922;\n public static final int PlayerReturnTakePointRewardCsReq = 4582;\n public static final int ChessRogueSelectBpCsReq = 5597;\n public static final int AceAntiCheaterScRsp = 89;\n public static final int GetAllLineupDataCsReq = 792;\n public static final int TakeFightActivityRewardCsReq = 3660;\n public static final int MultipleDropInfoNotify = 4660;\n public static final int GetPunkLordDataCsReq = 3252;\n public static final int UnlockTutorialGuideScRsp = 1619;\n public static final int WaypointShowNewCsNotify = 442;\n public static final int AlleyShopLevelScNotify = 4746;\n public static final int EnterSceneByServerScNotify = 1448;\n public static final int GeneralVirtualItemDataNotify = 514;\n public static final int DeleteFriendScRsp = 2964;\n public static final int GetTutorialScRsp = 1661;\n public static final int PlayerGetTokenCsReq = 82;\n public static final int GiveUpBoxingClubChallengeCsReq = 4242;\n public static final int SwitchAetherDivideLineUpSlotScRsp = 4892;\n public static final int HeliobusEnterBattleCsReq = 5892;\n public static final int FinishCurTurnCsReq = 4349;\n public static final int TakeRogueScoreRewardScRsp = 1880;\n public static final int GetFriendRecommendListInfoScRsp = 2992;\n public static final int PlayerReturnSignCsReq = 4561;\n public static final int GetFriendLoginInfoCsReq = 2916;\n public static final int GetFriendListInfoScRsp = 2961;\n public static final int BoxingClubRewardScNotify = 4297;\n public static final int GetQuestDataCsReq = 983;\n public static final int PlayerReturnInfoQueryScRsp = 4538;\n public static final int PlayerReturnStartScNotify = 4583;\n public static final int ChallengeLineupNotify = 1709;\n public static final int ExchangeRogueBuffWithMiracleScRsp = 5692;\n public static final int UpdateMechanismBarScNotify = 1451;\n public static final int UpdatePlayerSettingCsReq = 99;\n public static final int GetAssistHistoryScRsp = 2903;\n public static final int PlayBackGroundMusicCsReq = 3104;\n public static final int StartBattleCollegeScRsp = 5782;\n public static final int LeaveAetherDivideSceneCsReq = 4804;\n public static final int SyncRogueCommonPendingActionScNotify = 5670;\n public static final int MarkReadMailScRsp = 884;\n public static final int GetRogueDialogueEventDataScRsp = 1871;\n public static final int MarkChatEmojiScRsp = 3909;\n public static final int GetServerPrefsDataCsReq = 6104;\n public static final int GetSecretKeyInfoCsReq = 35;\n public static final int ChessRogueSelectCellScRsp = 5532;\n public static final int GetTrainVisitorBehaviorScRsp = 3784;\n public static final int SelectInclinationTextScRsp = 2138;\n public static final int SetIsDisplayAvatarInfoScRsp = 2819;\n public static final int GetRogueInitialScoreCsReq = 1814;\n public static final int LeaveChallengeCsReq = 1782;\n public static final int BuyBpLevelScRsp = 3042;\n public static final int AcceptMissionEventScRsp = 1220;\n public static final int GetQuestRecordCsReq = 942;\n public static final int StartTimedCocoonStageCsReq = 1405;\n public static final int EnterRogueScRsp = 1860;\n public static final int LastSpringRefreshTimeNotify = 1492;\n public static final int LogisticsDetonateStarSkiffScRsp = 4793;\n public static final int TakeOffEquipmentCsReq = 349;\n public static final int GetRogueBuffEnhanceInfoScRsp = 1846;\n public static final int EnhanceChessRogueBuffCsReq = 5455;\n public static final int CancelCacheNotifyScRsp = 4138;\n public static final int SendMsgCsReq = 3983;\n public static final int SwitchLineupIndexScRsp = 773;\n public static final int ChessRogueUpdateBoardScNotify = 5499;\n public static final int GetQuestDataScRsp = 961;\n public static final int BuyNpcStuffCsReq = 4304;\n public static final int TakeRogueScoreRewardCsReq = 1859;\n public static final int CancelActivityExpeditionCsReq = 2509;\n public static final int HeliobusEnterBattleScRsp = 5859;\n public static final int GetLevelRewardTakenListScRsp = 90;\n public static final int SetHeadIconScRsp = 2884;\n public static final int AcceptExpeditionCsReq = 2504;\n public static final int HandleRogueCommonPendingActionCsReq = 5679;\n public static final int LogisticsInfoScNotify = 4765;\n public static final int DailyFirstMeetPamScRsp = 3484;\n public static final int ChessRogueQuestFinishNotify = 5490;\n public static final int RechargeSuccNotify = 559;\n public static final int SyncRogueMapRoomScNotify = 1816;\n public static final int SetCurWaypointCsReq = 404;\n public static final int ChessRogueUpdateAllowedSelectCellScNotify = 5444;\n public static final int SceneEntityTeleportCsReq = 1426;\n public static final int ChessRogueCheatRollScRsp = 5542;\n public static final int UnlockTutorialScRsp = 1660;\n public static final int UnlockTeleportNotify = 1429;\n public static final int SetFriendRemarkNameScRsp = 2980;\n public static final int GetFriendListInfoCsReq = 2983;\n public static final int ExchangeHcoinCsReq = 580;\n public static final int HeliobusLineupUpdateScNotify = 5808;\n public static final int ChessRogueQueryBpCsReq = 5558;\n public static final int TakeChapterRewardCsReq = 419;\n public static final int SelectPhoneThemeScRsp = 5142;\n public static final int SyncRoguePickAvatarInfoScNotify = 1875;\n public static final int TakeRogueMiracleHandbookRewardScRsp = 5614;\n public static final int GetSaveLogisticsMapCsReq = 4706;\n public static final int StartChallengeScRsp = 1784;\n public static final int PVEBattleResultScRsp = 161;\n public static final int UpdateRedDotDataCsReq = 5904;\n public static final int FinishPlotCsReq = 1183;\n public static final int BuyGoodsScRsp = 1584;\n public static final int BuyRogueShopBuffCsReq = 5638;\n public static final int ExpeditionDataChangeScNotify = 2597;\n public static final int FinishTutorialCsReq = 1697;\n public static final int GroupStateChangeScRsp = 1412;\n public static final int SyncRogueReviveInfoScNotify = 1824;\n public static final int HeliobusUpgradeLevelCsReq = 5855;\n public static final int HeliobusSelectSkillCsReq = 5852;\n public static final int PlayerKickOutScNotify = 97;\n public static final int FinishFirstTalkByPerformanceNpcScRsp = 2164;\n public static final int SyncClientResVersionCsReq = 142;\n public static final int SceneUpdatePositionVersionNotify = 1409;\n public static final int TrainVisitorRewardSendNotify = 3760;\n public static final int GetMarkItemListCsReq = 577;\n public static final int AetherDivideRefreshEndlessScRsp = 4894;\n public static final int EnterTrialActivityStageScRsp = 2685;\n public static final int ChessRogueSkipTeachingLevelScRsp = 5539;\n public static final int EntityBindPropCsReq = 1493;\n public static final int GetMultipleDropInfoCsReq = 4683;\n public static final int GetDailyActiveInfoCsReq = 3304;\n public static final int GetPhoneDataCsReq = 5183;\n public static final int SpaceZooExchangeItemCsReq = 6709;\n public static final int ChessRogueReRollDiceCsReq = 5581;\n public static final int PlayerHeartBeatScRsp = 98;\n public static final int SecurityReportScRsp = 4109;\n public static final int GetPrivateChatHistoryCsReq = 3982;\n public static final int PlayerReturnTakeRewardCsReq = 4542;\n public static final int GetSingleRedDotParamGroupScRsp = 5960;\n public static final int RankUpAvatarCsReq = 364;\n public static final int GameplayCounterCountDownScRsp = 1402;\n public static final int GetRogueHandbookDataCsReq = 5627;\n public static final int SceneCastSkillScRsp = 1460;\n public static final int ChessRogueGoAheadScRsp = 5525;\n public static final int ChessRogueChangeyAeonDimensionNotify = 5550;\n public static final int ChessRogueNousGetRogueTalentInfoCsReq = 5596;\n public static final int GetTutorialCsReq = 1683;\n public static final int GetArchiveDataScRsp = 2361;\n public static final int SyncAddBlacklistScNotify = 2945;\n public static final int AlleyTakeEventRewardCsReq = 4753;\n public static final int ExchangeRogueRewardKeyCsReq = 1851;\n public static final int ChessRogueGiveUpCsReq = 5477;\n public static final int ChessRogueQuitCsReq = 5415;\n public static final int QueryProductInfoScRsp = 25;\n public static final int StartTimedFarmElementScRsp = 1469;\n public static final int ReplaceLineupCsReq = 790;\n public static final int GetTrainVisitorRegisterCsReq = 3742;\n public static final int SetBoxingClubResonanceLineupCsReq = 4255;\n public static final int GetAllRedDotDataCsReq = 5983;\n public static final int UseItemCsReq = 542;\n public static final int ShareScRsp = 4161;\n public static final int StartTrialActivityCsReq = 2698;\n public static final int GetStrongChallengeActivityDataCsReq = 6683;\n public static final int TakeAllApRewardScRsp = 3342;\n public static final int GetTrialActivityDataScRsp = 2671;\n public static final int GetChessRogueBuffEnhanceInfoCsReq = 5552;\n public static final int GetFriendApplyListInfoScRsp = 2960;\n public static final int GetPlayerBoardDataCsReq = 2883;\n public static final int UnlockSkilltreeCsReq = 382;\n public static final int TakeAllRewardCsReq = 3019;\n public static final int ChessRogueQueryAeonDimensionsCsReq = 5530;\n public static final int PunkLordMonsterInfoScNotify = 3240;\n public static final int NewMailScNotify = 897;\n public static final int ChessRogueStartScRsp = 5589;\n public static final int GetRogueInfoScRsp = 1861;\n public static final int RogueModifierSelectCellCsReq = 5384;\n public static final int LogisticsGameScRsp = 4784;\n public static final int TakePromotionRewardCsReq = 392;\n public static final int ShowNewSupplementVisitorCsReq = 3749;\n public static final int GetAssistListCsReq = 2987;\n public static final int EnterAdventureCsReq = 1383;\n public static final int GetAetherDivideInfoScRsp = 4809;\n public static final int GetCurAssistScRsp = 2994;\n public static final int GetNpcStatusScRsp = 2784;\n public static final int RogueNpcDisappearScRsp = 5655;\n public static final int GetEnhanceCommonRogueBuffInfoScRsp = 5680;\n public static final int RankUpEquipmentScRsp = 538;\n public static final int GetMonsterResearchActivityDataScRsp = 2645;\n public static final int SellItemScRsp = 592;\n public static final int FinishChessRogueNousSubStoryScRsp = 5441;\n public static final int GetPlatformPlayerInfoScRsp = 2918;\n public static final int SpaceZooTakeCsReq = 6764;\n public static final int AddAvatarScNotify = 355;\n public static final int SelectChessRogueSubStoryScRsp = 5560;\n public static final int FinishQuestScRsp = 949;\n public static final int SyncChessRogueNousValueScNotify = 5522;\n public static final int ChangeLineupLeaderScRsp = 740;\n public static final int TakePictureCsReq = 4182;\n public static final int GetBagScRsp = 561;\n public static final int GetHeroBasicTypeInfoCsReq = 77;\n public static final int GetChatFriendHistoryCsReq = 3942;\n public static final int GetPunkLordMonsterDataScRsp = 3261;\n public static final int SavePointsInfoNotify = 1453;\n public static final int DeleteBlacklistCsReq = 2908;\n public static final int PrivateMsgOfflineUsersScNotify = 3984;\n public static final int TakeActivityExpeditionRewardCsReq = 2564;\n public static final int UnlockBackGroundMusicCsReq = 3182;\n public static final int GetPlayerReplayInfoScRsp = 3584;\n public static final int ClientObjUploadCsReq = 2;\n public static final int GetChallengeRaidInfoScRsp = 2242;\n public static final int GetRogueScoreRewardInfoScRsp = 1802;\n public static final int GetLoginChatInfoCsReq = 3940;\n public static final int QuitLineupCsReq = 742;\n public static final int GetFirstTalkNpcCsReq = 2182;\n public static final int GetAvatarDataCsReq = 383;\n public static final int GetBoxingClubInfoScRsp = 4261;\n public static final int StartAetherDivideSceneBattleCsReq = 4882;\n public static final int TakeChallengeRewardScRsp = 1752;\n public static final int DressRelicAvatarCsReq = 352;\n public static final int FightTreasureDungeonMonsterCsReq = 4473;\n public static final int GetFantasticStoryActivityDataScRsp = 4961;\n public static final int ChooseBoxingClubResonanceScRsp = 4209;\n public static final int GetAetherDivideChallengeInfoCsReq = 4833;\n public static final int GetRogueEndlessActivityDataScRsp = 6061;\n public static final int GetMissionEventDataCsReq = 1240;\n public static final int StopRogueAdventureRoomScRsp = 5633;\n public static final int GetBattleCollegeDataScRsp = 5761;\n public static final int SyncRogueAdventureRoomInfoScNotify = 5683;\n public static final int TakePrestigeRewardScRsp = 4709;\n public static final int LockEquipmentScRsp = 560;\n public static final int SetLineupNameScRsp = 720;\n public static final int HeliobusStartRaidScRsp = 5890;\n public static final int HeliobusChallengeUpdateScNotify = 5846;\n public static final int HeliobusActivityDataScRsp = 5861;\n public static final int GetShareDataScRsp = 4184;\n public static final int SpringRefreshScRsp = 1420;\n public static final int GetCurLineupDataScRsp = 784;\n public static final int HeliobusSnsCommentCsReq = 5897;\n public static final int PrestigeLevelUpCsReq = 4759;\n public static final int SetStuffToAreaCsReq = 4382;\n public static final int GetCurChallengeCsReq = 1738;\n public static final int SetMissionEventProgressScRsp = 1208;\n public static final int SubMissionRewardScNotify = 1233;\n public static final int StartFinishSubMissionScNotify = 1287;\n public static final int TakeTalkRewardCsReq = 2104;\n public static final int ChessRogueUpdateMoneyInfoScNotify = 5480;\n public static final int TakeBpRewardScRsp = 3082;\n public static final int GetRaidInfoScRsp = 2209;\n public static final int CityShopInfoScNotify = 1542;\n public static final int SpaceZooDataScRsp = 6761;\n public static final int PromoteAvatarScRsp = 319;\n public static final int ChessRogueGiveUpRollScRsp = 5509;\n public static final int SetLanguageCsReq = 65;\n public static final int DeactivateFarmElementCsReq = 1416;\n public static final int ReportPlayerCsReq = 2990;\n public static final int SyncAcceptedPamMissionNotify = 4004;\n public static final int DressAvatarCsReq = 397;\n public static final int TakeExpeditionRewardCsReq = 2542;\n public static final int TrainVisitorBehaviorFinishCsReq = 3783;\n public static final int TakeMonsterResearchActivityRewardCsReq = 2659;\n public static final int SpaceZooDeleteCatScRsp = 6738;\n public static final int OpenTreasureDungeonGridScRsp = 4452;\n public static final int GetRogueAeonInfoScRsp = 1801;\n public static final int QuitTreasureDungeonScRsp = 4446;\n public static final int EnterFightActivityStageScRsp = 3682;\n public static final int RogueModifierDelNotify = 5397;\n public static final int RaidInfoNotify = 2282;\n public static final int UpgradeAreaScRsp = 4364;\n public static final int ChessRogueQueryScRsp = 5425;\n public static final int MuseumRandomEventQueryScRsp = 4359;\n public static final int SearchPlayerScRsp = 2965;\n public static final int TeleportToMissionResetPointScRsp = 1265;\n public static final int GmTalkScRsp = 49;\n public static final int GetCurSceneInfoCsReq = 1442;\n public static final int CancelExpeditionCsReq = 2582;\n public static final int SyncApplyFriendScNotify = 2997;\n public static final int EnteredSceneChangeScNotify = 1432;\n public static final int GetAllServerPrefsDataCsReq = 6183;\n public static final int SyncRogueVirtualItemInfoScNotify = 1857;\n public static final int EnhanceRogueBuffScRsp = 1833;\n public static final int SpaceZooCatUpdateNotify = 6749;\n public static final int GetRogueTalentInfoScRsp = 1839;\n public static final int HeliobusSnsPostCsReq = 5882;\n public static final int RogueModifierAddNotify = 5304;\n public static final int AcceptActivityExpeditionScRsp = 2549;\n public static final int PunkLordDataChangeNotify = 3224;\n public static final int SetClientRaidTargetCountScRsp = 2264;\n public static final int ChessRogueUpdateDiceInfoScNotify = 5511;\n public static final int StartPunkLordRaidCsReq = 3204;\n public static final int GetChallengeGroupStatisticsScRsp = 1745;\n public static final int ChessRogueEnterCellCsReq = 5483;\n public static final int GetSaveRaidCsReq = 2240;\n public static final int ChallengeSettleNotify = 1742;\n public static final int RecoverAllLineupScRsp = 1494;\n public static final int DoGachaScRsp = 1984;\n public static final int RefreshTriggerByClientScNotify = 1423;\n public static final int ChessRogueLeaveScRsp = 5429;\n public static final int ReviveRogueAvatarScRsp = 1892;\n public static final int RemoveStuffFromAreaCsReq = 4342;\n public static final int GetFirstTalkByPerformanceNpcCsReq = 2149;\n public static final int SetAssistCsReq = 2924;\n public static final int SyncRogueHandbookDataUpdateScNotify = 5656;\n public static final int SpaceZooOpCatteryScRsp = 6719;\n public static final int SetPlayerInfoCsReq = 22;\n public static final int GetAssistHistoryCsReq = 2953;\n public static final int ShowNewSupplementVisitorScRsp = 3709;\n public static final int ChessRogueConfirmRollCsReq = 5476;\n public static final int PickRogueAvatarCsReq = 1852;\n public static final int GetRogueInfoCsReq = 1883;\n public static final int ChooseBoxingClubStageOptionalBuffCsReq = 4240;\n public static final int TakeRogueAeonLevelRewardScRsp = 1830;\n public static final int SetGroupCustomSaveDataCsReq = 1498;\n public static final int GetUpdatedArchiveDataScRsp = 2384;\n public static final int AetherDivideSpiritExpUpScRsp = 4846;\n public static final int MissionEventRewardScNotify = 1273;\n public static final int HeliobusInfoChangedScNotify = 5809;\n public static final int FantasticStoryActivityBattleEndScNotify = 4960;\n public static final int GetStuffScNotify = 4397;\n public static final int TakePromotionRewardScRsp = 359;\n public static final int GetFirstTalkNpcScRsp = 2160;\n public static final int GetRogueTalentInfoCsReq = 1807;\n public static final int SceneEntityUpdateScNotify = 1497;\n public static final int GameplayCounterRecoverCsReq = 1450;\n public static final int PromoteEquipmentCsReq = 504;\n public static final int GetRogueAdventureRoomInfoCsReq = 5664;\n public static final int EnterSectionScRsp = 1465;\n public static final int TakeAssistRewardCsReq = 2993;\n public static final int GetLineupAvatarDataCsReq = 709;\n public static final int GetChessRogueStoryInfoCsReq = 5409;\n public static final int HeliobusUnlockSkillScNotify = 5840;\n public static final int TakeTrialActivityRewardCsReq = 2686;\n public static final int GetHeroBasicTypeInfoScRsp = 94;\n public static final int TakeRogueEndlessActivityPointRewardCsReq = 6060;\n public static final int QuitRogueScRsp = 1877;\n public static final int SwitchAetherDivideLineUpSlotCsReq = 4820;\n public static final int GateServerScNotify = 13;\n public static final int UnlockTutorialGuideCsReq = 1642;\n public static final int MuseumTargetRewardNotify = 4388;\n public static final int PlayerLoginFinishCsReq = 96;\n public static final int StartRaidCsReq = 2283;\n public static final int GetPunkLordMonsterDataCsReq = 3283;\n public static final int EnterSceneScRsp = 1472;\n public static final int ChessRogueEnterNextLayerCsReq = 5412;\n public static final int BatchMarkChatEmojiCsReq = 3955;\n public static final int SceneGroupRefreshScNotify = 1431;\n public static final int GetBasicInfoCsReq = 76;\n public static final int TakeCityShopRewardCsReq = 1582;\n public static final int EnterFantasticStoryActivityStageScRsp = 4982;\n public static final int FinishCurTurnScRsp = 4309;\n public static final int SceneEnterStageScRsp = 1446;\n public static final int RogueEndlessActivityBattleEndScNotify = 6082;\n public static final int TakeOffAvatarSkinScRsp = 308;\n public static final int AlleyShipmentEventEffectsScNotify = 4787;\n public static final int GetChallengeScRsp = 1761;\n public static final int MuseumDispatchFinishedScNotify = 4346;\n public static final int GetGachaInfoScRsp = 1961;\n public static final int GetExpeditionDataScRsp = 2561;\n public static final int TextJoinSaveScRsp = 3861;\n public static final int SelectChessRogueNousSubStoryScRsp = 5449;\n public static final int ChessRogueEnterCsReq = 5501;\n public static final int ExchangeRogueBuffWithMiracleCsReq = 5620;\n public static final int HeliobusSnsCommentScRsp = 5838;\n public static final int MonthCardRewardNotify = 85;\n public static final int SelectPhoneThemeCsReq = 5160;\n public static final int FinishTutorialGuideScRsp = 1609;\n public static final int SetCurInteractEntityScRsp = 1478;\n public static final int PunkLordMonsterKilledNotify = 3265;\n public static final int TakeOffRelicScRsp = 320;\n public static final int GetMultipleDropInfoScRsp = 4661;\n public static final int TakeApRewardCsReq = 3383;\n public static final int GetUnlockTeleportScRsp = 1434;\n public static final int GetMissionDataScRsp = 1261;\n public static final int StartAetherDivideSceneBattleScRsp = 4860;\n public static final int ChessRogueReviveAvatarCsReq = 5510;\n public static final int SceneEntityDisappearScNotify = 1438;\n public static final int GetMainMissionCustomValueScRsp = 1294;\n public static final int TextJoinQueryScRsp = 3884;\n public static final int DressRelicAvatarScRsp = 373;\n public static final int LeaveRaidCsReq = 2204;\n public static final int HeliobusStartRaidCsReq = 5880;\n public static final int SpringRecoverSingleAvatarScRsp = 1486;\n public static final int DailyFirstMeetPamCsReq = 3404;\n public static final int TakeMonsterResearchActivityRewardScRsp = 2680;\n public static final int FinishRogueDialogueGroupCsReq = 1879;\n public static final int SyncEntityBuffChangeListScNotify = 1455;\n public static final int SetFriendRemarkNameCsReq = 2959;\n public static final int FinishFirstTalkNpcCsReq = 2142;\n public static final int HeliobusSnsLikeScRsp = 5819;\n public static final int EnterRogueMapRoomCsReq = 1856;\n public static final int MatchBoxingClubOpponentCsReq = 4204;\n public static final int EnterTreasureDungeonCsReq = 4455;\n public static final int GetFantasticStoryActivityDataCsReq = 4983;\n public static final int SpaceZooDataCsReq = 6783;\n public static final int TriggerVoiceScRsp = 4164;\n public static final int PrepareRogueAdventureRoomCsReq = 5661;\n public static final int AceAntiCheaterCsReq = 79;\n public static final int GetRogueShopBuffInfoCsReq = 5660;\n public static final int SetForbidOtherApplyFriendScRsp = 2943;\n public static final int ExpUpEquipmentScRsp = 509;\n public static final int SetDisplayAvatarScRsp = 2860;\n public static final int ChessRogueRollDiceCsReq = 5526;\n public static final int GetTutorialGuideCsReq = 1604;\n public static final int MultipleDropInfoScNotify = 4604;\n public static final int ChessRogueMoveCellNotify = 5470;\n public static final int DelMailCsReq = 882;\n public static final int ChessRogueUpdateAeonModifierValueScNotify = 5506;\n public static final int GetServerPrefsDataScRsp = 6184;\n public static final int GetChatEmojiListScRsp = 3938;\n public static final int SetAssistAvatarScRsp = 2855;\n public static final int GetRogueDialogueEventDataCsReq = 1844;\n public static final int TakePunkLordPointRewardCsReq = 3255;\n public static final int QuitBattleScRsp = 184;\n public static final int TakeTrainVisitorUntakenBehaviorRewardCsReq = 3797;\n public static final int SelectChatBubbleCsReq = 5104;\n public static final int MissionRewardScNotify = 1282;\n public static final int SyncRogueSeasonFinishScNotify = 1803;\n public static final int MuseumTakeCollectRewardScRsp = 4387;\n public static final int UnlockedAreaMapScNotify = 1415;\n public static final int CancelCacheNotifyCsReq = 4197;\n public static final int GetMuseumInfoScRsp = 4361;\n public static final int PlayerLoginCsReq = 83;\n public static final int ChessRogueUpdateLevelBaseInfoScNotify = 5563;\n public static final int GetFriendLoginInfoScRsp = 2925;\n public static final int GetChapterCsReq = 482;\n public static final int GetSaveLogisticsMapScRsp = 4724;\n public static final int GetTrialActivityDataCsReq = 2644;\n public static final int GetTrainVisitorBehaviorCsReq = 3704;\n public static final int GetSpringRecoverDataCsReq = 1476;\n public static final int SharePunkLordMonsterScRsp = 3260;\n public static final int GetActivityScheduleConfigScRsp = 2660;\n public static final int GetFriendRecommendListInfoCsReq = 2920;\n public static final int GetRogueHandbookDataScRsp = 5693;\n public static final int HandleRogueCommonPendingActionScRsp = 5689;\n public static final int ChessRogueNousGetRogueTalentInfoScRsp = 5573;\n public static final int GetSceneMapInfoScRsp = 1474;\n public static final int UpdatePlayerSettingScRsp = 91;\n public static final int GetMailCsReq = 883;\n public static final int FeatureSwitchClosedScNotify = 63;\n public static final int TakeQuestRewardScRsp = 984;\n public static final int TakeKilledPunkLordMonsterScoreCsReq = 3287;\n public static final int AetherDivideSpiritInfoScNotify = 4808;\n public static final int SaveLogisticsCsReq = 4733;\n public static final int GetRndOptionScRsp = 3461;\n public static final int SpaceZooBornScRsp = 6784;\n public static final int HandleFriendCsReq = 2938;\n public static final int GetPlayerDetailInfoScRsp = 2984;\n public static final int RevcMsgScNotify = 3904;\n public static final int InterruptMissionEventCsReq = 1280;\n public static final int TakeQuestOptionalRewardScRsp = 955;\n public static final int LeaveTrialActivityCsReq = 2663;\n public static final int StaminaInfoScNotify = 34;\n public static final int GetMissionStatusScRsp = 1259;\n public static final int SetAetherDivideLineUpScRsp = 4864;\n public static final int ClearAetherDividePassiveSkillCsReq = 4873;\n public static final int FinishTalkMissionScRsp = 1284;\n public static final int GetPunkLordBattleRecordCsReq = 3278;\n public static final int SetClientPausedScRsp = 1414;\n public static final int AetherDivideTakeChallengeRewardCsReq = 4803;\n public static final int ChessRogueQuitScRsp = 5551;\n public static final int FinishSectionIdCsReq = 2742;\n public static final int FinishPerformSectionIdCsReq = 2797;\n public static final int VirtualLineupDestroyNotify = 780;\n public static final int GetSingleRedDotParamGroupCsReq = 5982;\n public static final int MarkItemScRsp = 503;\n public static final int PlayerReturnSignScRsp = 4504;\n public static final int ActivateFarmElementScRsp = 1443;\n public static final int ReturnLastTownCsReq = 1459;\n public static final int StartAlleyEventScRsp = 4719;\n public static final int FinishTutorialScRsp = 1638;\n public static final int PlayerLogoutScRsp = 84;\n public static final int GetEnteredSceneCsReq = 1401;\n public static final int SelectRogueDialogueEventCsReq = 1896;\n public static final int StartChallengeCsReq = 1704;\n public static final int GetMarkItemListScRsp = 594;\n public static final int SetSpringRecoverConfigCsReq = 1468;\n public static final int GetAllLineupDataScRsp = 759;\n public static final int CancelMarkItemNotify = 527;\n public static final int SetGameplayBirthdayCsReq = 44;\n public static final int SyncRogueAreaUnlockScNotify = 1862;\n public static final int DestroyItemCsReq = 524;\n public static final int GetChessRogueNousStoryInfoScRsp = 5568;\n public static final int GetPunkLordDataScRsp = 3273;\n public static final int TakeFightActivityRewardScRsp = 3642;\n public static final int SummonPunkLordMonsterCsReq = 3242;\n public static final int StartAetherDivideStageBattleScRsp = 4880;\n public static final int GetRecyleTimeScRsp = 565;\n public static final int GetNpcTakenRewardCsReq = 2183;\n public static final int ExchangeGachaCeilingScRsp = 1919;\n public static final int GetGachaCeilingScRsp = 1960;\n public static final int FinishChessRogueSubStoryCsReq = 5401;\n public static final int TrialBackGroundMusicCsReq = 3142;\n public static final int GetRecyleTimeCsReq = 588;\n public static final int AddEquipmentScNotify = 533;\n public static final int ChessRogueSelectBpScRsp = 5571;\n public static final int GetNpcMessageGroupScRsp = 2761;\n public static final int GetKilledPunkLordMonsterDataCsReq = 3246;\n public static final int OpenRogueChestScRsp = 1886;\n public static final int GetVideoVersionKeyCsReq = 72;\n public static final int GetPlayerReturnMultiDropInfoCsReq = 4684;\n public static final int GetAlleyInfoScRsp = 4761;\n public static final int AddBlacklistScRsp = 2973;\n public static final int TextJoinBatchSaveScRsp = 3860;\n public static final int ClearAetherDividePassiveSkillScRsp = 4845;\n public static final int TakeLoginActivityRewardCsReq = 2604;\n public static final int GetStrongChallengeActivityDataScRsp = 6661;\n public static final int DestroyItemScRsp = 578;\n public static final int GetJukeboxDataCsReq = 3183;\n public static final int SyncRogueAeonLevelUpRewardScNotify = 1891;\n public static final int TakeRogueEndlessActivityAllBonusRewardScRsp = 6097;\n public static final int SyncTaskCsReq = 1260;\n public static final int SyncChessRogueNousMainStoryScNotify = 5502;\n public static final int UpdateRogueAdventureRoomScoreCsReq = 5643;\n public static final int FinishItemIdScRsp = 2760;\n public static final int MuseumRandomEventSelectScRsp = 4390;\n public static final int ExpUpRelicCsReq = 540;\n public static final int GetSceneMapInfoCsReq = 1495;\n public static final int SpaceZooMutateScRsp = 6760;\n public static final int ComposeItemScRsp = 564;\n public static final int EnterChessRogueAeonRoomScRsp = 5519;\n public static final int PlayerLoginScRsp = 61;\n public static final int GameplayCounterCountDownCsReq = 1410;\n public static final int ChessRogueLayerAccountInfoNotify = 5468;\n public static final int GetStageLineupCsReq = 783;\n public static final int AlleyFundsScNotify = 4790;\n public static final int EnterStrongChallengeActivityStageCsReq = 6604;\n public static final int GetChapterScRsp = 460;\n public static final int MuseumFundsChangedScNotify = 4345;\n public static final int EnhanceCommonRogueBuffScRsp = 5646;\n public static final int ReEnterLastElementStageCsReq = 1411;\n public static final int TakeRogueEventHandbookRewardScRsp = 5616;\n public static final int ChessRogueUpdateActionPointScNotify = 5431;\n public static final int UpgradeAreaStatScRsp = 4352;\n public static final int UnlockTutorialCsReq = 1682;\n public static final int GetLevelRewardScRsp = 8;\n public static final int AvatarExpUpScRsp = 384;\n public static final int MuseumTargetStartNotify = 4308;\n public static final int AlleyEventChangeNotify = 4797;\n public static final int TakeQuestOptionalRewardCsReq = 909;\n public static final int GetWaypointScRsp = 461;\n public static final int GetMailScRsp = 861;\n public static final int GetReplayTokenScRsp = 3561;\n public static final int StartBoxingClubBattleCsReq = 4282;\n public static final int UpdateServerPrefsDataScRsp = 6160;\n public static final int TakeChallengeRaidRewardCsReq = 2219;\n public static final int SceneEntityMoveCsReq = 1483;\n public static final int GetChatFriendHistoryScRsp = 3919;\n public static final int TakePunkLordPointRewardScRsp = 3264;\n public static final int GetMuseumInfoCsReq = 4383;\n public static final int SetTurnFoodSwitchCsReq = 556;\n public static final int BattleCollegeDataChangeScNotify = 5704;\n public static final int SetAssistAvatarCsReq = 2809;\n public static final int GetMonsterResearchActivityDataCsReq = 2673;\n public static final int SyncRogueDialogueEventDataScNotify = 1872;\n public static final int SetGenderCsReq = 93;\n public static final int EnterAdventureScRsp = 1361;\n public static final int LogisticsGameCsReq = 4704;\n public static final int GetChatEmojiListCsReq = 3997;\n public static final int DressAvatarSkinScRsp = 390;\n public static final int GetAssistListScRsp = 2906;\n public static final int AetherDivideTakeChallengeRewardScRsp = 4827;\n public static final int SetClientRaidTargetCountCsReq = 2255;\n public static final int GetMissionStatusCsReq = 1292;\n public static final int RogueNpcDisappearCsReq = 5609;\n public static final int GetNpcStatusCsReq = 2704;\n public static final int GetTrainVisitorRegisterScRsp = 3719;\n public static final int ChessRoguePickAvatarCsReq = 5434;\n public static final int ChessRogueNousEnableRogueTalentCsReq = 5433;\n public static final int GetBattleCollegeDataCsReq = 5783;\n public static final int InteractTreasureDungeonGridCsReq = 4420;\n public static final int SetSignatureScRsp = 2849;\n public static final int SyncServerSceneChangeNotify = 1430;\n public static final int EquipAetherDividePassiveSkillScRsp = 4852;\n public static final int SelectChessRogueSubStoryCsReq = 5407;\n public static final int GetChallengeRaidInfoCsReq = 2260;\n public static final int UnlockChatBubbleScNotify = 5182;\n public static final int HealPoolInfoNotify = 1489;\n public static final int SetForbidOtherApplyFriendCsReq = 2970;\n public static final int ReEnterLastElementStageScRsp = 1435;\n public static final int InterruptMissionEventScRsp = 1290;\n public static final int GetPlatformPlayerInfoCsReq = 2914;\n public static final int GetAetherDivideInfoCsReq = 4849;\n public static final int RefreshTriggerByClientScRsp = 1439;\n public static final int ClientObjUploadScRsp = 54;\n public static final int AvatarExpUpCsReq = 304;\n public static final int GetArchiveDataCsReq = 2383;\n public static final int GetPlayerDetailInfoCsReq = 2904;\n public static final int GetShopListCsReq = 1583;\n public static final int CancelExpeditionScRsp = 2560;\n public static final int LockRelicScRsp = 545;\n public static final int FinishRogueDialogueGroupScRsp = 1889;\n public static final int GetPrivateChatHistoryScRsp = 3960;\n public static final int StartPunkLordRaidScRsp = 3284;\n public static final int SceneCastSkillCsReq = 1482;\n public static final int ChessRogueStartCsReq = 5554;\n public static final int EnterRogueMapRoomScRsp = 1822;\n public static final int SaveLogisticsScRsp = 4788;\n public static final int SyncRogueCommonActionResultScNotify = 5625;\n public static final int AcceptedPamMissionExpireCsReq = 4083;\n public static final int GetNpcMessageGroupCsReq = 2783;\n public static final int HeliobusSnsReadScRsp = 5884;\n public static final int SpringRecoverSingleAvatarCsReq = 1485;\n public static final int MuseumTargetMissionFinishNotify = 4333;\n public static final int QuitTreasureDungeonCsReq = 4490;\n public static final int GetBagCsReq = 583;\n public static final int TakePictureScRsp = 4160;\n public static final int SetRedPointStatusScNotify = 62;\n public static final int FinishChessRogueNousSubStoryCsReq = 5504;\n public static final int GetLoginActivityScRsp = 2661;\n public static final int DressAvatarScRsp = 338;\n public static final int ChessRogueQueryCsReq = 5564;\n public static final int TeleportToMissionResetPointCsReq = 1288;\n public static final int UpgradeAreaCsReq = 4355;\n public static final int ChessRogueNousEditDiceScRsp = 5440;\n public static final int DailyActiveInfoNotify = 3382;\n public static final int ExchangeGachaCeilingCsReq = 1942;\n public static final int SceneCastSkillMpUpdateScNotify = 1452;\n public static final int AetherDivideSkillItemScNotify = 4806;\n public static final int RaidKickByServerScNotify = 2292;\n public static final int DelMailScRsp = 860;\n public static final int ChessRogueSkipTeachingLevelCsReq = 5489;\n public static final int GetGachaCeilingCsReq = 1982;\n public static final int SyncClientResVersionScRsp = 119;\n public static final int FinishFirstTalkByPerformanceNpcCsReq = 2155;\n public static final int StartCocoonStageCsReq = 1403;\n public static final int DeleteFriendCsReq = 2955;\n public static final int PlayBackGroundMusicScRsp = 3184;\n public static final int ChessRogueEnterCellScRsp = 5547;\n public static final int MuseumInfoChangedScNotify = 4373;\n public static final int StartBattleCollegeCsReq = 5784;\n public static final int GetCurChallengeScRsp = 1749;\n public static final int GetTreasureDungeonActivityDataCsReq = 4449;\n public static final int GetMainMissionCustomValueCsReq = 1277;\n public static final int FinishCosumeItemMissionScRsp = 1264;\n public static final int PlayerReturnInfoQueryCsReq = 4597;\n public static final int GetPhoneDataScRsp = 5161;\n public static final int GetLevelRewardCsReq = 46;\n public static final int GetChessRogueStoryAeonTalkInfoScRsp = 5578;\n public static final int UpgradeAreaStatCsReq = 4340;\n public static final int EnhanceRogueBuffCsReq = 1808;\n public static final int TakeApRewardScRsp = 3361;\n public static final int ChessRogueQueryBpScRsp = 5416;\n public static final int GetNpcTakenRewardScRsp = 2161;\n public static final int GetShareDataCsReq = 4104;\n public static final int TakeMailAttachmentCsReq = 842;\n public static final int HandleFriendScRsp = 2949;\n public static final int AetherDivideRefreshEndlessScNotify = 4853;\n public static final int SearchPlayerCsReq = 2988;\n public static final int HeliobusSelectSkillScRsp = 5873;\n public static final int SelectRogueDialogueEventScRsp = 1817;\n public static final int EnterSectionCsReq = 1488;\n public static final int EnterChessRogueAeonRoomCsReq = 5419;\n public static final int QuitLineupScRsp = 719;\n public static final int DeleteBlacklistScRsp = 2933;\n public static final int EnterFightActivityStageCsReq = 3684;\n public static final int TakeKilledPunkLordMonsterScoreScRsp = 3206;\n public static final int ComposeLimitNumCompleteNotify = 587;\n public static final int SpaceZooBornCsReq = 6704;\n public static final int GetJukeboxDataScRsp = 3161;\n public static final int SetNicknameScRsp = 59;\n public static final int TakeRogueMiracleHandbookRewardCsReq = 5622;\n public static final int GameplayCounterRecoverScRsp = 1441;\n public static final int GetSpringRecoverDataScRsp = 1467;\n public static final int TakeExpeditionRewardScRsp = 2519;\n public static final int GetVideoVersionKeyScRsp = 48;\n public static final int TakeRogueEndlessActivityAllBonusRewardCsReq = 6019;\n public static final int SyncTurnFoodNotify = 593;\n public static final int FinishTalkMissionCsReq = 1204;\n public static final int RefreshAlleyOrderCsReq = 4773;\n public static final int PlayerReturnTakePointRewardScRsp = 4560;\n public static final int FinishSectionIdScRsp = 2719;\n public static final int SpaceZooDeleteCatCsReq = 6797;\n public static final int GetFarmStageGachaInfoScRsp = 1384;\n public static final int JoinLineupScRsp = 760;\n public static final int GetCurBattleInfoCsReq = 182;\n public static final int ChooseBoxingClubResonanceCsReq = 4249;\n public static final int SetHeroBasicTypeScRsp = 78;\n public static final int GetKilledPunkLordMonsterDataScRsp = 3208;\n public static final int ChallengeRaidNotify = 2238;\n public static final int AddBlacklistCsReq = 2952;\n public static final int GetRogueAeonInfoCsReq = 1866;\n public static final int AcceptExpeditionScRsp = 2584;\n public static final int FightActivityDataChangeScNotify = 3604;\n public static final int TrialBackGroundMusicScRsp = 3119;\n public static final int OpenRogueChestCsReq = 1885;\n public static final int QuitRogueCsReq = 1878;\n public static final int ComposeSelectedRelicScRsp = 508;\n public static final int GetLineupAvatarDataScRsp = 755;\n public static final int ChessRogueSelectCellCsReq = 5497;\n public static final int AcceptMissionEventCsReq = 1245;\n public static final int PunkLordRaidTimeOutScNotify = 3220;\n public static final int EnableRogueTalentScRsp = 1847;\n public static final int TakeAssistRewardScRsp = 2956;\n public static final int GetChessRogueNousStoryInfoCsReq = 5404;\n public static final int SpaceZooOpCatteryCsReq = 6742;\n public static final int AlleyGuaranteedFundsScRsp = 4794;\n public static final int MarkReadMailCsReq = 804;\n public static final int GetRogueShopMiracleInfoScRsp = 5682;\n public static final int GetRogueBuffEnhanceInfoCsReq = 1890;\n public static final int SelectInclinationTextCsReq = 2197;\n public static final int PunkLordBattleResultScNotify = 3290;\n public static final int BuyBpLevelCsReq = 3060;\n public static final int SetAssistScRsp = 2978;\n public static final int PlayerReturnPointChangeScNotify = 4584;\n public static final int SetPlayerInfoScRsp = 14;\n public static final int SetIsDisplayAvatarInfoCsReq = 2842;\n public static final int EnterAetherDivideSceneScRsp = 4861;\n public static final int CommonRogueQueryCsReq = 5685;\n public static final int SwapLineupCsReq = 797;\n public static final int ChessRogueLeaveCsReq = 5421;\n public static final int PlayerReturnForceFinishScNotify = 4549;\n public static final int DoGachaCsReq = 1904;\n public static final int SpringRecoverScRsp = 1479;\n public static final int ChessRogueConfirmRollScRsp = 5545;\n public static final int ReplaceLineupScRsp = 746;\n public static final int SubmitMonsterResearchActivityMaterialScRsp = 2692;\n public static final int BatchMarkChatEmojiScRsp = 3964;\n public static final int LogisticsDetonateStarSkiffCsReq = 4727;\n public static final int DeleteSummonUnitScRsp = 1436;\n public static final int GetSaveRaidScRsp = 2252;\n public static final int GetFightActivityDataCsReq = 3683;\n public static final int MuseumRandomEventQueryCsReq = 4392;\n public static final int SyncChessRogueNousSubStoryScNotify = 5496;\n public static final int PlayerLoginFinishScRsp = 17;\n public static final int EnterRogueCsReq = 1882;\n public static final int AetherDivideLineupScNotify = 4878;\n public static final int SyncChessRogueMainStoryFinishScNotify = 5579;\n public static final int AcceptActivityExpeditionCsReq = 2538;\n public static final int GetAuthkeyCsReq = 52;\n public static final int ExpUpEquipmentCsReq = 549;\n public static final int ChessRogueCheatRollCsReq = 5427;\n public static final int GetRogueInitialScoreScRsp = 1818;\n public static final int GetSecretKeyInfoScRsp = 26;\n public static final int MarkChatEmojiCsReq = 3949;\n public static final int ShareCsReq = 4183;\n public static final int SyncRogueGetItemScNotify = 1895;\n public static final int OpenTreasureDungeonGridCsReq = 4440;\n public static final int MissionAcceptScNotify = 1253;\n public static final int ChessRogueGoAheadCsReq = 5559;\n public static final int SceneEntityTeleportScRsp = 1496;\n public static final int GetChessRogueStoryInfoScRsp = 5452;\n public static final int GmTalkCsReq = 38;\n public static final int HeroBasicTypeChangedNotify = 18;\n public static final int UnlockSkilltreeScRsp = 360;\n public static final int PlayerSyncScNotify = 683;\n public static final int SetBoxingClubResonanceLineupScRsp = 4264;\n public static final int GetAllRedDotDataScRsp = 5961;\n public static final int InteractPropCsReq = 1404;\n public static final int SetHeadIconCsReq = 2804;\n public static final int ChessRogueGiveUpRollCsReq = 5512;\n public static final int EnhanceChessRogueBuffScRsp = 5518;\n public static final int ChessRogueGiveUpScRsp = 5517;\n public static final int SendMsgScRsp = 3961;\n public static final int StartTrialActivityScRsp = 2613;\n public static final int PromoteAvatarCsReq = 342;\n public static final int ReportPlayerScRsp = 2946;\n public static final int TakeTalkRewardScRsp = 2184;\n public static final int EnterTrialActivityStageCsReq = 2689;\n public static final int GetAllServerPrefsDataScRsp = 6161;\n public static final int SyncRogueStatusScNotify = 1869;\n public static final int ApplyFriendScRsp = 2919;\n public static final int StartTimedCocoonStageScRsp = 1437;\n public static final int GetDailyActiveInfoScRsp = 3384;\n public static final int StartRogueCsReq = 1804;\n public static final int TakeAllRewardScRsp = 3097;\n public static final int GetAllSaveRaidCsReq = 2273;\n public static final int EnterRogueEndlessActivityStageCsReq = 6004;\n public static final int GetChallengeCsReq = 1783;\n public static final int SyncDeleteFriendScNotify = 2940;\n public static final int GetCurLineupDataCsReq = 704;\n public static final int ExchangeStaminaCsReq = 64;\n public static final int BattleLogReportCsReq = 138;\n public static final int BuyGoodsCsReq = 1504;\n public static final int FinishPlotScRsp = 1161;\n public static final int BuyRogueShopBuffScRsp = 5649;\n public static final int PrestigeLevelUpScRsp = 4780;\n public static final int ChessRogueReviveAvatarScRsp = 5521;\n public static final int StopRogueAdventureRoomCsReq = 5608;\n public static final int GetRaidInfoCsReq = 2249;\n public static final int SyncRogueAeonScNotify = 1848;\n public static final int SetStuffToAreaScRsp = 4360;\n public static final int TakeOffAvatarSkinCsReq = 346;\n public static final int GetRogueScoreRewardInfoCsReq = 1810;\n public static final int AlleyOrderChangedScNotify = 4720;\n public static final int SceneEnterStageCsReq = 1490;\n public static final int TakePrestigeRewardCsReq = 4749;\n public static final int PrepareRogueAdventureRoomScRsp = 5604;\n public static final int TakeBpRewardCsReq = 3084;\n public static final int AlleyPlacingGameScRsp = 4764;\n public static final int TakeChallengeRewardCsReq = 1740;\n public static final int StartTimedFarmElementCsReq = 1457;\n public static final int GetExhibitScNotify = 4338;\n public static final int UpdateRedDotDataScRsp = 5984;\n public static final int GetAetherDivideChallengeInfoScRsp = 4888;\n public static final int GetRogueShopBuffInfoScRsp = 5642;\n public static final int GetLoginChatInfoScRsp = 3952;\n public static final int GroupStateChangeCsReq = 1428;\n public static final int GetPlayerReplayInfoCsReq = 3504;\n public static final int UnlockBackGroundMusicScRsp = 3160;\n public static final int ExchangeRogueRewardKeyScRsp = 1898;\n public static final int GetRogueAdventureRoomInfoScRsp = 5640;\n public static final int TakeActivityExpeditionRewardScRsp = 2540;\n public static final int GetBoxingClubInfoCsReq = 4283;\n public static final int GetUpdatedArchiveDataCsReq = 2304;\n public static final int ReserveStaminaExchangeCsReq = 30;\n public static final int AcceptMainMissionScRsp = 1278;\n public static final int FinishAeonDialogueGroupScRsp = 1832;\n public static final int SceneEntityDieScNotify = 1418;\n public static final int TakeOffEquipmentScRsp = 309;\n public static final int CancelActivityExpeditionScRsp = 2555;\n public static final int TakeChapterRewardScRsp = 497;\n public static final int SetLineupNameCsReq = 745;\n public static final int LeaveRaidScRsp = 2284;\n public static final int SpringRefreshCsReq = 1445;\n public static final int SetCurWaypointScRsp = 484;\n public static final int EnterFantasticStoryActivityStageCsReq = 4984;\n public static final int GetMissionEventDataScRsp = 1252;\n public static final int DailyRefreshNotify = 68;\n public static final int GmTalkScNotify = 19;\n public static final int UseTreasureDungeonItemCsReq = 4459;\n public static final int SelectChessRogueNousSubStoryCsReq = 5516;\n public static final int LeaveRogueCsReq = 1842;\n public static final int PlayerHeartBeatCsReq = 51;\n public static final int GetRogueEndlessActivityDataCsReq = 6083;\n public static final int AetherDivideRefreshEndlessCsReq = 4877;\n public static final int SetCurInteractEntityCsReq = 1424;\n public static final int SpaceZooTakeScRsp = 6740;\n public static final int ChessRogueReRollDiceScRsp = 5533;\n public static final int SecurityReportCsReq = 4149;\n public static final int BuyRogueShopMiracleScRsp = 5697;\n public static final int GetAvatarDataScRsp = 361;\n public static final int RankUpEquipmentCsReq = 597;\n public static final int AntiAddictScNotify = 20;\n public static final int StartAetherDivideChallengeBattleCsReq = 4842;\n public static final int TextJoinSaveCsReq = 3883;\n}", "answers": [" session.send(new PacketGetAvatarDataScRsp(session.getPlayer()));"], "length": 7390, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "7fe93bd9-4b8c-42f9-8cf5-29b4cb436ba9", "reasoning": "The handler’s handle method should respond to the GetAvatarData request by sending a GetAvatarDataScRsp packet. The PacketGetAvatarDataScRsp constructor requires a Player object, which can be obtained from the GameSession via session.getPlayer(). Therefore the next line sends this packet using session.send.", "reasoning_model_answer": "session.send(new PacketGetAvatarDataScRsp(session.getPlayer()));", "assistant_with_reasoning": "\nThe handler’s handle method should respond to the GetAvatarData request by sending a GetAvatarDataScRsp packet. The PacketGetAvatarDataScRsp constructor requires a Player object, which can be obtained from the GameSession via session.getPlayer(). Therefore the next line sends this packet using session.send.\n\nsession.send(new PacketGetAvatarDataScRsp(session.getPlayer()));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.625, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36274, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "session.send(new PacketGetAvatarDataScRsp(session.getPlayer()));", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import frost.storage.FileListCallback;\r\nimport frost.storage.perst.filelist.FileListStorage;\r\nimport frost.util.TextSearchFun;\r\nimport java.util.HashMap;\r\nimport java.util.Iterator;\r\nimport java.util.Map;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\nimport frost.Core;\r\nimport frost.SettingsClass;\r\nimport frost.fileTransfer.FrostFileListFileObject;\r\nimport frost.fileTransfer.FrostFileListFileObjectOwner;\r\nimport frost.identities.Identity;\r", "context": "src/main/java/frost/fileTransfer/search/SearchThread.java\n/*\r\n SearchThread.java / Frost\r\n Copyright (C) 2001 Frost Project \r\n\r\n This program is free software; you can redistribute it and/or\r\n modify it under the terms of the GNU General Public License as\r\n published by the Free Software Foundation; either version 2 of\r\n the License, or (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program; if not, write to the Free Software\r\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r\n*/\r\npackage frost.fileTransfer.search;\r\n\r\n\r\n\r\n\r\nclass SearchThread extends Thread implements FileListCallback {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(SearchThread.class);\r\n\r\n private SearchParameters searchParams;\r\n\r\n private String[] audioExtension;\r\n private String[] videoExtension;\r\n private String[] imageExtension;\r\n private String[] documentExtension;\r\n private String[] executableExtension;\r\n private String[] archiveExtension;\r\n\r\n private int allFileCount;\r\n private int maxSearchResults;\r\n\r\n private SearchTable searchTable;\r\n\r\n private boolean isCancelRequested = false;\r\n private boolean isMaximumSearchResultsReached = false;\r\n\r\n private SearchPanel.ProxyPanel tabComponent;\r\n\r\n private boolean isCancelRequested() {\r\n return isCancelRequested;\r\n }\r\n public void requestCancel() {\r\n isCancelRequested = true;\r\n }\r\n\r\n private boolean isMaximumSearchResultsReached() {\r\n return isMaximumSearchResultsReached;\r\n }\r\n public void maximumSearchResultsReached() {\r\n isMaximumSearchResultsReached = true;\r\n }\r\n\r\n private String lowerCase(String s) {\r\n if( s == null ) {\r\n return \"\";\r\n } else {\r\n return s.toLowerCase();\r\n }\r\n }\r\n\r\n /**\r\n * Check search options, step 1.\r\n */\r\n private boolean searchFile1(FrostFileListFileObject fo) {\r\n\r\n // check if file has a key\r\n if( searchParams.isHideFilesWithoutChkKey() ) {\r\n if( fo.getKey() == null || fo.getKey().length() == 0 ) {\r\n return false;\r\n }\r\n }\r\n\r\n // hideFiles: show file if no bad/check/observe owner; or if at least 1 owner is good/observe\r\n if( searchParams.isHideBadUserFiles()\r\n || searchParams.isHideCheckUserFiles()\r\n || searchParams.isHideObserveUserFiles())\r\n {\r\n boolean accept = true;\r\n\nsrc/main/java/frost/Core.java\npublic class Core {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(Core.class);\r\n\r\n // Core instanciates itself, frostSettings must be created before instance=Core() !\r\n public static final SettingsClass frostSettings = new SettingsClass();\r\n\r\n private static Core instance = null;\r\n\r\n private static final FrostCrypt crypto = new FrostCrypt();\r\n\r\n private static boolean isHelpHtmlSecure = false;\r\n\r\n private Language language = null;\r\n\r\n private static boolean freenetIsOnline = false;\r\n private static boolean freetalkIsTalkable = false;\r\n\r\n private final Timer timer = new Timer(true);\r\n\r\n private MainFrame mainFrame;\r\n private MessagingManager messagingManager;\r\n private FileTransferManager fileTransferManager;\r\n\r\n private static IdentitiesManager identitiesManager;\r\n\r\n /**\r\n *\r\n */\r\n private Core() {\r\n initializeLanguage();\r\n }\r\n\r\n /**\r\n * This methods parses the list of available nodes (and converts it if it is in\r\n * the old format). If there are no available nodes, it shows a Dialog warning the\r\n * user of the situation and returns false.\r\n * @return boolean false if no nodes are available. True otherwise.\r\n */\r\n private boolean initializeConnectivity() {\r\n\r\n // determine configured freenet version\r\n final int freenetVersion = frostSettings.getIntValue(SettingsClass.FREENET_VERSION); // only 7 is supported\r\n if( freenetVersion != 7 ) {\r\n MiscToolkit.showMessage(\r\n language.getString(\"Core.init.UnsupportedFreenetVersionBody\")+\": \"+freenetVersion,\r\n JOptionPane.ERROR_MESSAGE,\r\n language.getString(\"Core.init.UnsupportedFreenetVersionTitle\"));\r\n return false;\r\n }\r\n\r\n // get the list of available nodes\r\n String nodesUnparsed = frostSettings.getValue(SettingsClass.FREENET_FCP_ADDRESS);\r\n if ((nodesUnparsed == null) || (nodesUnparsed.length() == 0)) {\r\n frostSettings.setValue(SettingsClass.FREENET_FCP_ADDRESS, \"127.0.0.1:9481\");\r\n nodesUnparsed = frostSettings.getValue(SettingsClass.FREENET_FCP_ADDRESS);\r\n }\r\n\r\n final List nodes = new ArrayList();\r\n\r\n // earlier we supported multiple nodes, so check if there is more than one node\r\n if( nodesUnparsed != null ) {\r\n final String[] _nodes = nodesUnparsed.split(\",\");\r\n for( final String element : _nodes ) {\r\n nodes.add(element);\r\n }\r\n }\r\n\r\n // paranoia, should never happen\r\n if (nodes.size() == 0) {\r\n MiscToolkit.showMessage(\r\n \"Not a single Freenet node configured. Frost cannot start.\",\r\n JOptionPane.ERROR_MESSAGE,\r\n \"ERROR: No Freenet nodes are configured.\");\r\n return false;\r\n }\r\n\r\n if (nodes.size() > 1) {\r\n MiscToolkit.showMessage(\r\n \"Frost doesn' support multiple Freenet nodes and will use the first configured node.\",\r\n JOptionPane.ERROR_MESSAGE,\r\n \"Warning: Using first configured node\");\r\n frostSettings.setValue(SettingsClass.FREENET_FCP_ADDRESS, nodes.get(0));\r\n }\r\n\r\n // init the factory with configured node\r\n try {\r\n FcpHandler.initializeFcp(nodes.get(0));\r\n } catch(final Exception ex) {\r\n MiscToolkit.showMessage(\r\n ex.getMessage(),\r\n JOptionPane.ERROR_MESSAGE,\r\n language.getString(\"Core.init.UnsupportedFreenetVersionTitle\"));\r\n return false;\r\n }\r\n\r\n // install our security manager that only allows connections to the configured FCP hosts\r\n System.setSecurityManager(new FrostSecurityManager());\r\n\r\n // check if node is online and if we run on 0.7 testnet\r\n setFreenetOnline(false);\r\n\r\n if( Frost.isOfflineMode() ) {\r\n // keep offline\r\n return true;\r\n }\r\n\r\n // We warn the user when he connects to a 0.7 testnet node\r\n // this also tries to connect to a configured node and sets 'freenetOnline'\r\n boolean runningOnTestnet = false;\r\n try {\r\n final FcpConnection fcpConn = new FcpConnection(FcpHandler.inst().getFreenetNode());\r\n final NodeMessage nodeMessage = fcpConn.getNodeInfo();\r\n\r\n // node answered, freenet is online\r\n setFreenetOnline(true);\r\n\r\n if (nodeMessage.getBoolValue(\"Testnet\")) {\r\n runningOnTestnet = true;\r\n }\r\n\r\n final boolean freetalkTalkable = fcpConn.checkFreetalkPlugin();\r\n setFreetalkTalkable (freetalkTalkable);\r\n\r\n if (freetalkTalkable) {\r\n logger.info(\"**** Freetalk is Talkable. ****\");\r\n } else {\r\n logger.warn(\"**** Freetalk is NOT Talkable. ****\");\r\n }\r\n\r\n fcpConn.close();\r\n\r\n } catch (final Exception e) {\r\n logger.error(\"Exception thrown in initializeConnectivity\", e);\r\n }\r\n\r\n if (runningOnTestnet) {\r\n MiscToolkit.showMessage(\r\n language.getString(\"Core.init.TestnetWarningBody\"),\r\n JOptionPane.WARNING_MESSAGE,\r\n language.getString(\"Core.init.TestnetWarningTitle\"));\r\n }\r\n\r\n // We warn the user if there aren't any running nodes\r\n if (!isFreenetOnline()) {\r\n MiscToolkit.showMessage(\r\n language.getString(\"Core.init.NodeNotRunningBody\"),\r\n JOptionPane.WARNING_MESSAGE,\r\n language.getString(\"Core.init.NodeNotRunningTitle\"));\r\n } else {\r\n // maybe start a single message connection\r\n FcpHandler.inst().goneOnline();\r\n }\r\n\r\n if (!frostSettings.getBoolValue(SettingsClass.FILESHARING_DISABLE)) {\r\n MiscToolkit.showSuppressableConfirmDialog(\r\n MainFrame.getInstance(),\r\n language.getString(\"Core.init.FileSharingEnabledBody\"),\r\n language.getString(\"Core.init.FileSharingEnabledTitle\"),\r\n JOptionPane.OK_OPTION,\r\n JOptionPane.WARNING_MESSAGE,\r\n SettingsClass.CONFIRM_FILESHARING_IS_ENABLED,\r\n language.getString(\"Common.suppressConfirmationCheckbox\") );\r\n }\r\n\r\n return true;\r\n }\r\n\r\n public static void setFreenetOnline(final boolean v) {\r\n freenetIsOnline = v;\r\n }\r\n public static boolean isFreenetOnline() {\r\n return freenetIsOnline;\r\n }\r\n\r\n public static void setFreetalkTalkable(final boolean v) {\r\n freetalkIsTalkable = v;\r\n }\r\n public static boolean isFreetalkTalkable() {\r\n return freetalkIsTalkable;\r\n }\r\n\r\n public static FrostCrypt getCrypto() {\r\n return crypto;\r\n }\r\n\r\n public static void schedule(final TimerTask task, final long delay) {\r\n getInstance().timer.schedule(task, delay);\r\n }\r\n\r\n public static void schedule(final TimerTask task, final long delay, final long period) {\r\n getInstance().timer.schedule(task, delay, period);\r\n }\r\n\r\n /**\r\n * @return pointer to the live core\r\n */\r\n public static Core getInstance() {\r\n if( instance == null ) {\r\n instance = new Core();\r\n }\r\n return instance;\r\n }\r\n\r\n private void showFirstStartupDialog() {\r\n // clean startup, ask user which freenet version to use, set correct default availableNodes\r\n final FirstStartupDialog startdlg = new FirstStartupDialog();\r\n final boolean exitChoosed = startdlg.startDialog();\r\n if( exitChoosed ) {\r\n System.exit(1);\r\n }\r\n\r\n // first startup, no migrate needed\r\n frostSettings.setValue(SettingsClass.MIGRATE_VERSION, 3);\r\n\r\n // set used version\r\n final int freenetVersion = 7;\r\n frostSettings.setValue(SettingsClass.FREENET_VERSION, freenetVersion);\r\n // init availableNodes with correct port\r\n if( startdlg.getOwnHostAndPort() != null ) {\r\n // user set own host:port\r\n frostSettings.setValue(SettingsClass.FREENET_FCP_ADDRESS, startdlg.getOwnHostAndPort());\r\n } else {\r\n // 0.7 darknet\r\n frostSettings.setValue(SettingsClass.FREENET_FCP_ADDRESS, \"127.0.0.1:9481\");\r\n }\r\n }\r\n\r\n private void compactPerstStorages(final Splashscreen splashscreen) throws Exception {\r\n try {\r\n long savedBytes = 0;\r\n savedBytes += compactStorage(splashscreen, IndexSlotsStorage.inst());\r\n savedBytes += compactStorage(splashscreen, FrostFilesStorage.inst());\r\n savedBytes += compactStorage(splashscreen, IdentitiesStorage.inst());\r\n savedBytes += compactStorage(splashscreen, SharedFilesCHKKeyStorage.inst());\r\n savedBytes += compactStorage(splashscreen, MessageStorage.inst());\r\n savedBytes += compactStorage(splashscreen, MessageContentStorage.inst());\r\n savedBytes += compactStorage(splashscreen, FileListStorage.inst());\r\n savedBytes += compactStorage(splashscreen, ArchiveMessageStorage.inst());\r\n\r\n final NumberFormat nf = NumberFormat.getInstance();\r\n logger.info(\"Finished compact of storages, released {} bytes.\", nf.format(savedBytes));\r\n } catch(final Exception ex) {\r\n logger.error(\"Error compacting perst storages\", ex);\r\n MiscToolkit.showMessage(\r\n \"Error compacting perst storages, compact did not complete: \"+ex.getMessage(),\r\n JOptionPane.ERROR_MESSAGE,\r\n \"Error compacting perst storages\");\r\n throw ex;\r\n }\r\n }\r\n\r\n private long compactStorage(final Splashscreen splashscreen, final AbstractFrostStorage storage) throws Exception {\r\n splashscreen.setText(\"Compacting storage file '\"+storage.getStorageFilename()+\"'...\");\r\n return storage.compactStorage();\r\n }\r\n\r\n private void exportStoragesToXml(final Splashscreen splashscreen) throws Exception {\r\n try {\r\n exportStorage(splashscreen, IndexSlotsStorage.inst());\r\n exportStorage(splashscreen, FrostFilesStorage.inst());\r\n exportStorage(splashscreen, IdentitiesStorage.inst());\r\n exportStorage(splashscreen, SharedFilesCHKKeyStorage.inst());\r\n exportStorage(splashscreen, MessageStorage.inst());\r\n exportStorage(splashscreen, MessageContentStorage.inst());\r\n exportStorage(splashscreen, FileListStorage.inst());\r\n exportStorage(splashscreen, ArchiveMessageStorage.inst());\r\n logger.info(\"Finished export to XML\");\r\n } catch(final Exception ex) {\r\n logger.error(\"Error exporting perst storages\", ex);\r\n MiscToolkit.showMessage(\r\n \"Error exporting perst storages, export did not complete: \"+ex.getMessage(),\r\n JOptionPane.ERROR_MESSAGE,\r\n \"Error exporting perst storages\");\r\n throw ex;\r\n }\r\n }\r\n\r\n private void exportStorage(final Splashscreen splashscreen, final AbstractFrostStorage storage) throws Exception {\r\n splashscreen.setText(\"Exporting storage file '\"+storage.getStorageFilename()+\"'...\");\r\n storage.exportToXml();\r\n }\r\n\r\n /**\r\n * Initialize, show splashscreen.\r\n */\r\n public void initialize() throws Exception {\r\n\r\n final Splashscreen splashscreen = new Splashscreen(frostSettings.getBoolValue(SettingsClass.DISABLE_SPLASHSCREEN));\r\n splashscreen.setVisible(true);\r\n\r\n splashscreen.setText(language.getString(\"Splashscreen.message.1\"));\r\n splashscreen.setProgress(20);\r\n\r\n // CLEANS TEMP DIR! START NO INSERTS BEFORE THIS DID RUN\r\n Startup.startupCheck(frostSettings);\r\n\r\n // if first startup ask user for freenet version to use\r\n if( frostSettings.getIntValue(SettingsClass.FREENET_VERSION) == 0 ) {\r\n showFirstStartupDialog();\r\n }\r\n\r\n // we must be at migration level 2 (no mckoi)!!!\r\n if( frostSettings.getIntValue(SettingsClass.MIGRATE_VERSION) < 2 ) {\r\n logger.error(\"You must update this Frost version from version 11-Dec-2007 !!!\");\r\n System.exit(8);\r\n }\r\n\r\n // before opening the storages, maybe compact them\r\n if( frostSettings.getBoolValue(SettingsClass.PERST_COMPACT_STORAGES) ) {\r\n compactPerstStorages(splashscreen);\r\n frostSettings.setValue(SettingsClass.PERST_COMPACT_STORAGES, false);\r\n }\r\n\r\n // one time: change cleanup settings to new default, they were way to high\r\n if( frostSettings.getIntValue(SettingsClass.MIGRATE_VERSION) < 3 ) {\r\n frostSettings.setValue(SettingsClass.DB_CLEANUP_REMOVEOFFLINEFILEWITHKEY, true);\r\n if (frostSettings.getIntValue(SettingsClass.DB_CLEANUP_OFFLINEFILESMAXDAYSOLD) > 30) {\r\n frostSettings.setValue(SettingsClass.DB_CLEANUP_OFFLINEFILESMAXDAYSOLD, 30);\r\n }\r\n\r\n // run cleanup now\r\n frostSettings.setValue(SettingsClass.DB_CLEANUP_LASTRUN, 0L);\r\n // run compact during next startup (after the cleanup)\r\n frostSettings.setValue(SettingsClass.PERST_COMPACT_STORAGES, true);\r\n // migration is done\r\n frostSettings.setValue(SettingsClass.MIGRATE_VERSION, 3);\r\n }\r\n\r\n // maybe export perst storages to XML\r\n if( frostSettings.getBoolValue(SettingsClass.PERST_EXPORT_STORAGES) ) {\r\n exportStoragesToXml(splashscreen);\r\n frostSettings.setValue(SettingsClass.PERST_EXPORT_STORAGES, false);\r\n }\r\n\r\n // initialize perst storages\r\n IndexSlotsStorage.inst().initStorage();\r\n SharedFilesCHKKeyStorage.inst().initStorage();\r\n FrostFilesStorage.inst().initStorage();\r\n MessageStorage.inst().initStorage();\r\n MessageContentStorage.inst().initStorage();\r\n ArchiveMessageStorage.inst().initStorage();\r\n IdentitiesStorage.inst().initStorage();\r\n FileListStorage.inst().initStorage();\r\n TrackDownloadKeysStorage.inst().initStorage();\r\n\r\n splashscreen.setText(language.getString(\"Splashscreen.message.2\"));\r\n splashscreen.setProgress(40);\r\n\r\n // check if help.zip contains only secure files (no http or ftp links at all)\r\n {\r\n final CheckHtmlIntegrity chi = new CheckHtmlIntegrity();\r\n isHelpHtmlSecure = chi.scanZipFile(\"help/help.zip\");\r\n }\r\n\r\n splashscreen.setText(language.getString(\"Splashscreen.message.3\"));\r\n splashscreen.setProgress(60);\r\n\r\n // sets the freenet version, initializes identities\r\n if (!initializeConnectivity()) {\r\n System.exit(1);\r\n }\r\n\r\n getIdentitiesManager().initialize();\r\n\r\n String title = \"Frost\";\r\n\r\n if( !isFreenetOnline() ) {\r\n title += \" (offline mode)\";\r\n }\r\n\r\n // Main frame\r\n mainFrame = new MainFrame(frostSettings, title);\r\n getMessagingManager().initialize();\r\n\r\n getFileTransferManager().initialize();\r\n UnsentMessagesManager.initialize();\r\n\r\n if (frostSettings.getBoolValue(SettingsClass.FREETALK_SHOW_TAB)) {\r\n FreetalkManager.initialize();\r\n }\r\n\r\n splashscreen.setText(language.getString(\"Splashscreen.message.4\"));\r\n splashscreen.setProgress(70);\r\n\r\n // Display the tray icon (do this before mainframe initializes)\r\n if ((frostSettings.getBoolValue(SettingsClass.SHOW_SYSTRAY_ICON) == true) && SystraySupport.isSupported()) {\r\n try {\r\n if (!SystraySupport.initialize(title)) {\r\n logger.error(\"Could not create systray icon.\");\r\n }\r\n } catch(final Throwable t) {\r\n logger.error(\"Could not create systray icon.\", t);\r\n }\r\n }\r\n\r\n mainFrame.initialize();\r\n\r\n // cleanup gets the expiration mode from settings\r\n CleanUp.runExpirationTasks(splashscreen, MainFrame.getInstance().getMessagingTab().getTofTreeModel().getAllBoards());\r\n\r\n // Show enqueued startup messages before showing the mainframe,\r\n // otherwise the glasspane used during load of board messages could corrupt the modal message dialog!\r\n SwingUtilities.invokeAndWait(new Runnable() {\r\n public void run() {\r\n mainFrame.showStartupMessages();\r\n }\r\n });\r\n\r\n // After expiration, select previously selected board tree row.\r\n // NOTE: This loads the message table!!!\r\n mainFrame.postInitialize();\r\n\r\n splashscreen.setText(language.getString(\"Splashscreen.message.5\"));\r\n splashscreen.setProgress(80);\r\n\r\n SwingUtilities.invokeAndWait(new Runnable() {\r\n public void run() {\r\n mainFrame.setVisible(true);\r\n }\r\n });\r\n\r\n splashscreen.closeMe();\r\n\r\n // boot up the machinery ;)\r\n initializeTasks(mainFrame);\r\n }\r\n\r\n /**\r\n * @return\r\n */\r\n public FileTransferManager getFileTransferManager() {\r\n if (fileTransferManager == null) {\r\n fileTransferManager = FileTransferManager.inst();\r\n }\r\n return fileTransferManager;\r\n }\r\n\r\n /**\r\n * @return\r\n */\r\n private MessagingManager getMessagingManager() {\r\n if (messagingManager == null) {\r\n messagingManager = new MessagingManager(frostSettings, mainFrame);\r\n }\r\n return messagingManager;\r\n }\r\n\r\n /**\r\n * @param parentFrame the frame that will be the parent of any\r\n * dialog that has to be shown in case an error happens\r\n * in one of those tasks\r\n */\r\n private void initializeTasks(final MainFrame mainframe) {\r\n // initialize the task that frees memory\r\n TimerTask cleaner = new TimerTask() {\r\n @Override\r\n public void run() {\r\n logger.info(\"freeing memory\");\r\n System.gc();\r\n }\r\n };\r\n final long gcMinutes = 10;\r\n timer.schedule(cleaner, gcMinutes * 60L * 1000L, gcMinutes * 60L * 1000L);\r\n cleaner = null;\r\n\r\n // initialize the task that saves data\r\n final StorageManager saver = new StorageManager(frostSettings);\r\n\r\n // auto savables\r\n saver.addAutoSavable(getMessagingManager().getTofTree());\r\n saver.addAutoSavable(getFileTransferManager());\r\n saver.addAutoSavable(new IdentityAutoBackupTask());\r\n\r\n // exit savables, must run before the perst storages are closed\r\n saver.addExitSavable(new IdentityAutoBackupTask());\r\n saver.addExitSavable(getMessagingManager().getTofTree());\r\n saver.addExitSavable(getFileTransferManager());\r\n\r\n saver.addExitSavable(frostSettings);\r\n\r\n // close perst Storages\r\n saver.addExitSavable(IndexSlotsStorage.inst());\r\n saver.addExitSavable(SharedFilesCHKKeyStorage.inst());\r\n saver.addExitSavable(FrostFilesStorage.inst());\r\n saver.addExitSavable(MessageStorage.inst());\r\n saver.addExitSavable(MessageContentStorage.inst());\r\n saver.addExitSavable(ArchiveMessageStorage.inst());\r\n saver.addExitSavable(IdentitiesStorage.inst());\r\n saver.addExitSavable(FileListStorage.inst());\r\n saver.addExitSavable(TrackDownloadKeysStorage.inst());\r\n\r\n // invoke the mainframe ticker (board updates, clock, ...)\r\n mainframe.startTickerThread();\r\n\r\n // start file attachment uploads\r\n FileAttachmentUploadThread.getInstance().start();\r\n\r\n // start all filetransfer tickers\r\n getFileTransferManager().startTickers();\r\n\r\n // after X seconds, start filesharing threads if enabled\r\n if( isFreenetOnline() && !frostSettings.getBoolValue(SettingsClass.FILESHARING_DISABLE)) {\r\n final Thread t = new Thread() {\r\n @Override\r\n public void run() {\r\n Mixed.wait(10000);\r\n FileSharingManager.startFileSharing();\r\n }\r\n };\r\n t.start();\r\n }\r\n }\r\n\r\n /**\r\n * @return\r\n */\r\n public static IdentitiesManager getIdentitiesManager() {\r\n if (identitiesManager == null) {\r\n identitiesManager = new IdentitiesManager();\r\n }\r\n return identitiesManager;\r\n }\r\n\r\n /**\r\n * This method returns the language resource to get internationalized messages\r\n * from. That language resource is initialized the first time this method is called.\r\n * In that case, if the locale field has a value, it is used to select the\r\n * LanguageResource. If not, the locale value in frostSettings is used for that.\r\n */\r\n private void initializeLanguage() {\r\n if( Frost.getCmdLineLocaleFileName() != null ) {\r\n // external bundle specified on command line (overrides config setting)\r\n final File f = new File(Frost.getCmdLineLocaleFileName());\r\n Language.initializeWithFile(f);\r\n } else if (Frost.getCmdLineLocaleName() != null) {\r\n // use locale specified on command line (overrides config setting)\r\n Language.initializeWithName(Frost.getCmdLineLocaleName());\r\n } else {\r\n // use config file parameter (format: de or de;ext\r\n final String lang = frostSettings.getValue(SettingsClass.LANGUAGE_LOCALE);\r\n final String langIsExternal = frostSettings.getValue(\"localeExternal\");\r\n if( (lang == null) || (lang.length() == 0) || lang.equals(\"default\") ) {\r\n // for default or if not set at all\r\n frostSettings.setValue(SettingsClass.LANGUAGE_LOCALE, \"default\");\r\n Language.initializeWithName(null);\r\n } else {\r\n boolean isExternal;\r\n if( (langIsExternal == null) || (langIsExternal.length() == 0) || !langIsExternal.equals(\"true\")) {\r\n isExternal = false;\r\n } else {\r\n isExternal = true;\r\n }\r\n Language.initializeWithName(lang, isExternal);\r\n }\r\n }\r\n language = Language.getInstance();\r\n }\r\n\r\n public void showAutoSaveError(final Exception exception) {\r\n final StringWriter stringWriter = new StringWriter();\r\n exception.printStackTrace(new PrintWriter(stringWriter));\r\n\r\n SwingUtilities.invokeLater(new Runnable() {\r\n public void run() {\r\n if (mainFrame != null) {\r\n JDialogWithDetails.showErrorDialog(\r\n mainFrame,\r\n language.getString(\"Saver.AutoTask.title\"),\r\n language.getString(\"Saver.AutoTask.message\"),\r\n stringWriter.toString());\r\n System.exit(3);\r\n }\r\n }\r\n });\r\n }\r\n\r\n public static boolean isHelpHtmlSecure() {\r\n return isHelpHtmlSecure;\r\n }\r\n}\r\n\nsrc/main/java/frost/identities/Identity.java\npublic class Identity extends Persistent implements XMLizable {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(Identity.class);\r\n\r\n private static transient final int GOOD = 1;\r\n private static transient final int CHECK = 2;\r\n private static transient final int OBSERVE = 3;\r\n private static transient final int BAD = 4;\r\n\r\n private static transient final String GOOD_STRING = \"GOOD\";\r\n private static transient final String CHECK_STRING = \"CHECK\";\r\n private static transient final String OBSERVE_STRING = \"OBSERVE\";\r\n private static transient final String BAD_STRING = \"BAD\";\r\n\r\n private String uniqueName;\r\n private long lastSeenTimestamp = -1;\r\n private int receivedMessageCount = 0;\r\n private String comment = \"\";\r\n\r\n private int state = CHECK;\r\n private transient String stateString = CHECK_STRING;\r\n\r\n private transient String publicKey;\r\n\r\n private PerstIdentityPublicKey pPublicKey;\r\n\r\n /**\r\n * @param el\r\n * @throws Exception\r\n */\r\n protected Identity(final Element el) throws Exception {\r\n try {\r\n loadXMLElement(el);\r\n } catch (final SAXException e) {\r\n logger.error(\"Exception thrown in constructor\", e);\r\n }\r\n }\r\n\r\n /**\r\n * we use this constructor whenever we have all the info\r\n *\r\n * @param name\r\n * @param key\r\n */\r\n private Identity(final String name, final String key) {\r\n this.publicKey = key;\r\n this.uniqueName = name;\r\n }\r\n\r\n /**\r\n * If a LocalIdentity is deleted, we ceate a GOOD Identity for the deleted LocalIdentity\r\n *\r\n * @param li\r\n */\r\n public Identity(final LocalIdentity li) {\r\n uniqueName = li.getUniqueName();\r\n publicKey = li.getPublicKey();\r\n lastSeenTimestamp = li.getLastSeenTimestamp();\r\n receivedMessageCount = li.getReceivedMessageCount();\r\n comment = li.getComment();\r\n updateStateString();\r\n }\r\n\r\n /**\r\n * Create a new Identity from the specified uniqueName and publicKey.\r\n * If uniqueName does not contain an '@', this method creates a new digest\r\n * for the publicKey and appens it to the uniqueName.\r\n * Finally Mixed.makeFilename() is called for the uniqueName.\r\n *\r\n * @param name\r\n * @param key\r\n * @param createNew\r\n */\r\n protected Identity(String name, final String key, final boolean createNew) {\r\n if( name.indexOf(\"@\") < 0 ) {\r\n name = name + \"@\" + Core.getCrypto().digest(key);\r\n }\r\n name = Mixed.makeFilename(name);\r\n\r\n this.publicKey = key;\r\n this.uniqueName = name;\r\n }\r\n\r\n ////////////////////////////////////////////////////////////////////\r\n // FACTORY METHODS /////////////////////////////////////////////////\r\n ////////////////////////////////////////////////////////////////////\r\n\r\n /**\r\n * Create a new Identity from the specified uniqueName and publicKey.\r\n * Does not convert the specified uniqueName using Mixed.makeFilename() !\r\n *\r\n * @return null if the Identity cannot be created\r\n */\r\n public static Identity createIdentityFromExactStrings(final String name, final String key) {\r\n return new Identity(name, key);\r\n }\r\n\r\n /**\r\n * Create a new Identity, read from the specified XML element.\r\n * Calls Mixed.makeFilename() on read uniqueName.\r\n *\r\n * @param el the XML element containing the Identity information\r\n * @return the new Identity, or null if Identity cannot be created (invalid input)\r\n */\r\n public static Identity createIdentityFromXmlElement(final Element el) {\r\n try {\r\n return new Identity(el);\r\n } catch (final Exception e) {\r\n return null;\r\n }\r\n }\r\n\r\n ////////////////////////////////////////////////////////////////////\r\n ////////////////////////////////////////////////////////////////////\r\n\r\n @Override\r\n public boolean recursiveLoading() {\r\n return false;\r\n }\r\n\r\n @Override\r\n public void deallocate() {\r\n if( pPublicKey != null ) {\r\n pPublicKey.deallocate();\r\n pPublicKey = null;\r\n }\r\n super.deallocate();\r\n }\r\n\r\n class PerstIdentityPublicKey extends Persistent {\r\n private String perstPublicKey;\r\n public PerstIdentityPublicKey() {}\r\n public PerstIdentityPublicKey(final String pk) {\r\n perstPublicKey = pk;\r\n }\r\n public String getPublicKey() {\r\n return perstPublicKey;\r\n }\r\n\r\n\t\tpublic void onLoad() {\r\n\t\t\tlogger.debug(\"load pubkey\");\r\n\t\t}\r\n\r\n @Override\r\n public boolean recursiveLoading() {\r\n return false; // load publicKey on demand\r\n }\r\n }\r\n\r\n @Override\r\n public void onStore() {\r\n if( pPublicKey == null && publicKey != null ) {\r\n // link public key\r\n pPublicKey = new PerstIdentityPublicKey(publicKey);\r\n }\r\n }\r\n\r\n @Override\r\n public void onLoad() {\r\n updateStateString();\r\n }\r\n\r\n public Element getXMLElement(final Document doc) {\r\n\r\n final Element el = doc.createElement(\"Identity\");\r\n\r\n Element element = doc.createElement(\"name\");\r\n CDATASection cdata = doc.createCDATASection(getUniqueName());\r\n element.appendChild( cdata );\r\n el.appendChild( element );\r\n\r\n element = doc.createElement(\"key\");\r\n cdata = doc.createCDATASection(getPublicKey());\r\n element.appendChild( cdata );\r\n el.appendChild( element );\r\n\r\n return el;\r\n }\r\n\r\n @Deprecated\r\n public Element getXMLElement_old(final Document doc) {\r\n\r\n final Element el = doc.createElement(\"MyIdentity\");\r\n\r\n Element element = doc.createElement(\"name\");\r\n CDATASection cdata = doc.createCDATASection(getUniqueName());\r\n element.appendChild( cdata );\r\n el.appendChild( element );\r\n\r\n element = doc.createElement(\"key\");\r\n cdata = doc.createCDATASection(getPublicKey());\r\n element.appendChild( cdata );\r\n el.appendChild( element );\r\n\r\n return el;\r\n }\r\n\r\n public Element getExportXMLElement(final Document doc) {\r\n final Element el = getXMLElement(doc);\r\n\r\n if( getLastSeenTimestamp() > -1 ) {\r\n final Element element = doc.createElement(\"lastSeen\");\r\n final Text txt = doc.createTextNode(Long.toString(getLastSeenTimestamp()));\r\n element.appendChild( txt );\r\n el.appendChild( element );\r\n }\r\n if( getReceivedMessageCount() > -1 ) {\r\n final Element element = doc.createElement(\"messageCount\");\r\n final Text txt = doc.createTextNode(Long.toString(getReceivedMessageCount()));\r\n element.appendChild( txt );\r\n el.appendChild( element );\r\n }\r\n return el;\r\n }\r\n\r\n public void loadXMLElement(final Element e) throws SAXException {\r\n uniqueName = XMLTools.getChildElementsCDATAValue(e, \"name\");\r\n publicKey = XMLTools.getChildElementsCDATAValue(e, \"key\");\r\n\r\n String lastSeenStr = XMLTools.getChildElementsTextValue(e,\"lastSeen\");\r\n if( lastSeenStr != null && ((lastSeenStr=lastSeenStr.trim())).length() > 0 ) {\r\n lastSeenTimestamp = Long.parseLong(lastSeenStr);\r\n } else {\r\n // not yet set, init with current timestamp\r\n lastSeenTimestamp = System.currentTimeMillis();\r\n }\r\n\r\n String msgCount = XMLTools.getChildElementsTextValue(e,\"messageCount\");\r\n if( msgCount != null && ((msgCount=msgCount.trim())).length() > 0 ) {\r\n receivedMessageCount = Integer.parseInt(msgCount);\r\n } else {\r\n receivedMessageCount = 0;\r\n }\r\n// uniqueName = Mixed.makeFilename(uniqueName);\r\n }\r\n\r\n /**\r\n * @return the public key of this Identity\r\n */\r\n public String getPublicKey() {\r\n if( publicKey == null && pPublicKey != null ) {\r\n pPublicKey.load();\r\n return pPublicKey.getPublicKey();\r\n }\r\n return publicKey;\r\n }\r\n\r\n public String getUniqueName() {\r\n return uniqueName;\r\n }\r\n\r\n public void correctUniqueName() {\r\n uniqueName = Mixed.makeFilename(uniqueName);\r\n }\r\n\r\n // dont't store BoardAttachment with pubKey=SSK@...\r\n public static boolean isForbiddenBoardAttachment(final BoardAttachment ba) {\r\n if( ba != null &&\r\n ba.getBoardObj().getPublicKey() != null &&\r\n ba.getBoardObj().getPublicKey().startsWith(\"SSK@\") )\r\n {\r\n return true; // let delete SSK pubKey board\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n public long getLastSeenTimestamp() {\r\n return lastSeenTimestamp;\r\n }\r\n\r\n public void setLastSeenTimestamp(final long v) {\r\n lastSeenTimestamp = v;\r\n updateIdentitiesStorage();\r\n }\r\n\r\n public void setLastSeenTimestampWithoutUpdate(final long v) {\r\n lastSeenTimestamp = v;\r\n }\r\n\r\n public int getState() {\r\n return state;\r\n }\r\n\r\n public String getComment() {\r\n return comment;\r\n }\r\n\r\n public void setComment(String comment) {\r\n this.comment = comment;\r\n updateIdentitiesStorage();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return getUniqueName();\r\n }\r\n\r\n public boolean isGOOD() {\r\n return state==GOOD;\r\n }\r\n public boolean isCHECK() {\r\n return state==CHECK;\r\n }\r\n public boolean isOBSERVE() {\r\n return state==OBSERVE;\r\n }\r\n public boolean isBAD() {\r\n return state==BAD;\r\n }\r\n\r\n public void setGOOD() {\r\n state=GOOD;\r\n updateStateString();\r\n updateIdentitiesStorage();\r\n }\r\n public void setCHECK() {\r\n state=CHECK;\r\n updateStateString();\r\n updateIdentitiesStorage();\r\n }\r\n public void setOBSERVE() {\r\n state=OBSERVE;\r\n updateStateString();\r\n updateIdentitiesStorage();\r\n }\r\n public void setBAD() {\r\n state=BAD;\r\n updateStateString();\r\n updateIdentitiesStorage();\r\n }\r\n\r\n public void setGOODWithoutUpdate() {\r\n state=GOOD;\r\n updateStateString();\r\n }\r\n public void setCHECKWithoutUpdate() {\r\n state=CHECK;\r\n updateStateString();\r\n }\r\n public void setOBSERVEWithoutUpdate() {\r\n state=OBSERVE;\r\n updateStateString();\r\n }\r\n public void setBADWithoutUpdate() {\r\n state=BAD;\r\n updateStateString();\r\n }\r\n\r\n private void updateStateString() {\r\n if( isCHECK() ) {\r\n stateString = CHECK_STRING;\r\n } else if( isOBSERVE() ) {\r\n stateString = OBSERVE_STRING;\r\n } else if( isGOOD() ) {\r\n stateString = GOOD_STRING;\r\n } else if( isBAD() ) {\r\n stateString = BAD_STRING;\r\n } else {\r\n stateString = \"*ERR*\";\r\n }\r\n }\r\n\r\n public String getStateString() {\r\n return stateString;\r\n }\r\n\r\n protected boolean updateIdentitiesStorage() {\r\n if( !IdentitiesStorage.inst().beginExclusiveThreadTransaction() ) {\r\n return false;\r\n }\r\n modify();\r\n IdentitiesStorage.inst().endThreadTransaction();\r\n return true;\r\n }\r\n\r\n public int getReceivedMessageCount() {\r\n return receivedMessageCount;\r\n }\r\n\r\n public void setReceivedMessageCount(final int i) {\r\n receivedMessageCount = i;\r\n }\r\n\r\n public void incReceivedMessageCount() {\r\n this.receivedMessageCount++;\r\n updateIdentitiesStorage();\r\n }\r\n}\r\n\nsrc/main/java/frost/fileTransfer/FrostFileListFileObject.java\npublic class FrostFileListFileObject extends Persistent {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(FrostFileListFileObject.class);\r\n\r\n private String sha = null; // SHA of the file\r\n private long size = 0; // Filesize\r\n private String key = null; // CHK key\r\n\r\n private long lastDownloaded = 0;\r\n private long lastUploaded = 0;\r\n private long firstReceived = 0;\r\n private long lastReceived = 0;\r\n\r\n private long requestLastReceived = 0; // time when we received the last request for this sha\r\n private int requestsReceivedCount = 0; // received requests count\r\n\r\n private long requestLastSent = 0; // time when we sent the last request for this file\r\n private int requestsSentCount = 0; // sent requests count\r\n\r\n private boolean isHidden = false; // user can hide files in search panel\r\n\r\n private IPersistentList frostFileListFileObjectOwnerList;\r\n\r\n // non-persistent fields\r\n private transient String displayName = null;\r\n private transient String displayComment = null;\r\n private transient String displayKeywords = null;\r\n private transient int displayRating = -1;\r\n private transient Boolean hasInfosFromMultipleSources = null;\r\n\r\n private transient List listeners;\r\n\r\n /**\r\n * Used if item is loaded from database.\r\n */\r\n public FrostFileListFileObject(\r\n final String newSha1,\r\n final long newSize,\r\n final String newKey,\r\n final long newLastDownloaded,\r\n final long newLastUploaded,\r\n final long newFirstReceived,\r\n final long newLastReceived,\r\n final long newRequestLastReceived,\r\n final int newRequestsReceivedCount,\r\n final long newRequestLastSent,\r\n final int newRequestSentCount)\r\n {\r\n sha = newSha1;\r\n size = newSize;\r\n key = newKey;\r\n lastDownloaded = newLastDownloaded;\r\n lastUploaded = newLastUploaded;\r\n firstReceived = newFirstReceived;\r\n lastReceived = newLastReceived;\r\n requestLastReceived = newRequestLastReceived;\r\n requestsReceivedCount = newRequestsReceivedCount;\r\n requestLastSent = newRequestLastSent;\r\n requestsSentCount = newRequestSentCount;\r\n }\r\n\r\n /**\r\n * Create instance with data from SharedFilesXmlFile.\r\n * After creation this item should only be saved to database,\r\n * this merges the data from this item in case this files is\r\n * already in the filelist (adds new owner/board).\r\n */\r\n public FrostFileListFileObject(final SharedFileXmlFile sfo, final Identity owner, final long timestamp) {\r\n\r\n sha = sfo.getSha();\r\n size = sfo.getSize().longValue();\r\n key = sfo.getKey();\r\n lastDownloaded = 0;\r\n firstReceived = timestamp;\r\n lastReceived = timestamp; // set or updated after add\r\n\r\n long lastUploadDate = 0;\r\n if( sfo.getKey() != null ) {\r\n if( sfo.getLastUploaded() != null ) {\r\n try {\r\n\t\t\t\t\tfinal OffsetDateTime dt = DateFun.parseDate(sfo.getLastUploaded(), DateFun.FORMAT_DATE,\r\n\t\t\t\t\t\t\tDateFun.getTimeZone());\r\n\t\t\t\t\tlastUploadDate = DateFun.toMilli(dt);\r\n } catch(final Throwable t) {\r\n logger.error(\"error parsing file last uploaded date\", t);\r\n }\r\n }\r\n }\r\n lastUploaded = lastUploadDate;\r\n\r\n final FrostFileListFileObjectOwner ob = new FrostFileListFileObjectOwner(\r\n sfo.getFilename(),\r\n owner.getUniqueName(),\r\n sfo.getComment(),\r\n sfo.getKeywords(),\r\n sfo.getRating(),\r\n timestamp,\r\n lastUploadDate,\r\n sfo.getKey());\r\n\r\n addFrostFileListFileObjectOwner(ob);\r\n }\r\n\r\n private IPersistentList getFrostFileListFileObjectOwnerList() {\r\n if( frostFileListFileObjectOwnerList == null ) {\r\n frostFileListFileObjectOwnerList = FileListStorage.inst().createList(); // ATTN: is used without store also!\r\n }\r\n return frostFileListFileObjectOwnerList;\r\n }\r\n \r\n public void addFrostFileListFileObjectOwner(final FrostFileListFileObjectOwner v) {\r\n v.setFileListFileObject(this);\r\n getFrostFileListFileObjectOwnerList().add(v);\r\n }\r\n \r\n public void deleteFrostFileListFileObjectOwner(final FrostFileListFileObjectOwner v) {\r\n getFrostFileListFileObjectOwnerList().remove(v);\r\n }\r\n \r\n public Iterator getFrostFileListFileObjectOwnerIterator() {\r\n return getFrostFileListFileObjectOwnerList().iterator();\r\n }\r\n \r\n public int getFrostFileListFileObjectOwnerListSize() {\r\n return getFrostFileListFileObjectOwnerList().size();\r\n }\r\n\r\n public String getKey() {\r\n return key;\r\n }\r\n\r\n public void setKey(final String key) {\r\n this.key = key;\r\n notifyListeners();\r\n }\r\n\r\n public long getLastDownloaded() {\r\n return lastDownloaded;\r\n }\r\n\r\n public void setLastDownloaded(final long lastDownloaded) {\r\n this.lastDownloaded = lastDownloaded;\r\n }\r\n\r\n public long getLastUploaded() {\r\n return lastUploaded;\r\n }\r\n\r\n public void setLastUploaded(final long lastUploaded) {\r\n this.lastUploaded = lastUploaded;\r\n notifyListeners();\r\n }\r\n\r\n public long getLastReceived() {\r\n return lastReceived;\r\n }\r\n\r\n public void setLastReceived(final long lastReceived) {\r\n this.lastReceived = lastReceived;\r\n notifyListeners();\r\n }\r\n\r\n public String getSha() {\r\n return sha;\r\n }\r\n\r\n public long getSize() {\r\n return size;\r\n }\r\n\r\n public long getRequestLastReceived() {\r\n return requestLastReceived;\r\n }\r\n\r\n public void setRequestLastReceived(final long requestLastReceived) {\r\n this.requestLastReceived = requestLastReceived;\r\n notifyListeners();\r\n }\r\n\r\n public long getRequestLastSent() {\r\n return requestLastSent;\r\n }\r\n\r\n public void setRequestLastSent(final long requestLastSent) {\r\n this.requestLastSent = requestLastSent;\r\n notifyListeners();\r\n }\r\n\r\n public int getRequestsReceivedCount() {\r\n return requestsReceivedCount;\r\n }\r\n\r\n public void setRequestsReceivedCount(final int requestsReceivedCount) {\r\n this.requestsReceivedCount = requestsReceivedCount;\r\n }\r\n\r\n public int getRequestsSentCount() {\r\n return requestsSentCount;\r\n }\r\n\r\n public void setRequestsSentCount(final int requestsSentCount) {\r\n this.requestsSentCount = requestsSentCount;\r\n }\r\n\r\n public long getFirstReceived() {\r\n return firstReceived;\r\n }\r\n public void setFirstReceived(final long v) {\r\n firstReceived = v;\r\n }\r\n\r\n public boolean isHidden() {\r\n return isHidden;\r\n }\r\n public void setHidden(final boolean isHidden) {\r\n this.isHidden = isHidden;\r\n }\r\n\r\n static class MutableInt {\r\n public int i = 0;\r\n public String name = \"\";\r\n public int rating = 0;\r\n }\r\n\r\n private static MutableInt defaultMutableInt = new MutableInt();\r\n\r\n public String getDisplayName() {\r\n if( displayName == null ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n displayName = \"(no sources)\";\r\n } else {\r\n // choose most often used name\r\n final Hashtable ht = new Hashtable();\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n MutableInt mi = ht.get( e.getName() );\r\n if( mi == null ) {\r\n mi = new MutableInt();\r\n mi.name = e.getName();\r\n mi.i = 1;\r\n ht.put(e.getName(), mi);\r\n } else {\r\n mi.i++;\r\n }\r\n }\r\n MutableInt bestMi = defaultMutableInt;\r\n for( final MutableInt mi : ht.values() ) {\r\n if( mi.i > bestMi.i ) {\r\n bestMi = mi;\r\n }\r\n }\r\n displayName = bestMi.name;\r\n }\r\n }\r\n return displayName;\r\n }\r\n\r\n /**\r\n * @return true if this file has infos from multiple sources (comments, ratings, keywords)\r\n */\r\n public Boolean hasInfosFromMultipleSources() {\r\n if( hasInfosFromMultipleSources == null ) {\r\n if( getFrostFileListFileObjectOwnerList().size() > 1 ) {\r\n int valuesCount = 0;\r\n for( final FrostFileListFileObjectOwner o : getFrostFileListFileObjectOwnerList() ) {\r\n // valuesCount is increased by 1 per FrostFileListFileObjectOwner\r\n if( o.getComment() != null && o.getComment().length() > 0 ) {\r\n valuesCount++;\r\n } else if( o.getKeywords() != null && o.getKeywords().length() > 0 ) {\r\n valuesCount++;\r\n } else if( o.getRating() > 0 ) {\r\n valuesCount++;\r\n }\r\n // if valuesCount is greater 1 we have at least 2 sources that provide informations\r\n if( valuesCount > 1 ) {\r\n hasInfosFromMultipleSources = Boolean.TRUE;\r\n break;\r\n }\r\n }\r\n if( hasInfosFromMultipleSources == null ) {\r\n hasInfosFromMultipleSources = Boolean.FALSE;\r\n }\r\n } else {\r\n hasInfosFromMultipleSources = Boolean.FALSE;\r\n }\r\n }\r\n return hasInfosFromMultipleSources;\r\n }\r\n\r\n public String getDisplayComment() {\r\n if( displayComment == null ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n displayComment = \"(no sources)\";\r\n } else {\r\n // choose most often used name\r\n final Hashtable ht = new Hashtable();\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n final String c = e.getComment();\r\n if( c == null || c.length() == 0 ) {\r\n continue;\r\n }\r\n MutableInt mi = ht.get( c );\r\n if( mi == null ) {\r\n mi = new MutableInt();\r\n mi.name = c;\r\n mi.i = 1;\r\n ht.put(c, mi);\r\n } else {\r\n mi.i++;\r\n }\r\n }\r\n MutableInt bestMi = defaultMutableInt;\r\n for( final MutableInt mi : ht.values() ) {\r\n if( mi.i > bestMi.i ) {\r\n bestMi = mi;\r\n }\r\n }\r\n displayComment = bestMi.name;\r\n }\r\n }\r\n return displayComment;\r\n }\r\n\r\n public String getDisplayKeywords() {\r\n if( displayKeywords == null ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n displayKeywords = \"(no sources)\";\r\n } else {\r\n // choose most often used name\r\n final Hashtable ht = new Hashtable();\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n final String c = e.getKeywords();\r\n if( c == null || c.length() == 0 ) {\r\n continue;\r\n }\r\n MutableInt mi = ht.get( c );\r\n if( mi == null ) {\r\n mi = new MutableInt();\r\n mi.name = c;\r\n mi.i = 1;\r\n ht.put(c, mi);\r\n } else {\r\n mi.i++;\r\n }\r\n }\r\n MutableInt bestMi = defaultMutableInt;\r\n for( final MutableInt mi : ht.values() ) {\r\n if( mi.i > bestMi.i ) {\r\n bestMi = mi;\r\n }\r\n }\r\n displayKeywords = bestMi.name;\r\n }\r\n }\r\n return displayKeywords;\r\n }\r\n\r\n public int getDisplayRating() {\r\n if( displayRating < 0 ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n return 0;\r\n }\r\n // choose most often used rating\r\n // choose most often used name\r\n final int ratings[] = new int[6];\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n final int r = e.getRating();\r\n if( r < 1 || r > 5 ) {\r\n continue;\r\n }\r\n ratings[r]++;\r\n }\r\n int bestRating = 0;\r\n for(int x=1; x < ratings.length; x++ ) {\r\n if( ratings[x] > bestRating ) {\r\n bestRating = x;\r\n }\r\n }\r\n displayRating = bestRating;\r\n }\r\n return displayRating;\r\n }\r\n\r\n public void addListener(final FrostDownloadItem d) {\r\n if( !getListeners().contains(d) ) {\r\n getListeners().add(d);\r\n }\r\n }\r\n public void removeListener(final FrostDownloadItem d) {\r\n if( getListeners().contains(d) ) {\r\n getListeners().remove(d);\r\n }\r\n }\r\n public List getListeners() {\r\n if( listeners == null ) {\r\n listeners = new ArrayList();\r\n }\r\n return listeners;\r\n }\r\n private void notifyListeners() {\r\n for( final FrostDownloadItem dl : getListeners() ) {\r\n dl.fireValueChanged();\r\n }\r\n }\r\n}\r\n\nsrc/main/java/frost/fileTransfer/FrostFileListFileObjectOwner.java\npublic class FrostFileListFileObjectOwner extends Persistent {\r\n\r\n protected FrostFileListFileObject fileListFileObject;\r\n\r\n protected String name;\r\n protected String owner;\r\n\r\n protected String comment;\r\n protected String keywords;\r\n protected int rating;\r\n\r\n protected String key;\r\n\r\n protected long lastReceived = 0;\r\n protected long lastUploaded = 0;\r\n\r\n public FrostFileListFileObjectOwner(\r\n final String newName,\r\n final String newOwner,\r\n final String newComment,\r\n final String newKeywords,\r\n final int newRating,\r\n final long newLastReceived,\r\n final long newLastUploaded,\r\n final String newKey)\r\n {\r\n name = newName;\r\n owner = newOwner;\r\n comment = newComment;\r\n keywords = newKeywords;\r\n rating = newRating;\r\n lastReceived = newLastReceived;\r\n lastUploaded = newLastUploaded;\r\n key = newKey;\r\n }\r\n\r\n public long getLastReceived() {\r\n return lastReceived;\r\n }\r\n public String getName() {\r\n return name;\r\n }\r\n public String getOwner() {\r\n return owner;\r\n }\r\n\r\n public long getLastUploaded() {\r\n return lastUploaded;\r\n }\r\n\r\n public void setLastReceived(final long lastReceived) {\r\n this.lastReceived = lastReceived;\r\n }\r\n\r\n public void setName(final String name) {\r\n this.name = name;\r\n }\r\n\r\n public void setLastUploaded(final long newLastUploaded) {\r\n this.lastUploaded = newLastUploaded;\r\n }\r\n\r\n public void setOwner(final String owner) {\r\n this.owner = owner;\r\n }\r\n\r\n public String getComment() {\r\n return comment;\r\n }\r\n\r\n public void setComment(final String comment) {\r\n this.comment = comment;\r\n }\r\n\r\n public String getKeywords() {\r\n return keywords;\r\n }\r\n\r\n public void setKeywords(final String keywords) {\r\n this.keywords = keywords;\r\n }\r\n\r\n public int getRating() {\r\n return rating;\r\n }\r\n\r\n public void setRating(final int rating) {\r\n this.rating = rating;\r\n }\r\n\r\n public String getKey() {\r\n return key;\r\n }\r\n\r\n public void setKey(final String key) {\r\n this.key = key;\r\n }\r\n\r\n public FrostFileListFileObject getFileListFileObject() {\r\n return fileListFileObject;\r\n }\r\n\r\n public void setFileListFileObject(final FrostFileListFileObject fileListFileObject) {\r\n this.fileListFileObject = fileListFileObject;\r\n }\r\n}\r\n\nsrc/main/java/frost/util/TextSearchFun.java\npublic class TextSearchFun {\r\n\r\n private final static SearchStringParser searchStringParser = new SearchStringParser();\r\n\r\n private static final String NOT_IDENT = \">?*NOT*?<\";\r\n \r\n private static List emptyList = new LinkedList();\r\n\r\n\tpublic enum SPLIT {\r\n\t\tSEARCH, NOT_SEARCH\r\n\t};\r\n\r\n /**\r\n * Searches text for occurence of any of the provided strings.\r\n * @param text text to search into\r\n * @param notStrings list of strings\r\n * @return true if any string occurs in text, false if no string occurs in text\r\n */\r\n public static boolean containsAnyString(String text, List notStrings) {\r\n if( notStrings != null && !notStrings.isEmpty() && text != null && text.length() > 0 ) {\r\n for(int x=0; x < notStrings.size(); x++) {\r\n String notName = notStrings.get(x);\r\n if( text.indexOf(notName) > -1 ) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Searches text for all occurences of provided strings.\r\n * @param text text to search into\r\n * @param strings List of strings to search\r\n * @return true if ALL strings occur in the text, false otherwise\r\n */\r\n public static boolean containsEachString(String text, List strings) {\r\n for(int x=0; x < strings.size(); x++) {\r\n String string = strings.get(x);\r\n if( text.indexOf(string) < 0 ) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Splits an input search string into search words and NOT search words.\r\n * @return List[2] where List[0] is a list of search string and List[1] is a List of NOT search strings\r\n */\r\n\tpublic static EnumMap> splitStrings(String input, boolean makeLowerCase) {\r\n \r\n List strList;\r\n\r\n // we share one instance of the parser\r\n synchronized(searchStringParser) {\r\n strList = searchStringParser.parseSearchText(input);\r\n }\r\n\r\n\t\tEnumMap> retVal = new EnumMap<>(SPLIT.class);\r\n\t\tArrayList searchStrings = new ArrayList<>();\r\n\t\tArrayList notSearchStrings = new ArrayList<>();\r\n\t\tretVal.put(SPLIT.SEARCH, searchStrings);\r\n\t\tretVal.put(SPLIT.NOT_SEARCH, notSearchStrings);\r\n\r\n // all strings until SearchStringParser.NOT_IDENT are ANDed, all after NOT are the notStrings\r\n boolean collectNotStrings = false;\r\n for(Iterator i=strList.iterator(); i.hasNext(); ) {\r\n String s = i.next();\r\n if( s.equals(NOT_IDENT) ) {\r\n collectNotStrings = true;\r\n } else {\r\n if( makeLowerCase ) {\r\n s = s.toLowerCase();\r\n }\r\n if( !collectNotStrings ) {\r\n searchStrings.add(s);\r\n } else {\r\n notSearchStrings.add(s);\r\n }\r\n }\r\n }\r\n return retVal;\r\n }\r\n \r\n /**\r\n * Splits a String into parts. \r\n * First NOT is converted to \">?*NOT*?<\", more NOTs are dropped. \"NOT\" keeps NOT.\r\n * Input: \"mars venus \\\"milky way\\\" NOT \\\"NOT\\\" NOT sun\" \r\n * Output: [mars, venus, milky way, >?*NOT*?<, NOT, sun]\r\n */\r\n private static class SearchStringParser {\r\n\r\n /**\r\n * Parse the user's search box input into a Set of String tokens.\r\n * \r\n * @return Set of Strings, one for each word in fSearchText; here \"word\" is defined as either a lone word\r\n * surrounded by whitespace, or as a series of words surrounded by double quotes, \"like this\".\r\n */\r\n public List parseSearchText(String aSearchText) {\r\n \r\n if( aSearchText == null ) {\r\n return emptyList;\r\n }\r\n fSearchText = aSearchText;\r\n notAdded = false;\r\n\r\n List result = new LinkedList();\r\n\r\n boolean returnTokens = true;\r\n String currentDelims = fWHITESPACE_AND_QUOTES;\r\n StringTokenizer parser = new StringTokenizer(fSearchText, currentDelims, returnTokens);\r\n\r\n String token = null;\r\n boolean inQuotes = false;\r\n while( parser.hasMoreTokens() ) {\r\n token = parser.nextToken(currentDelims);\r\n if( !isDoubleQuote(token) ) {\r\n addNonTrivialWordToResult(token, result, inQuotes);\r\n } else {\r\n currentDelims = flipDelimiters(currentDelims);\r\n inQuotes = !inQuotes;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n // PRIVATE //\r\n private String fSearchText;\r\n private static final String fDOUBLE_QUOTE = \"\\\"\";\r\n\r\n // the parser flips between these two sets of delimiters\r\n private static final String fWHITESPACE_AND_QUOTES = \" \\t\\r\\n\\\"\";\r\n private static final String fQUOTES_ONLY = \"\\\"\";\r\n \r\n private boolean notAdded;\r\n\r\n private boolean textHasContent(String aText) {\r\n return (aText != null) && (aText.trim().length() > 0);\r\n }\r\n\r\n private void addNonTrivialWordToResult(String aToken, List aResult, boolean inQuotes) {\r\n if( textHasContent(aToken) ) {\r\n aToken = aToken.trim();\r\n if( !inQuotes && aToken.equals(\"NOT\") ) {\r\n if( !notAdded ) {\r\n // add NOT one time\r\n aResult.add(NOT_IDENT);\r\n notAdded = true;\r\n }\r\n } else {\r\n aResult.add(aToken.trim());\r\n }\r\n }\r\n }\r\n\r\n private boolean isDoubleQuote(String aToken) {\r\n return aToken.equals(fDOUBLE_QUOTE);\r\n }\r\n\r\n private String flipDelimiters(String aCurrentDelims) {\r\n String result = null;\r\n if( aCurrentDelims.equals(fWHITESPACE_AND_QUOTES) ) {\r\n result = fQUOTES_ONLY;\r\n } else {\r\n result = fWHITESPACE_AND_QUOTES;\r\n }\r\n return result;\r\n }\r\n }\r\n}\r\n\nsrc/main/java/frost/storage/FileListCallback.java\npublic interface FileListCallback {\r\n public boolean fileRetrieved(FrostFileListFileObject fo);\r\n}\r\n\nsrc/main/java/frost/storage/perst/filelist/FileListStorage.java\npublic class FileListStorage extends AbstractFrostStorage implements ExitSavable, PropertyChangeListener {\r\n\t\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(FileListStorage.class);\r\n\r\n private FileListStorageRoot storageRoot = null;\r\n\r\n private static final String STORAGE_FILENAME = \"filelist.dbs\";\r\n\r\n private static FileListStorage instance = new FileListStorage();\r\n\r\n private boolean rememberSharedFileDownloaded;\r\n\r\n protected FileListStorage() {\r\n super();\r\n }\r\n\r\n public static FileListStorage inst() {\r\n return instance;\r\n }\r\n\r\n @Override\r\n public String getStorageFilename() {\r\n return STORAGE_FILENAME;\r\n }\r\n\r\n @Override\r\n public boolean initStorage() {\r\n rememberSharedFileDownloaded = Core.frostSettings.getBoolValue(SettingsClass.REMEMBER_SHAREDFILE_DOWNLOADED);\r\n Core.frostSettings.addPropertyChangeListener(SettingsClass.REMEMBER_SHAREDFILE_DOWNLOADED, this);\r\n\r\n final String databaseFilePath = buildStoragePath(getStorageFilename()); // path to the database file\r\n final long pagePoolSize = getPagePoolSize(SettingsClass.PERST_PAGEPOOLSIZE_FILELIST);\r\n\r\n open(databaseFilePath, pagePoolSize, true, true, false);\r\n\r\n storageRoot = (FileListStorageRoot)getStorage().getRoot();\r\n if (storageRoot == null) {\r\n // Storage was not initialized yet\r\n storageRoot = new FileListStorageRoot(getStorage());\r\n getStorage().setRoot(storageRoot);\r\n commit(); // commit transaction\r\n }\r\n storageRoot.createNewFields(getStorage());\r\n return true;\r\n }\r\n\r\n public void silentClose() {\r\n close();\r\n storageRoot = null;\r\n }\r\n\r\n public void exitSave() {\r\n close();\r\n storageRoot = null;\r\n logger.info(\"FileListStorage closed.\");\r\n }\r\n\r\n public IPersistentList createList() {\r\n return getStorage().createScalableList();\r\n }\r\n\r\n public boolean insertOrUpdateFileListFileObject(final FrostFileListFileObject flf) {\r\n // check for dups and update them!\r\n final FrostFileListFileObject pflf = storageRoot.getFileListFileObjects().get(flf.getSha());\r\n if( pflf == null ) {\r\n // insert new\r\n storageRoot.getFileListFileObjects().put(flf.getSha(), flf);\r\n\r\n for( final Iterator i = flf.getFrostFileListFileObjectOwnerIterator(); i.hasNext(); ) {\r\n final FrostFileListFileObjectOwner o = i.next();\r\n addFileListFileOwnerToIndices(o);\r\n }\r\n } else {\r\n // update existing\r\n updateFileListFileFromOtherFileListFile(pflf, flf);\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Adds a new FrostFileListFileObjectOwner to the indices.\r\n */\r\n private void addFileListFileOwnerToIndices(final FrostFileListFileObjectOwner o) {\r\n // maybe the owner already shares other files\r\n PerstIdentitiesFiles pif = storageRoot.getIdentitiesFiles().get(o.getOwner());\r\n if( pif == null ) {\r\n pif = new PerstIdentitiesFiles(o.getOwner(), getStorage());\r\n storageRoot.getIdentitiesFiles().put(o.getOwner(), pif);\r\n }\r\n pif.addFileToIdentity(o);\r\n\r\n // add to indices\r\n maybeAddFileListFileInfoToIndex(o.getName(), o, storageRoot.getFileNameIndex());\r\n maybeAddFileListFileInfoToIndex(o.getComment(), o, storageRoot.getFileCommentIndex());\r\n maybeAddFileListFileInfoToIndex(o.getKeywords(), o, storageRoot.getFileKeywordIndex());\r\n maybeAddFileListFileInfoToIndex(o.getOwner(), o, storageRoot.getFileOwnerIndex());\r\n }\r\n\r\n private void maybeAddFileListFileInfoToIndex(String lName, final FrostFileListFileObjectOwner o, final Index ix) {\r\n if( lName == null || lName.length() == 0 ) {\r\n return;\r\n }\r\n lName = lName.toLowerCase();\r\n PerstFileListIndexEntry ie = ix.get(lName);\r\n if( ie == null ) {\r\n ie = new PerstFileListIndexEntry(getStorage());\r\n ix.put(lName, ie);\r\n }\r\n ie.getFileOwnersWithText().add(o);\r\n }\r\n\r\n public FrostFileListFileObject getFileBySha(final String sha) {\r\n if( !beginCooperativeThreadTransaction() ) {\r\n return null;\r\n }\r\n final FrostFileListFileObject o;\r\n try {\r\n o = storageRoot.getFileListFileObjects().get(sha);\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return o;\r\n }\r\n\r\n public int getFileCount() {\r\n if( !beginCooperativeThreadTransaction() ) {\r\n return 0;\r\n }\r\n final int count;\r\n try {\r\n count = storageRoot.getFileListFileObjects().size();\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return count;\r\n }\r\n\r\n public int getFileCount(final String idUniqueName) {\r\n if( !beginCooperativeThreadTransaction() ) {\r\n return 0;\r\n }\r\n final int count;\r\n try {\r\n final PerstIdentitiesFiles pif = storageRoot.getIdentitiesFiles().get(idUniqueName);\r\n if( pif != null ) {\r\n count = pif.getFilesFromIdentity().size();\r\n } else {\r\n count = 0;\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return count;\r\n }\r\n\r\n public int getSharerCount() {\r\n if( !beginCooperativeThreadTransaction() ) {\r\n return 0;\r\n }\r\n final int count;\r\n try {\r\n count = storageRoot.getIdentitiesFiles().size();\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return count;\r\n }\r\n\r\n // FIXME: implement this faster, e.g. maintain the sum in storageRoot, update on each insert/remove\r\n public long getFileSizes() {\r\n if( !beginCooperativeThreadTransaction() ) {\r\n return 0L;\r\n }\r\n long sizes = 0;\r\n try {\r\n for( final FrostFileListFileObject fo : storageRoot.getFileListFileObjects() ) {\r\n sizes += fo.getSize();\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return sizes;\r\n }\r\n\r\n /**\r\n * Must be called within a perst thread transaction!\r\n */\r\n public void markFileListFileHidden(final FrostFileListFileObject fof) {\r\n if (!fof.isHidden()) {\r\n fof.setHidden(true);\r\n fof.modify();\r\n storageRoot.getHiddenFileOids().add(new PerstHiddenFileOid(fof.getOid()));\r\n }\r\n }\r\n\r\n public void resetHiddenFiles() {\r\n if( beginExclusiveThreadTransaction() ) {\r\n try {\r\n \tfinal Storage storage = getStorage();\r\n for (final Iterator it = storageRoot.getHiddenFileOids().iterator(); it.hasNext(); ) {\r\n final PerstHiddenFileOid hf = it.next();\r\n final FrostFileListFileObject fof = (FrostFileListFileObject) storage.getObjectByOID(hf.getHiddenFileOid());\r\n if (fof != null && fof.isHidden()) {\r\n fof.setHidden(false);\r\n fof.modify();\r\n }\r\n it.remove();\r\n hf.deallocate();\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n }\r\n\r\n public int getHiddenFilesCount() {\r\n return storageRoot.getHiddenFileOids().size();\r\n }\r\n\r\n private void maybeRemoveFileListFileInfoFromIndex(\r\n final String lName,\r\n final FrostFileListFileObjectOwner o,\r\n final Index ix)\r\n {\r\n if( lName != null && lName.length() > 0 ) {\r\n final String lowerCaseName = lName.toLowerCase();\r\n final PerstFileListIndexEntry ie = ix.get(lowerCaseName);\r\n if( ie != null ) {\r\n ie.getFileOwnersWithText().remove(o);\r\n\r\n if( ie.getFileOwnersWithText().size() == 0 ) {\r\n // no more owners for this text, remove from index\r\n if( ix.remove(lowerCaseName) != null ) {\r\n ie.deallocate();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Remove owners that were not seen for more than MINIMUM_DAYS_OLD days and have no CHK key set.\r\n */\r\n public int cleanupFileListFileOwners(final boolean removeOfflineFilesWithKey, final int offlineFilesMaxDaysOld) {\r\n\r\n if( !beginExclusiveThreadTransaction() ) {\r\n return 0;\r\n }\r\n\r\n int count = 0;\r\n try {\r\n final long minVal = System.currentTimeMillis() - (offlineFilesMaxDaysOld * 24L * 60L * 60L * 1000L);\r\n for( final PerstIdentitiesFiles pif : storageRoot.getIdentitiesFiles() ) {\r\n for( final Iterator i = pif.getFilesFromIdentity().iterator(); i.hasNext(); ) {\r\n final FrostFileListFileObjectOwner o = i.next();\r\n boolean remove = false;\r\n\r\n if( o.getLastReceived() < minVal ) {\r\n // outdated owner\r\n if( o.getKey() != null && o.getKey().length() > 0 ) {\r\n // has a key\r\n if( removeOfflineFilesWithKey ) {\r\n remove = true;\r\n }\r\n } else {\r\n // has no key\r\n remove = true;\r\n }\r\n }\r\n\r\n if( remove ) {\r\n // remove this owner file info from file list object\r\n final FrostFileListFileObject fof = o.getFileListFileObject();\r\n o.setFileListFileObject(null);\r\n fof.deleteFrostFileListFileObjectOwner(o);\r\n\r\n // remove from indices\r\n maybeRemoveFileListFileInfoFromIndex(o.getName(), o, storageRoot.getFileNameIndex());\r\n maybeRemoveFileListFileInfoFromIndex(o.getComment(), o, storageRoot.getFileCommentIndex());\r\n maybeRemoveFileListFileInfoFromIndex(o.getKeywords(), o, storageRoot.getFileKeywordIndex());\r\n maybeRemoveFileListFileInfoFromIndex(o.getOwner(), o, storageRoot.getFileOwnerIndex());\r\n\r\n // remove this owner file info from identities files\r\n i.remove();\r\n // delete from store\r\n o.deallocate();\r\n\r\n fof.modify();\r\n\r\n count++;\r\n }\r\n }\r\n if( pif.getFilesFromIdentity().size() == 0 ) {\r\n // no more files for this identity, remove\r\n if( storageRoot.getIdentitiesFiles().remove(pif.getUniqueName()) != null ) {\r\n pif.deallocate();\r\n }\r\n }\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return count;\r\n }\r\n\r\n /**\r\n * Remove files that have no owner.\r\n */\r\n public int cleanupFileListFiles() {\r\n if( !beginExclusiveThreadTransaction() ) {\r\n return 0;\r\n }\r\n\r\n int count = 0;\r\n try {\r\n final HashSet oidsToRemove = new HashSet();\r\n for( final Iterator i = storageRoot.getFileListFileObjects().iterator(); i.hasNext(); ) {\r\n final FrostFileListFileObject fof = i.next();\r\n if( fof.getFrostFileListFileObjectOwnerListSize() == 0 ) {\r\n // no more owners, we also have no name, remove\r\n\t\t\t\t\toidsToRemove.add(fof.getOid());\r\n i.remove();\r\n fof.deallocate();\r\n count++;\r\n }\r\n }\r\n // remove deleted files from hiddenFilesOid list\r\n for (final Iterator it = storageRoot.getHiddenFileOids().iterator(); it.hasNext(); ) {\r\n final PerstHiddenFileOid hf = it.next();\r\n\t\t\t\tif (oidsToRemove.contains(hf.getHiddenFileOid())) {\r\n it.remove();\r\n hf.deallocate();\r\n }\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n\r\n return count;\r\n }\r\n\r\n /**\r\n * Reset the lastdownloaded column for all file entries.\r\n */\r\n public void resetLastDownloaded() {\r\n\r\n if( !beginExclusiveThreadTransaction() ) {\r\n return;\r\n }\r\n try {\r\n for( final FrostFileListFileObject fof : storageRoot.getFileListFileObjects() ) {\r\n fof.setLastDownloaded(0);\r\n fof.modify();\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n /**\r\n * Update the item with SHA, set requestlastsent and requestssentcount.\r\n * Does NOT commit!\r\n */\r\n public boolean updateFrostFileListFileObjectAfterRequestSent(final String sha, final long requestLastSent) {\r\n\r\n final FrostFileListFileObject oldSfo = getFileBySha(sha);\r\n if( oldSfo == null ) {\r\n return false;\r\n }\r\n\r\n oldSfo.setRequestLastSent(requestLastSent);\r\n oldSfo.setRequestsSentCount(oldSfo.getRequestsSentCount() + 1);\r\n\r\n oldSfo.modify();\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Update the item with SHA, set requestlastsent and requestssentcount\r\n * Does NOT commit!\r\n */\r\n public boolean updateFrostFileListFileObjectAfterRequestReceived(final String sha, long requestLastReceived) {\r\n\r\n final FrostFileListFileObject oldSfo = getFileBySha(sha);\r\n if( oldSfo == null ) {\r\n return false;\r\n }\r\n\r\n if( oldSfo.getRequestLastReceived() > requestLastReceived ) {\r\n requestLastReceived = oldSfo.getRequestLastReceived();\r\n }\r\n\r\n oldSfo.setRequestLastReceived(requestLastReceived);\r\n oldSfo.setRequestsReceivedCount(oldSfo.getRequestsReceivedCount() + 1);\r\n\r\n oldSfo.modify();\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Update the item with SHA, set lastdownloaded\r\n */\r\n public boolean updateFrostFileListFileObjectAfterDownload(final String sha, final long lastDownloaded) {\r\n\r\n if( !rememberSharedFileDownloaded ) {\r\n return true;\r\n }\r\n\r\n if( !beginExclusiveThreadTransaction() ) {\r\n return false;\r\n }\r\n\r\n try {\r\n final FrostFileListFileObject oldSfo = getFileBySha(sha);\r\n if( oldSfo == null ) {\r\n endThreadTransaction();\r\n return false;\r\n }\r\n oldSfo.setLastDownloaded(lastDownloaded);\r\n oldSfo.modify();\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Retrieves a list of FrostSharedFileOjects.\r\n */\r\n public void retrieveFiles(\r\n final FileListCallback callback,\r\n final List names,\r\n final List comments,\r\n final List keywords,\r\n final List owners,\r\n String[] extensions)\r\n {\r\n if( !beginCooperativeThreadTransaction() ) {\r\n return;\r\n }\r\n\r\n logger.info(\"Starting file search...\");\r\n final long t = System.currentTimeMillis();\r\n\r\n boolean searchForNames = true;\r\n boolean searchForComments = true;\r\n boolean searchForKeywords = true;\r\n boolean searchForOwners = true;\r\n boolean searchForExtensions = true;\r\n\r\n if( names == null || names.size() == 0 ) { searchForNames = false; }\r\n if( comments == null || comments.size() == 0 ) { searchForComments = false; }\r\n if( keywords == null || keywords.size() == 0 ) { searchForKeywords = false; }\r\n if( owners == null || owners.size() == 0 ) { searchForOwners = false; }\r\n if( extensions == null || extensions.length == 0 ) { searchForExtensions = false; }\r\n\r\n try {\r\n if( !searchForNames && !searchForComments && ! searchForKeywords && !searchForOwners && !searchForExtensions) {\r\n // find ALL files\r\n for(final FrostFileListFileObject o : storageRoot.getFileListFileObjects()) {\r\n if(callback.fileRetrieved(o)) {\r\n return; // stop requested\r\n }\r\n }\r\n return;\r\n }\r\n\r\n if( !searchForExtensions ) {\r\n extensions = null;\r\n }\r\n\r\n final HashSet ownerOids = new HashSet();\r\n\r\n if( searchForNames || searchForExtensions ) {\r\n searchForFiles(ownerOids, names, extensions, storageRoot.getFileNameIndex());\r\n }\r\n\r\n if( searchForComments ) {\r\n searchForFiles(ownerOids, comments, null, storageRoot.getFileCommentIndex());\r\n }\r\n\r\n if( searchForKeywords ) {\r\n searchForFiles(ownerOids, keywords, null, storageRoot.getFileKeywordIndex());\r\n }\r\n\r\n if( searchForOwners ) {\r\n searchForFiles(ownerOids, owners, null, storageRoot.getFileOwnerIndex());\r\n }\r\n\r\n // collect oids to prevent duplicate FileListFileObjects\r\n final HashSet foundFileObjectOids = new HashSet();\r\n\r\n for( final Integer i : ownerOids ) {\r\n final FrostFileListFileObjectOwner owner = (FrostFileListFileObjectOwner) getStorage().getObjectByOID(i);\r\n final FrostFileListFileObject fileObject = owner.getFileListFileObject();\r\n if (fileObject != null) {\r\n if (fileObject.isHidden()) {\r\n // ignore hidden file\r\n continue;\r\n }\r\n final int oid = fileObject.getOid();\r\n if (!foundFileObjectOids.contains(oid)) {\r\n foundFileObjectOids.add(oid);\r\n if (callback.fileRetrieved(fileObject)) {\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n logger.info(\"Finished file search, duration = {}\", System.currentTimeMillis() - t);\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n private void searchForFiles(\r\n final HashSet oids,\r\n final List searchStrings,\r\n final String[] extensions, // only used for name search\r\n final Index ix)\r\n {\r\n for(final Map.Entry entry : ix.entryIterator() ) {\r\n final String key = (String)entry.getKey();\r\n IPersistentList fileOwnersWithText = entry.getValue().getFileOwnersWithText();\r\n \r\n if( searchStrings != null ) {\r\n for(final String searchString : searchStrings) {\r\n if( key.indexOf(searchString) > -1 ) {\r\n // add all owner oids\r\n \tfinal Iterator i = fileOwnersWithText.iterator();\r\n while(i.hasNext()) {\r\n final int oid = ((PersistentIterator)i).nextOid();\r\n oids.add(oid);\r\n }\r\n }\r\n }\r\n }\r\n \r\n if( extensions != null ) {\r\n for( final String extension : extensions ) {\r\n if( key.endsWith(extension) ) {\r\n // add all owner oids\r\n final Iterator i = fileOwnersWithText.iterator();\r\n while(i.hasNext()) {\r\n final int oid = ((PersistentIterator)i).nextOid();\r\n oids.add(oid);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\nboolean alwaysUseLatestChkKey = true; // FIXME: must be true as long as the key changes now and then. False prevents fake files.\r\n\r\n private boolean updateFileListFileFromOtherFileListFile(final FrostFileListFileObject oldFof, final FrostFileListFileObject newFof) {\r\n // file is already in FILELIST table, maybe add new FILEOWNER and update fields\r\n // maybe update oldSfo\r\n boolean doUpdate = false;\r\n if( oldFof.getKey() == null && newFof.getKey() != null ) {\r\n oldFof.setKey(newFof.getKey()); doUpdate = true;\r\n } else if( alwaysUseLatestChkKey\r\n && oldFof.getLastUploaded() < newFof.getLastUploaded()\r\n && oldFof.getKey() != null\r\n && newFof.getKey() != null\r\n && !oldFof.getKey().equals(newFof.getKey()) )\r\n {\r\n oldFof.setKey(newFof.getKey()); doUpdate = true;\r\n }\r\n if( oldFof.getFirstReceived() > newFof.getFirstReceived() ) {\r\n oldFof.setFirstReceived(newFof.getFirstReceived()); doUpdate = true;\r\n }\r\n if( oldFof.getLastReceived() < newFof.getLastReceived() ) {\r\n oldFof.setLastReceived(newFof.getLastReceived()); doUpdate = true;\r\n }\r\n if( oldFof.getLastUploaded() < newFof.getLastUploaded() ) {\r\n oldFof.setLastUploaded(newFof.getLastUploaded()); doUpdate = true;\r\n }\r\n if( oldFof.getLastDownloaded() < newFof.getLastDownloaded() ) {\r\n oldFof.setLastDownloaded(newFof.getLastDownloaded()); doUpdate = true;\r\n }\r\n if( oldFof.getRequestLastReceived() < newFof.getRequestLastReceived() ) {\r\n oldFof.setRequestLastReceived(newFof.getRequestLastReceived()); doUpdate = true;\r\n }\r\n if( oldFof.getRequestLastSent() < newFof.getRequestLastSent() ) {\r\n oldFof.setRequestLastSent(newFof.getRequestLastSent()); doUpdate = true;\r\n }\r\n if( oldFof.getRequestsReceivedCount() < newFof.getRequestsReceivedCount() ) {\r\n oldFof.setRequestsReceivedCount(newFof.getRequestsReceivedCount()); doUpdate = true;\r\n }\r\n if( oldFof.getRequestsSentCount() < newFof.getRequestsSentCount() ) {\r\n oldFof.setRequestsSentCount(newFof.getRequestsSentCount()); doUpdate = true;\r\n }\r\n\r\n for(final Iterator i = newFof.getFrostFileListFileObjectOwnerIterator(); i.hasNext(); ) {\r\n\r\n final FrostFileListFileObjectOwner obNew = i.next();\r\n\r\n // check if we have an owner object for this sharer\r\n FrostFileListFileObjectOwner obOld = null;\r\n for(final Iterator j = oldFof.getFrostFileListFileObjectOwnerIterator(); j.hasNext(); ) {\r\n final FrostFileListFileObjectOwner o = j.next();\r\n if( o.getOwner().equals(obNew.getOwner()) ) {\r\n obOld = o;\r\n break;\r\n }\r\n }\r\n\r\n if( obOld == null ) {\r\n // add new\r\n oldFof.addFrostFileListFileObjectOwner(obNew);\r\n addFileListFileOwnerToIndices(obNew);\r\n doUpdate = true;\r\n } else {\r\n // update existing\r\n if( obOld.getLastReceived() < obNew.getLastReceived() ) {\r\n\r\n maybeUpdateFileListInfoInIndex(obOld.getName(), obNew.getName(), obOld, storageRoot.getFileNameIndex());\r\n obOld.setName(obNew.getName());\r\n\r\n maybeUpdateFileListInfoInIndex(obOld.getComment(), obNew.getComment(), obOld, storageRoot.getFileCommentIndex());\r\n obOld.setComment(obNew.getComment());\r\n\r\n maybeUpdateFileListInfoInIndex(obOld.getKeywords(), obNew.getKeywords(), obOld, storageRoot.getFileKeywordIndex());\r\n obOld.setKeywords(obNew.getKeywords());\r\n\r\n obOld.setLastReceived(obNew.getLastReceived());\r\n obOld.setLastUploaded(obNew.getLastUploaded());\r\n obOld.setRating(obNew.getRating());\r\n obOld.setKey(obNew.getKey());\r\n\r\n obOld.modify();\r\n\r\n doUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if( doUpdate ) {\r\n oldFof.modify();\r\n }\r\n\r\n return doUpdate;\r\n }\r\n\r\n private void maybeUpdateFileListInfoInIndex(\r\n final String oldValue,\r\n final String newValue,\r\n final FrostFileListFileObjectOwner o,\r\n final Index ix)\r\n {\r\n // remove current value from index of needed, add new value to index if needed\r\n if( oldValue != null ) {\r\n if( newValue != null ) {\r\n if( oldValue.toLowerCase().equals(newValue.toLowerCase()) ) {\r\n // value not changed, ignore index change\r\n return;\r\n }\r\n // we have to add this value to the index\r\n maybeAddFileListFileInfoToIndex(newValue, o, ix);\r\n }\r\n // we have to remove the old value from index\r\n maybeRemoveFileListFileInfoFromIndex(oldValue, o, ix);\r\n }\r\n }\r\n\r\n public void propertyChange(final PropertyChangeEvent evt) {\r\n rememberSharedFileDownloaded = Core.frostSettings.getBoolValue(SettingsClass.REMEMBER_SHAREDFILE_DOWNLOADED);\r\n }\r\n}\r", "answers": [" for( Iterator i = fo.getFrostFileListFileObjectOwnerIterator(); i.hasNext(); ) {\r"], "length": 7346, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "e209a646-0c8b-4833-8ebd-83110b11a289", "reasoning": "The method searchFile1 begins checking hide‑file options. After initializing a boolean accept = true, the code will need to examine each owner of the file to possibly set accept to false based on hideBadUserFiles / hideCheckUserFiles / hideObserveUserFiles flags. In the Frost codebase owners are iterated with an Iterator obtained via fo.getFrostFileListFileObjectOwnerIterator(). Therefore the next line should start that loop.", "reasoning_model_answer": "for (final Iterator i = fo.getFrostFileListFileObjectOwnerIterator(); i.hasNext(); ) {", "assistant_with_reasoning": "\nThe method searchFile1 begins checking hide‑file options. After initializing a boolean accept = true, the code will need to examine each owner of the file to possibly set accept to false based on hideBadUserFiles / hideCheckUserFiles / hideObserveUserFiles flags. In the Frost codebase owners are iterated with an Iterator obtained via fo.getFrostFileListFileObjectOwnerIterator(). Therefore the next line should start that loop.\n\nfor (final Iterator i = fo.getFrostFileListFileObjectOwnerIterator(); i.hasNext(); ) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.824, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36484, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "for (final Iterator i = fo.getFrostFileListFileObjectOwnerIterator(); i.hasNext(); ) {", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.shatteredpixel.shatteredpixeldungeon.effects.particles.ShadowParticle;\nimport com.shatteredpixel.shatteredpixeldungeon.effects.particles.SparkParticle;\nimport com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;\nimport com.shatteredpixel.shatteredpixeldungeon.tiles.DungeonTilemap;\nimport com.watabou.noosa.TextureFilm;\nimport com.watabou.noosa.audio.Sample;\nimport com.watabou.noosa.particles.Emitter;\nimport com.watabou.utils.Callback;\nimport com.shatteredpixel.shatteredpixeldungeon.Assets;\nimport com.shatteredpixel.shatteredpixeldungeon.actors.Char;\nimport com.shatteredpixel.shatteredpixeldungeon.actors.mobs.YogFist;\nimport com.shatteredpixel.shatteredpixeldungeon.effects.Beam;\nimport com.shatteredpixel.shatteredpixeldungeon.effects.MagicMissile;\nimport com.shatteredpixel.shatteredpixeldungeon.effects.Speck;\nimport com.shatteredpixel.shatteredpixeldungeon.effects.particles.CorrosionParticle;\nimport com.shatteredpixel.shatteredpixeldungeon.effects.particles.FlameParticle;\nimport com.shatteredpixel.shatteredpixeldungeon.effects.particles.LeafParticle;", "context": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/FistSprite.java\n\tpublic static class Soiled extends FistSprite {\n\n\t\t{\n\t\t\tboltType = MagicMissile.FOLIAGE;\n\t\t}\n\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 10;\n\t\t}\n\n\t\t@Override\n\t\tprotected Emitter createEmitter() {\n\t\t\tEmitter emitter = emitter();\n\t\t\temitter.pour( LeafParticle.GENERAL, 0.06f );\n\t\t\treturn emitter;\n\t\t}\n\n\t\t@Override\n\t\tpublic int blood() {\n\t\t\treturn 0xFF7F5424;\n\t\t}\n\n\t}\n\n\tpublic static class Rotting extends FistSprite {\n\n\t\t{\n\t\t\tboltType = MagicMissile.TOXIC_VENT;\n\t\t}\n\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 20;\n\t\t}\n\n\t\t@Override\n\t\tprotected Emitter createEmitter() {\n\t\t\tEmitter emitter = emitter();\n\t\t\temitter.pour(Speck.factory(Speck.TOXIC), 0.25f );\n\t\t\treturn emitter;\n\t\t}\n\n\t\t@Override\n\t\tpublic int blood() {\n\t\t\treturn 0xFFB8BBA1;\n\t\t}\n\n\t}\n\n\tpublic static class Rusted extends FistSprite {\n\n\t\t{\n\t\t\tboltType = MagicMissile.CORROSION;\n\t\t}\n\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 30;\n\t\t}\n\n\t\t@Override\n\t\tprotected Emitter createEmitter() {\n\t\t\tEmitter emitter = emitter();\n\t\t\temitter.pour(CorrosionParticle.MISSILE, 0.06f );\n\t\t\treturn emitter;\n\t\t}\n\n\t\t@Override\n\t\tpublic int blood() {\n\t\t\treturn 0xFF7F7F7F;\n\t\t}\n\n\t}\n\n\tpublic static class Bright extends FistSprite {\n\n\t\t{\n\t\t\tboltType = MagicMissile.RAINBOW;\n\t\t}\n\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 40;\n\t\t}\n\n\t\t@Override\n\t\tprotected Emitter createEmitter() {\n\t\t\tEmitter emitter = emitter();\n\t\t\temitter.pour(SparkParticle.STATIC, 0.06f );\n\t\t\treturn emitter;\n\t\t}\n\n\t\t@Override\n\t\tpublic void zap( int cell ) {\n\t\t\tsuper.zap( cell, null );\n\n\t\t\t((YogFist)ch).onZapComplete();\n\t\t\tparent.add( new Beam.LightRay(center(), DungeonTilemap.raisedTileCenterToWorld(cell)));\n\t\t}\n\t\t@Override\n\t\tpublic int blood() {\n\t\t\treturn 0xFFFFFFFF;\n\t\t}\n\n\t}\n\n\tpublic static class Dark extends FistSprite {\n\n\t\t{\n\t\t\tboltType = MagicMissile.SHADOW;\n\t\t}\n\n\t\t@Override\n\t\tprotected int texOffset() {\n\t\t\treturn 50;\n\t\t}\n\n\t\t@Override\n\t\tprotected Emitter createEmitter() {\n\ncore/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/particles/SparkParticle.java\npublic class SparkParticle extends PixelParticle {\n\n\tpublic static final Emitter.Factory FACTORY = new Factory() {\n\t\t@Override\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\t((SparkParticle)emitter.recycle( SparkParticle.class )).reset( x, y );\n\t\t}\n\t\t@Override\n\t\tpublic boolean lightMode() {\n\t\t\treturn true;\n\t\t}\n\t};\n\t\n\tpublic static final Emitter.Factory STATIC = new Factory() {\n\t\t@Override\n\t\tpublic void emit( Emitter emitter, int index, float x, float y ) {\n\t\t\t((SparkParticle)emitter.recycle( SparkParticle.class )).resetStatic( x, y );\n\t\t}\n\t\t@Override\n\t\tpublic boolean lightMode() {\n\t\t\treturn true;\n\t\t}\n\t};\n\t\n\tpublic SparkParticle() {\n\t\tsuper();\n\t\t\n\t\tsize( 2 );\n\t\t\n\t\tacc.set( 0, +50 );\n\t}\n\t\n\tpublic void reset( float x, float y ) {\n\t\trevive();\n\t\t\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tsize = 5;\n\t\t\n\t\tleft = lifespan = Random.Float( 0.5f, 1.0f );\n\t\t\n\t\tspeed.polar( -Random.Float( 3.1415926f ), Random.Float( 20, 40 ) );\n\t}\n\t\n\tpublic void resetStatic( float x, float y){\n\t\treset(x, y);\n\t\t\n\t\tleft = lifespan = Random.Float( 0.25f, 0.5f );\n\t\t\n\t\tacc.set( 0, 0 );\n\t\tspeed.set( 0, 0 );\n\t}\n\n\tpublic void setMaxSize( float value ){\n\t\tsize = value;\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\t\tsuper.update();\n\t\tsize( Random.Float( size * left / lifespan ) );\n\t}\n}\n\nSPD-classes/src/main/java/com/watabou/noosa/particles/Emitter.java\npublic class Emitter extends Group {\n\n\tprotected boolean lightMode = false;\n\t\n\tpublic float x;\n\tpublic float y;\n\tpublic float width;\n\tpublic float height;\n\t\n\tprotected Visual target;\n\tpublic boolean fillTarget = true;\n\t\n\tprotected float interval;\n\tprotected int quantity;\n\t\n\tpublic boolean on = false;\n\n\tprivate boolean started = false;\n\tpublic boolean autoKill = true;\n\t\n\tprotected int count;\n\tprotected float time;\n\t\n\tprotected Factory factory;\n\t\n\tpublic void pos( float x, float y ) {\n\t\tpos( x, y, 0, 0 );\n\t}\n\t\n\tpublic void pos( PointF p ) {\n\t\tpos( p.x, p.y, 0, 0 );\n\t}\n\t\n\tpublic void pos( float x, float y, float width, float height ) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\t\n\t\ttarget = null;\n\t}\n\n\tpublic void pos( Visual target ) {\n\t\tthis.target = target;\n\t}\n\n\tpublic void pos( Visual target, float x, float y, float width, float height ) {\n\t\tpos(x, y, width, height);\n\t\tpos(target);\n\t}\n\t\n\tpublic void burst( Factory factory, int quantity ) {\n\t\tstart( factory, 0, quantity );\n\t}\n\t\n\tpublic void pour( Factory factory, float interval ) {\n\t\tstart( factory, interval, 0 );\n\t}\n\n\tpublic void start( Factory factory, float interval, int quantity ) {\n\n\t\tthis.factory = factory;\n\t\tthis.lightMode = factory.lightMode();\n\t\t\n\t\tthis.interval = interval;\n\t\tthis.quantity = quantity;\n\t\t\n\t\tcount = 0;\n\t\ttime = Random.Float( interval );\n\t\t\n\t\ton = true;\n\t\tstarted = true;\n\t}\n\n\tpublic static boolean freezeEmitters = false;\n\n\tprotected boolean isFrozen(){\n\t\treturn Game.timeTotal > 1 && freezeEmitters;\n\t}\n\t\n\t@Override\n\tpublic void update() {\n\n\t\tif (isFrozen()){\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (on) {\n\t\t\ttime += Game.elapsed;\n\t\t\twhile (time > interval) {\n\t\t\t\ttime -= interval;\n\t\t\t\temit( count++ );\n\t\t\t\tif (quantity > 0 && count >= quantity) {\n\t\t\t\t\ton = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (started && autoKill && countLiving() == 0) {\n\t\t\tkill();\n\t\t}\n\t\t\n\t\tsuper.update();\n\t}\n\n\t@Override\n\tpublic void revive() {\n\t\tstarted = false;\n\t\t//some emitters may be killed while not visible, this ensures true is always the default\n\t\tvisible = true;\n\t\tsuper.revive();\n\t}\n\n\tprotected void emit( int index ) {\n\t\tif (target == null) {\n\t\t\tfactory.emit(\n\t\t\t\tthis,\n\t\t\t\tindex,\n\t\t\t\tx + Random.Float( width ),\n\t\t\t\ty + Random.Float( height ) );\n\t\t} else {\n\t\t\tif (fillTarget) {\n\t\t\t\tfactory.emit(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\ttarget.x + Random.Float( target.width ),\n\t\t\t\t\t\ttarget.y + Random.Float( target.height ) );\n\t\t\t} else {\n\t\t\t\tfactory.emit(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\ttarget.x + x + Random.Float( width ),\n\t\t\t\t\t\ttarget.y + y + Random.Float( height ) );\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void draw() {\n\t\tif (lightMode) {\n\t\t\tBlending.setLightMode();\n\t\t\tsuper.draw();\n\t\t\tBlending.setNormalMode();\n\t\t} else {\n\t\t\tsuper.draw();\n\t\t}\n\t}\n\t\n\tabstract public static class Factory {\n\t\t\n\t\tabstract public void emit( Emitter emitter, int index, float x, float y );\n\t\t\n\t\tpublic boolean lightMode() {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\ncore/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Assets.java\npublic class Assets {\n\n\tpublic static class Effects {\n\t\tpublic static final String EFFECTS = \"effects/effects.png\";\n\t\tpublic static final String FIREBALL = \"effects/fireball.png\";\n\t\tpublic static final String SPECKS = \"effects/specks.png\";\n\t\tpublic static final String SPELL_ICONS = \"effects/spell_icons.png\";\n\t}\n\n\tpublic static class Environment {\n\t\tpublic static final String TERRAIN_FEATURES = \"environment/terrain_features.png\";\n\n\t\tpublic static final String VISUAL_GRID = \"environment/visual_grid.png\";\n\t\tpublic static final String WALL_BLOCKING= \"environment/wall_blocking.png\";\n\n\t\tpublic static final String TILES_SEWERS = \"environment/tiles_sewers.png\";\n\t\tpublic static final String TILES_PRISON = \"environment/tiles_prison.png\";\n\t\tpublic static final String TILES_CAVES = \"environment/tiles_caves.png\";\n\t\tpublic static final String TILES_CITY = \"environment/tiles_city.png\";\n\t\tpublic static final String TILES_HALLS = \"environment/tiles_halls.png\";\n\t\tpublic static final String TILES_TEMPLE = \"environment/tiles_temple.png\";\n\t\tpublic static final String TILES_LABS\t= \"environment/tiles_labs.png\";\n\n\t\tpublic static final String WATER_SEWERS = \"environment/water0.png\";\n\t\tpublic static final String WATER_PRISON = \"environment/water1.png\";\n\t\tpublic static final String WATER_CAVES = \"environment/water2.png\";\n\t\tpublic static final String WATER_CITY = \"environment/water3.png\";\n\t\tpublic static final String WATER_HALLS = \"environment/water4.png\";\n\t\tpublic static final String WATER_TEMPLE = \"environment/water0_temple.png\";\n\t\tpublic static final String WATER_LABS\t= \"environment/water5.png\";\n\n\t\tpublic static final String WEAK_FLOOR = \"environment/custom_tiles/weak_floor.png\";\n\t\tpublic static final String SEWER_BOSS = \"environment/custom_tiles/sewer_boss.png\";\n\t\tpublic static final String PRISON_QUEST = \"environment/custom_tiles/prison_quest.png\";\n\t\tpublic static final String PRISON_EXIT = \"environment/custom_tiles/prison_exit.png\";\n\t\tpublic static final String CAVES_QUEST = \"environment/custom_tiles/caves_quest.png\";\n\t\tpublic static final String CAVES_BOSS = \"environment/custom_tiles/caves_boss.png\";\n\t\tpublic static final String CITY_BOSS = \"environment/custom_tiles/city_boss.png\";\n\t\tpublic static final String HALLS_SP = \"environment/custom_tiles/halls_special.png\";\n\t\tpublic static final String TEMPLE_SP = \"environment/custom_tiles/temple_special.png\";\n\t}\n\t\n\t//TODO include other font assets here? Some are platform specific though...\n\tpublic static class Fonts {\n\t\tpublic static final String PIXELFONT= \"fonts/pixel_font.png\";\n\t}\n\n\tpublic static class Interfaces {\n\t\tpublic static final String ARCS_BG = \"interfaces/arcs1.png\";\n\t\tpublic static final String ARCS_FG = \"interfaces/arcs2.png\";\n\n\t\tpublic static final String BANNERS = \"interfaces/banners.png\";\n\t\tpublic static final String BADGES = \"interfaces/badges.png\";\n\t\tpublic static final String LOCKED = \"interfaces/locked_badge.png\";\n\n\t\tpublic static final String CHROME = \"interfaces/chrome.png\";\n\t\tpublic static final String ICONS = \"interfaces/icons.png\";\n\t\tpublic static final String STATUS = \"interfaces/status_pane.png\";\n\t\tpublic static final String MENU = \"interfaces/menu_pane.png\";\n\t\tpublic static final String MENU_BTN = \"interfaces/menu_button.png\";\n\t\tpublic static final String TOOLBAR = \"interfaces/toolbar.png\";\n\t\tpublic static final String SHADOW = \"interfaces/shadow.png\";\n\t\tpublic static final String BOSSHP = \"interfaces/boss_hp.png\";\n\n\t\tpublic static final String SURFACE = \"interfaces/surface.png\";\n\n\t\tpublic static final String LOADING_SEWERS = \"interfaces/loading_sewers.png\";\n\t\tpublic static final String LOADING_PRISON = \"interfaces/loading_prison.png\";\n\t\tpublic static final String LOADING_CAVES = \"interfaces/loading_caves.png\";\n\t\tpublic static final String LOADING_CITY = \"interfaces/loading_city.png\";\n\t\tpublic static final String LOADING_HALLS = \"interfaces/loading_halls.png\";\n\n\t\tpublic static final String BUFFS_SMALL = \"interfaces/buffs.png\";\n\t\tpublic static final String BUFFS_LARGE = \"interfaces/large_buffs.png\";\n\n\t\tpublic static final String TALENT_ICONS = \"interfaces/talent_icons.png\";\n\t\tpublic static final String TALENT_BUTTON = \"interfaces/talent_button.png\";\n\n\t\tpublic static final String HERO_ICONS = \"interfaces/hero_icons.png\";\n\n\t\tpublic static final String RADIAL_MENU = \"interfaces/radial_menu.png\";\n\t}\n\n\t//these points to resource bundles, not raw asset files\n\tpublic static class Messages {\n\t\tpublic static final String ACTORS = \"messages/actors/actors\";\n\t\tpublic static final String ITEMS = \"messages/items/items\";\n\t\tpublic static final String JOURNAL = \"messages/journal/journal\";\n\t\tpublic static final String LEVELS = \"messages/levels/levels\";\n\t\tpublic static final String MISC = \"messages/misc/misc\";\n\t\tpublic static final String PLANTS = \"messages/plants/plants\";\n\t\tpublic static final String SCENES = \"messages/scenes/scenes\";\n\t\tpublic static final String UI = \"messages/ui/ui\";\n\t\tpublic static final String WINDOWS = \"messages/windows/windows\";\n\t}\n\n\tpublic static class Music {\n\t\tpublic static final String THEME_1 = \"music/theme_1.ogg\";\n\t\tpublic static final String THEME_2 = \"music/theme_2.ogg\";\n\t\tpublic static final String THEME_FINALE = \"music/theme_finale.ogg\";\n\n\t\tpublic static final String SEWERS_1 = \"music/sewers_1.ogg\";\n\t\tpublic static final String SEWERS_2 = \"music/sewers_2.ogg\";\n\t\tpublic static final String SEWERS_3 = \"music/sewers_3.ogg\";\n\t\tpublic static final String SEWERS_TENSE = \"music/sewers_tense.ogg\";\n\t\tpublic static final String SEWERS_BOSS = \"music/sewers_boss.ogg\";\n\n\t\tpublic static final String PRISON_1 = \"music/prison_1.ogg\";\n\t\tpublic static final String PRISON_2 = \"music/prison_2.ogg\";\n\t\tpublic static final String PRISON_3 = \"music/prison_3.ogg\";\n\t\tpublic static final String PRISON_TENSE = \"music/prison_tense.ogg\";\n\t\tpublic static final String PRISON_BOSS = \"music/prison_boss.ogg\";\n\n\t\tpublic static final String CAVES_1 = \"music/caves_1.ogg\";\n\t\tpublic static final String CAVES_2 = \"music/caves_2.ogg\";\n\t\tpublic static final String CAVES_3 = \"music/caves_3.ogg\";\n\t\tpublic static final String CAVES_TENSE = \"music/caves_tense.ogg\";\n\t\tpublic static final String CAVES_BOSS = \"music/caves_boss.ogg\";\n\t\tpublic static final String CAVES_BOSS_FINALE = \"music/caves_boss_finale.ogg\";\n\n\t\tpublic static final String CITY_1 = \"music/city_1.ogg\";\n\t\tpublic static final String CITY_2 = \"music/city_2.ogg\";\n\t\tpublic static final String CITY_3 = \"music/city_3.ogg\";\n\t\tpublic static final String CITY_TENSE = \"music/city_tense.ogg\";\n\t\tpublic static final String CITY_BOSS = \"music/city_boss.ogg\";\n\t\tpublic static final String CITY_BOSS_FINALE = \"music/city_boss_finale.ogg\";\n\n\t\tpublic static final String HALLS_1 = \"music/halls_1.ogg\";\n\t\tpublic static final String HALLS_2 = \"music/halls_2.ogg\";\n\t\tpublic static final String HALLS_3 = \"music/halls_3.ogg\";\n\t\tpublic static final String HALLS_TENSE = \"music/halls_tense.ogg\";\n\t\tpublic static final String HALLS_BOSS = \"music/halls_boss.ogg\";\n\t\tpublic static final String HALLS_BOSS_FINALE = \"music/halls_boss_finale.ogg\";\n\t}\n\n\tpublic static class Sounds {\n\t\tpublic static final String CLICK = \"sounds/click.mp3\";\n\t\tpublic static final String BADGE = \"sounds/badge.mp3\";\n\t\tpublic static final String GOLD = \"sounds/gold.mp3\";\n\n\t\tpublic static final String OPEN = \"sounds/door_open.mp3\";\n\t\tpublic static final String UNLOCK = \"sounds/unlock.mp3\";\n\t\tpublic static final String ITEM = \"sounds/item.mp3\";\n\t\tpublic static final String DEWDROP = \"sounds/dewdrop.mp3\";\n\t\tpublic static final String STEP = \"sounds/step.mp3\";\n\t\tpublic static final String WATER = \"sounds/water.mp3\";\n\t\tpublic static final String GRASS = \"sounds/grass.mp3\";\n\t\tpublic static final String TRAMPLE = \"sounds/trample.mp3\";\n\t\tpublic static final String STURDY = \"sounds/sturdy.mp3\";\n\n\t\tpublic static final String HIT = \"sounds/hit.mp3\";\n\t\tpublic static final String MISS = \"sounds/miss.mp3\";\n\t\tpublic static final String HIT_SLASH = \"sounds/hit_slash.mp3\";\n\t\tpublic static final String HIT_STAB = \"sounds/hit_stab.mp3\";\n\t\tpublic static final String HIT_CRUSH = \"sounds/hit_crush.mp3\";\n\t\tpublic static final String HIT_MAGIC = \"sounds/hit_magic.mp3\";\n\t\tpublic static final String HIT_STRONG = \"sounds/hit_strong.mp3\";\n\t\tpublic static final String HIT_PARRY = \"sounds/hit_parry.mp3\";\n\t\tpublic static final String HIT_ARROW = \"sounds/hit_arrow.mp3\";\n\t\tpublic static final String ATK_SPIRITBOW = \"sounds/atk_spiritbow.mp3\";\n\t\tpublic static final String ATK_CROSSBOW = \"sounds/atk_crossbow.mp3\";\n\t\tpublic static final String HEALTH_WARN = \"sounds/health_warn.mp3\";\n\t\tpublic static final String HEALTH_CRITICAL = \"sounds/health_critical.mp3\";\n\n\t\tpublic static final String DESCEND = \"sounds/descend.mp3\";\n\t\tpublic static final String EAT = \"sounds/eat.mp3\";\n\t\tpublic static final String READ = \"sounds/read.mp3\";\n\t\tpublic static final String LULLABY = \"sounds/lullaby.mp3\";\n\t\tpublic static final String DRINK = \"sounds/drink.mp3\";\n\t\tpublic static final String SHATTER = \"sounds/shatter.mp3\";\n\t\tpublic static final String ZAP = \"sounds/zap.mp3\";\n\t\tpublic static final String LIGHTNING= \"sounds/lightning.mp3\";\n\t\tpublic static final String LEVELUP = \"sounds/levelup.mp3\";\n\t\tpublic static final String DEATH = \"sounds/death.mp3\";\n\t\tpublic static final String CHALLENGE= \"sounds/challenge.mp3\";\n\t\tpublic static final String CURSED = \"sounds/cursed.mp3\";\n\t\tpublic static final String TRAP = \"sounds/trap.mp3\";\n\t\tpublic static final String EVOKE = \"sounds/evoke.mp3\";\n\t\tpublic static final String TOMB = \"sounds/tomb.mp3\";\n\t\tpublic static final String ALERT = \"sounds/alert.mp3\";\n\t\tpublic static final String MELD = \"sounds/meld.mp3\";\n\t\tpublic static final String BOSS = \"sounds/boss.mp3\";\n\t\tpublic static final String BLAST = \"sounds/blast.mp3\";\n\t\tpublic static final String PLANT = \"sounds/plant.mp3\";\n\t\tpublic static final String RAY = \"sounds/ray.mp3\";\n\t\tpublic static final String BEACON = \"sounds/beacon.mp3\";\n\t\tpublic static final String TELEPORT = \"sounds/teleport.mp3\";\n\t\tpublic static final String CHARMS = \"sounds/charms.mp3\";\n\t\tpublic static final String MASTERY = \"sounds/mastery.mp3\";\n\t\tpublic static final String PUFF = \"sounds/puff.mp3\";\n\t\tpublic static final String ROCKS = \"sounds/rocks.mp3\";\n\t\tpublic static final String BURNING = \"sounds/burning.mp3\";\n\t\tpublic static final String FALLING = \"sounds/falling.mp3\";\n\t\tpublic static final String GHOST = \"sounds/ghost.mp3\";\n\t\tpublic static final String SECRET = \"sounds/secret.mp3\";\n\t\tpublic static final String BONES = \"sounds/bones.mp3\";\n\t\tpublic static final String BEE = \"sounds/bee.mp3\";\n\t\tpublic static final String DEGRADE = \"sounds/degrade.mp3\";\n\t\tpublic static final String MIMIC = \"sounds/mimic.mp3\";\n\t\tpublic static final String DEBUFF = \"sounds/debuff.mp3\";\n\t\tpublic static final String CHARGEUP = \"sounds/chargeup.mp3\";\n\t\tpublic static final String GAS = \"sounds/gas.mp3\";\n\t\tpublic static final String CHAINS = \"sounds/chains.mp3\";\n\t\tpublic static final String SCAN = \"sounds/scan.mp3\";\n\t\tpublic static final String SHEEP = \"sounds/sheep.mp3\";\n\t\tpublic static final String MINE = \"sounds/mine.mp3\";\n\n\t\tpublic static final String[] all = new String[]{\n\t\t\t\tCLICK, BADGE, GOLD,\n\n\t\t\t\tOPEN, UNLOCK, ITEM, DEWDROP, STEP, WATER, GRASS, TRAMPLE, STURDY,\n\n\t\t\t\tHIT, MISS, HIT_SLASH, HIT_STAB, HIT_CRUSH, HIT_MAGIC, HIT_STRONG, HIT_PARRY,\n\t\t\t\tHIT_ARROW, ATK_SPIRITBOW, ATK_CROSSBOW, HEALTH_WARN, HEALTH_CRITICAL,\n\n\t\t\t\tDESCEND, EAT, READ, LULLABY, DRINK, SHATTER, ZAP, LIGHTNING, LEVELUP, DEATH,\n\t\t\t\tCHALLENGE, CURSED, TRAP, EVOKE, TOMB, ALERT, MELD, BOSS, BLAST, PLANT, RAY, BEACON,\n\t\t\t\tTELEPORT, CHARMS, MASTERY, PUFF, ROCKS, BURNING, FALLING, GHOST, SECRET, BONES,\n\t\t\t\tBEE, DEGRADE, MIMIC, DEBUFF, CHARGEUP, GAS, CHAINS, SCAN, SHEEP, MINE\n\t\t};\n\t}\n\n\tpublic static class Splashes {\n\t\tpublic static final String WARRIOR = \"splashes/warrior.jpg\";\n\t\tpublic static final String MAGE = \"splashes/mage.jpg\";\n\t\tpublic static final String ROGUE = \"splashes/rogue.jpg\";\n\t\tpublic static final String HUNTRESS = \"splashes/huntress.jpg\";\n\t\tpublic static final String DUELIST = \"splashes/duelist.jpg\";\n\t\tpublic static final String GUNNER\t= \"splashes/gunner.jpg\";\n\t\tpublic static final String SAMURAI = \"splashes/samurai.jpg\";\n\t\tpublic static final String PLANTER\t= \"splashes/planter.jpg\";\n\t\tpublic static final String KNIGHT\t= \"splashes/knight.jpg\";\n\t\tpublic static final String NURSE\t= \"splashes/nurse.jpg\";\n\t}\n\n\tpublic static class Sprites {\n\t\tpublic static final String ITEMS = \"sprites/items.png\";\n\t\tpublic static final String ITEM_ICONS = \"sprites/item_icons.png\";\n\n\t\tpublic static final String WARRIOR = \"sprites/warrior.png\";\n\t\tpublic static final String MAGE = \"sprites/mage.png\";\n\t\tpublic static final String ROGUE = \"sprites/rogue.png\";\n\t\tpublic static final String HUNTRESS = \"sprites/huntress.png\";\n\t\tpublic static final String DUELIST = \"sprites/duelist.png\";\n\t\tpublic static final String GUNNER\t= \"sprites/gunner.png\";\n\t\tpublic static final String SAMURAI\t= \"sprites/samurai.png\";\n\t\tpublic static final String PLANTER\t= \"sprites/planter.png\";\n\t\tpublic static final String KNIGHT\t= \"sprites/knight.png\";\n\t\tpublic static final String NURSE\t= \"sprites/nurse.png\";\n\t\tpublic static final String AVATARS = \"sprites/avatars.png\";\n\t\tpublic static final String PET = \"sprites/pet.png\";\n\t\tpublic static final String AMULET = \"sprites/amulet.png\";\n\n\t\tpublic static final String RAT = \"sprites/rat.png\";\n\t\tpublic static final String BRUTE = \"sprites/brute.png\";\n\t\tpublic static final String SPINNER = \"sprites/spinner.png\";\n\t\tpublic static final String DM300 = \"sprites/dm300.png\";\n\t\tpublic static final String WRAITH = \"sprites/wraith.png\";\n\t\tpublic static final String UNDEAD = \"sprites/undead.png\";\n\t\tpublic static final String KING = \"sprites/king.png\";\n\t\tpublic static final String PIRANHA = \"sprites/piranha.png\";\n\t\tpublic static final String EYE = \"sprites/eye.png\";\n\t\tpublic static final String GNOLL = \"sprites/gnoll.png\";\n\t\tpublic static final String CRAB = \"sprites/crab.png\";\n\t\tpublic static final String GOO = \"sprites/goo.png\";\n\t\tpublic static final String SWARM = \"sprites/swarm.png\";\n\t\tpublic static final String SKELETON = \"sprites/skeleton.png\";\n\t\tpublic static final String SHAMAN = \"sprites/shaman.png\";\n\t\tpublic static final String THIEF = \"sprites/thief.png\";\n\t\tpublic static final String TENGU = \"sprites/tengu.png\";\n\t\tpublic static final String SHEEP = \"sprites/sheep.png\";\n\t\tpublic static final String KEEPER = \"sprites/shopkeeper.png\";\n\t\tpublic static final String BAT = \"sprites/bat.png\";\n\t\tpublic static final String ELEMENTAL= \"sprites/elemental.png\";\n\t\tpublic static final String MONK = \"sprites/monk.png\";\n\t\tpublic static final String WARLOCK = \"sprites/warlock.png\";\n\t\tpublic static final String GOLEM = \"sprites/golem.png\";\n\t\tpublic static final String STATUE = \"sprites/statue.png\";\n\t\tpublic static final String SUCCUBUS = \"sprites/succubus.png\";\n\t\tpublic static final String SCORPIO = \"sprites/scorpio.png\";\n\t\tpublic static final String FISTS = \"sprites/yog_fists.png\";\n\t\tpublic static final String YOG = \"sprites/yog.png\";\n\t\tpublic static final String LARVA = \"sprites/larva.png\";\n\t\tpublic static final String GHOST = \"sprites/ghost.png\";\n\t\tpublic static final String MAKER = \"sprites/wandmaker.png\";\n\t\tpublic static final String TROLL = \"sprites/blacksmith.png\";\n\t\tpublic static final String IMP = \"sprites/demon.png\";\n\t\tpublic static final String RATKING = \"sprites/ratking.png\";\n\t\tpublic static final String BEE = \"sprites/bee.png\";\n\t\tpublic static final String MIMIC = \"sprites/mimic.png\";\n\t\tpublic static final String ROT_LASH = \"sprites/rot_lasher.png\";\n\t\tpublic static final String ROT_HEART= \"sprites/rot_heart.png\";\n\t\tpublic static final String GUARD = \"sprites/guard.png\";\n\t\tpublic static final String WARDS = \"sprites/wards.png\";\n\t\tpublic static final String GUARDIAN = \"sprites/guardian.png\";\n\t\tpublic static final String SLIME = \"sprites/slime.png\";\n\t\tpublic static final String SNAKE = \"sprites/snake.png\";\n\t\tpublic static final String NECRO = \"sprites/necromancer.png\";\n\t\tpublic static final String GHOUL = \"sprites/ghoul.png\";\n\t\tpublic static final String RIPPER = \"sprites/ripper.png\";\n\t\tpublic static final String SPAWNER = \"sprites/spawner.png\";\n\t\tpublic static final String DM100 = \"sprites/dm100.png\";\n\t\tpublic static final String PYLON = \"sprites/pylon.png\";\n\t\tpublic static final String DM200 = \"sprites/dm200.png\";\n\t\tpublic static final String LOTUS = \"sprites/lotus.png\";\n\t\tpublic static final String NINJA_LOG= \"sprites/ninja_log.png\";\n\t\tpublic static final String SPIRIT_HAWK= \"sprites/spirit_hawk.png\";\n\t\tpublic static final String RED_SENTRY= \"sprites/red_sentry.png\";\n\t\tpublic static final String NEW_SENTRY= \"sprites/new_sentry.png\";\n\t\tpublic static final String CRYSTAL_WISP= \"sprites/crystal_wisp.png\";\n\t\tpublic static final String CRYSTAL_GUARDIAN= \"sprites/crystal_guardian.png\";\n\t\tpublic static final String CRYSTAL_SPIRE= \"sprites/crystal_spire.png\";\n\t\tpublic static final String GNOLL_GUARD= \"sprites/gnoll_guard.png\";\n\n\t\tpublic static final String SOLDIER= \"sprites/soldier.png\";\n\t\tpublic static final String RESEARCHER= \"sprites/researcher.png\";\n\t\tpublic static final String TANK= \"sprites/tank.png\";\n\t\tpublic static final String SUPRESSION= \"sprites/supression.png\";\n\t\tpublic static final String MEDIC= \"sprites/medic.png\";\n\t\tpublic static final String REBEL= \"sprites/rebel.png\";\n\t}\n}\n\ncore/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/Char.java\npublic abstract class Char extends Actor {\n\t\n\tpublic int pos = 0;\n\t\n\tpublic CharSprite sprite;\n\t\n\tpublic int HT;\n\tpublic int HP;\n\t\n\tprotected float baseSpeed\t= 1;\n\tprotected PathFinder.Path path;\n\n\tpublic int paralysed\t = 0;\n\tpublic boolean rooted\t\t= false;\n\tpublic boolean flying\t\t= false;\n\tpublic int invisible\t\t= 0;\n\t\n\t//these are relative to the hero\n\tpublic enum Alignment{\n\t\tENEMY,\n\t\tNEUTRAL,\n\t\tALLY\n\t}\n\tpublic Alignment alignment;\n\t\n\tpublic int viewDistance\t= 8;\n\t\n\tpublic boolean[] fieldOfView = null;\n\t\n\tprivate LinkedHashSet buffs = new LinkedHashSet<>();\n\t\n\t@Override\n\tprotected boolean act() {\n\t\tif (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){\n\t\t\tfieldOfView = new boolean[Dungeon.level.length()];\n\t\t}\n\t\tDungeon.level.updateFieldOfView( this, fieldOfView );\n\n\t\t//throw any items that are on top of an immovable char\n\t\tif (properties().contains(Property.IMMOVABLE)){\n\t\t\tthrowItems();\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected void throwItems(){\n\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\tif (heap != null && heap.type == Heap.Type.HEAP\n\t\t\t\t&& !(heap.peek() instanceof Tengu.BombAbility.BombItem)\n\t\t\t\t&& !(heap.peek() instanceof Tengu.ShockerAbility.ShockerItem)) {\n\t\t\tArrayList candidates = new ArrayList<>();\n\t\t\tfor (int n : PathFinder.NEIGHBOURS8){\n\t\t\t\tif (Dungeon.level.passable[pos+n]){\n\t\t\t\t\tcandidates.add(pos+n);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!candidates.isEmpty()){\n\t\t\t\tDungeon.level.drop( heap.pickUp(), Random.element(candidates) ).sprite.drop( pos );\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String name(){\n\t\treturn Messages.get(this, \"name\");\n\t}\n\n\tpublic boolean canInteract(Char c){\n\t\tif (Dungeon.level.adjacent( pos, c.pos )){\n\t\t\treturn true;\n\t\t} else if (c instanceof Hero\n\t\t\t\t&& alignment == Alignment.ALLY\n\t\t\t\t&& Dungeon.level.distance(pos, c.pos) <= 2*Dungeon.hero.pointsInTalent(Talent.ALLY_WARP)){\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//swaps places by default\n\tpublic boolean interact(Char c){\n\n\t\t//don't allow char to swap onto hazard unless they're flying\n\t\t//you can swap onto a hazard though, as you're not the one instigating the swap\n\t\tif (!Dungeon.level.passable[pos] && !c.flying){\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap into a space without room\n\t\tif (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[c.pos]\n\t\t\t|| c.properties().contains(Property.LARGE) && !Dungeon.level.openSpace[pos]){\n\t\t\treturn true;\n\t\t}\n\n\t\t//we do a little raw position shuffling here so that the characters are never\n\t\t// on the same cell when logic such as occupyCell() is triggered\n\t\tint oldPos = pos;\n\t\tint newPos = c.pos;\n\n\t\t//warp instantly with allies in this case\n\t\tif (c == Dungeon.hero && Dungeon.hero.hasTalent(Talent.ALLY_WARP)){\n\t\t\tPathFinder.buildDistanceMap(c.pos, BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null));\n\t\t\tif (PathFinder.distance[pos] == Integer.MAX_VALUE){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpos = newPos;\n\t\t\tc.pos = oldPos;\n\t\t\tScrollOfTeleportation.appear(this, newPos);\n\t\t\tScrollOfTeleportation.appear(c, oldPos);\n\t\t\tDungeon.observe();\n\t\t\tGameScene.updateFog();\n\t\t\treturn true;\n\t\t}\n\n\t\t//can't swap places if one char has restricted movement\n\t\tif (rooted || c.rooted || buff(Vertigo.class) != null || c.buff(Vertigo.class) != null){\n\t\t\treturn true;\n\t\t}\n\n\t\tc.pos = oldPos;\n\t\tmoveSprite( oldPos, newPos );\n\t\tmove( newPos );\n\n\t\tc.pos = newPos;\n\t\tc.sprite.move( newPos, oldPos );\n\t\tc.move( oldPos );\n\t\t\n\t\tc.spend( 1 / c.speed() );\n\n\t\tif (c == Dungeon.hero){\n\t\t\tif (Dungeon.hero.subClass == HeroSubClass.FREERUNNER){\n\t\t\t\tBuff.affect(Dungeon.hero, Momentum.class).gainStack();\n\t\t\t}\n\n\t\t\tDungeon.hero.busy();\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprotected boolean moveSprite( int from, int to ) {\n\t\t\n\t\tif (sprite.isVisible() && sprite.parent != null && (Dungeon.level.heroFOV[from] || Dungeon.level.heroFOV[to])) {\n\t\t\tsprite.move( from, to );\n\t\t\treturn true;\n\t\t} else {\n\t\t\tsprite.turnTo(from, to);\n\t\t\tsprite.place( to );\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void hitSound( float pitch ){\n\t\tSample.INSTANCE.play(Assets.Sounds.HIT, 1, pitch);\n\t}\n\n\tpublic boolean blockSound( float pitch ) {\n\t\treturn false;\n\t}\n\t\n\tprotected static final String POS = \"pos\";\n\tprotected static final String TAG_HP = \"HP\";\n\tprotected static final String TAG_HT = \"HT\";\n\tprotected static final String TAG_SHLD = \"SHLD\";\n\tprotected static final String BUFFS\t = \"buffs\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( POS, pos );\n\t\tbundle.put( TAG_HP, HP );\n\t\tbundle.put( TAG_HT, HT );\n\t\tbundle.put( BUFFS, buffs );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\t\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\tpos = bundle.getInt( POS );\n\t\tHP = bundle.getInt( TAG_HP );\n\t\tHT = bundle.getInt( TAG_HT );\n\t\t\n\t\tfor (Bundlable b : bundle.getCollection( BUFFS )) {\n\t\t\tif (b != null) {\n\t\t\t\t((Buff)b).attachTo( this );\n\t\t\t}\n\t\t}\n\t}\n\n\tfinal public boolean attack( Char enemy ){\n\t\treturn attack(enemy, 1f, 0f, 1f);\n\t}\n\t\n\tpublic boolean attack( Char enemy, float dmgMulti, float dmgBonus, float accMulti ) {\n\n\t\tif (enemy == null) return false;\n\t\t\n\t\tboolean visibleFight = Dungeon.level.heroFOV[pos] || Dungeon.level.heroFOV[enemy.pos];\n\n\t\tif (enemy.isInvulnerable(getClass())) {\n\n\t\t\tif (visibleFight) {\n\t\t\t\tenemy.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, \"invulnerable\") );\n\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.HIT_PARRY, 1f, Random.Float(0.96f, 1.05f));\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t} else if (hit( this, enemy, accMulti, false )) {\n\t\t\t\n\t\t\tint dr = Math.round(enemy.drRoll() * AscensionChallenge.statModifier(enemy));\n\t\t\t\n\t\t\tif (this instanceof Hero){\n\t\t\t\tHero h = (Hero)this;\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof MissileWeapon\n\t\t\t\t\t\t&& h.subClass == HeroSubClass.SNIPER\n\t\t\t\t\t\t&& !Dungeon.level.adjacent(h.pos, enemy.pos)){\n\t\t\t\t\tdr = 0;\n\t\t\t\t}\n\n\t\t\t\tif (h.belongings.attackingWeapon() instanceof Gun.Bullet) {\n\t\t\t\t\tdr *= ((Gun.Bullet) h.belongings.attackingWeapon()).whatBullet().armorFactor();\n\t\t\t\t}\n\n\t\t\t\tif (h.buff(MonkEnergy.MonkAbility.UnarmedAbilityTracker.class) != null){\n\t\t\t\t\tdr = 0;\n\t\t\t\t} else if (h.subClass == HeroSubClass.MONK) {\n\t\t\t\t\t//3 turns with standard attack delay\n\t\t\t\t\tBuff.prolong(h, MonkEnergy.MonkAbility.JustHitTracker.class, 4f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//we use a float here briefly so that we don't have to constantly round while\n\t\t\t// potentially applying various multiplier effects\n\t\t\tfloat dmg;\n\t\t\tPreparation prep = buff(Preparation.class);\n\t\t\tif (prep != null){\n\t\t\t\tdmg = prep.damageRoll(this);\n\t\t\t\tif (this == Dungeon.hero && Dungeon.hero.hasTalent(Talent.BOUNTY_HUNTER)) {\n\t\t\t\t\tBuff.affect(Dungeon.hero, Talent.BountyHunterTracker.class, 0.0f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdmg = damageRoll();\n\t\t\t}\n\n\t\t\tdmg = Math.round(dmg*dmgMulti);\n\n\t\t\tBerserk berserk = buff(Berserk.class);\n\t\t\tif (berserk != null) dmg = berserk.damageFactor(dmg);\n\n\t\t\tif (buff( Fury.class ) != null) {\n\t\t\t\tdmg *= 1.5f;\n\t\t\t}\n\n\t\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\t\tdmg *= buff.meleeDamageFactor();\n\t\t\t}\n\n\t\t\tdmg *= AscensionChallenge.statModifier(this);\n\n\t\t\t//flat damage bonus is applied after positive multipliers, but before negative ones\n\t\t\tdmg += dmgBonus;\n\n\t\t\t//friendly endure\n\t\t\tEndure.EndureTracker endure = buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null) dmg = endure.damageFactor(dmg);\n\n\t\t\t//enemy endure\n\t\t\tendure = enemy.buff(Endure.EndureTracker.class);\n\t\t\tif (endure != null){\n\t\t\t\tdmg = endure.adjustDamageTaken(dmg);\n\t\t\t}\n\n\t\t\tif (enemy.buff(ScrollOfChallenge.ChallengeArena.class) != null){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif (enemy.buff(MonkEnergy.MonkAbility.Meditate.MeditateResistance.class) != null){\n\t\t\t\tdmg *= 0.2f;\n\t\t\t}\n\n\t\t\tif ( buff(Weakness.class) != null ){\n\t\t\t\tdmg *= 0.67f;\n\t\t\t}\n\n\t\t\tif ( buff(SoulMark.class) != null && hero.hasTalent(Talent.MARK_OF_WEAKNESS)) {\n\t\t\t\tif (this.alignment != Alignment.ALLY) {\n\t\t\t\t\tdmg *= Math.pow(0.9f, hero.pointsInTalent(Talent.MARK_OF_WEAKNESS));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint effectiveDamage = enemy.defenseProc( this, Math.round(dmg) );\n\t\t\t//do not trigger on-hit logic if defenseProc returned a negative value\n\t\t\tif (effectiveDamage >= 0) {\n\t\t\t\teffectiveDamage = Math.max(effectiveDamage - dr, 0);\n\n\t\t\t\tif (enemy.buff(Viscosity.ViscosityTracker.class) != null) {\n\t\t\t\t\teffectiveDamage = enemy.buff(Viscosity.ViscosityTracker.class).deferDamage(effectiveDamage);\n\t\t\t\t\tenemy.buff(Viscosity.ViscosityTracker.class).detach();\n\t\t\t\t}\n\n\t\t\t\t//vulnerable specifically applies after armor reductions\n\t\t\t\tif (enemy.buff(Vulnerable.class) != null) {\n\t\t\t\t\teffectiveDamage *= 1.33f;\n\t\t\t\t}\n\n\t\t\t\teffectiveDamage = attackProc(enemy, effectiveDamage);\n\t\t\t}\n\t\t\tif (visibleFight) {\n\t\t\t\tif (effectiveDamage > 0 || !enemy.blockSound(Random.Float(0.96f, 1.05f))) {\n\t\t\t\t\thitSound(Random.Float(0.87f, 1.15f));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the enemy is already dead, interrupt the attack.\n\t\t\t// This matters as defence procs can sometimes inflict self-damage, such as armor glyphs.\n\t\t\tif (!enemy.isAlive()){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tenemy.damage( effectiveDamage, this );\n\n\t\t\tif (buff(FireImbue.class) != null) buff(FireImbue.class).proc(enemy);\n\t\t\tif (buff(FrostImbue.class) != null) buff(FrostImbue.class).proc(enemy);\n\t\t\tif (buff(ThunderImbue.class) != null) buff(ThunderImbue.class).proc(enemy, (int)dmg);\n\n\t\t\tif (enemy.isAlive() && enemy.alignment != alignment && prep != null && prep.canKO(enemy)){\n\t\t\t\tenemy.HP = 0;\n\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\tenemy.die(this);\n\t\t\t\t} else {\n\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t}\n\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Preparation.class, \"assassinated\"));\n\t\t\t\t}\n\t\t\t\tif (Random.Float() < hero.pointsInTalent(Talent.ENERGY_DRAW)/3f) {\n\t\t\t\t\tCloakOfShadows cloak = hero.belongings.getItem(CloakOfShadows.class);\n\t\t\t\t\tif (cloak != null) {\n\t\t\t\t\t\tcloak.overCharge(1);\n\t\t\t\t\t\tScrollOfRecharging.charge(Dungeon.hero);\n\t\t\t\t\t\tSpellSprite.show(hero, SpellSprite.CHARGE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tTalent.CombinedLethalityTriggerTracker combinedLethality = buff(Talent.CombinedLethalityTriggerTracker.class);\n\t\t\tif (combinedLethality != null){\n\t\t\t\tif ( enemy.isAlive() && enemy.alignment != alignment && !Char.hasProp(enemy, Property.BOSS)\n\t\t\t\t\t\t&& !Char.hasProp(enemy, Property.MINIBOSS) && this instanceof Hero &&\n\t\t\t\t\t\t(enemy.HP/(float)enemy.HT) <= 0.4f*((Hero)this).pointsInTalent(Talent.COMBINED_LETHALITY)/3f) {\n\t\t\t\t\tenemy.HP = 0;\n\t\t\t\t\tif (!enemy.isAlive()) {\n\t\t\t\t\t\tenemy.die(this);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//helps with triggering any on-damage effects that need to activate\n\t\t\t\t\t\tenemy.damage(-1, this);\n\t\t\t\t\t\tDeathMark.processFearTheReaper(enemy);\n\t\t\t\t\t}\n\t\t\t\t\tif (enemy.sprite != null) {\n\t\t\t\t\t\tenemy.sprite.showStatus(CharSprite.NEGATIVE, Messages.get(Talent.CombinedLethalityTriggerTracker.class, \"executed\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcombinedLethality.detach();\n\t\t\t}\n\n\t\t\tif (enemy.sprite != null) {\n\t\t\t\tenemy.sprite.bloodBurstA(sprite.center(), effectiveDamage);\n\t\t\t\tenemy.sprite.flash();\n\t\t\t}\n\n\t\t\tif (!enemy.isAlive() && visibleFight) {\n\t\t\t\tif (enemy == Dungeon.hero) {\n\t\t\t\t\t\n\t\t\t\t\tif (this == Dungeon.hero) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this instanceof WandOfLivingEarth.EarthGuardian\n\t\t\t\t\t\t\t|| this instanceof MirrorImage || this instanceof PrismaticImage){\n\t\t\t\t\t\tBadges.validateDeathFromFriendlyMagic();\n\t\t\t\t\t}\n\t\t\t\t\tDungeon.fail( this );\n\t\t\t\t\tGLog.n( Messages.capitalize(Messages.get(Char.class, \"kill\", name())) );\n\t\t\t\t\t\n\t\t\t\t} else if (this == Dungeon.hero) {\n\t\t\t\t\tGLog.i( Messages.capitalize(Messages.get(Char.class, \"defeat\", enemy.name())) );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\n\t\t\tif (enemy instanceof Hero) {\n\t\t\t\tif (hero.pointsInTalent(Talent.SWIFT_MOVEMENT) == 3) {\n\t\t\t\t\tBuff.prolong(hero, Invisibility.class, 1.0001f);\n\t\t\t\t}\n\t\t\t\tif (Random.Int(5) < hero.pointsInTalent(Talent.COUNTER_ATTACK)) {\n\t\t\t\t\tBuff.affect(hero, Talent.CounterAttackTracker.class);\n\t\t\t\t}\n\t\t\t\tif (hero.hasTalent(Talent.QUICK_PREP)) {\n\t\t\t\t\tMomentum momentum = hero.buff(Momentum.class);\n\t\t\t\t\tif (momentum != null) {\n\t\t\t\t\t\tmomentum.quickPrep(hero.pointsInTalent(Talent.QUICK_PREP));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenemy.sprite.showStatus( CharSprite.NEUTRAL, enemy.defenseVerb() );\n\t\t\tif (visibleFight) {\n\t\t\t\t//TODO enemy.defenseSound? currently miss plays for monks/crab even when they parry\n\t\t\t\tSample.INSTANCE.play(Assets.Sounds.MISS);\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\t}\n\n\tpublic static int INFINITE_ACCURACY = 1_000_000;\n\tpublic static int INFINITE_EVASION = 1_000_000;\n\n\tfinal public static boolean hit( Char attacker, Char defender, boolean magic ) {\n\t\treturn hit(attacker, defender, magic ? 2f : 1f, magic);\n\t}\n\n\tpublic static boolean hit( Char attacker, Char defender, float accMulti, boolean magic ) {\n\t\tfloat acuStat = attacker.attackSkill( defender );\n\t\tfloat defStat = defender.defenseSkill( attacker );\n\n\t\tif (defender instanceof Hero && ((Hero) defender).damageInterrupt){\n\t\t\t((Hero) defender).interrupt();\n\t\t}\n\n\t\t//invisible chars always hit (for the hero this is surprise attacking)\n\t\tif (attacker.invisible > 0 && attacker.canSurpriseAttack()){\n\t\t\tacuStat = INFINITE_ACCURACY;\n\t\t}\n\n\t\tif (defender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class) != null && !magic){\n\t\t\tdefStat = INFINITE_EVASION;\n\t\t\tdefender.buff(MonkEnergy.MonkAbility.Focus.FocusBuff.class).detach();\n\t\t\tBuff.affect(defender, MonkEnergy.MonkAbility.Focus.FocusActivation.class, 0);\n\t\t}\n\n\t\t//if accuracy or evasion are large enough, treat them as infinite.\n\t\t//note that infinite evasion beats infinite accuracy\n\t\tif (defStat >= INFINITE_EVASION){\n\t\t\treturn false;\n\t\t} else if (acuStat >= INFINITE_ACCURACY){\n\t\t\treturn true;\n\t\t}\n\n\t\tfloat acuRoll = Random.Float( acuStat );\n\t\tif (attacker.buff(Bless.class) != null) acuRoll *= 1.25f;\n\t\tif (attacker.buff( Hex.class) != null) acuRoll *= 0.8f;\n\t\tif (attacker.buff( Daze.class) != null) acuRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : attacker.buffs(ChampionEnemy.class)){\n\t\t\tacuRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tacuRoll *= AscensionChallenge.statModifier(attacker);\n\t\t\n\t\tfloat defRoll = Random.Float( defStat );\n\t\tif (defender.buff(Bless.class) != null) defRoll *= 1.25f;\n\t\tif (defender.buff( Hex.class) != null) defRoll *= 0.8f;\n\t\tif (defender.buff( Daze.class) != null) defRoll *= 0.5f;\n\t\tfor (ChampionEnemy buff : defender.buffs(ChampionEnemy.class)){\n\t\t\tdefRoll *= buff.evasionAndAccuracyFactor();\n\t\t}\n\t\tdefRoll *= AscensionChallenge.statModifier(defender);\n\t\t\n\t\treturn (acuRoll * accMulti) >= defRoll;\n\t}\n\t\n\tpublic int attackSkill( Char target ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic int defenseSkill( Char enemy ) {\n\t\treturn 0;\n\t}\n\t\n\tpublic String defenseVerb() {\n\t\treturn Messages.get(this, \"def_verb\");\n\t}\n\t\n\tpublic int drRoll() {\n\t\tint dr = 0;\n\n\t\tdr += Random.NormalIntRange( 0 , Barkskin.currentLevel(this) );\n\n\t\treturn dr;\n\t}\n\t\n\tpublic int damageRoll() {\n\t\treturn 1;\n\t}\n\t\n\t//TODO it would be nice to have a pre-armor and post-armor proc.\n\t// atm attack is always post-armor and defence is already pre-armor\n\t\n\tpublic int attackProc( Char enemy, int damage ) {\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tbuff.onAttackProc( enemy );\n\t\t}\n\t\treturn damage;\n\t}\n\t\n\tpublic int defenseProc( Char enemy, int damage ) {\n\n\t\tEarthroot.Armor armor = buff( Earthroot.Armor.class );\n\t\tif (armor != null) {\n\t\t\tdamage = armor.absorb( damage );\n\t\t}\n\n\t\treturn damage;\n\t}\n\t\n\tpublic float speed() {\n\t\tfloat speed = baseSpeed;\n\t\tif ( buff( Cripple.class ) != null ) speed /= 2f;\n\t\tif ( buff( Stamina.class ) != null) speed *= 1.5f;\n\t\tif ( buff( Adrenaline.class ) != null) speed *= 2f;\n\t\tif ( buff( Haste.class ) != null) speed *= 3f;\n\t\tif ( buff( Dread.class ) != null) speed *= 2f;\n\t\treturn speed;\n\t}\n\n\t//currently only used by invisible chars, or by the hero\n\tpublic boolean canSurpriseAttack(){\n\t\treturn true;\n\t}\n\t\n\t//used so that buffs(Shieldbuff.class) isn't called every time unnecessarily\n\tprivate int cachedShield = 0;\n\tpublic boolean needsShieldUpdate = true;\n\t\n\tpublic int shielding(){\n\t\tif (!needsShieldUpdate){\n\t\t\treturn cachedShield;\n\t\t}\n\t\t\n\t\tcachedShield = 0;\n\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\tcachedShield += s.shielding();\n\t\t}\n\t\tneedsShieldUpdate = false;\n\t\treturn cachedShield;\n\t}\n\t\n\tpublic void damage( int dmg, Object src ) {\n\t\t\n\t\tif (!isAlive() || dmg < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(isInvulnerable(src.getClass())){\n\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.get(this, \"invulnerable\"));\n\t\t\treturn;\n\t\t}\n\n\t\tfor (ChampionEnemy buff : buffs(ChampionEnemy.class)){\n\t\t\tdmg = (int) Math.ceil(dmg * buff.damageTakenFactor());\n\t\t}\n\n\t\tif (!(src instanceof LifeLink) && buff(LifeLink.class) != null){\n\t\t\tHashSet links = buffs(LifeLink.class);\n\t\t\tfor (LifeLink link : links.toArray(new LifeLink[0])){\n\t\t\t\tif (Actor.findById(link.object) == null){\n\t\t\t\t\tlinks.remove(link);\n\t\t\t\t\tlink.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t\tdmg = (int)Math.ceil(dmg / (float)(links.size()+1));\n\t\t\tfor (LifeLink link : links){\n\t\t\t\tChar ch = (Char)Actor.findById(link.object);\n\t\t\t\tif (ch != null) {\n\t\t\t\t\tch.damage(dmg, link);\n\t\t\t\t\tif (!ch.isAlive()) {\n\t\t\t\t\t\tlink.detach();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTerror t = buff(Terror.class);\n\t\tif (t != null){\n\t\t\tt.recover();\n\t\t}\n\t\tDread d = buff(Dread.class);\n\t\tif (d != null){\n\t\t\td.recover();\n\t\t}\n\t\tCharm c = buff(Charm.class);\n\t\tif (c != null){\n\t\t\tc.recover(src);\n\t\t}\n\t\tif (this.buff(Frost.class) != null){\n\t\t\tBuff.detach( this, Frost.class );\n\t\t}\n\t\tif (this.buff(MagicalSleep.class) != null){\n\t\t\tBuff.detach(this, MagicalSleep.class);\n\t\t}\n\t\tif (this.buff(Doom.class) != null && !isImmune(Doom.class)){\n\t\t\tdmg *= 1.67f;\n\t\t}\n\t\tif (alignment != Alignment.ALLY && this.buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tdmg *= 1.25f;\n\t\t}\n\t\t\n\t\tClass srcClass = src.getClass();\n\t\tif (isImmune( srcClass )) {\n\t\t\tdmg = 0;\n\t\t} else {\n\t\t\tdmg = Math.round( dmg * resist( srcClass ));\n\t\t}\n\t\t\n\t\t//TODO improve this when I have proper damage source logic\n\t\tif (AntiMagic.RESISTS.contains(src.getClass()) && buff(ArcaneArmor.class) != null){\n\t\t\tdmg -= Random.NormalIntRange(0, buff(ArcaneArmor.class).level());\n\t\t\tif (dmg < 0) dmg = 0;\n\t\t}\n\n\t\tif (buff(Sickle.HarvestBleedTracker.class) != null){\n\t\t\tif (isImmune(Bleeding.class)){\n\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(Messages.get(this, \"immune\")));\n\t\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tBleeding b = buff(Bleeding.class);\n\t\t\tif (b == null){\n\t\t\t\tb = new Bleeding();\n\t\t\t}\n\t\t\tb.announced = false;\n\t\t\tb.set(dmg*buff(Sickle.HarvestBleedTracker.class).bleedFactor, Sickle.HarvestBleedTracker.class);\n\t\t\tb.attachTo(this);\n\t\t\tsprite.showStatus(CharSprite.WARNING, Messages.titleCase(b.name()) + \" \" + (int)b.level());\n\t\t\tbuff(Sickle.HarvestBleedTracker.class).detach();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (buff( Paralysis.class ) != null) {\n\t\t\tbuff( Paralysis.class ).processDamage(dmg);\n\t\t}\n\n\t\tint shielded = dmg;\n\t\t//FIXME: when I add proper damage properties, should add an IGNORES_SHIELDS property to use here.\n\t\tif (!(src instanceof Hunger)){\n\t\t\tfor (ShieldBuff s : buffs(ShieldBuff.class)){\n\t\t\t\tdmg = s.absorbDamage(dmg);\n\t\t\t\tif (dmg == 0) break;\n\t\t\t}\n\t\t}\n\t\tshielded -= dmg;\n\t\tHP -= dmg;\n\n\t\tif (HP > 0 && buff(Grim.GrimTracker.class) != null){\n\n\t\t\tfloat finalChance = buff(Grim.GrimTracker.class).maxChance;\n\t\t\tfinalChance *= (float)Math.pow( ((HT - HP) / (float)HT), 2);\n\n\t\t\tif (Random.Float() < finalChance) {\n\t\t\t\tint extraDmg = Math.round(HP*resist(Grim.class));\n\t\t\t\tdmg += extraDmg;\n\t\t\t\tHP -= extraDmg;\n\n\t\t\t\tsprite.emitter().burst( ShadowParticle.UP, 5 );\n\t\t\t\tif (!isAlive() && buff(Grim.GrimTracker.class).qualifiesForBadge){\n\t\t\t\t\tBadges.validateGrimWeapon();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (HP < 0 && src instanceof Char && alignment == Alignment.ENEMY){\n\t\t\tif (((Char) src).buff(Kinetic.KineticTracker.class) != null){\n\t\t\t\tint dmgToAdd = -HP;\n\t\t\t\tdmgToAdd -= ((Char) src).buff(Kinetic.KineticTracker.class).conservedDamage;\n\t\t\t\tdmgToAdd = Math.round(dmgToAdd * Weapon.Enchantment.genericProcChanceMultiplier((Char) src));\n\t\t\t\tif (dmgToAdd > 0) {\n\t\t\t\t\tBuff.affect((Char) src, Kinetic.ConservedDamage.class).setBonus(dmgToAdd);\n\t\t\t\t}\n\t\t\t\t((Char) src).buff(Kinetic.KineticTracker.class).detach();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (sprite != null) {\n\t\t\tsprite.showStatus(HP > HT / 2 ?\n\t\t\t\t\t\t\tCharSprite.WARNING :\n\t\t\t\t\t\t\tCharSprite.NEGATIVE,\n\t\t\t\t\tInteger.toString(dmg + shielded));\n\t\t}\n\n\t\tif (HP < 0) HP = 0;\n\n\t\tif (!isAlive()) {\n\t\t\tdie( src );\n\t\t} else if (HP == 0 && buff(DeathMark.DeathMarkTracker.class) != null){\n\t\t\tDeathMark.processFearTheReaper(this);\n\t\t}\n\t}\n\t\n\tpublic void destroy() {\n\t\tHP = 0;\n\t\tActor.remove( this );\n\n\t\tfor (Char ch : Actor.chars().toArray(new Char[0])){\n\t\t\tif (ch.buff(Charm.class) != null && ch.buff(Charm.class).object == id()){\n\t\t\t\tch.buff(Charm.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Dread.class) != null && ch.buff(Dread.class).object == id()){\n\t\t\t\tch.buff(Dread.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Terror.class) != null && ch.buff(Terror.class).object == id()){\n\t\t\t\tch.buff(Terror.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(SnipersMark.class) != null && ch.buff(SnipersMark.class).object == id()){\n\t\t\t\tch.buff(SnipersMark.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.FollowupStrikeTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.FollowupStrikeTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.FollowupStrikeTracker.class).detach();\n\t\t\t}\n\t\t\tif (ch.buff(Talent.DeadlyFollowupTracker.class) != null\n\t\t\t\t\t&& ch.buff(Talent.DeadlyFollowupTracker.class).object == id()){\n\t\t\t\tch.buff(Talent.DeadlyFollowupTracker.class).detach();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void die( Object src ) {\n\t\tdestroy();\n\t\tif (src != Chasm.class) sprite.die();\n\t}\n\n\t//we cache this info to prevent having to call buff(...) in isAlive.\n\t//This is relevant because we call isAlive during drawing, which has both performance\n\t//and thread coordination implications\n\tpublic boolean deathMarked = false;\n\t\n\tpublic boolean isAlive() {\n\t\treturn HP > 0 || deathMarked;\n\t}\n\n\tpublic boolean isActive() {\n\t\treturn isAlive();\n\t}\n\n\t@Override\n\tprotected void spendConstant(float time) {\n\t\tTimekeepersHourglass.timeFreeze freeze = buff(TimekeepersHourglass.timeFreeze.class);\n\t\tif (freeze != null) {\n\t\t\tfreeze.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tSwiftthistle.TimeBubble bubble = buff(Swiftthistle.TimeBubble.class);\n\t\tif (bubble != null){\n\t\t\tbubble.processTime(time);\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.spendConstant(time);\n\t}\n\n\t@Override\n\tprotected void spend( float time ) {\n\n\t\tfloat timeScale = 1f;\n\t\tif (buff( Slow.class ) != null) {\n\t\t\ttimeScale *= 0.5f;\n\t\t\t//slowed and chilled do not stack\n\t\t} else if (buff( Chill.class ) != null) {\n\t\t\ttimeScale *= buff( Chill.class ).speedFactor();\n\t\t}\n\t\tif (buff( Speed.class ) != null) {\n\t\t\ttimeScale *= 2.0f;\n\t\t}\n\t\t\n\t\tsuper.spend( time / timeScale );\n\t}\n\t\n\tpublic synchronized LinkedHashSet buffs() {\n\t\treturn new LinkedHashSet<>(buffs);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t//returns all buffs assignable from the given buff class\n\tpublic synchronized HashSet buffs( Class c ) {\n\t\tHashSet filtered = new HashSet<>();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (c.isInstance( b )) {\n\t\t\t\tfiltered.add( (T)b );\n\t\t\t}\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t//returns an instance of the specific buff class, if it exists. Not just assignable\n\tpublic synchronized T buff( Class c ) {\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b.getClass() == c) {\n\t\t\t\treturn (T)b;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic synchronized boolean isCharmedBy( Char ch ) {\n\t\tint chID = ch.id();\n\t\tfor (Buff b : buffs) {\n\t\t\tif (b instanceof Charm && ((Charm)b).object == chID) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic synchronized boolean add( Buff buff ) {\n\n\t\tif (buff(PotionOfCleansing.Cleanse.class) != null) { //cleansing buff\n\t\t\tif (buff.type == Buff.buffType.NEGATIVE\n\t\t\t\t\t&& !(buff instanceof AllyBuff)\n\t\t\t\t\t&& !(buff instanceof LostInventory)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tif (sprite != null && buff(Challenge.SpectatorFreeze.class) != null){\n\t\t\treturn false; //can't add buffs while frozen and game is loaded\n\t\t}\n\n\t\tbuffs.add( buff );\n\t\tif (Actor.chars().contains(this)) Actor.add( buff );\n\n\t\tif (sprite != null && buff.announced) {\n\t\t\tswitch (buff.type) {\n\t\t\t\tcase POSITIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.POSITIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEGATIVE:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEGATIVE, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NEUTRAL:\n\t\t\t\tdefault:\n\t\t\t\t\tsprite.showStatus(CharSprite.NEUTRAL, Messages.titleCase(buff.name()));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\n\t}\n\t\n\tpublic synchronized boolean remove( Buff buff ) {\n\t\t\n\t\tbuffs.remove( buff );\n\t\tActor.remove( buff );\n\n\t\treturn true;\n\t}\n\t\n\tpublic synchronized void remove( Class buffClass ) {\n\t\tfor (Buff buff : buffs( buffClass )) {\n\t\t\tremove( buff );\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected synchronized void onRemove() {\n\t\tfor (Buff buff : buffs.toArray(new Buff[buffs.size()])) {\n\t\t\tbuff.detach();\n\t\t}\n\t}\n\t\n\tpublic synchronized void updateSpriteState() {\n\t\tfor (Buff buff:buffs) {\n\t\t\tbuff.fx( true );\n\t\t}\n\t}\n\t\n\tpublic float stealth() {\n\t\treturn 0;\n\t}\n\n\tpublic final void move( int step ) {\n\t\tmove( step, true );\n\t}\n\n\t//travelling may be false when a character is moving instantaneously, such as via teleportation\n\tpublic void move( int step, boolean travelling ) {\n\n\t\tif (travelling && Dungeon.level.adjacent( step, pos ) && buff( Vertigo.class ) != null) {\n\t\t\tsprite.interruptMotion();\n\t\t\tint newPos = pos + PathFinder.NEIGHBOURS8[Random.Int( 8 )];\n\t\t\tif (!(Dungeon.level.passable[newPos] || Dungeon.level.avoid[newPos])\n\t\t\t\t\t|| (properties().contains(Property.LARGE) && !Dungeon.level.openSpace[newPos])\n\t\t\t\t\t|| Actor.findChar( newPos ) != null)\n\t\t\t\treturn;\n\t\t\telse {\n\t\t\t\tsprite.move(pos, newPos);\n\t\t\t\tstep = newPos;\n\t\t\t}\n\t\t}\n\n\t\tif (Dungeon.level.map[pos] == Terrain.OPEN_DOOR) {\n\t\t\tDoor.leave( pos );\n\t\t}\n\n\t\tpos = step;\n\t\t\n\t\tif (this != Dungeon.hero) {\n\t\t\tsprite.visible = Dungeon.level.heroFOV[pos];\n\t\t}\n\t\t\n\t\tDungeon.level.occupyCell(this );\n\t}\n\t\n\tpublic int distance( Char other ) {\n\t\treturn Dungeon.level.distance( pos, other.pos );\n\t}\n\n\tpublic boolean[] modifyPassable( boolean[] passable){\n\t\t//do nothing by default, but some chars can pass over terrain that others can't\n\t\treturn passable;\n\t}\n\t\n\tpublic void onMotionComplete() {\n\t\t//Does nothing by default\n\t\t//The main actor thread already accounts for motion,\n\t\t// so calling next() here isn't necessary (see Actor.process)\n\t}\n\t\n\tpublic void onAttackComplete() {\n\t\tnext();\n\t}\n\t\n\tpublic void onOperateComplete() {\n\t\tnext();\n\t}\n\t\n\tprotected final HashSet resistances = new HashSet<>();\n\t\n\t//returns percent effectiveness after resistances\n\t//TODO currently resistances reduce effectiveness by a static 50%, and do not stack.\n\tpublic float resist( Class effect ){\n\t\tHashSet resists = new HashSet<>(resistances);\n\t\tfor (Property p : properties()){\n\t\t\tresists.addAll(p.resistances());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\tresists.addAll(b.resistances());\n\t\t}\n\t\t\n\t\tfloat result = 1f;\n\t\tfor (Class c : resists){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\tresult *= 0.5f;\n\t\t\t}\n\t\t}\n\t\treturn result * RingOfElements.resist(this, effect);\n\t}\n\t\n\tprotected final HashSet immunities = new HashSet<>();\n\t\n\tpublic boolean isImmune(Class effect ){\n\t\tHashSet immunes = new HashSet<>(immunities);\n\t\tfor (Property p : properties()){\n\t\t\timmunes.addAll(p.immunities());\n\t\t}\n\t\tfor (Buff b : buffs()){\n\t\t\timmunes.addAll(b.immunities());\n\t\t}\n\t\t\n\t\tfor (Class c : immunes){\n\t\t\tif (c.isAssignableFrom(effect)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t//similar to isImmune, but only factors in damage.\n\t//Is used in AI decision-making\n\tpublic boolean isInvulnerable( Class effect ){\n\t\treturn buff(Challenge.SpectatorFreeze.class) != null;\n\t}\n\n\tprotected HashSet properties = new HashSet<>();\n\n\tpublic HashSet properties() {\n\t\tHashSet props = new HashSet<>(properties);\n\t\t//TODO any more of these and we should make it a property of the buff, like with resistances/immunities\n\t\tif (buff(ChampionEnemy.Giant.class) != null) {\n\t\t\tprops.add(Property.LARGE);\n\t\t}\n\t\treturn props;\n\t}\n\n\tpublic enum Property{\n\t\tBOSS ( new HashSet( Arrays.asList(Grim.class, GrimTrap.class, ScrollOfRetribution.class, ScrollOfPsionicBlast.class)),\n\t\t\t\tnew HashSet( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tMINIBOSS ( new HashSet(),\n\t\t\t\tnew HashSet( Arrays.asList(AllyBuff.class, Dread.class) )),\n\t\tBOSS_MINION,\n\t\tUNDEAD,\n\t\tDEMONIC,\n\t\tINORGANIC ( new HashSet(),\n\t\t\t\tnew HashSet( Arrays.asList(Bleeding.class, ToxicGas.class, Poison.class) )),\n\t\tFIERY ( new HashSet( Arrays.asList(WandOfFireblast.class, Elemental.FireElemental.class)),\n\t\t\t\tnew HashSet( Arrays.asList(Burning.class, Blazing.class))),\n\t\tICY ( new HashSet( Arrays.asList(WandOfFrost.class, Elemental.FrostElemental.class)),\n\t\t\t\tnew HashSet( Arrays.asList(Frost.class, Chill.class))),\n\t\tACIDIC ( new HashSet( Arrays.asList(Corrosion.class)),\n\t\t\t\tnew HashSet( Arrays.asList(Ooze.class))),\n\t\tELECTRIC ( new HashSet( Arrays.asList(WandOfLightning.class, Shocking.class, Potential.class, Electricity.class, ShockingDart.class, Elemental.ShockElemental.class )),\n\t\t\t\tnew HashSet()),\n\t\tLARGE,\n\t\tIMMOVABLE;\n\t\t\n\t\tprivate HashSet resistances;\n\t\tprivate HashSet immunities;\n\t\t\n\t\tProperty(){\n\t\t\tthis(new HashSet(), new HashSet());\n\t\t}\n\t\t\n\t\tProperty( HashSet resistances, HashSet immunities){\n\t\t\tthis.resistances = resistances;\n\t\t\tthis.immunities = immunities;\n\t\t}\n\t\t\n\t\tpublic HashSet resistances(){\n\t\t\treturn new HashSet<>(resistances);\n\t\t}\n\t\t\n\t\tpublic HashSet immunities(){\n\t\t\treturn new HashSet<>(immunities);\n\t\t}\n\n\t}\n\n\tpublic static boolean hasProp( Char ch, Property p){\n\t\treturn (ch != null && ch.properties().contains(p));\n\t}\n\n\tpublic void heal(int amount) {\n\t\tamount = Math.min( amount, this.HT - this.HP );\n\t\tif (amount > 0 && this.isAlive()) {\n\t\t\tthis.HP += amount;\n\t\t\tthis.sprite.emitter().start( Speck.factory( Speck.HEALING ), 0.4f, 1 );\n\t\t\tthis.sprite.showStatus( CharSprite.POSITIVE, Integer.toString( amount ) );\n\t\t}\n\t}\n}", "answers": ["\t\t\tEmitter emitter = emitter();"], "length": 6056, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "c51e13c3-1f77-49d1-b44c-2b34066fd5ba", "reasoning": "The Dark class follows the same pattern as the other inner FistSprite subclasses. Its createEmitter method should start by creating an Emitter instance via the helper method emitter(). The first line inside the method body is therefore \"Emitter emitter = emitter();\".", "reasoning_model_answer": "Emitter emitter = emitter();", "assistant_with_reasoning": "\nThe Dark class follows the same pattern as the other inner FistSprite subclasses. Its createEmitter method should start by creating an Emitter instance via the helper method emitter(). The first line inside the method body is therefore \"Emitter emitter = emitter();\".\n\nEmitter emitter = emitter();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.878, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37109, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "Emitter emitter = emitter();", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.google.common.base.Objects;\nimport java.util.Collection;\nimport nl.esi.pps.tmsc.Dependency;\nimport nl.esi.pps.tmsc.Event;\nimport nl.esi.pps.tmsc.Interval;\nimport nl.esi.pps.tmsc.ScopedTMSC;\nimport nl.esi.pps.tmsc.TMSC;\nimport nl.esi.pps.tmsc.util.TmscQueries;\nimport org.eclipse.emf.common.util.EList;\nimport org.eclipse.lsat.common.util.BranchIterable;\nimport org.eclipse.lsat.common.xtend.Queries;\nimport org.eclipse.xtend2.lib.StringConcatenation;\nimport org.eclipse.xtext.xbase.lib.Extension;\nimport org.eclipse.xtext.xbase.lib.Functions.Function1;\nimport org.eclipse.xtext.xbase.lib.IterableExtensions;", "context": "plugins/nl.esi.pps.tmsc.analysis/xtend-gen/nl/esi/pps/tmsc/analysis/CriticalPathAnalysis.java\n/**\n * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community\n * \n * This program and the accompanying materials are made available\n * under the terms of the MIT License which is available at\n * https://opensource.org/licenses/MIT\n * \n * SPDX-License-Identifier: MIT\n */\npackage nl.esi.pps.tmsc.analysis;\n\n\n@SuppressWarnings(\"all\")\npublic final class CriticalPathAnalysis {\n private final boolean markCritical;\n \n private final Function1 timestampFunc;\n \n private final Function1 timeBoundFunc;\n \n public CriticalPathAnalysis() {\n this.markCritical = true;\n final Function1 _function = (Event it) -> {\n return it.getTimestamp();\n };\n this.timestampFunc = _function;\n final Function1 _function_1 = (Dependency it) -> {\n return it.getTimeBound();\n };\n this.timeBoundFunc = _function_1;\n }\n \n public CriticalPathAnalysis(final Function1 timestampFunc, final Function1 timeBoundFunc) {\n this.markCritical = false;\n this.timestampFunc = timestampFunc;\n this.timeBoundFunc = timeBoundFunc;\n }\n \n public static ScopedTMSC analyseCriticalPath(final Interval interval) {\n final Function1 _function = (ScopedTMSC it) -> {\n return Boolean.valueOf(CriticalPathAnalysis.isCriticalPathAnalysisResult(it));\n };\n final ScopedTMSC previousCriticalPath = IterableExtensions.findFirst(interval.getScopes(), _function);\n if ((previousCriticalPath != null)) {\n return previousCriticalPath;\n }\n @Extension\n final CriticalPathAnalysis criticalPathAnalysis = new CriticalPathAnalysis();\n BranchIterable _findCriticalPathBetween = criticalPathAnalysis.findCriticalPathBetween(interval.getTmsc(), interval.getFrom(), interval.getTo());\n StringConcatenation _builder = new StringConcatenation();\n _builder.append(\"Critical path for \");\n String _name = interval.getName();\n _builder.append(_name);\n final ScopedTMSC criticalPath = TmscQueries.createScopedTMSC(_findCriticalPathBetween, _builder, interval.getFrom(), interval.getTo());\n CriticalPathAnalysis.setCriticalPathAnalysisResult(criticalPath, true);\n EList _scopes = interval.getScopes();\n _scopes.add(criticalPath);\n return criticalPath;\n }\n \n /**\n * Finds {@link Dependency dependencies} that denote the critical path to\n * the specified {@code event}.\n * \n * @see #analyseCriticalDependenciesTo(TMSC, Event)\n */\n public BranchIterable findCriticalPathTo(final TMSC tmsc, final Event event) {\n final Function1 _function = (Dependency it) -> {\n boolean _analyseCritical = this.analyseCritical(it);\n return Boolean.valueOf((!_analyseCritical));\n };\n return Queries.until(this.closureIncomingDependencies(tmsc, event), _function);\n }\n \n /**\n * Finds {@link Dependency dependencies} that denote the critical path to\n * the specified {@code to} event. Analysis is stopped when {@code from} event\n * is detected or at the {@link Event#getTimestamp() time} of {@code from}.\n * \n * @see #findCriticalPathTo(TMSC, Event)\n */\n public BranchIterable findCriticalPathBetween(final TMSC tmsc, final Event from, final Event to) {\n final Function1 _function = (Dependency it) -> {\n return Boolean.valueOf((Objects.equal(it.getTarget(), from) || (it.getTarget().getTimestamp().compareTo(from.getTimestamp()) <= 0)));\n };\n final Function1 _function_1 = (Dependency it) -> {\n boolean _analyseCritical = this.analyseCritical(it);\n return Boolean.valueOf((!_analyseCritical));\n };\n return Queries.until(Queries.until(this.closureIncomingDependencies(tmsc, to), _function), _function_1);\n }\n \n private BranchIterable closureIncomingDependencies(@Extension final TMSC tmsc, final Event event) {\n final Function1> _function = (Dependency it) -> {\n Event _source = it.getSource();\n Collection _incomingDependencies = null;\n if (_source!=null) {\n _incomingDependencies=tmsc.getIncomingDependencies(_source);\n }\n return _incomingDependencies;\n };\n return Queries.closure(tmsc.getIncomingDependencies(event), true, _function);\n }\n \n private boolean analyseCritical(final Dependency dependency) {\n Long _xifexpression = null;\n Event _source = dependency.getSource();\n boolean _tripleNotEquals = (_source != null);\n if (_tripleNotEquals) {\n _xifexpression = this.timestampFunc.apply(dependency.getSource());\n }\n final Long sourceTimestamp = _xifexpression;\n Long _xifexpression_1 = null;\n Event _target = dependency.getTarget();\n boolean _tripleNotEquals_1 = (_target != null);\n if (_tripleNotEquals_1) {\n _xifexpression_1 = this.timestampFunc.apply(dependency.getTarget());\n }\n final Long targetTimestamp = _xifexpression_1;\n final Long timeBound = this.timeBoundFunc.apply(dependency);\n if ((((sourceTimestamp == null) || (targetTimestamp == null)) || (timeBound == null))) {\n if (this.markCritical) {\n CriticalPathAnalysis.unsetCritical(dependency);\n }\n return false;\n } else {\n final boolean criticalValue = (((sourceTimestamp).longValue() + (timeBound).longValue()) >= (targetTimestamp).longValue());\n if (this.markCritical) {\n CriticalPathAnalysis.setCritical(dependency, criticalValue);\n }\n return criticalValue;\n }\n }\n \n /**\n * Default value for persisted {@code critical} property on Dependency\n */\n private static final boolean _DEFAULT_DEPENDENCY_CRITICAL = false;\n \n public static boolean isCritical(final Dependency container) {\n final String key = \"critical\";\n final Object value = container.getProperties().get(key);\n if (value == null) {\n return _DEFAULT_DEPENDENCY_CRITICAL;\n }\n return (boolean) value;\n }\n \n public static void setCritical(final Dependency container, final boolean value) {\n final String key = \"critical\";\n container.getProperties().put(key, value);\n }\n \n /**\n * Returns whether the value of the '{@link nl.esi.pps.tmsc.analysis.CriticalPathAnalysis#isCritical critical}' property is set on {@code container}.\n */\n public static boolean isSetCritical(final Dependency container) {\n final String key = \"critical\";\n\nplugins/nl.esi.pps.tmsc/src-gen/nl/esi/pps/tmsc/Event.java\npublic interface Event extends PropertiesContainer {\n\t/**\n\t * Returns the value of the 'Lifeline' container reference.\n\t * It is bidirectional and its opposite is '{@link nl.esi.pps.tmsc.Lifeline#getEvents Events}'.\n\t * \n\t * \n\t * @return the value of the 'Lifeline' container reference.\n\t * @see #setLifeline(Lifeline)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Lifeline()\n\t * @see nl.esi.pps.tmsc.Lifeline#getEvents\n\t * @model opposite=\"events\" required=\"true\" transient=\"false\"\n\t * @generated\n\t */\n\tLifeline getLifeline();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Event#getLifeline Lifeline}' container reference.\n\t * \n\t * \n\t * @param value the new value of the 'Lifeline' container reference.\n\t * @see #getLifeline()\n\t * @generated\n\t */\n\tvoid setLifeline(Lifeline value);\n\n\t/**\n\t * Returns the value of the 'Arguments' map.\n\t * The key is of type {@link nl.esi.pps.architecture.implemented.FunctionParameter},\n\t * and the value is of type {@link java.lang.String},\n\t * \n\t * \n\t * @return the value of the 'Arguments' map.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Arguments()\n\t * @model mapType=\"nl.esi.pps.tmsc.FunctionArgumentMapEntry<nl.esi.pps.architecture.implemented.FunctionParameter, org.eclipse.emf.ecore.EString>\"\n\t * @generated\n\t */\n\tEMap getArguments();\n\n\t/**\n\t * Returns the value of the 'Full Scope Incoming Dependencies' reference list.\n\t * The list contents are of type {@link nl.esi.pps.tmsc.Dependency}.\n\t * It is bidirectional and its opposite is '{@link nl.esi.pps.tmsc.Dependency#getTarget Target}'.\n\t * \n\t * \n\t * @return the value of the 'Full Scope Incoming Dependencies' reference list.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_FullScopeIncomingDependencies()\n\t * @see nl.esi.pps.tmsc.Dependency#getTarget\n\t * @model opposite=\"target\" resolveProxies=\"false\"\n\t * @generated\n\t */\n\tEList getFullScopeIncomingDependencies();\n\n\t/**\n\t * Returns the value of the 'Full Scope Outgoing Dependencies' reference list.\n\t * The list contents are of type {@link nl.esi.pps.tmsc.Dependency}.\n\t * It is bidirectional and its opposite is '{@link nl.esi.pps.tmsc.Dependency#getSource Source}'.\n\t * \n\t * \n\t * @return the value of the 'Full Scope Outgoing Dependencies' reference list.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_FullScopeOutgoingDependencies()\n\t * @see nl.esi.pps.tmsc.Dependency#getSource\n\t * @model opposite=\"source\" resolveProxies=\"false\"\n\t * @generated\n\t */\n\tEList getFullScopeOutgoingDependencies();\n\n\t/**\n\t * Returns the value of the 'Tmsc' reference.\n\t * \n\t * \n\t * @return the value of the 'Tmsc' reference.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Tmsc()\n\t * @model resolveProxies=\"false\" required=\"true\" transient=\"true\" changeable=\"false\" volatile=\"true\" derived=\"true\"\n\t * @generated\n\t */\n\tFullScopeTMSC getTmsc();\n\n\t/**\n\t * Returns the value of the 'Scopes' reference list.\n\t * The list contents are of type {@link nl.esi.pps.tmsc.ScopedTMSC}.\n\t * \n\t * \n\t * \n\t * Note that this is a derived 'many' relation. Though the return type 'EList' provides methods to alter the content, no altering method should be used and will throw an UnsupportedOperationException upon usage.\n\t * \n\t * @return the value of the 'Scopes' reference list.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Scopes()\n\t * @model resolveProxies=\"false\" transient=\"true\" changeable=\"false\" volatile=\"true\" derived=\"true\" ordered=\"false\"\n\t * @generated\n\t */\n\tEList getScopes();\n\n\t/**\n\t * Returns the value of the 'Component' reference.\n\t * \n\t * \n\t * @return the value of the 'Component' reference.\n\t * @see #setComponent(Component)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Component()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tComponent getComponent();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Event#getComponent Component}' reference.\n\t * \n\t * \n\t * @param value the new value of the 'Component' reference.\n\t * @see #getComponent()\n\t * @generated\n\t */\n\tvoid setComponent(Component value);\n\n\t/**\n\t * Returns the value of the 'Function' reference.\n\t * \n\t * \n\t * @return the value of the 'Function' reference.\n\t * @see #setFunction(Function)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Function()\n\t * @model required=\"true\"\n\t * @generated\n\t */\n\tFunction getFunction();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Event#getFunction Function}' reference.\n\t * \n\t * \n\t * @param value the new value of the 'Function' reference.\n\t * @see #getFunction()\n\t * @generated\n\t */\n\tvoid setFunction(Function value);\n\n\t/**\n\t * Returns the value of the 'Timestamp' attribute.\n\t * \n\t * \n\t * @return the value of the 'Timestamp' attribute.\n\t * @see #setTimestamp(Long)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Timestamp()\n\t * @model dataType=\"nl.esi.pps.tmsc.ETimestamp\" required=\"true\"\n\t * @generated\n\t */\n\tLong getTimestamp();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Event#getTimestamp Timestamp}' attribute.\n\t * \n\t * \n\t * @param value the new value of the 'Timestamp' attribute.\n\t * @see #getTimestamp()\n\t * @generated\n\t */\n\tvoid setTimestamp(Long value);\n\n\t/**\n\t * Returns the value of the 'Traced' attribute.\n\t * The default value is \"true\".\n\t * \n\t * \n\t * @return the value of the 'Traced' attribute.\n\t * @see #setTraced(boolean)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getEvent_Traced()\n\t * @model default=\"true\" required=\"true\"\n\t * @generated\n\t */\n\tboolean isTraced();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Event#isTraced Traced}' attribute.\n\t * \n\t * \n\t * @param value the new value of the 'Traced' attribute.\n\t * @see #isTraced()\n\t * @generated\n\t */\n\tvoid setTraced(boolean value);\n\n\t/**\n\t * \n\t * \n\t * @model kind=\"operation\"\n\t * @generated\n\t */\n\tExecution getExecution();\n\n\t/**\n\t * \n\t * \n\t * @model\n\t * @generated\n\t */\n\tvoid setExecution(Execution Execution);\n\n} // Event\n\nplugins/nl.esi.pps.tmsc/xtend-gen/nl/esi/pps/tmsc/util/TmscQueries.java\n@SuppressWarnings(\"all\")\npublic final class TmscQueries {\n public static class CachedQueryTMSC implements ITMSC {\n @Accessors\n private final List origin = new ArrayList(2);\n \n @Accessors\n private final List dependencies;\n \n private final Map> incomingDependencies;\n \n private final Map> outgoingDependencies;\n \n @Accessors\n private String name;\n \n public CachedQueryTMSC(final Iterable dependencies) {\n if ((dependencies instanceof Collection)) {\n int _size = ((Collection)dependencies).size();\n ArrayList _arrayList = new ArrayList(_size);\n this.dependencies = _arrayList;\n int _size_1 = ((Collection)dependencies).size();\n LinkedHashMap> _linkedHashMap = new LinkedHashMap>(_size_1);\n this.incomingDependencies = _linkedHashMap;\n int _size_2 = ((Collection)dependencies).size();\n LinkedHashMap> _linkedHashMap_1 = new LinkedHashMap>(_size_2);\n this.outgoingDependencies = _linkedHashMap_1;\n } else {\n LinkedList _linkedList = new LinkedList();\n this.dependencies = _linkedList;\n LinkedHashMap> _linkedHashMap_2 = new LinkedHashMap>();\n this.incomingDependencies = _linkedHashMap_2;\n LinkedHashMap> _linkedHashMap_3 = new LinkedHashMap>();\n this.outgoingDependencies = _linkedHashMap_3;\n }\n for (final Dependency dependency : dependencies) {\n {\n this.dependencies.add(dependency);\n final Function> _function = (Event it) -> {\n return new ArrayList();\n };\n List _computeIfAbsent = this.incomingDependencies.computeIfAbsent(dependency.getTarget(), _function);\n _computeIfAbsent.add(dependency);\n final Function> _function_1 = (Event it) -> {\n return new ArrayList();\n };\n List _computeIfAbsent_1 = this.outgoingDependencies.computeIfAbsent(dependency.getSource(), _function_1);\n _computeIfAbsent_1.add(dependency);\n }\n }\n }\n \n @Override\n public List getIncomingDependencies(final Event event) {\n return this.incomingDependencies.getOrDefault(event, Collections.emptyList());\n }\n \n @Override\n public List getOutgoingDependencies(final Event event) {\n return this.outgoingDependencies.getOrDefault(event, Collections.emptyList());\n }\n \n @Override\n public Collection getInitialEvents() {\n Set _keySet = this.outgoingDependencies.keySet();\n final LinkedHashSet initialEvents = new LinkedHashSet(_keySet);\n initialEvents.removeAll(this.incomingDependencies.keySet());\n return initialEvents;\n }\n \n @Override\n public boolean isInitialEvent(final Event event) {\n boolean _containsKey = this.incomingDependencies.containsKey(event);\n return (!_containsKey);\n }\n \n @Override\n public Collection getFinalEvents() {\n Set _keySet = this.incomingDependencies.keySet();\n final LinkedHashSet finalEvents = new LinkedHashSet(_keySet);\n finalEvents.removeAll(this.outgoingDependencies.keySet());\n return finalEvents;\n }\n \n @Override\n public boolean isFinalEvent(final Event event) {\n boolean _containsKey = this.outgoingDependencies.containsKey(event);\n return (!_containsKey);\n }\n \n public ScopedTMSC createScopedTMSC() {\n ScopedTMSC _createScopedTMSC = TmscQueries.createScopedTMSC(this.dependencies, this.name);\n final Procedure1 _function = (ScopedTMSC scope) -> {\n EList _origin = scope.getOrigin();\n Iterables.addAll(_origin, this.origin);\n };\n return ObjectExtensions.operator_doubleArrow(_createScopedTMSC, _function);\n }\n \n @Pure\n public List getOrigin() {\n return this.origin;\n }\n \n @Pure\n @Override\n public List getDependencies() {\n return this.dependencies;\n }\n \n @Pure\n public String getName() {\n return this.name;\n }\n \n public void setName(final String name) {\n this.name = name;\n }\n }\n \n private TmscQueries() {\n }\n \n public static String toDebugString(final nl.esi.pps.architecture.implemented.Function function) {\n StringConcatenation _builder = new StringConcatenation();\n EClass _eClass = null;\n if (function!=null) {\n _eClass=function.eClass();\n }\n String _name = null;\n if (_eClass!=null) {\n _name=_eClass.getName();\n }\n _builder.append(_name);\n _builder.append(\"[\");\n String _name_1 = null;\n if (function!=null) {\n _name_1=function.getName();\n }\n _builder.append(_name_1);\n _builder.append(\"]\");\n return _builder.toString();\n }\n \n public static String toDebugString(final Execution execution) {\n StringConcatenation _builder = new StringConcatenation();\n nl.esi.pps.architecture.implemented.Function _function = null;\n if (execution!=null) {\n _function=execution.getFunction();\n }\n String _debugString = null;\n if (_function!=null) {\n _debugString=TmscQueries.toDebugString(_function);\n }\n _builder.append(_debugString);\n EntryEvent _entry = null;\n if (execution!=null) {\n _entry=execution.getEntry();\n }\n String _debugString_1 = null;\n if (_entry!=null) {\n _debugString_1=TmscQueries.toDebugString(_entry);\n }\n _builder.append(_debugString_1);\n ExitEvent _exit = null;\n if (execution!=null) {\n _exit=execution.getExit();\n }\n String _debugString_2 = null;\n if (_exit!=null) {\n _debugString_2=TmscQueries.toDebugString(_exit);\n }\n _builder.append(_debugString_2);\n return _builder.toString();\n }\n \n public static String toDebugString(final Dependency dependency) {\n StringConcatenation _builder = new StringConcatenation();\n Event _source = null;\n if (dependency!=null) {\n _source=dependency.getSource();\n }\n String _debugString = null;\n if (_source!=null) {\n _debugString=TmscQueries.toDebugString(_source);\n }\n _builder.append(_debugString);\n _builder.append(\" -\");\n EClass _eClass = null;\n if (dependency!=null) {\n _eClass=dependency.eClass();\n }\n String _name = null;\n if (_eClass!=null) {\n _name=_eClass.getName();\n }\n _builder.append(_name);\n _builder.append(\"-> \");\n Event _target = null;\n if (dependency!=null) {\n _target=dependency.getTarget();\n }\n String _debugString_1 = null;\n if (_target!=null) {\n _debugString_1=TmscQueries.toDebugString(_target);\n }\n _builder.append(_debugString_1);\n return _builder.toString();\n }\n \n public static String toDebugString(final Event event) {\n StringConcatenation _builder = new StringConcatenation();\n {\n if ((event instanceof EntryEvent)) {\n _builder.append(\"↑\");\n } else {\n _builder.append(\"↓\");\n }\n }\n Lifeline _lifeline = null;\n if (event!=null) {\n _lifeline=event.getLifeline();\n }\n Executor _executor = null;\n if (_lifeline!=null) {\n _executor=_lifeline.getExecutor();\n }\n String _name = null;\n if (_executor!=null) {\n _name=_executor.getName();\n }\n _builder.append(_name);\n _builder.append(\"@\");\n Long _timestamp = null;\n if (event!=null) {\n _timestamp=event.getTimestamp();\n }\n String _format = ETimestampFormat.eINSTANCE.format(_timestamp);\n _builder.append(_format);\n return _builder.toString();\n }\n \n public static BranchIterable getCallStack(final Execution execution) {\n final Function1> _function = (Execution it) -> {\n return it.getChildren();\n };\n return Queries.walkTree(Collections.singletonList(execution), true, _function);\n }\n \n public static Iterable getCallStackEvents(final Execution execution) {\n Iterable _switchResult = null;\n final Execution it = execution;\n boolean _matched = false;\n if (((it.getEntry() != null) && (it.getExit() != null))) {\n _matched=true;\n final Function1 _function = (LifelineSegment it_1) -> {\n return it_1.getSource();\n };\n _switchResult = Queries.union(IterableExtensions.map(TmscQueries.getCallStackLifelineSegments(execution), _function), execution.getExit());\n }\n if (!_matched) {\n EntryEvent _entry = it.getEntry();\n boolean _tripleNotEquals = (_entry != null);\n if (_tripleNotEquals) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getEntry());\n }\n }\n if (!_matched) {\n ExitEvent _exit = it.getExit();\n boolean _tripleNotEquals_1 = (_exit != null);\n if (_tripleNotEquals_1) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getExit());\n }\n }\n if (!_matched) {\n _switchResult = Collections.emptyList();\n }\n return _switchResult;\n }\n \n public static Iterable getCallStackLifelineSegments(final Execution execution) {\n if (((execution.getEntry() == null) || (execution.getExit() == null))) {\n return Collections.emptyList();\n }\n final Function1 _function = (LifelineSegment it) -> {\n Event _target = it.getTarget();\n LifelineSegment _outgoingLifelineSegment = null;\n if (_target!=null) {\n _outgoingLifelineSegment=TmscQueries.getOutgoingLifelineSegment(_target);\n }\n return _outgoingLifelineSegment;\n };\n final Function1 _function_1 = (LifelineSegment it) -> {\n Event _target = it.getTarget();\n ExitEvent _exit = execution.getExit();\n return Boolean.valueOf(Objects.equal(_target, _exit));\n };\n return Queries.upToAndIncluding(Queries.climbTree(Collections.singleton(TmscQueries.getOutgoingLifelineSegment(execution.getEntry())), true, _function), _function_1);\n }\n \n /**\n * Returns a list, containing the {@link Dependency#getSource() source event}\n * and/or {@link Dependency#getTarget() target event}. The list only contains an\n * event if it is not null.\n */\n public static List getEvents(final Dependency dependency) {\n List _switchResult = null;\n final Dependency it = dependency;\n boolean _matched = false;\n if (((it.getSource() != null) && (it.getTarget() != null))) {\n _matched=true;\n _switchResult = Arrays.asList(it.getSource(), it.getTarget());\n }\n if (!_matched) {\n Event _source = it.getSource();\n boolean _tripleNotEquals = (_source != null);\n if (_tripleNotEquals) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getSource());\n }\n }\n if (!_matched) {\n Event _target = it.getTarget();\n boolean _tripleNotEquals_1 = (_target != null);\n if (_tripleNotEquals_1) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getTarget());\n }\n }\n if (!_matched) {\n _switchResult = Collections.emptyList();\n }\n return _switchResult;\n }\n \n /**\n * Returns a list, containing the {@link Execution#getEntry() entry event}\n * and/or {@link Execution#getExit() exit event}. The list only contains an\n * event if it is not null.\n */\n public static List getEvents(final Execution execution) {\n List _switchResult = null;\n final Execution it = execution;\n boolean _matched = false;\n if (((it.getEntry() != null) && (it.getExit() != null))) {\n _matched=true;\n _switchResult = Arrays.asList(it.getEntry(), it.getExit());\n }\n if (!_matched) {\n EntryEvent _entry = it.getEntry();\n boolean _tripleNotEquals = (_entry != null);\n if (_tripleNotEquals) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getEntry());\n }\n }\n if (!_matched) {\n ExitEvent _exit = it.getExit();\n boolean _tripleNotEquals_1 = (_exit != null);\n if (_tripleNotEquals_1) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getExit());\n }\n }\n if (!_matched) {\n _switchResult = Collections.emptyList();\n }\n return _switchResult;\n }\n \n /**\n * Returns a list, containing the {@link Interval#getFrom() from event}\n * and/or {@link Interval#getTo() to event}. The list only contains an\n * event if it is not null.\n */\n public static List getEvents(final Interval interval) {\n List _switchResult = null;\n final Interval it = interval;\n boolean _matched = false;\n if (((it.getFrom() != null) && (it.getTo() != null))) {\n _matched=true;\n _switchResult = Arrays.asList(it.getFrom(), it.getTo());\n }\n if (!_matched) {\n Event _from = it.getFrom();\n boolean _tripleNotEquals = (_from != null);\n if (_tripleNotEquals) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getFrom());\n }\n }\n if (!_matched) {\n Event _to = it.getTo();\n boolean _tripleNotEquals_1 = (_to != null);\n if (_tripleNotEquals_1) {\n _matched=true;\n _switchResult = Collections.singletonList(it.getTo());\n }\n }\n if (!_matched) {\n _switchResult = Collections.emptyList();\n }\n return _switchResult;\n }\n \n /**\n * Returns true if both {@link Dependency#getSource() source} and\n * {@link Dependency#getTarget() target} are set and both are\n * {@link Event#isTraced() traced}, false otherwise.\n */\n public static boolean isFullyTraced(final Dependency dependency) {\n return (TmscQueries.isSourceTraced(dependency) && TmscQueries.isTargetTraced(dependency));\n }\n \n /**\n * Returns true if {@link Dependency#getSource() source} is set and\n * {@link Event#isTraced() traced}, false otherwise.\n */\n public static boolean isSourceTraced(final Dependency dependency) {\n boolean _and = false;\n Event _source = null;\n if (dependency!=null) {\n _source=dependency.getSource();\n }\n boolean _tripleNotEquals = (_source != null);\n if (!_tripleNotEquals) {\n _and = false;\n } else {\n boolean _isTraced = dependency.getSource().isTraced();\n _and = _isTraced;\n }\n return _and;\n }\n \n /**\n * Returns true if {@link Dependency#getTarget() target} is set and\n * {@link Event#isTraced() traced}, false otherwise.\n */\n public static boolean isTargetTraced(final Dependency dependency) {\n boolean _and = false;\n Event _target = null;\n if (dependency!=null) {\n _target=dependency.getTarget();\n }\n boolean _tripleNotEquals = (_target != null);\n if (!_tripleNotEquals) {\n _and = false;\n } else {\n boolean _isTraced = dependency.getTarget().isTraced();\n _and = _isTraced;\n }\n return _and;\n }\n \n /**\n * Returns true if both {@link Execution#getEntry() entry event} and\n * {@link Execution#getExit() exit event} are set and both are\n * {@link Event#isTraced() traced}, false otherwise.\n */\n public static boolean isFullyTraced(final Execution execution) {\n return (TmscQueries.isEntryTraced(execution) && TmscQueries.isExitTraced(execution));\n }\n \n /**\n * Returns true if {@link Execution#getEntry() entry event} is set and\n * {@link Event#isTraced() traced}, false otherwise.\n */\n public static boolean isEntryTraced(final Execution execution) {\n boolean _and = false;\n EntryEvent _entry = null;\n if (execution!=null) {\n _entry=execution.getEntry();\n }\n boolean _tripleNotEquals = (_entry != null);\n if (!_tripleNotEquals) {\n _and = false;\n } else {\n boolean _isTraced = execution.getEntry().isTraced();\n _and = _isTraced;\n }\n return _and;\n }\n \n /**\n * Returns true if {@link Execution#getExit() exit event} is set and\n * {@link Event#isTraced() traced}, false otherwise.\n */\n public static boolean isExitTraced(final Execution execution) {\n boolean _and = false;\n ExitEvent _exit = null;\n if (execution!=null) {\n _exit=execution.getExit();\n }\n boolean _tripleNotEquals = (_exit != null);\n if (!_tripleNotEquals) {\n _and = false;\n } else {\n boolean _isTraced = execution.getExit().isTraced();\n _and = _isTraced;\n }\n return _and;\n }\n \n /**\n * Returns the nearest common ancestor for both execution1 and execution2.\n */\n public static Execution getCommonAncestor(final Execution execution1, final Execution execution2) {\n final Function1 _function = (Execution it) -> {\n return it.getParent();\n };\n final Set ancestors1 = IterableExtensions.toSet(Queries.climbTree(Collections.singleton(execution1), true, _function));\n final Function1 _function_1 = (Execution it) -> {\n return it.getParent();\n };\n final BranchIterable ancestors2 = Queries.climbTree(Collections.singleton(execution2), true, _function_1);\n final Function1 _function_2 = (Execution e) -> {\n return Boolean.valueOf(ancestors1.contains(e));\n };\n return IterableExtensions.findFirst(ancestors2, _function_2);\n }\n \n /**\n * Creates a valid {@link TmscPackage.Literals#EID EID} string for\n * text.
\n * Replaces each sequence of illegal EID characters by a single '_' (underscore)\n * character.\n */\n public static String toEID(final CharSequence text) {\n String _xifexpression = null;\n if ((text != null)) {\n _xifexpression = text.toString().replaceAll(\"\\\\W+\", \"_\");\n }\n return _xifexpression;\n }\n \n /**\n * Causal dependencies are defined as the intersection of the transitive closure\n * of outgoing dependencies of 'from' and the transitive closure of incoming\n * dependencies of 'to'.\n * \n * @see #findCausalDependenciesBetween(ITMSC, Iterable, Iterable)\n */\n public static Set findCausalDependenciesBetween(final ITMSC tmsc, final Event from, final Event to) {\n return TmscQueries.findCausalDependenciesBetween(tmsc, Collections.singleton(from), Collections.singleton(to));\n }\n \n /**\n * Causal dependencies are defined as the intersection of the transitive closure\n * of outgoing dependencies of 'from' and the transitive closure of incoming\n * dependencies of 'to'.\n *

\n * Please note that, due to incomplete tracing (i.e. untraced Executors), the\n * returned set of dependencies might not contain a fully connected path. This\n * can be checked by calling {@link TmscQueries#findDisjunctTMSCs(Iterable)},\n * which should return a single entry in case of a fully connected path.\n *

\n */\n public static Set findCausalDependenciesBetween(@Extension final ITMSC tmsc, final Iterable froms, final Iterable tos) {\n final Function1 _function = (Event it) -> {\n return it.getTimestamp();\n };\n final Long minTimeStamp = IterableExtensions.min(IterableExtensions.map(froms, _function));\n final Function1 _function_1 = (Event it) -> {\n return it.getTimestamp();\n };\n final Long maxTimeStamp = IterableExtensions.max(IterableExtensions.map(tos, _function_1));\n boolean _greaterThan = (minTimeStamp.compareTo(maxTimeStamp) > 0);\n if (_greaterThan) {\n StringConcatenation _builder = new StringConcatenation();\n _builder.append(\"From nanos (\");\n _builder.append(minTimeStamp);\n _builder.append(\") should be before to nanos (\");\n _builder.append(maxTimeStamp);\n _builder.append(\")\");\n throw new IllegalArgumentException(_builder.toString());\n }\n final Function1> _function_2 = (Event it) -> {\n return tmsc.getOutgoingDependencies(it);\n };\n final Function1> _function_3 = (Dependency it) -> {\n return tmsc.getOutgoingDependencies(it.getTarget());\n };\n final Function1 _function_4 = (Dependency it) -> {\n Long _endTime = it.getEndTime();\n return Boolean.valueOf((_endTime.compareTo(maxTimeStamp) > 0));\n };\n final BranchIterable effect = Queries.until(Queries.closure(IterableExtensions.flatMap(froms, _function_2), true, _function_3), _function_4);\n final Function1> _function_5 = (Event it) -> {\n return tmsc.getIncomingDependencies(it);\n };\n final Function1> _function_6 = (Dependency it) -> {\n return tmsc.getIncomingDependencies(it.getSource());\n };\n final Function1 _function_7 = (Dependency it) -> {\n Long _startTime = it.getStartTime();\n return Boolean.valueOf((_startTime.compareTo(minTimeStamp) < 0));\n };\n final BranchIterable cause = Queries.until(Queries.closure(IterableExtensions.flatMap(tos, _function_5), true, _function_6), _function_7);\n final Set causalDependencies = IterableExtensions.toSet(effect);\n causalDependencies.retainAll(IterableExtensions.toSet(cause));\n return causalDependencies;\n }\n \n /**\n * Finds the transitive closure of adjacent (a.k.a. in any direction) dependencies\n * that match the {@code predicate} and are not before from.timestamp on the from.lifeline and\n * not after to.timestamp on the to.lifeline.\n */\n public static Set findAdjacentDependenciesBetween(@Extension final ITMSC tmsc, final Event from, final Event to, final Function1 predicate) {\n Long _timestamp = from.getTimestamp();\n Long _timestamp_1 = to.getTimestamp();\n boolean _greaterThan = (_timestamp.compareTo(_timestamp_1) > 0);\n if (_greaterThan) {\n StringConcatenation _builder = new StringConcatenation();\n _builder.append(\"From nanos (\");\n Long _timestamp_2 = from.getTimestamp();\n _builder.append(_timestamp_2);\n _builder.append(\") should be before to nanos (\");\n Long _timestamp_3 = to.getTimestamp();\n _builder.append(_timestamp_3);\n _builder.append(\")\");\n throw new IllegalArgumentException(_builder.toString());\n }\n final LinkedHashSet adjacentDependencies = CollectionLiterals.newLinkedHashSet();\n final UniqueQueue eventsToProcess = new UniqueQueue(from, to);\n final Function1 _function = (Dependency it) -> {\n return Boolean.valueOf(TmscQueries.isAfter(it.getTarget(), to));\n };\n final Consumer _function_1 = (Dependency d) -> {\n adjacentDependencies.add(d);\n Event _target = d.getTarget();\n eventsToProcess.add(_target);\n };\n IterableExtensions.filter(IterableExtensions.reject(tmsc.getOutgoingDependencies(from), _function), ((Function1)predicate)).forEach(_function_1);\n final Function1 _function_2 = (Dependency it) -> {\n return Boolean.valueOf(TmscQueries.isBefore(it.getSource(), from));\n };\n final Consumer _function_3 = (Dependency d) -> {\n adjacentDependencies.add(d);\n Event _source = d.getSource();\n eventsToProcess.add(_source);\n };\n IterableExtensions.filter(IterableExtensions.reject(tmsc.getIncomingDependencies(to), _function_2), ((Function1)predicate)).forEach(_function_3);\n while ((!eventsToProcess.isEmpty())) {\n {\n final Event event = eventsToProcess.remove();\n if ((event != null)) {\n final Function1 _function_4 = (Dependency it) -> {\n return Boolean.valueOf(TmscQueries.isBefore(it.getTarget(), from));\n };\n final Function1 _function_5 = (Dependency it) -> {\n return Boolean.valueOf(TmscQueries.isAfter(it.getTarget(), to));\n };\n final Consumer _function_6 = (Dependency d) -> {\n adjacentDependencies.add(d);\n Event _target = d.getTarget();\n eventsToProcess.add(_target);\n };\n IterableExtensions.filter(IterableExtensions.reject(IterableExtensions.reject(tmsc.getOutgoingDependencies(event), _function_4), _function_5), ((Function1)predicate)).forEach(_function_6);\n final Function1 _function_7 = (Dependency it) -> {\n return Boolean.valueOf(TmscQueries.isBefore(it.getSource(), from));\n };\n final Function1 _function_8 = (Dependency it) -> {\n return Boolean.valueOf(TmscQueries.isAfter(it.getSource(), to));\n };\n final Consumer _function_9 = (Dependency d) -> {\n adjacentDependencies.add(d);\n Event _source = d.getSource();\n eventsToProcess.add(_source);\n };\n IterableExtensions.filter(IterableExtensions.reject(IterableExtensions.reject(tmsc.getIncomingDependencies(event), _function_7), _function_8), ((Function1)predicate)).forEach(_function_9);\n }\n }\n }\n return adjacentDependencies;\n }\n \n private static boolean isBefore(final Event event, final Event anchor) {\n boolean _switchResult = false;\n boolean _matched = false;\n Lifeline _lifeline = event.getLifeline();\n Lifeline _lifeline_1 = anchor.getLifeline();\n boolean _tripleNotEquals = (_lifeline != _lifeline_1);\n if (_tripleNotEquals) {\n _matched=true;\n _switchResult = false;\n }\n if (!_matched) {\n Long _timestamp = event.getTimestamp();\n Long _timestamp_1 = anchor.getTimestamp();\n boolean _equals = Objects.equal(_timestamp, _timestamp_1);\n if (_equals) {\n _matched=true;\n int _indexOnLifeline = TmscQueries.indexOnLifeline(event);\n int _indexOnLifeline_1 = TmscQueries.indexOnLifeline(anchor);\n _switchResult = (_indexOnLifeline < _indexOnLifeline_1);\n }\n }\n if (!_matched) {\n Long _timestamp_2 = event.getTimestamp();\n Long _timestamp_3 = anchor.getTimestamp();\n _switchResult = (_timestamp_2.compareTo(_timestamp_3) < 0);\n }\n return _switchResult;\n }\n \n private static boolean isAfter(final Event event, final Event anchor) {\n boolean _switchResult = false;\n boolean _matched = false;\n Lifeline _lifeline = event.getLifeline();\n Lifeline _lifeline_1 = anchor.getLifeline();\n boolean _tripleNotEquals = (_lifeline != _lifeline_1);\n if (_tripleNotEquals) {\n _matched=true;\n _switchResult = false;\n }\n if (!_matched) {\n Long _timestamp = event.getTimestamp();\n Long _timestamp_1 = anchor.getTimestamp();\n boolean _equals = Objects.equal(_timestamp, _timestamp_1);\n if (_equals) {\n _matched=true;\n int _indexOnLifeline = TmscQueries.indexOnLifeline(event);\n int _indexOnLifeline_1 = TmscQueries.indexOnLifeline(anchor);\n _switchResult = (_indexOnLifeline > _indexOnLifeline_1);\n }\n }\n if (!_matched) {\n Long _timestamp_2 = event.getTimestamp();\n Long _timestamp_3 = anchor.getTimestamp();\n _switchResult = (_timestamp_2.compareTo(_timestamp_3) > 0);\n }\n return _switchResult;\n }\n \n /**\n * Returns the {@link List#indexOf(Object) index of} {@code event} within its\n * life-line.\n * \n * @see Event#getLifeline()\n * @see Lifeline#getEvents()\n */\n private static int indexOnLifeline(final Event event) {\n return event.getLifeline().getEvents().indexOf(event);\n }\n \n /**\n * Group dependencies to disjunct TMSCs (as groups of dependencies):
    \n *
  1. When source and target of a dependency do not belong to an TMSC, assign the dependency to a new TMSC
  2. \n *
  3. When source or target are part of the same TMSC, then the dependency belongs to that TMSC as well
  4. \n *
  5. When both assigned to different TMSCs then copy the dependencies of one TMSC to the other
  6. \n *
\n */\n public static List> findDisjunctTMSCs(final Iterable dependencies) {\n final Map> event2tmsc = CollectionLiterals.>newLinkedHashMap();\n for (final Dependency dependency : dependencies) {\n {\n final List sourceTmsc = event2tmsc.get(dependency.getSource());\n final List targetTmsc = event2tmsc.get(dependency.getTarget());\n if (((sourceTmsc != null) && (targetTmsc != null))) {\n if ((sourceTmsc == targetTmsc)) {\n sourceTmsc.add(dependency);\n } else {\n int _size = sourceTmsc.size();\n int _size_1 = targetTmsc.size();\n boolean _lessThan = (_size < _size_1);\n if (_lessThan) {\n Iterables.addAll(targetTmsc, sourceTmsc);\n targetTmsc.add(dependency);\n final Function1 _function = (Dependency it) -> {\n return it.getSource();\n };\n final Function1 _function_1 = (Dependency it) -> {\n return it.getTarget();\n };\n final Consumer _function_2 = (Event e) -> {\n event2tmsc.put(e, targetTmsc);\n };\n Queries.union(ListExtensions.map(sourceTmsc, _function), ListExtensions.map(sourceTmsc, _function_1)).forEach(_function_2);\n } else {\n Iterables.addAll(sourceTmsc, targetTmsc);\n sourceTmsc.add(dependency);\n final Function1 _function_3 = (Dependency it) -> {\n return it.getSource();\n };\n final Function1 _function_4 = (Dependency it) -> {\n return it.getTarget();\n };\n final Consumer _function_5 = (Event e) -> {\n event2tmsc.put(e, sourceTmsc);\n };\n Queries.union(ListExtensions.map(targetTmsc, _function_3), ListExtensions.map(targetTmsc, _function_4)).forEach(_function_5);\n }\n }\n } else {\n if ((sourceTmsc != null)) {\n sourceTmsc.add(dependency);\n event2tmsc.put(dependency.getTarget(), sourceTmsc);\n } else {\n if ((targetTmsc != null)) {\n targetTmsc.add(dependency);\n event2tmsc.put(dependency.getSource(), targetTmsc);\n } else {\n final ArrayList tmsc = CollectionLiterals.newArrayList(dependency);\n event2tmsc.put(dependency.getSource(), tmsc);\n event2tmsc.put(dependency.getTarget(), tmsc);\n }\n }\n }\n }\n }\n return IterableExtensions.>toList(Queries.>unique(event2tmsc.values(), false));\n }\n \n /**\n * Group dependencies to disjunct TMSCs (as groups of dependencies):
    \n *
  1. When source and target of a dependency do not belong to an TMSC, assign the dependency to a new TMSC
  2. \n *
  3. When source or target are part of the same TMSC, then the dependency belongs to that TMSC as well
  4. \n *
  5. When both assigned to different TMSCs then copy the dependencies of one TMSC to the other
  6. \n *
\n * In addition, {@link Event events} that match the predicate are also considered to be both initial and final events.\n */\n public static List> findDisjunctTMSCs(final Iterable dependencies, final Predicate predicate) {\n final Map> sourceEvent2tmsc = CollectionLiterals.>newLinkedHashMap();\n final Map> targetEvent2tmsc = CollectionLiterals.>newLinkedHashMap();\n for (final Dependency dependency : dependencies) {\n {\n final List sourceTmsc = sourceEvent2tmsc.get(dependency.getSource());\n final List targetTmsc = targetEvent2tmsc.get(dependency.getTarget());\n final boolean sourceInitial = predicate.test(dependency.getSource());\n final boolean targetFinal = predicate.test(dependency.getTarget());\n if (((sourceTmsc != null) && (targetTmsc != null))) {\n if ((sourceTmsc == targetTmsc)) {\n sourceTmsc.add(dependency);\n } else {\n Iterables.addAll(sourceTmsc, targetTmsc);\n sourceTmsc.add(dependency);\n final Function1>, Boolean> _function = (Map.Entry> it) -> {\n List _value = it.getValue();\n return Boolean.valueOf((_value == targetTmsc));\n };\n final Consumer>> _function_1 = (Map.Entry> it) -> {\n it.setValue(sourceTmsc);\n };\n IterableExtensions.>>filter(sourceEvent2tmsc.entrySet(), _function).forEach(_function_1);\n final Function1>, Boolean> _function_2 = (Map.Entry> it) -> {\n List _value = it.getValue();\n return Boolean.valueOf((_value == targetTmsc));\n };\n final Consumer>> _function_3 = (Map.Entry> it) -> {\n it.setValue(sourceTmsc);\n };\n IterableExtensions.>>filter(targetEvent2tmsc.entrySet(), _function_2).forEach(_function_3);\n }\n } else {\n if ((sourceTmsc != null)) {\n sourceTmsc.add(dependency);\n targetEvent2tmsc.put(dependency.getTarget(), sourceTmsc);\n if ((!targetFinal)) {\n sourceEvent2tmsc.put(dependency.getTarget(), sourceTmsc);\n }\n } else {\n if ((targetTmsc != null)) {\n targetTmsc.add(dependency);\n sourceEvent2tmsc.put(dependency.getSource(), targetTmsc);\n if ((!sourceInitial)) {\n targetEvent2tmsc.put(dependency.getSource(), targetTmsc);\n }\n } else {\n final ArrayList tmsc = CollectionLiterals.newArrayList(dependency);\n sourceEvent2tmsc.put(dependency.getSource(), tmsc);\n if ((!sourceInitial)) {\n targetEvent2tmsc.put(dependency.getSource(), tmsc);\n }\n targetEvent2tmsc.put(dependency.getTarget(), tmsc);\n if ((!targetFinal)) {\n sourceEvent2tmsc.put(dependency.getTarget(), tmsc);\n }\n }\n }\n }\n }\n }\n return IterableExtensions.>toList(Queries.>unique(Queries.>union(sourceEvent2tmsc.values(), targetEvent2tmsc.values()), false));\n }\n \n /**\n * Trims a TMSC, removing all events at the border that match the predicate.\n */\n public static Set trim(@Extension final ITMSC tmsc, final Predicate predicate) {\n final Function1> _function = (Event it) -> {\n return tmsc.getOutgoingDependencies(it);\n };\n final Function1> _function_1 = (Dependency it) -> {\n return tmsc.getOutgoingDependencies(it.getTarget());\n };\n final Function1 _function_2 = (Dependency it) -> {\n boolean _test = predicate.test(it.getSource());\n return Boolean.valueOf((!_test));\n };\n final BranchIterable leadingDependencies = Queries.until(Queries.closure(IterableExtensions.flatMap(tmsc.getInitialEvents(), _function), true, _function_1), _function_2);\n final Function1> _function_3 = (Event it) -> {\n return tmsc.getIncomingDependencies(it);\n };\n final Function1> _function_4 = (Dependency it) -> {\n return tmsc.getIncomingDependencies(it.getSource());\n };\n final Function1 _function_5 = (Dependency it) -> {\n boolean _test = predicate.test(it.getTarget());\n return Boolean.valueOf((!_test));\n };\n final BranchIterable trailingDependencies = Queries.until(Queries.closure(IterableExtensions.flatMap(tmsc.getFinalEvents(), _function_3), true, _function_4), _function_5);\n Collection _dependencies = tmsc.getDependencies();\n final LinkedHashSet trimmedDependencies = new LinkedHashSet(_dependencies);\n CollectionExtensions.removeAll(trimmedDependencies, leadingDependencies);\n CollectionExtensions.removeAll(trimmedDependencies, trailingDependencies);\n return trimmedDependencies;\n }\n \n /**\n * Returns all dependencies (including dependency) of the same type (i.e.\n * same {@link EObject#eClass() eClass}) between the source lifeline and target\n * lifeline of dependency.\n */\n public static Iterable findAllOfTypeBetweenLifelines(final T dependency) {\n final Function1> _function = (Event it) -> {\n return it.getFullScopeOutgoingDependencies();\n };\n final Function1 _function_1 = (Dependency it) -> {\n return Boolean.valueOf((Objects.equal(it.eClass(), dependency.eClass()) && Objects.equal(it.getTarget().getLifeline(), dependency.getTarget().getLifeline())));\n };\n Iterable _filter = IterableExtensions.filter(IterableExtensions.flatMap(dependency.getSource().getLifeline().getEvents(), _function), _function_1);\n return ((Iterable) _filter);\n }\n \n /**\n * Returns all executions with the same {@link Execution#getFunction() function}\n * for the same {@link Execution#getComponent() component}\n */\n public static Iterable findAllWithFunctionAndComponent(final Execution execution) {\n final Function1> _function = (Lifeline it) -> {\n return it.getExecutions();\n };\n final Function1 _function_1 = (Execution it) -> {\n return Boolean.valueOf((Objects.equal(it.getFunction(), execution.getFunction()) && Objects.equal(it.getComponent(), execution.getComponent())));\n };\n return IterableExtensions.filter(IterableExtensions.flatMap(execution.getTmsc().getLifelines(), _function), _function_1);\n }\n \n /**\n * Returns all executions with the same {@link Execution#getFunction() function}\n * for the same {@link Execution#getLifeline() lifeline}\n */\n public static Iterable findAllWithFunctionAndLifeline(final Execution execution) {\n final Function1 _function = (Execution it) -> {\n nl.esi.pps.architecture.implemented.Function _function_1 = it.getFunction();\n nl.esi.pps.architecture.implemented.Function _function_2 = execution.getFunction();\n return Boolean.valueOf(Objects.equal(_function_1, _function_2));\n };\n return IterableExtensions.filter(execution.getLifeline().getExecutions(), _function);\n }\n \n /**\n * Convenience method for creating {@link ITMSC} instances that are required by some queries.\n */\n public static TmscQueries.CachedQueryTMSC createCachedQueryTMSC(final Iterable cacheDependencies, final Event... cacheOrigin) {\n TmscQueries.CachedQueryTMSC _cachedQueryTMSC = new TmscQueries.CachedQueryTMSC(cacheDependencies);\n final Procedure1 _function = (TmscQueries.CachedQueryTMSC cache) -> {\n Iterables.addAll(cache.origin, ((Iterable)Conversions.doWrapArray(cacheOrigin)));\n };\n return ObjectExtensions.operator_doubleArrow(_cachedQueryTMSC, _function);\n }\n \n /**\n * Convenience method for creating {@link ITMSC} instances that are required by some queries.\n */\n public static TmscQueries.CachedQueryTMSC createCachedQueryTMSC(final Iterable cacheDependencies, final CharSequence cacheName, final Event... cacheOrigin) {\n TmscQueries.CachedQueryTMSC _cachedQueryTMSC = new TmscQueries.CachedQueryTMSC(cacheDependencies);\n final Procedure1 _function = (TmscQueries.CachedQueryTMSC cache) -> {\n cache.name = cacheName.toString();\n Iterables.addAll(cache.origin, ((Iterable)Conversions.doWrapArray(cacheOrigin)));\n };\n return ObjectExtensions.operator_doubleArrow(_cachedQueryTMSC, _function);\n }\n \n /**\n * Convenience method for creating a {@link ScopedTMSC} instance, that does two things:\n *
    \n *
  1. Ensures a valid {@code scopeName}, see {@link #toEID(CharSequence)}
  2. \n *
  3. Applies a performance improvement in adding dependencies
  4. \n *
\n * Please note that the resulting {@link ScopedTMSC} is not yet {@link TMSC#getChildScopes() contained}.\n */\n public static ScopedTMSC createScopedTMSC(final Iterable scopeDependencies, final CharSequence scopeName, final Event... scopeOrigin) {\n ScopedTMSC _createScopedTMSC = TmscFactory.eINSTANCE.createScopedTMSC();\n final Procedure1 _function = (ScopedTMSC it) -> {\n it.setName(TmscQueries.toEID(scopeName));\n EList _origin = it.getOrigin();\n Iterables.addAll(_origin, ((Iterable)Conversions.doWrapArray(scopeOrigin)));\n if ((scopeDependencies instanceof Collection)) {\n it.getDependencies().addAll(((Collection)scopeDependencies));\n } else {\n it.getDependencies().addAll(IterableExtensions.toList(scopeDependencies));\n }\n };\n return ObjectExtensions.operator_doubleArrow(_createScopedTMSC, _function);\n }\n \n /**\n * Adding a {@code child} scope might require to add (new) dependencies\n * to the {@code parent} TMSC and its ancestors.\n * Only the added dependencies are returned.\n */\n public static Set addScopedTMSC(final TMSC parent, final ScopedTMSC child) {\n EList _childScopes = parent.getChildScopes();\n _childScopes.add(child);\n return TmscQueries.addDependencies(parent, child.getDependencies());\n }\n \n /**\n * Adds dependencies to a TMSC and its ancestors, only if they are not yet added.\n * Only the added dependencies are returned.\n */\n public static Set addDependencies(final TMSC tmsc, final Iterable dependencies) {\n final LinkedHashSet dependenciesToAdd = Sets.newLinkedHashSet(dependencies);\n dependenciesToAdd.removeAll(tmsc.getDependencies());\n boolean _isEmpty = dependenciesToAdd.isEmpty();\n boolean _not = (!_isEmpty);\n if (_not) {\n Collection _dependencies = tmsc.getDependencies();\n Iterables.addAll(_dependencies, dependenciesToAdd);\n if ((tmsc instanceof ScopedTMSC)) {\n TMSC _parentScope = ((ScopedTMSC)tmsc).getParentScope();\n boolean _tripleNotEquals = (_parentScope != null);\n if (_tripleNotEquals) {\n TmscQueries.addDependencies(((ScopedTMSC)tmsc).getParentScope(), dependenciesToAdd);\n }\n }\n }\n return dependenciesToAdd;\n }\n \n /**\n * An performance optimized version of {@code event.getScopes().contains(tmsc)}.\n */\n public static boolean isInScope(final Event event, final ScopedTMSC tmsc) {\n return ((tmsc != null) && IterableExtensions.exists(Queries.union(event.getFullScopeIncomingDependencies(), event.getFullScopeOutgoingDependencies()), ((Function1) (Dependency it) -> {\n return Boolean.valueOf(it.getScopes().contains(tmsc));\n })));\n }\n \n public static boolean isInScope(final Event event, final Iterable tmscs) {\n boolean _isNullOrEmpty = IterableExtensions.isNullOrEmpty(tmscs);\n if (_isNullOrEmpty) {\n return false;\n }\n final Function1> _function = (Dependency it) -> {\n return it.getScopes();\n };\n final Iterable eventScopes = IterableExtensions.flatMap(Queries.union(event.getFullScopeIncomingDependencies(), event.getFullScopeOutgoingDependencies()), _function);\n final Function1 _function_1 = (ScopedTMSC scope) -> {\n return Boolean.valueOf(IterableExtensions.contains(tmscs, scope));\n };\n return IterableExtensions.exists(eventScopes, _function_1);\n }\n \n public static void disposeTemp(final ScopedTMSC tmsc, final boolean disposeTempDependencies) {\n EObject _eContainer = tmsc.eContainer();\n boolean _tripleNotEquals = (_eContainer != null);\n if (_tripleNotEquals) {\n throw new IllegalArgumentException(\n \"This method is only intended for temporary TMCSs that are not added to the model yet\");\n }\n List _xifexpression = null;\n if (disposeTempDependencies) {\n final Function1 _function = (Dependency it) -> {\n EObject _eContainer_1 = it.eContainer();\n return Boolean.valueOf((_eContainer_1 == null));\n };\n _xifexpression = IterableExtensions.toList(IterableExtensions.filter(tmsc.getDependencies(), _function));\n } else {\n _xifexpression = Collections.emptyList();\n }\n final List tempDependencies = _xifexpression;\n final Function1> _function_1 = (ScopedTMSC it) -> {\n return it.getChildScopes();\n };\n final Consumer _function_2 = (ScopedTMSC it) -> {\n it.getDependencies().clear();\n };\n Queries.closure(Collections.singleton(tmsc), true, _function_1).forEach(_function_2);\n final Consumer _function_3 = (Dependency it) -> {\n TmscQueries.disposeTemp(it);\n };\n tempDependencies.forEach(_function_3);\n }\n \n public static void disposeTemp(final Iterable dependencies) {\n final Function1 _function = (Dependency it) -> {\n EObject _eContainer = it.eContainer();\n return Boolean.valueOf((_eContainer == null));\n };\n final List tempDependencies = IterableExtensions.toList(IterableExtensions.filter(dependencies, _function));\n final Function1>> _function_1 = (Dependency d) -> {\n final Function1> _function_2 = (ScopedTMSC s) -> {\n return Pair.of(s, d);\n };\n return ListExtensions.>map(d.getScopes(), _function_2);\n };\n final Function1, ScopedTMSC> _function_2 = (Pair it) -> {\n return it.getKey();\n };\n final Function1, Dependency> _function_3 = (Pair it) -> {\n return it.getValue();\n };\n final Map> tempDependenciesPerScope = Queries., ScopedTMSC, Dependency>groupBy(Queries.collect(tempDependencies, _function_1), _function_2, _function_3);\n final BiConsumer> _function_4 = (ScopedTMSC s, List d) -> {\n s.getDependencies().removeAll(d);\n };\n tempDependenciesPerScope.forEach(_function_4);\n final Consumer _function_5 = (Dependency it) -> {\n TmscQueries.disposeTemp(it);\n };\n tempDependencies.forEach(_function_5);\n }\n \n public static void disposeTemp(final Dependency dependency) {\n EObject _eContainer = dependency.eContainer();\n boolean _tripleNotEquals = (_eContainer != null);\n if (_tripleNotEquals) {\n throw new IllegalArgumentException(\n \"This method is only intended for temporary dependencies that are not added to the model yet\");\n }\n final Function1 _function = (EStructuralFeature it) -> {\n return Boolean.valueOf(it.isChangeable());\n };\n final Consumer _function_1 = (EStructuralFeature f) -> {\n dependency.eUnset(f);\n };\n IterableExtensions.filter(dependency.eClass().getEAllStructuralFeatures(), _function).forEach(_function_1);\n }\n \n /**\n * Returns the dependencies whose events include {@code event}.\n * \n *

\n * This is equal to the union of {@link Event#getFullScopeIncomingDependencies()\n * incoming } and {@link Event#getFullScopeOutgoingDependencies() outgoing }\n * dependencies.\n *

\n */\n public static Iterable getFullScopeDependencies(final Event event) {\n return Queries.union(event.getFullScopeIncomingDependencies(), event.getFullScopeOutgoingDependencies());\n }\n \n public static BranchIterable getPreviousEventsOnLifeline(final Event event) {\n final Function1 _function = (Event it) -> {\n LifelineSegment _incomingLifelineSegment = TmscQueries.getIncomingLifelineSegment(it);\n Event _source = null;\n if (_incomingLifelineSegment!=null) {\n _source=_incomingLifelineSegment.getSource();\n }\n return _source;\n };\n return Queries.climbTree(Collections.singleton(event), _function);\n }\n \n public static LifelineSegment getIncomingLifelineSegment(final Event event) {\n final Function1 _function = (LifelineSegment it) -> {\n return Boolean.valueOf(it.isProjection());\n };\n return TmscQueries.getAtMostOne(IterableExtensions.reject(Iterables.filter(event.getFullScopeIncomingDependencies(), LifelineSegment.class), _function));\n }\n \n public static BranchIterable getNextEventsOnLifeline(final Event event) {\n final Function1 _function = (Event it) -> {\n LifelineSegment _outgoingLifelineSegment = TmscQueries.getOutgoingLifelineSegment(it);\n Event _target = null;\n if (_outgoingLifelineSegment!=null) {\n _target=_outgoingLifelineSegment.getTarget();\n }\n return _target;\n };\n return Queries.climbTree(Collections.singleton(event), _function);\n }\n \n public static LifelineSegment getOutgoingLifelineSegment(final Event event) {\n final Function1 _function = (LifelineSegment it) -> {\n return Boolean.valueOf(it.isProjection());\n };\n return TmscQueries.getAtMostOne(IterableExtensions.reject(Iterables.filter(event.getFullScopeOutgoingDependencies(), LifelineSegment.class), _function));\n }\n \n public static T getAtMostOne(final Iterable source) {\n final Iterator iterator = source.iterator();\n boolean _hasNext = iterator.hasNext();\n if (_hasNext) {\n final T result = iterator.next();\n boolean _hasNext_1 = iterator.hasNext();\n if (_hasNext_1) {\n throw new IllegalArgumentException((\"Expected at most 1 element: \" + source));\n }\n return result;\n } else {\n return null;\n }\n }\n \n public static void makeRelativeTiming(final TMSC tmsc) {\n final FullScopeTMSC fullScope = tmsc.getFullScope();\n if ((tmsc instanceof ScopedTMSC)) {\n ScopedTmscCopier.deriveStartEndTime(((ScopedTMSC)tmsc));\n }\n Long _startTime = fullScope.getStartTime();\n long _minus = (-(_startTime).longValue());\n TmscQueries.shiftTime(fullScope, _minus);\n fullScope.setEpochTime(false);\n }\n \n public static void shiftTime(final FullScopeTMSC tmsc, final long delta) {\n final Function1 _function = (Event it) -> {\n Long _timestamp = it.getTimestamp();\n return Boolean.valueOf((_timestamp == null));\n };\n final Consumer _function_1 = (Event it) -> {\n Long _timestamp = it.getTimestamp();\n long _plus = ((_timestamp).longValue() + delta);\n it.setTimestamp(Long.valueOf(_plus));\n };\n IterableExtensions.reject(tmsc.getEvents(), _function).forEach(_function_1);\n Long _startTime = tmsc.getStartTime();\n long _plus = ((_startTime).longValue() + delta);\n tmsc.setStartTime(Long.valueOf(_plus));\n Long _endTime = tmsc.getEndTime();\n long _plus_1 = ((_endTime).longValue() + delta);\n tmsc.setEndTime(Long.valueOf(_plus_1));\n }\n}", "answers": [" return container.getProperties().containsKey(key);"], "length": 5911, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ae17294b-8578-4809-912f-24eaf703ea0b", "reasoning": "The method isSetCritical starts by defining the key string. The next logical step is to return whether the container's properties map contains that key. Therefore the next line should be the return statement checking the map for the key.", "reasoning_model_answer": "return container.getProperties().containsKey(key);", "assistant_with_reasoning": "\nThe method isSetCritical starts by defining the key string. The next logical step is to return whether the container's properties map contains that key. Therefore the next line should be the return statement checking the map for the key.\n\nreturn container.getProperties().containsKey(key);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.455, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36645, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return container.getProperties().containsKey(key);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.File;\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.time.LocalDateTime;\nimport java.time.temporal.ChronoUnit;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport tech.inceptive.ai4czc.entsoedataretrieval.csv.CSVGenerator;\nimport tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.CSVTransformer;\nimport tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.GLDocumentCSVTransformer;\nimport tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.PublicationDocCSVTransformer;\nimport tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers.UnavailabilityDocCSVTransformer;\nimport tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError;\nimport tech.inceptive.ai4czc.entsoedataretrieval.fetcher.ENTSOEDataFetcher;\nimport tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area;\nimport tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ColumnType;\nimport tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument;\nimport tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.PublicationMarketDocument;\nimport tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument;\nimport tech.inceptive.ai4czc.entsoedataretrieval.tools.DateTimeDivider;", "context": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/ENTSOEHistoricalDataRetrieval.java\n/*\n * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n */\npackage tech.inceptive.ai4czc.entsoedataretrieval;\n\n\n/**\n * The class to fetch an dataset from entsoe.\n *\n * @author andres\n */\npublic class ENTSOEHistoricalDataRetrieval {\n\n private final Set columnType;\n private ENTSOEDataFetcher fetcher; // not final for testing purpose\n private CSVGenerator csvGen; // not final for testing purpose\n private final String csvEscapeChar;\n private final String csvSeparator;\n // TODO : make the time granularity configurable?\n\n public ENTSOEHistoricalDataRetrieval(String authToken,\n Set columnType, String csvEscapeChar, String csvSeparator, boolean useRequestCache) {\n this.columnType = columnType;\n this.fetcher = new ENTSOEDataFetcher(authToken, useRequestCache);\n this.csvEscapeChar = csvEscapeChar;\n this.csvSeparator = csvSeparator;\n this.csvGen = new CSVGenerator(csvSeparator, csvEscapeChar);\n }\n\n /**\n * Retrieves to a temporal file the dataset, on CSV format.\n *\n * @param startDate\n * @param endDate\n * @return\n */\n public File fetchDataset(LocalDateTime startDate, LocalDateTime endDate, Duration timeStep, Set targetAreas,\n Area mainFlowsArea, Duration maxTimeDuration) {\n List transformers = new ArrayList<>(columnType.size());\n List splits;\n if (Duration.ofDays(365).minus(maxTimeDuration).isNegative()) {\n throw new DataRetrievalError(\"Maximal duration can not be bigger than 365 days\");\n }\n if (columnType.contains(ColumnType.ACTUAL_LOAD)) {\n // split request depending on stard and end date\n splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration,\n Duration.of(60, ChronoUnit.MINUTES));\n for (int i = 0; i < splits.size() - 1; i++) {\n for (Area targetArea : targetAreas) {\n Optional opt = fetcher.fetchActualLoad(targetArea, splits.get(i), splits.get(i + 1));\n if (opt.isPresent()) {\n transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get()));\n }\n }\n }\n }\n if (columnType.contains(ColumnType.DAY_AHEAD_LOAD)) {\n splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration,\n Duration.of(24, ChronoUnit.HOURS));\n for (int i = 0; i < splits.size() - 1; i++) {\n for (Area targetArea : targetAreas) {\n Optional opt = fetcher.fetchDayAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1));\n if (opt.isPresent()) {\n transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get()));\n }\n }\n }\n }\n if (columnType.contains(ColumnType.WEAK_AHEAD_LOAD)) {\n splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration,\n Duration.of(7, ChronoUnit.DAYS));\n for (int i = 0; i < splits.size() - 1; i++) {\n for (Area targetArea : targetAreas) {\n Optional opt = fetcher.fetchWeekAheadLoadForecast(targetArea, splits.get(i), splits.get(i + 1));\n if (opt.isPresent()) {\n transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get()));\n }\n }\n }\n }\n if (columnType.contains(ColumnType.AGGREGATED_GENERATION_TYPE)) {\n splits = DateTimeDivider.splitInMilestones(startDate, endDate, maxTimeDuration,\n Duration.of(60, ChronoUnit.MINUTES));\n for (int i = 0; i < splits.size() - 1; i++) {\n for (Area targetArea : targetAreas) {\n Optional opt = fetcher.fetchAggregatedGenerationType(targetArea, splits.get(i), splits.get(i + 1));\n if (opt.isPresent()) {\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/xjc/GLMarketDocument.java\n@XmlRootElement(name = \"GL_MarketDocument\", namespace = \"urn:iec62325.351:tc57wg16:451-6:generationloaddocument:3:0\")\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"GL_MarketDocument\", propOrder = {\n \"mrid\",\n \"revisionNumber\",\n \"type\",\n \"processProcessType\",\n \"senderMarketParticipantMRID\",\n \"senderMarketParticipantMarketRoleType\",\n \"receiverMarketParticipantMRID\",\n \"receiverMarketParticipantMarketRoleType\",\n \"createdDateTime\",\n \"timePeriodTimeInterval\",\n \"timeSeries\"\n})\npublic class GLMarketDocument {\n\n @XmlElement(name = \"mRID\", required = true)\n protected String mrid;\n @XmlElement(required = true)\n protected String revisionNumber;\n @XmlElement(required = true)\n protected String type;\n @XmlElement(name = \"process.processType\", required = true)\n protected String processProcessType;\n @XmlElement(name = \"sender_MarketParticipant.mRID\", required = true)\n protected PartyIDString senderMarketParticipantMRID;\n @XmlElement(name = \"sender_MarketParticipant.marketRole.type\", required = true)\n protected String senderMarketParticipantMarketRoleType;\n @XmlElement(name = \"receiver_MarketParticipant.mRID\", required = true)\n protected PartyIDString receiverMarketParticipantMRID;\n @XmlElement(name = \"receiver_MarketParticipant.marketRole.type\", required = true)\n protected String receiverMarketParticipantMarketRoleType;\n @XmlElement(required = true)\n @XmlSchemaType(name = \"dateTime\")\n protected XMLGregorianCalendar createdDateTime;\n @XmlElement(name = \"time_Period.timeInterval\", required = true)\n protected ESMPDateTimeInterval timePeriodTimeInterval;\n @XmlElement(name = \"TimeSeries\", required = true)\n protected List timeSeries;\n\n /**\n * Gets the value of the mrid property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getMRID() {\n return mrid;\n }\n\n /**\n * Sets the value of the mrid property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setMRID(String value) {\n this.mrid = value;\n }\n\n /**\n * Gets the value of the revisionNumber property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRevisionNumber() {\n return revisionNumber;\n }\n\n /**\n * Sets the value of the revisionNumber property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRevisionNumber(String value) {\n this.revisionNumber = value;\n }\n\n /**\n * Gets the value of the type property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setType(String value) {\n this.type = value;\n }\n\n /**\n * Gets the value of the processProcessType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getProcessProcessType() {\n return processProcessType;\n }\n\n /**\n * Sets the value of the processProcessType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setProcessProcessType(String value) {\n this.processProcessType = value;\n }\n\n /**\n * Gets the value of the senderMarketParticipantMRID property.\n * \n * @return\n * possible object is\n * {@link PartyIDString }\n * \n */\n public PartyIDString getSenderMarketParticipantMRID() {\n return senderMarketParticipantMRID;\n }\n\n /**\n * Sets the value of the senderMarketParticipantMRID property.\n * \n * @param value\n * allowed object is\n * {@link PartyIDString }\n * \n */\n public void setSenderMarketParticipantMRID(PartyIDString value) {\n this.senderMarketParticipantMRID = value;\n }\n\n /**\n * Gets the value of the senderMarketParticipantMarketRoleType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getSenderMarketParticipantMarketRoleType() {\n return senderMarketParticipantMarketRoleType;\n }\n\n /**\n * Sets the value of the senderMarketParticipantMarketRoleType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setSenderMarketParticipantMarketRoleType(String value) {\n this.senderMarketParticipantMarketRoleType = value;\n }\n\n /**\n * Gets the value of the receiverMarketParticipantMRID property.\n * \n * @return\n * possible object is\n * {@link PartyIDString }\n * \n */\n public PartyIDString getReceiverMarketParticipantMRID() {\n return receiverMarketParticipantMRID;\n }\n\n /**\n * Sets the value of the receiverMarketParticipantMRID property.\n * \n * @param value\n * allowed object is\n * {@link PartyIDString }\n * \n */\n public void setReceiverMarketParticipantMRID(PartyIDString value) {\n this.receiverMarketParticipantMRID = value;\n }\n\n /**\n * Gets the value of the receiverMarketParticipantMarketRoleType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getReceiverMarketParticipantMarketRoleType() {\n return receiverMarketParticipantMarketRoleType;\n }\n\n /**\n * Sets the value of the receiverMarketParticipantMarketRoleType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setReceiverMarketParticipantMarketRoleType(String value) {\n this.receiverMarketParticipantMarketRoleType = value;\n }\n\n /**\n * Gets the value of the createdDateTime property.\n * \n * @return\n * possible object is\n * {@link XMLGregorianCalendar }\n * \n */\n public XMLGregorianCalendar getCreatedDateTime() {\n return createdDateTime;\n }\n\n /**\n * Sets the value of the createdDateTime property.\n * \n * @param value\n * allowed object is\n * {@link XMLGregorianCalendar }\n * \n */\n public void setCreatedDateTime(XMLGregorianCalendar value) {\n this.createdDateTime = value;\n }\n\n /**\n * Gets the value of the timePeriodTimeInterval property.\n * \n * @return\n * possible object is\n * {@link ESMPDateTimeInterval }\n * \n */\n public ESMPDateTimeInterval getTimePeriodTimeInterval() {\n return timePeriodTimeInterval;\n }\n\n /**\n * Sets the value of the timePeriodTimeInterval property.\n * \n * @param value\n * allowed object is\n * {@link ESMPDateTimeInterval }\n * \n */\n public void setTimePeriodTimeInterval(ESMPDateTimeInterval value) {\n this.timePeriodTimeInterval = value;\n }\n\n /**\n * Gets the value of the timeSeries property.\n * \n *

\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a set method for the timeSeries property.\n * \n *

\n * For example, to add a new item, do as follows:\n *

\n     *    getTimeSeries().add(newItem);\n     * 
\n * \n * \n *

\n * Objects of the following type(s) are allowed in the list\n * {@link TimeSeries }\n * \n * \n */\n public List getTimeSeries() {\n if (timeSeries == null) {\n timeSeries = new ArrayList();\n }\n return this.timeSeries;\n }\n\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/inputs/ColumnType.java\npublic enum ColumnType {\n ACTUAL_LOAD(\"6.1.A\"),\n DAY_AHEAD_LOAD(\"6.1.B\"),\n WEAK_AHEAD_LOAD(\"6.1.C\"),\n TRANSMISSION_OUTAGE(\"10.1.A&B\"),\n WEEK_FORECAST_CAPACITY(\"11.1.A.C\"),\n PHYSICAL_FLOW(\"12.1.G\"),\n GENERATION_OUTAGE(\"15.1.A&B\"),\n AGGREGATED_GENERATION_TYPE(\"16.1.B&C\");\n \n private static final Logger LOGGER = LogManager.getLogger(ColumnType.class);\n \n private static final Map ARTICLE_TO_COLUMN_TYPE;\n \n static {\n ARTICLE_TO_COLUMN_TYPE = new HashMap<>();\n for(ColumnType curCol : ColumnType.values()) {\n ARTICLE_TO_COLUMN_TYPE.put(curCol.getRelevantArticle(), curCol);\n }\n }\n \n private final String relevantArticle;\n\n private ColumnType(String relevantArticle) {\n this.relevantArticle = relevantArticle;\n }\n\n public String getRelevantArticle() {\n return relevantArticle;\n }\n \n public static ColumnType ColumnTypeFromArticle(String article) {\n if (article == null) {\n throw new IllegalArgumentException(\"Article cannot be null\");\n }\n ColumnType colType = ARTICLE_TO_COLUMN_TYPE.get(article);\n if (colType == null) {\n throw new IllegalArgumentException(\"Can not find the columnType for input article \" + article);\n }\n return colType;\n }\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/tools/DateTimeDivider.java\npublic class DateTimeDivider {\n \n private static final Logger LOGGER = LogManager.getLogger(DateTimeDivider.class);\n\n private DateTimeDivider() {\n // API class\n }\n \n public static List splitInMilestones(LocalDateTime startDate, LocalDateTime endDate, Duration maxDur, \n Duration minDur) {\n if(maxDur.minus(minDur).isNegative()) {\n throw new DataRetrievalRuntimeException(\"Max duration should be bigger than min duration \");\n }\n LocalDateTime nextStep = startDate.plus(maxDur);\n List res = new ArrayList<>();\n res.add(startDate);\n while(nextStep.isBefore(endDate)) {\n res.add(nextStep);\n nextStep= nextStep.plus(maxDur);\n }\n LocalDateTime last = nextStep.minus(maxDur);\n if(Duration.between(last, endDate).isZero()) {\n return res;\n }\n if(Duration.between(nextStep, endDate).isZero()) {\n res.add(nextStep);\n return res;\n }\n if(maxDur.minus(minDur).isZero()) {\n throw new DataRetrievalRuntimeException(\"Max duration should be bigger than min duration \");\n }\n if(Duration.between(last, endDate).minus(minDur).isNegative()) {\n res.remove(res.size()-1);\n res.add(endDate.minus(minDur));\n }\n res.add(endDate);\n return res;\n }\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/ENTSOEDataFetcher.java\npublic class ENTSOEDataFetcher {\n\n private static final Logger LOGGER = LogManager.getLogger(ENTSOEDataFetcher.class);\n\n public static String BASE_URL = \"https://web-api.tp.entsoe.eu/api\";\n\n private String authToken;\n private HttpBridge bridge;\n private DisponibilityChecker checker;\n\n public ENTSOEDataFetcher(String authToken, boolean useRequestCache) {\n this.authToken = authToken;\n this.bridge = new HttpBridge(useRequestCache); // TODO : fix server URL\n this.checker = new DisponibilityChecker();\n }\n\n /**\n * One year limitation applies. Fetchs actual load (documentType : A65, ProcessType : A16)\n *\n * @return\n */\n public Optional fetchActualLoad(Area outBiddingZoneDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime dataStart = checker.checkAvailability(\"6.1.A\", periodStart, outBiddingZoneDomain);\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dataStart)) {\n if (dataStart.isAfter(periodEnd)) {\n return Optional.empty();\n }\n usedStart = dataStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return Optional.empty();\n }\n if (gap.toMinutes() < 60) {\n LOGGER.warn(\"Error, uncorrect duration. Expected at least 60 minutes but it was \" + gap.toMinutes() + \" minutes\");\n return Optional.empty();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId());\n params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId());\n params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n String msg = \"Unable to correctly fetch actual load at \" + outBiddingZoneDomain.getPrettyName() + \" from \"\n + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + \" to \"\n + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME);\n return performGetOperation(params, msg, GLMarketDocument.class);\n }\n\n public Optional fetchDayAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime dataStart = checker.checkAvailability(\"6.1.B\", periodStart, outBiddingZoneDomain);\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dataStart)) {\n if (dataStart.isAfter(periodEnd)) {\n return Optional.empty();\n }\n usedStart = dataStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return Optional.empty();\n }\n if (gap.toHours() < 24) {\n LOGGER.warn(\"Error, uncorrect duration. Expected at least 24 hours but it was \" + gap.toMinutes() + \" minutes\");\n return Optional.empty();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId());\n params.put(Params.PROCESS_TYPE.getValue(), ProcessType.DAY_AHEAD.getId());\n params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n GLMarketDocument doc = null;\n String msg = \"Unable to correctly fetch day ahead load at \" + outBiddingZoneDomain.getPrettyName() + \" from \"\n + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + \" to \"\n + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME);\n return performGetOperation(params, msg, GLMarketDocument.class);\n }\n\n public Optional fetchWeekAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime dataStart = checker.checkAvailability(\"6.1.C\", periodStart, outBiddingZoneDomain);\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dataStart)) {\n if (dataStart.isAfter(periodEnd)) {\n return Optional.empty();\n }\n usedStart = dataStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return Optional.empty();\n }\n if (gap.toDays() < 7) {\n LOGGER.warn(\"Error, uncorrect duration. Expected at least 7 days but it was \" + gap.toMinutes() + \" minutes\");\n return Optional.empty();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId());\n params.put(Params.PROCESS_TYPE.getValue(), ProcessType.WEEK_AHEAD.getId());\n params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n\n String msg = \"Unable to correctly fetch week ahead load at \" + outBiddingZoneDomain.getPrettyName() + \" from \"\n + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + \" to \"\n + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME);\n return performGetOperation(params, msg, GLMarketDocument.class);\n }\n\n public Optional fetchAggregatedGenerationType(Area inDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime dataStart = checker.checkAvailability(\"16.1.B&C\", periodStart, inDomain);\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dataStart)) {\n if (dataStart.isAfter(periodEnd)) {\n return Optional.empty();\n }\n usedStart = dataStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return Optional.empty();\n }\n if (gap.toDays() < 7) {\n LOGGER.warn(\"Error, uncorrect duration. Expected at least 7 days but it was \" + gap.toMinutes() + \" minutes\");\n return Optional.empty();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.ACTUAL_GENERATION_PER_TYPE.getId());\n params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId());\n params.put(Params.IN_DOMAIN.getValue(), inDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n\n String msg = \"Unable to correctly fetch aggregated generation per type on \" + inDomain.getPrettyName() + \" from \"\n + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + \" to \"\n + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME);\n return performGetOperation(params, msg, GLMarketDocument.class);\n }\n\n public Optional fetchPhysicalFlows(Area inDomain, Area outDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime dataStart1 = checker.checkAvailability(\"12.1.G\", periodStart, inDomain);\n LocalDateTime dataStart2 = checker.checkAvailability(\"12.1.G\", periodStart, outDomain);\n LocalDateTime dataStart;\n if (dataStart1.equals(dataStart2)) {\n dataStart = dataStart1;\n } else if (dataStart1.isAfter(dataStart2)) {\n dataStart = dataStart1;\n } else {\n dataStart = dataStart2;\n }\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dataStart)) {\n if (dataStart.isAfter(periodEnd)) {\n return Optional.empty();\n }\n usedStart = dataStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return Optional.empty();\n }\n if (gap.toHours() < 24) {\n LOGGER.warn(\"Error, uncorrect duration. Expected at least 24 hours but it was \" + gap.toMinutes() + \" minutes\");\n return Optional.empty();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.AGGREGATED_ENERGY_DATA_REPORT.getId());\n params.put(Params.IN_DOMAIN.getValue(), inDomain.getId());\n params.put(Params.OUT_DOMAIN.getValue(), outDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n String erroMsg = \"Unable to correctly retrieve physical flows from \" + outDomain.getPrettyName() + \" to \"\n + inDomain.getPrettyName() + \" from \" + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + \" to \"\n + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME);\n return performGetOperation(params, erroMsg, PublicationMarketDocument.class);\n }\n\n /**\n * Fetchs the transmission grid outages.\n *\n * @param inDomain\n * @param outDomain\n * @param periodStart\n * @param periodEnd\n * @return One document per outage (can be a lot)\n */\n public List fetchTransmissionGridOutages(Area inDomain, Area outDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime dataStart = checker.checkAvailability(\"10.1.A&B\", periodStart, inDomain);\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dataStart)) {\n if (dataStart.isAfter(periodEnd)) {\n return new ArrayList<>();\n }\n usedStart = dataStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return new ArrayList<>();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.TRANSMISSION_UNAVAILABILITY.getId());\n params.put(Params.IN_DOMAIN.getValue(), inDomain.getId());\n params.put(Params.OUT_DOMAIN.getValue(), outDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n try {\n return bridge.doZipGetOperation(params, BASE_URL, UnavailabilityMarketDocument.class);\n } catch (DataRetrievalRuntimeException ex) {\n LOGGER.catching(ex);\n LOGGER.warn(\"Unable to correctly retrieve outages between \" + inDomain.getPrettyName() + \" and \"\n + outDomain.getPrettyName() + \" for time between \" + usedStart.format(DateTimeFormatter.ISO_DATE_TIME)\n + \" and \" + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME));\n return new ArrayList<>();\n }\n }\n\n public List fetchGenerationUnitOutages(Area biddingZoneDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime dataStart = checker.checkAvailability(\"15.1.A&B\", periodStart, biddingZoneDomain);\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dataStart)) {\n if (dataStart.isAfter(periodEnd)) {\n return new ArrayList<>();\n }\n usedStart = dataStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return new ArrayList<>();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.GENERATION_UNAVAILABILITY.getId());\n params.put(Params.BIDDING_ZONE_DOMAIN.getValue(), biddingZoneDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n try {\n return bridge.doZipGetOperation(params, BASE_URL, UnavailabilityMarketDocument.class);\n } catch (DataRetrievalRuntimeException ex) {\n LOGGER.catching(ex);\n LOGGER.warn(\"Unable to correctly retrieve generation outages at \" + biddingZoneDomain.getPrettyName()\n + \" for time between \" + usedStart.format(DateTimeFormatter.ISO_DATE_TIME)\n + \" and \" + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME));\n return new ArrayList<>();\n }\n }\n\n public Optional fetchWeekAheadCapacityForecast(Area inDomain, Area outDomain, LocalDateTime periodStart,\n LocalDateTime periodEnd) {\n LocalDateTime date1 = checker.checkAvailability(ColumnType.WEEK_FORECAST_CAPACITY.getRelevantArticle(),\n periodStart, outDomain);\n LocalDateTime date2 = checker.checkAvailability(ColumnType.WEEK_FORECAST_CAPACITY.getRelevantArticle(),\n periodStart, inDomain);\n LocalDateTime dateStart = (date1.isAfter(date2)) ? date1 : date2;\n LocalDateTime usedStart = periodStart;\n if (!periodStart.equals(dateStart)) {\n if (dateStart.isAfter(periodEnd)) {\n return Optional.empty();\n }\n usedStart = dateStart;\n }\n Duration gap = Duration.between(usedStart, periodEnd);\n if (gap.toDays() > 365) {\n LOGGER.warn(\"Error, uncorrect duration. Expected request of less than 365 days, but was \" + gap.toDays() + \" days\");\n return Optional.empty();\n }\n if (gap.toDays() < 7) {\n LOGGER.warn(\"Error, uncorrect duration. Expected at least 24 hours but it was \" + gap.toMinutes() + \" minutes\");\n return Optional.empty();\n }\n Map params = new HashMap<>();\n params.put(Params.SECURITY_TOKEN.getValue(), authToken);\n params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.ESTIMATED_NET_TRANSFER_CAPACITY.getId());\n params.put(Params.CONTRACT_MARKET_AGREEMENT_TYPE.getValue(), ContractMarketAgreement.WEEKLY.getCode());\n params.put(Params.IN_DOMAIN.getValue(), inDomain.getId());\n params.put(Params.OUT_DOMAIN.getValue(), outDomain.getId());\n params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern(\"yyyyMMddHHmm\")));\n String erroMsg = \"Unable to correctly week ahead transfert capacity forecast from \" + outDomain.getPrettyName() + \" to \"\n + inDomain.getPrettyName() + \" from \" + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + \" to \"\n + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME);\n return performGetOperation(params, erroMsg, PublicationMarketDocument.class);\n }\n\n public String getAuthToken() {\n return authToken;\n }\n\n public void setAuthToken(String authToken) {\n this.authToken = authToken;\n }\n\n private Optional performGetOperation(Map params, String errorMsg, Class reflectedClass) throws DataBindingException {\n T doc = null;\n try {\n doc = bridge.doGetOperation(params, BASE_URL, reflectedClass);\n } catch (DataRetrievalRuntimeException ex) {\n LOGGER.catching(ex);\n LOGGER.warn(errorMsg);\n return Optional.empty();\n }\n return Optional.ofNullable(doc);\n }\n\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/CSVTransformer.java\npublic abstract class CSVTransformer {\n\n private static final Logger LOGGER = LogManager.getLogger(CSVTransformer.class);\n\n /**\n * A time serie with a selected point. Selected period : the period index selected on ts Selected point : the\n * selected index on ts.getPeriod.getPoint\n */\n public record MarkedTS(TimeSeries ts, int selectedPeriod, int selectedPoint) {\n\n /**\n * The value of the selected point of this time serie\n *\n * @return\n */\n public int getSelectedPointValue() {\n return ts.getPeriod().get(selectedPeriod).getPoint().get(selectedPoint).getQuantity().intValue();\n }\n }\n ;\n\n private final String csvSeparator;\n private final String csvEscapeChar;\n private List columnDefinition = null;\n\n public CSVTransformer(String csvSeparator, String csvEscapeChar) {\n this.csvSeparator = csvSeparator;\n this.csvEscapeChar = csvEscapeChar;\n }\n\n public List getColumnDefinition() {\n if (columnDefinition == null) {\n columnDefinition = computeColumnDef();\n }\n return columnDefinition;\n }\n\n /**\n * Writes the next line of the given time stamp.Starts with the separator.\n *\n * @param os\n * @return true if the entry was writed, false otherwise\n */\n public abstract boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os);\n\n protected abstract List computeColumnDef();\n\n /**\n *\n * @param startingPoint\n * @param timeStamp\n * @return\n */\n protected static List getPeriodForTimeStamp(List timeSeries,\n LocalDateTime timeStamp) {\n // search for the correct ts\n // compute the corresponding positions\n // we assume that is there is many point of interest, they will be in different ts\n List tsPositions = computeTSPosition(timeSeries,timeStamp);\n if (tsPositions.isEmpty()) {\n return new ArrayList<>();\n }\n // start of the time series\n List res = new ArrayList<>();\n for (int tsPosition : tsPositions) {\n for (int periodPosition = 0; periodPosition < timeSeries.size(); periodPosition++) {\n LocalDateTime startDT = timeSeries.get(tsPosition).getPeriod().get(0).getTimeInterval().getLDTStart();\n int resolutionInt = getResolutionInMinutes(timeSeries.get(tsPosition).getPeriod().get(0).getResolution());\n long gapMinutes = ChronoUnit.MINUTES.between(startDT, timeStamp);\n long selectPosition = (gapMinutes / resolutionInt);\n if (selectPosition > Integer.MAX_VALUE) {\n throw new DataRetrievalError(\"The position to select is to big. Please use smaller queries\");\n }\n List points = timeSeries.get(tsPosition).getPeriod().get(0).getPoint();\n if (selectPosition >= points.size()) {\n // we handle the exceptional case of some week ahead time series that have a lenght of 1 week and one hour and are in this \n // exceptional case. We handle it\n if (selectPosition == points.size()\n && (\"A60\".equals(timeSeries.get(tsPosition).getBusinessType()) || \"A61\".equals(timeSeries.get(tsPosition).getBusinessType()))) {\n res.add(new GLDocumentCSVTransformer.MarkedTS(timeSeries.get(tsPosition), periodPosition, (int) selectPosition - 1));\n break;\n }\n String msg = \"Error computing the selected position. Position computed : \" + selectPosition\n + \" in TS of size \" + points.size() + \" .Requested time stamp is : \"\n + timeStamp.format(DateTimeFormatter.ISO_DATE_TIME) + \" on document starting in \"\n + timeSeries.get(tsPosition).getPeriod().get(0).getTimeInterval().getLDTStart().format(DateTimeFormatter.ISO_DATE_TIME)\n + \" and ending at \" + timeSeries.get(tsPosition).getPeriod().get(0).getTimeInterval().getLDTEnd().format(DateTimeFormatter.ISO_DATE_TIME);\n LOGGER.warn(msg);\n LOGGER.warn(\"Gap in minutes : {}, resolution in minutes : {}, ratio in double {}\", gapMinutes, resolutionInt, gapMinutes / (double) resolutionInt);\n // invalid time series, do nothing\n } else {\n res.add(new GLDocumentCSVTransformer.MarkedTS(timeSeries.get(tsPosition), periodPosition, (int) selectPosition));\n // supose there is only one pertienent period\n break;\n }\n }\n }\n return res;\n }\n \n private static int getResolutionInMinutes(Duration duration) {\n if (duration.isSet(DatatypeConstants.MINUTES)) {\n return duration.getMinutes();\n } else if (duration.isSet(DatatypeConstants.DAYS)) {\n return duration.getDays() * 24 * 60;\n } else {\n throw new UnsupportedOperationException(\"Non suported duration type\");\n }\n }\n \n private static List computeTSPosition(List timeSeries, LocalDateTime timeStamp) {\n List res = new ArrayList<>();\n for (int curPos = 0; curPos < timeSeries.size(); curPos++) {\n // TODO : handle periods\n LocalDateTime curStart = timeSeries.get(curPos).getPeriod().get(0).getTimeInterval().getLDTStart();\n LocalDateTime curEnd = timeSeries.get(curPos).getPeriod().get(0).getTimeInterval().getLDTEnd();\n if ((timeStamp.isAfter(curStart) || timeStamp.isEqual(curStart)) && timeStamp.isBefore(curEnd)) {\n res.add(curPos);\n }\n }\n return res;\n }\n\n public String getCsvSeparator() {\n return csvSeparator;\n }\n\n public String getCsvEscapeChar() {\n return csvEscapeChar;\n }\n \n /**\n * Generates missing values for each element of column definition.\n * @return The missing values for this \n */\n public List getMissingValues() {\n return IntStream.range(0, getColumnDefinition().size()).\n mapToObj(i -> \"\").\n toList();\n }\n \n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/xjc/PublicationMarketDocument.java\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"Publication_MarketDocument\", propOrder = {\n \"mrid\",\n \"revisionNumber\",\n \"type\",\n \"senderMarketParticipantMRID\",\n \"senderMarketParticipantMarketRoleType\",\n \"receiverMarketParticipantMRID\",\n \"receiverMarketParticipantMarketRoleType\",\n \"createdDateTime\",\n \"periodTimeInterval\",\n \"domainMRID\",\n \"timeSeries\"\n})\n@XmlRootElement(name = \"Publication_MarketDocument\")\npublic class PublicationMarketDocument {\n\n @XmlElement(name = \"mRID\", required = true)\n protected String mrid;\n @XmlElement(required = true)\n protected String revisionNumber;\n @XmlElement(required = true)\n protected String type;\n @XmlElement(name = \"sender_MarketParticipant.mRID\", required = true)\n protected PartyIDString senderMarketParticipantMRID;\n @XmlElement(name = \"sender_MarketParticipant.marketRole.type\", required = true)\n protected String senderMarketParticipantMarketRoleType;\n @XmlElement(name = \"receiver_MarketParticipant.mRID\")\n protected PartyIDString receiverMarketParticipantMRID;\n @XmlElement(name = \"receiver_MarketParticipant.marketRole.type\")\n protected String receiverMarketParticipantMarketRoleType;\n @XmlElement(required = true)\n @XmlSchemaType(name = \"dateTime\")\n protected XMLGregorianCalendar createdDateTime;\n @XmlElement(name = \"period.timeInterval\", required = true)\n protected ESMPDateTimeInterval periodTimeInterval;\n @XmlElement(name = \"domain.mRID\")\n protected AreaIDString domainMRID;\n @XmlElement(name = \"TimeSeries\", required = true)\n protected List timeSeries;\n\n /**\n * Gets the value of the mrid property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getMRID() {\n return mrid;\n }\n\n /**\n * Sets the value of the mrid property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setMRID(String value) {\n this.mrid = value;\n }\n\n /**\n * Gets the value of the revisionNumber property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRevisionNumber() {\n return revisionNumber;\n }\n\n /**\n * Sets the value of the revisionNumber property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRevisionNumber(String value) {\n this.revisionNumber = value;\n }\n\n /**\n * Gets the value of the type property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setType(String value) {\n this.type = value;\n }\n\n /**\n * Gets the value of the senderMarketParticipantMRID property.\n * \n * @return\n * possible object is\n * {@link PartyIDString }\n * \n */\n public PartyIDString getSenderMarketParticipantMRID() {\n return senderMarketParticipantMRID;\n }\n\n /**\n * Sets the value of the senderMarketParticipantMRID property.\n * \n * @param value\n * allowed object is\n * {@link PartyIDString }\n * \n */\n public void setSenderMarketParticipantMRID(PartyIDString value) {\n this.senderMarketParticipantMRID = value;\n }\n\n /**\n * Gets the value of the senderMarketParticipantMarketRoleType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getSenderMarketParticipantMarketRoleType() {\n return senderMarketParticipantMarketRoleType;\n }\n\n /**\n * Sets the value of the senderMarketParticipantMarketRoleType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setSenderMarketParticipantMarketRoleType(String value) {\n this.senderMarketParticipantMarketRoleType = value;\n }\n\n /**\n * Gets the value of the receiverMarketParticipantMRID property.\n * \n * @return\n * possible object is\n * {@link PartyIDString }\n * \n */\n public PartyIDString getReceiverMarketParticipantMRID() {\n return receiverMarketParticipantMRID;\n }\n\n /**\n * Sets the value of the receiverMarketParticipantMRID property.\n * \n * @param value\n * allowed object is\n * {@link PartyIDString }\n * \n */\n public void setReceiverMarketParticipantMRID(PartyIDString value) {\n this.receiverMarketParticipantMRID = value;\n }\n\n /**\n * Gets the value of the receiverMarketParticipantMarketRoleType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getReceiverMarketParticipantMarketRoleType() {\n return receiverMarketParticipantMarketRoleType;\n }\n\n /**\n * Sets the value of the receiverMarketParticipantMarketRoleType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setReceiverMarketParticipantMarketRoleType(String value) {\n this.receiverMarketParticipantMarketRoleType = value;\n }\n\n /**\n * Gets the value of the createdDateTime property.\n * \n * @return\n * possible object is\n * {@link XMLGregorianCalendar }\n * \n */\n public XMLGregorianCalendar getCreatedDateTime() {\n return createdDateTime;\n }\n\n /**\n * Sets the value of the createdDateTime property.\n * \n * @param value\n * allowed object is\n * {@link XMLGregorianCalendar }\n * \n */\n public void setCreatedDateTime(XMLGregorianCalendar value) {\n this.createdDateTime = value;\n }\n\n /**\n * Gets the value of the periodTimeInterval property.\n * \n * @return\n * possible object is\n * {@link ESMPDateTimeInterval }\n * \n */\n public ESMPDateTimeInterval getPeriodTimeInterval() {\n return periodTimeInterval;\n }\n\n /**\n * Sets the value of the periodTimeInterval property.\n * \n * @param value\n * allowed object is\n * {@link ESMPDateTimeInterval }\n * \n */\n public void setPeriodTimeInterval(ESMPDateTimeInterval value) {\n this.periodTimeInterval = value;\n }\n\n /**\n * Gets the value of the domainMRID property.\n * \n * @return\n * possible object is\n * {@link AreaIDString }\n * \n */\n public AreaIDString getDomainMRID() {\n return domainMRID;\n }\n\n /**\n * Sets the value of the domainMRID property.\n * \n * @param value\n * allowed object is\n * {@link AreaIDString }\n * \n */\n public void setDomainMRID(AreaIDString value) {\n this.domainMRID = value;\n }\n\n /**\n * Gets the value of the timeSeries property.\n * \n *

\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a set method for the timeSeries property.\n * \n *

\n * For example, to add a new item, do as follows:\n *

\n     *    getTimeSeries().add(newItem);\n     * 
\n * \n * \n *

\n * Objects of the following type(s) are allowed in the list\n * {@link TimeSeries }\n * \n * \n */\n public List getTimeSeries() {\n if (timeSeries == null) {\n timeSeries = new ArrayList();\n }\n return this.timeSeries;\n }\n\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/UnavailabilityDocCSVTransformer.java\npublic class UnavailabilityDocCSVTransformer extends CSVTransformer {\n\n private static final Logger LOGGER = LogManager.getLogger(UnavailabilityDocCSVTransformer.class);\n\n private static record ReadedInfo(boolean isInTS, String nominalPower) {\n\n }\n ;\n\n static final String TRANSMISSION_UNAVAILABILITY_BASE_NAME = \"outage_grid_\";\n static final String UNAVAILABILITY_SCHEDULED_BN = \"scheduled_outage_\";\n static final String GENERATION_UNAVAILABILITY_BASE_NAME = \"outage_generation_\";\n static final String NOMINAL_OUTAGE_POWER = \"outage_gen_nominal_\";\n\n private final UnavailabilityMarketDocument doc;\n private final DocumentType docType;\n\n public UnavailabilityDocCSVTransformer(UnavailabilityMarketDocument doc, String csvSeparator, String csvEscapeChar) {\n super(csvSeparator, csvEscapeChar);\n this.doc = doc;\n docType = DocumentType.fromId(doc.getType());\n }\n\n @Override\n public boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os) {\n ReadedInfo readedInfo = checkIsInOutage(timeStamp);\n if (readedInfo.isInTS) {\n boolean isScheduled = checkIsScheduled();\n String content;\n if (isScheduled) {\n content = getCsvSeparator() + \"1\" + getCsvSeparator() + \"1\";\n } else {\n content = getCsvSeparator() + \"1\" + getCsvSeparator() + \"0\";\n }\n switch (docType) {\n case GENERATION_UNAVAILABILITY:\n String gen = readedInfo.nominalPower;\n if (gen == null) {\n throw new DataRetrievalRuntimeException(\"Generation unavailability without a nominal power\");\n }\n content += getCsvSeparator() + gen;\n break;\n case TRANSMISSION_UNAVAILABILITY:\n // nothing to do\n break;\n default:\n throw new UnsupportedOperationException(\"Not suported outage column name for type \" + docType.getId()\n + \" ; \" + docType.getDescription());\n }\n try {\n os.write(content);\n } catch (IOException ex) {\n throw new DataRetrievalRuntimeException(\"Error writing timeStamp \" + timeStamp.format(DateTimeFormatter.ISO_DATE), ex);\n }\n return true;\n } else {\n return false;\n }\n }\n\n private ReadedInfo checkIsInOutage(LocalDateTime timeStamp) {\n for (TimeSeries curTs : doc.getTimeSeries()) {\n LocalDateTime startDT = LocalDateTime.of(curTs.getStartDateAndOrTimeDate().getYear(),\n curTs.getStartDateAndOrTimeDate().getMonth(), curTs.getStartDateAndOrTimeDate().getDay(),\n curTs.getStartDateAndOrTimeTime().getHour(), curTs.getStartDateAndOrTimeTime().getMinute());\n LocalDateTime endDT = LocalDateTime.of(curTs.getEndDateAndOrTimeDate().getYear(),\n curTs.getEndDateAndOrTimeDate().getMonth(), curTs.getEndDateAndOrTimeDate().getDay(),\n curTs.getEndDateAndOrTimeTime().getHour(), curTs.getEndDateAndOrTimeTime().getMinute());\n if ((startDT.isBefore(timeStamp) && endDT.isAfter(timeStamp)) || startDT.equals(timeStamp)) {\n String nominalPower = null;\n if (curTs.getProductionRegisteredResourcePSRTypePowerSystemResourcesNominalP() != null) {\n nominalPower = Float.toString(curTs.getProductionRegisteredResourcePSRTypePowerSystemResourcesNominalP().getValue());\n }\n return new ReadedInfo(true, nominalPower);\n }\n }\n return new ReadedInfo(false, \"\");\n }\n\n private boolean checkIsScheduled() {\n List reasonList = doc.getReason();\n if (reasonList.size() != 1) {\n throw new UnsupportedOperationException(\"Expected one reason but there are \" + reasonList.size() + \" reasons\");\n }\n Reason reason = reasonList.get(0);\n switch (reason.getCode()) {\n case \"B19\":\n return true;\n case \"B20\": // shutdown\n case \"B18\": // failure on generation unit\n case \"A95\": // complentary info?\n return false;\n default:\n printCurDoc();\n throw new UnsupportedOperationException(\"Unknow reason code \" + reason.getCode());\n\n }\n }\n\n private void printCurDoc() {\n try {\n // just print th pb doucment\n JAXBContext jaxbContext = JAXBContext.newInstance(UnavailabilityMarketDocument.class);\n Marshaller marshaller = jaxbContext.createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);\n marshaller.marshal(doc, System.out);\n } catch (JAXBException ex) {\n LOGGER.catching(ex);\n }\n }\n\n @Override\n protected List computeColumnDef() {\n DocumentType docType = DocumentType.fromId(doc.getType());\n switch (docType) {\n case TRANSMISSION_UNAVAILABILITY:\n return doc.getTimeSeries().stream().\n flatMap(ts -> {\n if (ts.getAssetRegisteredResource().isEmpty()) {\n AssetRegisteredResource res = new AssetRegisteredResource();\n Area inDomain = Area.fromID(ts.getInDomainMRID().getValue());\n Area outDomain = Area.fromID(ts.getOutDomainMRID().getValue());\n ResourceIDString mrdid = new ResourceIDString();\n mrdid.setValue(\"Unknown_asset_\" + outDomain.getOptionCLIID() + \"_\" + inDomain.getOptionCLIID());\n res.setMRID(mrdid);\n return Stream.of(res);\n }\n return ts.getAssetRegisteredResource().stream();\n }).\n map(AssetRegisteredResource::getMRID).\n map(ResourceIDString::getValue).\n map(s -> Arrays.asList(new ColumnDefinition(TRANSMISSION_UNAVAILABILITY_BASE_NAME + s),\n new ColumnDefinition(UNAVAILABILITY_SCHEDULED_BN + s))).\n flatMap(List::stream).\n toList();\n case GENERATION_UNAVAILABILITY:\n Area area = Area.fromID(doc.getTimeSeries().get(0).getBiddingZoneDomainMRID().getValue());\n return doc.getTimeSeries().stream().\n map(ts -> ts.getProductionRegisteredResourceMRID()).\n map(ResourceIDString::getValue).\n map(s -> Arrays.asList(new ColumnDefinition(GENERATION_UNAVAILABILITY_BASE_NAME + s),\n new ColumnDefinition(UNAVAILABILITY_SCHEDULED_BN + s),\n new ColumnDefinition(area.getOptionCLIID() + \"_\" + NOMINAL_OUTAGE_POWER + s))).\n flatMap(List::stream).\n toList();\n default:\n throw new UnsupportedOperationException(\"Not suported outage column name for type \" + docType.getId()\n + \" ; \" + docType.getDescription());\n }\n\n }\n\n @Override\n public List getMissingValues() {\n return IntStream.range(0, getColumnDefinition().size()).\n mapToObj(i -> \"0\").\n toList();\n }\n\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/inputs/Area.java\npublic enum Area {\n MONTENEGRO(\"10YCS-CG-TSO---S\", \"BZN|ME, CTA|ME, Montenegro (ME), MBA|ME, SCA|ME, LFA|ME\",\n \"Montenegro\", \"ME\"),\n ITALY_CENTRE_SOUTH(\"10Y1001A1001A71M\", \"BZN|IT-Centre-South, SCA|IT-Centre-South, MBA|IT-Z-Centre-South\",\n \"Italy Centre South\", \"IT-CS\"),\n BOSNIA(\"10YBA-JPCC-----D\", \"LFA|BA, BZN|BA, CTA|BA, Bosnia and Herz. (BA), SCA|BA, MBA|BA\",\n \"Bosnia\", \"BA\"),\n SERBIA(\"10YCS-SERBIATSOV\", \"LFA|RS, SCA|RS, MBA|RS, Serbia (RS), CTA|RS, BZN|RS\",\n \"Serbia\", \"RS\"),\n KOSOVO(\"10Y1001C--00100H\", \"BZN|XK, CTA|XK, Kosovo (XK), MBA|XK, LFB|XK, LFA|XK\",\n \"Kosovo\", \"XK\"),\n ALBANIA(\"10YAL-KESH-----5\", \"LFB|AL, LFA|AL, BZN|AL, CTA|AL, Albania (AL), SCA|AL, MBA|AL\", \n \"Albania\", \"AL\");\n\n private static final Logger LOGGER = LogManager.getLogger(Area.class);\n\n private static final Map CLIID_TO_AREA = new HashMap<>();\n private static final Map ID_TO_AREA = new HashMap<>();\n\n static {\n for (Area area : Area.values()) {\n CLIID_TO_AREA.put(area.getOptionCLIID(), area);\n ID_TO_AREA.put(area.getId(), area);\n }\n }\n\n private final String id;\n private final String longDescription;\n private final String prettyName;\n private final String optionCLIID;\n\n private Area(String id, String longDescription, String prettyName, String optionCLIID) {\n this.id = id;\n this.longDescription = longDescription;\n this.prettyName = prettyName;\n this.optionCLIID = optionCLIID;\n }\n\n /**\n *\n * @return\n */\n public String getId() {\n return id;\n }\n\n /**\n * The long description as presented on ENTSOE platform\n *\n * @return\n */\n public String getLongDescription() {\n return longDescription;\n }\n\n /**\n * Pretty name of the selected area\n *\n * @return\n */\n public String getPrettyName() {\n return prettyName;\n }\n\n /**\n * The ID on the CLI interface\n *\n * @return\n */\n public String getOptionCLIID() {\n return optionCLIID;\n }\n\n public static Area fromCLIID(String cliId) {\n if (cliId == null) {\n throw new IllegalArgumentException(\"Id cannot be null\");\n }\n\n Area area = CLIID_TO_AREA.get(cliId);\n if (area == null) {\n throw new IllegalArgumentException(\"No enum instance found with id: \" + cliId);\n }\n return area;\n }\n\n public static Area fromID(String id) {\n if (id == null) {\n throw new IllegalArgumentException(\"Id cannot be null\");\n }\n Area area = ID_TO_AREA.get(id);\n if (area == null) {\n throw new IllegalArgumentException(\"Non enum instance found with id:\" + id);\n }\n return area;\n }\n\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/CSVGenerator.java\npublic class CSVGenerator {\n\n private static final Logger LOGGER = LogManager.getLogger(CSVGenerator.class);\n \n private static record ColumnBlock(List colDefs, List missingValues){\n\n public ColumnBlock(List colDefs, List missingValues) {\n if(colDefs.size() != missingValues.size()) {\n throw new DataRetrievalError(\"Malformed column signature. Column definition size of \" + colDefs.size() + \n \" while \" + missingValues.size());\n }\n this.colDefs = colDefs;\n this.missingValues = missingValues;\n }\n\n \n }\n\n private final String csvSepator;\n private final String csvEscapeChar;\n\n public CSVGenerator(String csvSepator, String csvEscapeChar) {\n this.csvSepator = csvSepator;\n this.csvEscapeChar = csvEscapeChar;\n }\n\n public void writeCSVFile(List transformers, File targetFile, LocalDateTime startDate,\n LocalDateTime endDate, Duration timeStep) {\n\n List colDefs = transformers.stream().\n map(t -> new ColumnBlock(t.getColumnDefinition(), t.getMissingValues())).\n distinct().// it can be many documents representing the same thing but at different \n toList();\n // column definitions as provided by transformers.getColumnDefinition\n // In the values, transformers are grouped by same column. In fact, they represent transformers of the same column, but at different time stamps\n Map> transformersIndex = buildTransformersIndex(transformers);\n FileWriter fw = null;\n BufferedWriter bw = null;\n try {\n fw = new FileWriter(targetFile);\n bw = new BufferedWriter(fw);\n //write header\n writeHeader(colDefs, bw);\n LocalDateTime curDT = startDate;\n int idCount = 0;\n while (curDT.isBefore(endDate)) {\n bw.newLine();\n // id\n bw.write(String.valueOf(idCount));\n bw.write(csvSepator);\n // Time stamp\n bw.write(curDT.format(DateTimeFormatter.ISO_DATE_TIME));\n bw.flush();\n for (ColumnBlock colBlock : colDefs) {\n boolean writedColumn = false;\n if(transformersIndex.containsKey(colBlock)) {\n List associatedTransformer = transformersIndex.get(colBlock);\n for(CSVTransformer curTransformer : associatedTransformer) {\n boolean writed = curTransformer.writeNextEntry(curDT, bw);\n if(writed) {\n // when one transformer\n writedColumn = true;\n break;\n }\n }\n if(!writedColumn) {\n // None of the transformers could write for the given entry, filling it\n for(int i=0; i colDefs, BufferedWriter bof) throws IOException {\n bof.write(\"id,time_stamp\");\n colDefs.stream().\n map(ColumnBlock::colDefs).\n flatMap(List::stream).\n forEach((Consumer) c -> {\n try {\n bof.write(csvSepator);\n String colName = c.colName();\n if (colName.contains(this.csvEscapeChar)) {\n throw new UnsupportedOperationException(\"Non suported, escapechar on column name \" + colName);\n }\n if (colName.contains(this.csvSepator)) {\n colName = csvEscapeChar + colName + csvEscapeChar;\n }\n bof.write(colName);\n } catch (IOException ex) {\n throw new DataRetrievalError(ex);\n }\n });\n bof.flush();\n }\n\n private Map> buildTransformersIndex(List transformers) {\n Map> res = new HashMap<>();\n for(CSVTransformer curTransformer : transformers) {\n List colDefs = curTransformer.getColumnDefinition();\n List missingValues = curTransformer.getMissingValues();\n ColumnBlock colBlock = new ColumnBlock(colDefs, missingValues);\n res.computeIfAbsent(colBlock, e -> new ArrayList<>());\n res.get(colBlock).add(curTransformer);\n }\n return res;\n }\n}\n\nsrc/main/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/GLDocumentCSVTransformer.java\npublic class GLDocumentCSVTransformer extends CSVTransformer {\n\n private static final Logger LOGGER = LogManager.getLogger(GLDocumentCSVTransformer.class);\n\n private final GLMarketDocument doc;\n\n public GLDocumentCSVTransformer(String csvSeparator, String csvEscapeChar, GLMarketDocument doc) {\n super(csvSeparator, csvEscapeChar);\n this.doc = doc;\n }\n\n @Override\n public boolean writeNextEntry(LocalDateTime timeStamp, BufferedWriter os) {\n // start inclusive, end exclusive\n if (doc.getTimePeriodTimeInterval().getLDTStart().isEqual(timeStamp)\n || (doc.getTimePeriodTimeInterval().getLDTStart().isBefore(timeStamp)\n && doc.getTimePeriodTimeInterval().getLDTEnd().isAfter(timeStamp))) {\n // we asume that the whole information was requested for a single continuos interval\n List timeSeries = getPeriodForTimeStamp(doc.getTimeSeries(),timeStamp);\n if (timeSeries.isEmpty()) {\n // probably a missing value, do not write nothing by convention\n return false;\n }\n DocumentType docType = DocumentType.fromId(doc.getType());\n ProcessType processType = ProcessType.fromId(doc.getProcessProcessType());\n String content;\n switch (docType) {\n case SYSTEM_TOTAL_LOAD:\n switch (processType) {\n case REALISED:\n case DAY_AHEAD:\n if (timeSeries.size() != 1) {\n throw new DataRetrievalError(\"Expected one point at time stamp \"\n + timeStamp.format(DateTimeFormatter.ISO_DATE_TIME) + \" but got \" + timeSeries.size());\n// int[] vals = pt.stream().mapToInt(cp -> cp.getQuantity().intValue()).toArray();\n // TODO : end the case where we check if values are the same or different\n// LOGGER.warn(\"Warning! Expected one valid point for processType {} but got {}. \"\n// + \"Values are different so stoping\", processType.getDescription(), pt.size());\n }\n content = this.getCsvSeparator() + Integer.toString(timeSeries.get(0).getSelectedPointValue());// only one point expected\n break;\n case WEEK_AHEAD:\n if (timeSeries.size() != 2) {\n throw new DataRetrievalError(\"Expected two point at time stamp \"\n + timeStamp.format(DateTimeFormatter.ISO_DATE_TIME) + \" but got \" + timeSeries.size());\n }\n int val1 = timeSeries.get(0).getSelectedPointValue();\n int val2 = timeSeries.get(1).getSelectedPointValue();\n content = getCsvSeparator() + Integer.toString(Math.min(val1, val2)) + getCsvSeparator() + Integer.toString(Math.max(val1, val2));\n break;\n default:\n throw new UnsupportedOperationException(\"Non suported processType \" + processType.name());\n }\n break;\n case ACTUAL_GENERATION_PER_TYPE:\n Area curArea = Area.fromID(doc.getTimeSeries().get(0).getInBiddingZoneDomainMRID().getValue());\n if (timeSeries.size() > getColumnDefinition().size()) {\n throw new DataRetrievalError(\"Expected at maximun \" + getColumnDefinition().size() + \" elements for \"\n + \" but got \" + timeSeries.size() + \" for \" + curArea.getPrettyName() + \" are on generation per type\");\n }\n // index the found time series\n Map indexedTs = new HashMap<>();\n timeSeries.stream().forEach(ts -> indexedTs.put(PsrType.fromID(ts.ts().getMktPSRType().getPsrType()),\n Integer.toString(ts.getSelectedPointValue())));\n List prodTypes = PsrTypesByArea.INSTANCE.getProductionTypesForArea(curArea);\n StringBuilder sb = new StringBuilder();\n for (PsrType curProdType : prodTypes) {\n sb.append(getCsvSeparator());\n sb.append(indexedTs.getOrDefault(curProdType, \"\"));\n }\n content = sb.toString();\n break;\n default:\n throw new UnsupportedOperationException(\"Non suported document type \" + docType.name());\n }\n try {\n os.write(content);\n return true;\n } catch (IOException ex) {\n throw new DataRetrievalRuntimeException(\"Error writing timeStamp \" + timeStamp.format(DateTimeFormatter.ISO_DATE), ex);\n }\n }\n // nothing to write, out of bounds\n return false;\n }\n\n @Override\n protected List computeColumnDef() {\n List res = new ArrayList<>();\n DocumentType docType = DocumentType.fromId(doc.getType());\n ProcessType processType = ProcessType.fromId(doc.getProcessProcessType());\n Area curArea;\n switch (docType) {\n case SYSTEM_TOTAL_LOAD:\n curArea = Area.fromID(doc.getTimeSeries().get(0).getOutBiddingZoneDomainMRID().getValue());\n switch (processType) {\n // TODO : add the geographic zone to the col name\n case REALISED:\n res.add(new ColumnDefinition(\"load_realised_actual_\" + curArea.getOptionCLIID()));\n break;\n case DAY_AHEAD:\n res.add(new ColumnDefinition(\"load_day_ahead_forecast_\" + curArea.getOptionCLIID()));\n break;\n case WEEK_AHEAD:\n res.add(new ColumnDefinition(\"load_week_ahead_forecast_min_\" + curArea.getOptionCLIID()));\n res.add(new ColumnDefinition(\"load_week_ahead_forecast_max_\" + curArea.getOptionCLIID()));\n break;\n default:\n throw new UnsupportedOperationException(\"Non suported processType \" + processType.name());\n }\n break;\n case ACTUAL_GENERATION_PER_TYPE:\n curArea = Area.fromID(doc.getTimeSeries().get(0).getInBiddingZoneDomainMRID().getValue());\n // list all the generation mediums available\n // Two options : \n // 1 column per document, so we need to keep a track of the productions types per area\n // ALL columns in document, but there is a problem if a doc has not all the production types of a country...\n // ALL columns in document, keep track of existing columns so we can handle when there are missing values\n //\n //The last seems better\n String baseName = \"_generation_\";\n List prodTypes = PsrTypesByArea.INSTANCE.getProductionTypesForArea(curArea);\n for (PsrType curType : prodTypes) {\n res.add(new ColumnDefinition(curArea.getOptionCLIID() + baseName + curType.getCsvName()));\n }\n break;\n default:\n throw new UnsupportedOperationException(\"Non suported docType \" + docType.name());\n }\n return Collections.unmodifiableList(res);\n }\n\n @Override\n public int hashCode() {\n int hash = 5;\n hash = 59 * hash + Objects.hashCode(this.doc);\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final GLDocumentCSVTransformer other = (GLDocumentCSVTransformer) obj;\n return Objects.equals(this.doc, other.doc);\n }\n\n}", "answers": [" transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get()));"], "length": 5994, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "7240eabe-e221-4005-8257-3a316d9251e5", "reasoning": "The method fetchDataset builds a list of CSVTransformer objects for each fetched document. In the earlier if blocks (ACTUAL_LOAD, DAY_AHEAD_LOAD, WEAK_AHEAD_LOAD) the code adds a new GLDocumentCSVTransformer to the transformers list when an Optional document is present. The AGGREGATED_GENERATION_TYPE block follows the same pattern, so the next line after the provided snippet should add the transformer for the fetched aggregated generation type document.", "reasoning_model_answer": "transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get()));", "assistant_with_reasoning": "\nThe method fetchDataset builds a list of CSVTransformer objects for each fetched document. In the earlier if blocks (ACTUAL_LOAD, DAY_AHEAD_LOAD, WEAK_AHEAD_LOAD) the code adds a new GLDocumentCSVTransformer to the transformers list when an Optional document is present. The AGGREGATED_GENERATION_TYPE block follows the same pattern, so the next line after the provided snippet should add the transformer for the fetched aggregated generation type document.\n\ntransformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get()));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.221, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37340, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "transformers.add(new GLDocumentCSVTransformer(csvSeparator, csvEscapeChar, opt.get()));", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "import numpy as np\nimport torch\nfrom .AffectNetDataModule import AffectNetExpressions\nfrom .VideoDatasetBase import VideoDatasetBase", "context": "inferno/datasets/ConditionedVideoTestDatasetWrapper.py\n\n\nclass ConditionedVideoTestDatasetWrapper(torch.utils.data.Dataset): \n\n def __init__(self,\n dataset : VideoDatasetBase,\n condition_source, \n condition_settings, \n key_prefix = \"\",\n conditioned_intensity = None, # defaults to 3 if needed and not provided\n ): \n self.dataset = dataset\n self.condition_source = condition_source or \"original\"\n self.condition_settings = condition_settings or None\n self.expand_temporal = True\n self.condition_prefix = key_prefix\n \n if self.condition_source == \"original\":\n self.condition_settings = None\n elif self.condition_source == \"expression\":\n if self.condition_settings is None: \n self.condition_settings = list(range(8)) \n \n for i, cond in enumerate(self.condition_settings):\n if isinstance(cond, str):\n self.condition_settings[i] = AffectNetExpressions[cond]\n if self.condition_settings[i] is None or self.condition_settings[i] > 7:\n raise ValueError(f\"Invalid basic expression {cond}\")\n assert isinstance(self.condition_settings, list), \"Condition_settings must be a list of integers\"\n\n elif self.condition_source in [\"gt_expression\", \"gt_expression_intensity\", \"gt_expression_intensity_identity\"]:\n if self.condition_settings is None: \n self.condition_settings = list(range(8)) \n \n for i, cond in enumerate(self.condition_settings):\n if isinstance(cond, str):\n\n\ninferno/datasets/VideoDatasetBase.py\nclass VideoDatasetBase(AbstractVideoDataset): \n\n def __init__(self,\n root_path,\n output_dir,\n video_list, \n video_metas,\n video_indices,\n # audio_paths, \n audio_metas,\n sequence_length,\n audio_noise_prob=0.0,\n stack_order_audio=4,\n audio_normalization=\"layer_norm\",\n landmark_types=\"mediapipe\", \n segmentation_type = \"bisenet\",\n landmark_source = \"original\",\n segmentation_source = \"original\",\n occlusion_length=0,\n occlusion_probability_mouth = 0.0,\n occlusion_probability_left_eye = 0.0,\n occlusion_probability_right_eye = 0.0,\n occlusion_probability_face = 0.0,\n image_size=None, ## the image size that the dataset will output\n transforms : imgaug.augmenters.Augmenter = None,\n hack_length=False,\n use_original_video=True,\n include_processed_audio = True,\n include_raw_audio = True,\n temporal_split_start=None, # if temporally splitting the video (train, val, test), this is the start of the split\n temporal_split_end=None, # if temporally splitting the video (train, val, test), this is the end of the split\n preload_videos=False, # cache all videos in memory (recommended for smaller datasets)\n inflate_by_video_size=False, \n include_filename=False, # if True includes the filename of the video in the sample\n align_images = True,\n use_audio=True, #if True, includes audio in the sample\n reconstruction_type = None,\n return_global_pose = False,\n return_appearance = False,\n average_shape_decode = False,\n emotion_type = None,\n return_emotion_feature=False,\n read_video=True,\n read_audio=True,\n original_image_size=None, ## the processed videos may be different in size and if they are, the landmarks will be, too. This is to remember\n return_mica_images=False,\n ) -> None:\n super().__init__()\n self.root_path = root_path\n self.output_dir = output_dir\n self.video_list = video_list\n self.video_indices = video_indices\n self.video_metas = video_metas\n self.sequence_length = sequence_length or 1\n # self.audio_paths = audio_paths\n self.audio_metas = audio_metas\n self.audio_noise_prob = audio_noise_prob\n self.image_size = image_size\n self.original_image_size = original_image_size or image_size\n self.scale = 1.25\n # if the video is 25 fps and the audio is 16 kHz, stack_order_audio corresponds to 4 \n # (i.e. 4 consecutive filterbanks will be concatenated to sync with the visual frame) \n self.stack_order_audio = stack_order_audio\n\n self.audio_normalization = audio_normalization\n\n self.landmark_types = landmark_types \n if isinstance(self.landmark_types, str): \n self.landmark_types = [self.landmark_types]\n self.landmark_source = landmark_source \n if isinstance(self.landmark_source, str): \n self.landmark_source = [self.landmark_source] * len(self.landmark_types)\n assert len(self.landmark_types) == len(self.landmark_source), \"landmark_types and landmark_source must have the same length\"\n self.segmentation_type = segmentation_type \n \n self.segmentation_source = segmentation_source\n\n\n self.landmark_normalizer = KeypointNormalization() # postprocesses final landmarks to be in [-1, 1]\n self.occluder = MediaPipeFaceOccluder()\n self.occlusion_probability_mouth = occlusion_probability_mouth\n self.occlusion_probability_left_eye = occlusion_probability_left_eye\n self.occlusion_probability_right_eye = occlusion_probability_right_eye\n self.occlusion_probability_face = occlusion_probability_face\n self.occlusion_length = occlusion_length\n if isinstance(self.occlusion_length, int):\n self.occlusion_length = [self.occlusion_length, self.occlusion_length+1]\n # self.occlusion_length = [20, 30]\n self.occlusion_length = sorted(self.occlusion_length)\n\n self.include_processed_audio = include_processed_audio\n self.include_raw_audio = include_raw_audio\n # self.align_images = True\n # self.align_images = False\n self.align_images = align_images\n self.use_audio = use_audio\n self.use_original_video = use_original_video\n self.transforms = transforms or imgaug.augmenters.Resize((image_size, image_size))\n\n self.hack_length = hack_length\n if self.hack_length == \"auto\": \n if self._true_len() < 64: # hacks the length for supersmall test datasets\n self.hack_length = (64 // self._true_len())\n if 64 % self._true_len() != 0:\n self.hack_length += 1\n self.hack_length = float(self.hack_length)\n # useful hack to repeat the elements in the dataset for really small datasets\n else: \n self.hack_length = False\n\n assert self.occlusion_length[0] >= 0\n # assert self.occlusion_length[1] <= self.sequence_length + 1\n\n self.temporal_split_start = temporal_split_start\n self.temporal_split_end = temporal_split_end\n\n self.preload_videos = preload_videos\n self.inflate_by_video_size = inflate_by_video_size\n\n # self.read_video = True\n self.read_video = read_video\n self.read_audio = read_audio\n\n self.reconstruction_type = reconstruction_type \n if self.reconstruction_type is not None: \n if isinstance(self.reconstruction_type, str): \n self.reconstruction_type = [self.reconstruction_type]\n assert isinstance(self.reconstruction_type, list), \"reconstruction_type must be a list or None\"\n self.return_global_pose = return_global_pose\n self.return_appearance = return_appearance\n self.average_shape_decode = average_shape_decode\n\n self.emotion_type = emotion_type\n self.return_emotion_feature = return_emotion_feature\n\n self.video_cache = {}\n self.audio_cache = {}\n self.seg_cache = {}\n self.lmk_cache = {}\n self.rec_cache = {}\n self.emo_cache = {}\n if self.preload_videos:\n self._preload_videos()\n \n self.video_sample_indices = None\n if self.inflate_by_video_size: \n self._inflate_by_video_size()\n\n self.include_filename = include_filename\n\n # if True, face alignment will not crash if invalid. By default this should be False to avoid silent data errors\n self._allow_alignment_fail = False \n\n self.return_mica_image = return_mica_images\n if not self.read_video:\n assert not bool(self.return_mica_image), \"return_mica_image is only supported when read_video is True\"\n\n if bool(self.return_mica_image):\n from inferno.models.mica.MicaInputProcessing import MicaInputProcessor\n if self.return_mica_image is True: \n self.return_mica_image = \"fan\"\n self.mica_preprocessor = MicaInputProcessor(self.return_mica_image)\n\n\n @property\n def invalid_cutoff(self):\n max_cutoff = 0 \n for rec_type in self.reconstruction_type:\n if rec_type == \"spectre\": \n max_cutoff = max(max_cutoff, 2 )\n elif rec_type in [\"emoca\", \"deca\"] or \"emoca\" in rec_type.lower() or \"emica\" in rec_type.lower() or \"edeca\" in rec_type.lower(): \n max_cutoff = max(max_cutoff, 0 )\n else:\n raise ValueError(f\"Invalid reconstruction type: '{rec_type}'\")\n return max_cutoff\n\n\n def _load_flame(self):\n if self.reconstruction_type is not None: \n from munch import Munch\n flame_cfg = Munch() \n\n flame_cfg.type = \"flame\"\n\n flame_cfg.flame = Munch({ \n \"flame_model_path\": \"/ps/scratch/rdanecek/data/FLAME/geometry/generic_model.pkl\" ,\n \"n_shape\": 100 ,\n # n_exp: 100\n \"n_exp\": 50,\n \"flame_lmk_embedding_path\": \"/ps/scratch/rdanecek/data/FLAME/geometry/landmark_embedding.npy\" \n })\n flame_cfg.use_texture = False\n from inferno.models.temporal.Preprocessors import FlamePreprocessor\n self.flame = FlamePreprocessor(flame_cfg)\n # prep = prep.to(\"cuda\")\n\n\n\n def _preload_videos(self): \n # indices = np.unique(self.video_indices)\n from tqdm import auto\n for i in auto.tqdm( range(len(self.video_indices)), desc=\"Preloading videos\" ):\n video_path = str(self._get_video_path(i))\n if self.read_video:\n if video_path not in self.video_cache:\n self.video_cache[video_path] = vread(video_path)\n self.seg_cache[video_path] = self._read_segmentations(i) \n if self.read_audio:\n if video_path not in self.audio_cache:\n self.audio_cache[i] = self._read_audio(i)\n for lmk_type, lmk_source in zip(self.landmark_types, self.landmark_source):\n if i not in self.lmk_cache:\n self.lmk_cache[i] = {}\n if lmk_type not in self.lmk_cache[i]:\n self.lmk_cache[i][lmk_type] = {}\n # if lmk_source not in self.lmk_cache[i][lmk_type]:\n self.lmk_cache[i][lmk_type][lmk_source] = self._read_landmarks(i, lmk_type, lmk_source)\n if self.reconstruction_type is not None: \n for rec_type in self.reconstruction_type: \n shape_pose_cam, appearance = self._load_reconstructions(i, rec_type, self.return_appearance)\n if i not in self.rec_cache:\n self.rec_cache[i] = {}\n video_dict = self.rec_cache[i]\n if rec_type not in video_dict:\n video_dict[rec_type] = {}\n self.rec_cache[i][rec_type][\"shape_pose_cam\"] = shape_pose_cam\n self.rec_cache[i][rec_type][\"appearance\"] = appearance\n if self.emotion_type is not None: \n emotions, features = self._load_emotions(i, features=self.return_emotion_feature)\n if i not in self.emo_cache:\n self.emo_cache[i] = {}\n self.emo_cache[i][\"emotions\"] = emotions \n self.emo_cache[i][\"features\"] = features\n \n\n print(\"Video cache loaded\")\n\n def _inflate_by_video_size(self):\n assert isinstance( self.sequence_length, int), \"'sequence_length' must be an integer when inflating by video size\"\n inflated_video_indices = []\n video_sample_indices = []\n for i in range(len(self.video_indices)):\n # for i in self.video_indices:\n idx = self.video_indices[i]\n num_frames = self._get_num_frames(i)\n if self.temporal_split_start is not None and self.temporal_split_end is not None:\n num_frames = int((self.temporal_split_end - self.temporal_split_start) * num_frames)\n num_samples_in_video = num_frames // self.sequence_length\n if num_frames % self.sequence_length != 0:\n num_samples_in_video += 1\n num_samples_in_video = max(1, num_samples_in_video)\n inflated_video_indices += [idx] * num_samples_in_video\n video_sample_indices += list(range(num_samples_in_video))\n self.video_indices = np.array(inflated_video_indices, dtype=np.int32)\n self.video_sample_indices = np.array(video_sample_indices, dtype=np.int32)\n\n def __getitem__(self, index):\n # max_attempts = 10\n max_attempts = 50\n for i in range(max_attempts):\n try: \n return self._getitem(index)\n except AssertionError as e:\n if not hasattr(self, \"num_total_failed_attempts\"):\n self.num_total_failed_attempts = 0\n old_index = index\n index = np.random.randint(0, self.__len__())\n tb = traceback.format_exc()\n if self.num_total_failed_attempts % 50 == 0:\n print(f\"[ERROR] AssertionError in {self.__class__.__name__} dataset while retrieving sample {old_index}, retrying with new index {index}\")\n print(f\"In total, there has been {self.num_total_failed_attempts} failed attempts. This number should be very small. If it's not, check the data.\")\n print(\"See the exception message for more details.\")\n print(tb)\n self.num_total_failed_attempts += 1\n print(\"[ERROR] Failed to retrieve sample after {} attempts\".format(max_attempts))\n raise RuntimeError(\"Failed to retrieve sample after {} attempts\".format(max_attempts))\n\n def _getitem(self, index):\n time = False\n if time:\n import timeit\n start_time = timeit.default_timer()\n if self.hack_length: \n index = index % self._true_len()\n\n # 1) VIDEO\n # load the video \n sample, start_frame, num_read_frames, video_fps, num_frames, num_available_frames = self._get_video(index)\n if time:\n video_read_time = timeit.default_timer() - start_time\n\n # 2) AUDIO\n if self.read_audio:\n sample = self._get_audio(index, start_frame, num_read_frames, video_fps, num_frames, sample)\n if time:\n audio_read_time = timeit.default_timer() - start_time - video_read_time\n\n # 3) LANDMARKS \n sample = self._get_landmarks(index, start_frame, num_read_frames, video_fps, num_frames, sample)\n if time:\n lmk_read_time = timeit.default_timer() - start_time - video_read_time - audio_read_time\n\n # 4) SEGMENTATIONS\n if self.read_video:\n sample = self._get_segmentations(index, start_frame, num_read_frames, video_fps, num_frames, sample)\n if time:\n seg_read_time = timeit.default_timer() - start_time - video_read_time - audio_read_time - lmk_read_time\n\n # 5) FACE ALIGNMENT IF ANY\n if self.read_video:\n sample = self._align_faces(index, sample)\n if time:\n face_align_time = timeit.default_timer() - start_time - video_read_time - audio_read_time - lmk_read_time - seg_read_time\n\n # 6) GEOMETRY \n if self.reconstruction_type is not None:\n sample = self._get_reconstructions(index, start_frame, num_read_frames, video_fps, num_frames, sample)\n if time:\n geom_read_time = timeit.default_timer() - start_time - video_read_time - audio_read_time - lmk_read_time - seg_read_time - face_align_time\n\n # 7) EMOTION \n if self.emotion_type is not None:\n sample = self._get_emotions(index, start_frame, num_read_frames, video_fps, num_frames, sample)\n if time:\n emo_read_time = timeit.default_timer() - start_time - video_read_time - audio_read_time - lmk_read_time - seg_read_time - face_align_time - geom_read_time\n\n # 8) AUGMENTATION\n if self.read_video:\n sample = self._augment_sequence_sample(index, sample)\n if time:\n aug_time = timeit.default_timer() - start_time - video_read_time - audio_read_time - lmk_read_time - seg_read_time - face_align_time - geom_read_time - emo_read_time\n\n # TO TORCH\n sample = to_torch(sample)\n\n\n # AUDIO NORMALIZATION (if any), this is a remnant from av-hubert and is not being used anywhere, will be removed in the future\n if self.read_audio:\n if self.include_processed_audio:\n if self.audio_normalization is not None:\n if self.audio_normalization == \"layer_norm\":\n sample[\"audio\"] = F.layer_norm(sample[\"audio\"], sample[\"audio\"].shape[1:])\n else: \n raise ValueError(f\"Unsupported audio normalization {self.audio_normalization}\")\n # audio_process_time = timeit.default_timer() - start_time - video_read_time - audio_read_time - lmk_read_time - seg_read_time - face_align_time - geom_read_time - emo_read_time - aug_time\n\n if self.read_video:\n # T,H,W,C to T,C,H,W\n sample[\"video\"] = sample[\"video\"].permute(0, 3, 1, 2)\n if \"video_masked\" in sample.keys():\n sample[\"video_masked\"] = sample[\"video_masked\"].permute(0, 3, 1, 2)\n # sample[\"segmenation\"] = sample[\"segmenation\"].permute(0, 2, 1)\n # sample[\"segmentation_masked\"] = sample[\"segmentation_masked\"].permute(0, 2, 1)\n\n if self.return_mica_image: \n fan_landmarks = None\n landmarks_validity = None\n if \"landmarks\" in sample.keys():\n if isinstance(sample[\"landmarks\"], dict):\n if \"fan3d\" in sample[\"landmarks\"].keys():\n fan_landmarks = sample[\"landmarks\"][\"fan3d\"]\n landmarks_validity = sample[\"landmarks_validity\"][\"fan3d\"]\n elif \"fan\" in sample[\"landmarks\"].keys():\n fan_landmarks = sample[\"landmarks\"][\"fan\"]\n landmarks_validity = sample[\"landmarks_validity\"][\"fan\"]\n elif isinstance(sample[\"landmarks\"], (np.ndarray, torch.Tensor)):\n if sample[\"landmarks\"].shape[1] == 68:\n fan_landmarks = sample[\"landmarks\"]\n landmarks_validity = sample[\"landmarks_validity\"]\n \n sample[\"mica_video\"] = self.mica_preprocessor(sample[\"video\"], fan_landmarks, landmarks_validity=landmarks_validity)\n sample[\"mica_video_masked\"] = self.mica_preprocessor(sample[\"video_masked\"], fan_landmarks, landmarks_validity=landmarks_validity)\n\n\n # # normalize landmarks \n # if self.landmark_normalizer is not None:\n # if isinstance(self.landmark_normalizer, KeypointScale):\n # raise NotImplementedError(\"Landmark normalization is deprecated\")\n # self.landmark_normalizer.set_scale(\n # img.shape[0] / input_img_shape[0],\n # img.shape[1] / input_img_shape[1])\n # elif isinstance(self.landmark_normalizer, KeypointNormalization):\n # self.landmark_normalizer.set_scale(sample[\"video\"].shape[2], sample[\"video\"].shape[3])\n # else:\n # raise ValueError(f\"Unsupported landmark normalizer type: {type(self.landmark_normalizer)}\")\n # for key in sample[\"landmarks\"].keys():\n # sample[\"landmarks\"][key] = self.landmark_normalizer(sample[\"landmarks\"][key])\n if time: \n print(f\"Video read time: {video_read_time:.2f} s\")\n print(f\"Audio read time: {audio_read_time:.2f} s\")\n print(f\"Landmark read time: {lmk_read_time:.2f} s\")\n print(f\"Segmentation read time: {seg_read_time:.2f} s\")\n print(f\"Face alignment time: {face_align_time:.2f} s\")\n print(f\"Geometry read time: {geom_read_time:.2f} s\")\n print(f\"Emotion read time: {emo_read_time:.2f} s\")\n print(f\"Augmentation time: {aug_time:.2f} s\")\n # print(f\"Audio process time: {audio_process_time:.2f} s\")\n print(f\"Total read time: {timeit.default_timer() - start_time:.2f} s\")\n return sample\n\n def _get_video_path(self, index):\n if self.use_original_video:\n video_path = self.root_path / self.video_list[self.video_indices[index]]\n else: \n video_path = Path(self.output_dir) / \"videos_aligned\" / self.video_list[self.video_indices[index]]\n return video_path\n\n def _get_audio_path(self, index):\n audio_path = (Path(self.output_dir) / \"audio\" / self.video_list[self.video_indices[index]]).with_suffix(\".wav\")\n return audio_path\n\n def _get_num_frames(self, index):\n video_meta = self.video_metas[self.video_indices[index]]\n # print(\"Video path: \", video_path)\n # num video frames \n num_frames = video_meta[\"num_frames\"]\n video_path = self._get_video_path(index)\n if num_frames == 0: \n # use ffprobe to get the number of frames\n num_frames = int(subprocess.check_output([\"ffprobe\", \"-v\", \"error\", \"-select_streams\", \"v:0\", \"-count_packets\", \"-show_entries\", \"stream=nb_read_packets\", \"-of\", \"csv=p=0\", str(video_path)]))\n if num_frames == 0: \n _vr = FFmpegReader(str(video_path))\n num_frames = _vr.getShape()[0]\n del _vr\n return num_frames\n\n def _get_sample_length(self, index):\n if isinstance(self.sequence_length, int): # if sequence length set, use it\n return self.sequence_length\n elif isinstance(self.sequence_length, str): # otherwise use the one from the metadata\n if self.sequence_length == \"all\":\n if self.temporal_split_start is not None and self.temporal_split_end is not None:\n num_frames = self._get_num_frames(index)\n temporal_split_start_frame = int(self.temporal_split_start * num_frames)\n temporal_split_end_frame = int(self.temporal_split_end * num_frames) \n return temporal_split_end_frame - temporal_split_start_frame\n else:\n num_frames = self._get_num_frames(index)\n else: \n raise ValueError(f\"Unsupported sequence length value: '{self.sequence_length}'\")\n return num_frames\n raise \n\n def _get_video(self, index):\n video_path = self._get_video_path(index)\n video_meta = self.video_metas[self.video_indices[index]]\n # print(\"Video path: \", video_path)\n # num video frames \n num_frames = self._get_num_frames(index)\n assert num_frames > 0, \"Number of frames is 0 for video {}\".format(video_path)\n video_fps = video_meta[\"fps\"]\n n1, n2 = video_fps.split(\"/\")\n n1 = int(n1)\n n2 = int(n2)\n assert n1 % n2 == 0\n video_fps = n1 // n2\n\n # assert num_frames >= self.sequence_length, f\"Video {video_path} has only {num_frames} frames, but sequence length is {self.sequence_length}\"\n # TODO: handle the case when sequence length is longer than the video length\n\n sequence_length = self._get_sample_length(index)\n\n # pick the starting video frame \n if self.temporal_split_start is not None and self.temporal_split_end is not None:\n temporal_split_start = int(self.temporal_split_start * num_frames)\n temporal_split_end = int(self.temporal_split_end * num_frames) \n num_available_frames = temporal_split_end - temporal_split_start\n # start_frame = np.random.randint(temporal_split_start, temporal_split_end - sequence_length)\n else: \n temporal_split_start = 0\n temporal_split_end = num_frames\n num_available_frames = num_frames\n\n if num_available_frames <= sequence_length:\n start_frame = temporal_split_start\n else:\n if self.video_sample_indices is None: # one video is one sample\n start_frame = np.random.randint(temporal_split_start, temporal_split_end - sequence_length)\n else: # one video is multiple samples (as many as the sequence length allows without repetition)\n start_frame = temporal_split_start + (self.video_sample_indices[index] * sequence_length)\n # start_frame = np.random.randint(0, num_frames - sequence_length)\n\n sample = {}\n if self.include_filename: \n sample[\"filename\"] = str(video_path)\n sample[\"fps\"] = video_fps # include the fps in the sample\n\n # TODO: picking the starting frame should probably be done a bit more robustly \n # (e.g. by ensuring the sequence has at least some valid landmarks) ... \n # maybe the video should be skipped altogether if it can't provide that \n\n # load the frames\n # frames = []\n # for i in range(start_frame, start_frame + sequence_length):\n # frame_path = video_path / f\"frame_{i:04d}.jpg\"\n # frame = imread(str(frame_path))\n # frames.append(frame)\n assert video_path.is_file(), f\"Video {video_path} does not exist\"\n num_read_frames = self._get_sample_length(index)\n num_read_frames_ = self._get_sample_length(index)\n if self.read_video:\n num_read_frames = 0\n try:\n if not self.preload_videos:\n # import timeit\n # start_time = timeit.default_timer()\n # frames = vread(video_path.as_posix())\n # end_time = timeit.default_timer()\n # print(f\"Video read time: {end_time - start_time:.2f} s\")\n # from decord import VideoReader\n # from decord import cpu, gpu\n # start_time = timeit.default_timer()\n vr = VideoReader(video_path.as_posix(), ctx=cpu(0), width=self.image_size, height=self.image_size) \n if len(vr) < sequence_length:\n sequence_length_ = len(vr)\n else: \n sequence_length_ = sequence_length\n frames = vr.get_batch(range(start_frame,(start_frame + sequence_length_))) \n frames = frames.asnumpy()\n\n if sequence_length_ < sequence_length:\n # pad with zeros if video shorter than sequence length\n frames = np.concatenate([frames, np.zeros((sequence_length - frames.shape[0], frames.shape[1], frames.shape[2], frames.shape[3]), dtype=frames.dtype)])\n\n # end_time = timeit.default_timer()\n # print(f\"Video read time: {end_time - start_time:.2f} s\")\n else: \n frames = self.video_cache[video_path.as_posix()]\n assert len(frames) == num_frames, f\"Video {video_path} has {len(frames)} frames, but meta says it has {num_frames}\"\n frames = frames[start_frame:(start_frame + sequence_length)] \n num_read_frames = frames.shape[0]\n # # plot frames \n # import matplotlib.pyplot as plt\n # frame_idx = 0 \n # plt.figure()\n # plt.imshow(frames[frame_idx])\n # plt.show()\n if frames.shape[0] < sequence_length:\n # pad with zeros if video shorter than sequence length\n frames = np.concatenate([frames, np.zeros((sequence_length - frames.shape[0], frames.shape[1], frames.shape[2]), dtype=frames.dtype)])\n except ValueError: \n # reader = vreader(video_path.as_posix())\n # create an opencv video reader \n import cv2\n reader = cv2.VideoCapture(video_path.as_posix())\n fi = 0 \n frames = []\n while fi < start_frame:\n fi += 1\n # _ = next(reader) \n _, frame = reader.read()\n for i in range(sequence_length):\n # frames.append(next(reader))\n if reader.isOpened():\n _, frame = reader.read()\n if frame is None: \n # frame = np.zeros((self.image_size, self.image_size, 3), dtype=np.uint8)\n frame = np.zeros_like(frames[0])\n frames.append(frame)\n continue\n num_read_frames += 1\n # bgr to rgb \n frame = frame[:, :, ::-1]\n else: \n # if we ran out of frames, pad with black\n frame = np.zeros_like(frames[0])\n frames.append(frame)\n reader.release()\n frames = np.stack(frames, axis=0)\n frames = frames.astype(np.float32) / 255.0\n\n # sample = { \n sample[\"video\"] = frames\n\n sample[\"frame_indices\"] = np.arange(start_frame, start_frame + sequence_length, dtype=np.int32)\n \n if num_read_frames_ != num_read_frames:\n print(f\"[Warning]: read {num_read_frames} frames instead of {num_read_frames_} for video {video_path}\")\n\n return sample, start_frame, num_read_frames, video_fps, num_frames, num_available_frames\n\n def _read_audio(self, index):\n # audio_path = (Path(self.output_dir) / \"audio\" / self.video_list[self.video_indices[index]]).with_suffix(\".wav\")\n audio_path = self._get_audio_path(index)\n # audio_meta = self.audio_metas[self.video_indices[index]]\n \n # load the audio \n # if self.include_raw_audio:\n import librosa\n sampling_rate = 16000\n wavdata, sampling_rate = librosa.load(audio_path, sr=sampling_rate)\n # wavdata, sampling_rate = librosa.load(audio_path, sr=sampling_rate)\n if wavdata.ndim > 1:\n wavdata = librosa.to_mono(wavdata)\n wavdata = (wavdata.astype(np.float64) * 32768.0).astype(np.int16)\n return wavdata, sampling_rate\n\n def _get_audio(self, index, start_frame, num_read_frames, video_fps, num_frames, sample):\n if self.preload_videos:\n wavdata, sampling_rate = self.audio_cache[index]\n else:\n wavdata, sampling_rate = self._read_audio(index)\n sequence_length = self._get_sample_length(index)\n\n # audio augmentation\n if np.random.rand() < self.audio_noise_prob:\n wavdata = self.add_noise(wavdata)\n\n if self.include_processed_audio:\n # sampling_rate, wavdata = wavfile.read(audio_path.as_posix())\n\n # assert samplerate == 16000 and len(wavdata.shape) == 1\n audio_feats = logfbank(wavdata, samplerate=sampling_rate).astype(np.float32) # [T (num audio frames), F (num filters)]\n # the audio feats frequency (and therefore num frames) is too high, so we stack them together to match num visual frames \n audio_feats = stacker(audio_feats, self.stack_order_audio)\n\n # audio_feats = audio_feats[start_frame:(start_frame + sequence_length)] \n audio_feats = audio_feats[start_frame:(start_frame + num_read_frames)] \n # temporal pad with zeros if necessary to match the desired video length \n if audio_feats.shape[0] < sequence_length:\n # concatente with zeros\n audio_feats = np.concatenate([audio_feats, \n np.zeros((sequence_length - audio_feats.shape[0], audio_feats.shape[1]),\n dtype=audio_feats.dtype)], axis=0)\n \n # stack the frames and audio feats together\n sample[\"audio\"] = audio_feats\n\n \n if self.include_raw_audio:\n assert sampling_rate % video_fps == 0 \n wav_per_frame = sampling_rate // video_fps \n wavdata_ = np.zeros((num_frames, wav_per_frame), dtype=wavdata.dtype) \n wavdata_ = wavdata_.reshape(-1)\n if wavdata.size > wavdata_.size:\n wavdata_[...] = wavdata[:wavdata_.size]\n else: \n wavdata_[:wavdata.size] = wavdata\n wavdata_ = wavdata_.reshape((num_frames, wav_per_frame))\n wavdata_ = wavdata_[start_frame:(start_frame + num_read_frames)] \n if wavdata_.shape[0] < sequence_length:\n # concatente with zeros\n wavdata_ = np.concatenate([wavdata_, \n np.zeros((sequence_length - wavdata_.shape[0], wavdata_.shape[1]),\n dtype=wavdata_.dtype)], axis=0)\n wavdata_ = wavdata_.astype(np.float64) / np.int16(np.iinfo(np.int16).max)\n\n # wavdata_ = np.zeros((sequence_length, samplerate // video_fps), dtype=wavdata.dtype)\n # wavdata_ = np.zeros((n * frames.shape[0]), dtype=wavdata.dtype)\n # wavdata_[:wavdata.shape[0]] = wavdata \n # wavdata_ = wavdata_.reshape((frames.shape[0], -1))\n sample[\"raw_audio\"] = wavdata_ \n sample[\"samplerate\"] = sampling_rate\n\n return sample\n\n def _path_to_landmarks(self, index, landmark_type, landmark_source): \n return (Path(self.output_dir) / f\"landmarks_{landmark_source}\" / landmark_type / self.video_list[self.video_indices[index]]).with_suffix(\"\")\n\n def _read_landmarks(self, index, landmark_type, landmark_source):\n landmarks_dir = self._path_to_landmarks(index, landmark_type, landmark_source)\n landmark_list = FaceDataModuleBase.load_landmark_list(landmarks_dir / f\"landmarks_{landmark_source}.pkl\") \n return landmark_list\n\n def _get_landmarks(self, index, start_frame, num_read_frames, video_fps, num_frames, sample): \n sequence_length = self._get_sample_length(index)\n landmark_dict = {}\n landmark_validity_dict = {}\n for lti, landmark_type in enumerate(self.landmark_types):\n landmark_source = self.landmark_source[lti]\n landmarks_dir = self._path_to_landmarks(index, landmark_type, landmark_source)\n landmarks = []\n if (landmarks_dir / \"landmarks.pkl\").exists(): # landmarks are saved per video in a single file\n # landmark_list = FaceDataModuleBase.load_landmark_list(landmarks_dir / \"landmarks.pkl\") \n # landmark_list = FaceDataModuleBase.load_landmark_list(landmarks_dir / \"landmarks_original.pkl\") \n if not self.preload_videos: \n # landmark_list = FaceDataModuleBase.load_landmark_list(landm?arks_dir / f\"landmarks_{landmark_source}.pkl\") \n landmark_list = self._read_landmarks(index, landmark_type, landmark_source)\n # landmark_types = FaceDataModuleBase.load_landmark_list(landmarks_dir / \"landmark_types.pkl\") \n else: \n landmark_list = self.lmk_cache[index][landmark_type][landmark_source]\n # landmark_types = self.lmk_cache[index][\"landmark_types\"]\n landmarks = landmark_list[start_frame: sequence_length + start_frame] \n landmark_validity = np.ones((len(landmarks), 1), dtype=np.float32)\n for li in range(len(landmarks)): \n if len(landmarks[li]) == 0: # dropped detection\n if landmark_type == \"mediapipe\":\n # [WARNING] mediapipe landmarks coordinates are saved in the scale [0.0-1.0] (for absolute they need to be multiplied by img size)\n landmarks[li] = np.zeros((MEDIAPIPE_LANDMARK_NUMBER, 3))\n elif landmark_type in [\"fan\", \"kpt68\"]:\n landmarks[li] = np.zeros((68, 2))\n else: \n raise ValueError(f\"Unknown landmark type '{landmark_type}'\")\n landmark_validity[li] = 0.\n elif len(landmarks[li]) > 1: # multiple faces detected\n landmarks[li] = landmarks[li][0] # just take the first one for now\n else: \\\n landmarks[li] = landmarks[li][0] \n\n # # pad landmarks with zeros if necessary to match the desired video length\n # # if landmarks.shape[0] < sequence_length:\n # if len(landmarks) < sequence_length:\n # # concatente with zeros\n # landmarks += [np.zeros((landmarks.shape[1]))] * (sequence_length - len(landmarks))\n \n\n # landmarks = np.concatenate([landmarks, np.zeros((sequence_length - landmarks.shape[0], landmarks.shape[1]))], axis=0)\n # landmark_validity = np.concatenate([landmark_validity, np.zeros((sequence_length - landmark_validity.shape[0]), dtype=np.bool)], axis=0)\n else: # landmarks are saved per frame\n landmark_validity = np.ones((len(landmarks), 1), dtype=np.float32)\n for i in range(start_frame, sequence_length + start_frame):\n landmark_path = landmarks_dir / f\"{i:05d}_000.pkl\"\n landmark_type, landmark = load_landmark(landmark_path)\n landmarks += [landmark]\n if len(landmark) == 0: # dropped detection\n landmark = [0, 0]\n landmark_validity[li] = 0.\n elif len(landmark) > 1: # multiple faces detected\n landmarks[li] = landmarks[li][0] # just take the first one for now\n else: \n landmark[li] = landmarks[li][0] \n landmarks = np.stack(landmarks, axis=0)\n # if landmark_type == \"mediapipe\" and self.align_images: \n # # # [WARNING] mediapipe landmarks coordinates are saved in the scale [0.0-1.0] (for absolute they need to be multiplied by img size)\n # # # landmarks -= 0.5 \n # # landmarks -= 1. \n # landmarks *= 2 \n # # # landmarks *= 2 \n # landmarks -= 1\n\n # pad landmarks with zeros if necessary to match the desired video length\n if landmarks.shape[0] < sequence_length:\n landmarks = np.concatenate([landmarks, np.zeros(\n (sequence_length - landmarks.shape[0], *landmarks.shape[1:]), \n dtype=landmarks.dtype)], axis=0)\n landmark_validity = np.concatenate([landmark_validity, np.zeros((sequence_length - landmark_validity.shape[0], 1), \n dtype=landmark_validity.dtype)], axis=0)\n\n landmark_dict[landmark_type] = landmarks.astype(np.float32)\n landmark_validity_dict[landmark_type] = landmark_validity\n\n\n sample[\"landmarks\"] = landmark_dict\n sample[\"landmarks_validity\"] = landmark_validity_dict\n return sample\n\n def _path_to_segmentations(self, index): \n return (Path(self.output_dir) / f\"segmentations_{self.segmentation_source}\" / self.segmentation_type / self.video_list[self.video_indices[index]]).with_suffix(\"\")\n\n def _read_segmentations(self, index, start_frame=None, end_frame=None):\n segmentations_dir = self._path_to_segmentations(index)\n if (segmentations_dir / \"segmentations.hdf5\").exists(): # if random access hdf5 exists (newest), let's use it\n segmentations, seg_types, seg_names = load_segmentation_list_v2(segmentations_dir / \"segmentations.hdf5\", start_frame, end_frame)\n elif (segmentations_dir / \"segmentations.pkl\").exists(): # segmentations are saved in a single pickle (no random access)\n segmentations, seg_types, seg_names = load_segmentation_list(segmentations_dir / \"segmentations.pkl\")\n if start_frame is not None and end_frame is not None:\n segmentations = segmentations[start_frame: end_frame]\n seg_types = seg_types[start_frame: end_frame]\n seg_names = seg_names[start_frame: end_frame]\n if isinstance(segmentations, list):\n segmentations = np.stack(segmentations, axis=0)\n if segmentations.ndim == 4: # T, C=1, W, H\n segmentations = segmentations[:,0,...]\n if isinstance(seg_types[0], bytes):\n seg_types = [seg_type.decode(\"utf-8\") for seg_type in seg_types]\n if isinstance(seg_names[0], bytes):\n seg_names = [seg_name.decode(\"utf-8\") for seg_name in seg_names]\n return segmentations, seg_types, seg_names\n\n def _retrieve_segmentations(self, index, start_frame, end_frame):\n if not self.preload_videos:\n # segmentations_dir = self._path_to_segmentations(index)\n # if (segmentations_dir / \"segmentations.hdf5\").exists(): # random access hdf5 exists, let's use it\n # segmentations, seg_types, seg_names = load_segmentation_list_v2(segmentations_dir / \"segmentations.hdf5\", start_frame, end_frame)\n # elif (segmentations_dir / \"segmentations.pkl\").exists(): # segmentations are saved in a single pickle\n # seg_images, seg_types, seg_names = load_segmentation_list(segmentations_dir / \"segmentations.pkl\")\n # segmentations = seg_images[start_frame: end_frame]\n # if isinstance(seg_images, list):\n # segmentations = np.stack(seg_images, axis=0)\n # if seg_images.ndim == 4: # T, C=1, W, H\n # segmentations = segmentations[:,0,...]\n segmentations, seg_types, seg_names = self._read_segmentations(index, start_frame, end_frame)\n\n return segmentations, seg_types, seg_names\n else:\n video_path = str(self._get_video_path(index))\n segmentations, seg_types, seg_names = self.seg_cache[video_path]\n segmentations = segmentations[start_frame: end_frame]\n seg_types = seg_types[start_frame: end_frame]\n seg_names = seg_names[start_frame: end_frame]\n return segmentations, seg_types, seg_names\n\n def _load_reconstructions(self, index, rec_type, appearance=False, start_frame=None, end_frame=None): \n reconstructions_dir = self._path_to_reconstructions(index, rec_type)\n if (reconstructions_dir / \"shape_pose_cam.hdf5\").exists(): # random access hdf5 exists, let's use it\n shape_pose_cam = load_reconstruction_list_v2(reconstructions_dir / \"shape_pose_cam.hdf5\", \n start_frame=start_frame, end_frame=end_frame)\n if appearance:\n appearance = load_reconstruction_list_v2(reconstructions_dir / \"appearance.hdf5\", \n start_frame=start_frame, end_frame=end_frame)\n else: \n appearance = None\n elif (reconstructions_dir / \"shape_pose_cam.pkl\").exists(): # reconstructions are saved in a single pickle\n shape_pose_cam = load_reconstruction_list(reconstructions_dir / \"shape_pose_cam.pkl\", \n start_frame=start_frame, end_frame=end_frame)\n if appearance:\n appearance = load_reconstruction_list(reconstructions_dir / \"appearance.pkl\", \n start_frame=start_frame, end_frame=end_frame)\n else: \n appearance = None\n\n ## should no longer be necessary as the start/end frame is now handled in the load_reconstruction_list function\n # if start_frame is not None and end_frame is not None:\n # shape_pose_cam = {key: shape_pose_cam[key][:, start_frame: end_frame] for key in shape_pose_cam.keys()}\n # if appearance is not None:\n # appearance = {key: appearance[key][:, start_frame: end_frame] for key in appearance.keys()}\n else: \n raise RuntimeError(f\"Reconstruction file not found in {reconstructions_dir}\")\n # for key in shape_pose_cam.keys():\n # shape_pose_cam[key] = np.copy(shape_pose_cam[key])\n # for key in appearance.keys():\n # appearance[key] = np.copy(appearance[key])\n return shape_pose_cam, appearance\n\n def _load_emotions(self, index, features=False, start_frame=None, end_frame=None): \n emotions_dir = self._path_to_emotions(index)\n\n if (emotions_dir / \"emotions.hdf5\").exists(): # random access hdf5 exists, let's use it\n emotions = load_emotion_list_v2(emotions_dir / \"emotions.hdf5\", start_frame, end_frame)\n if features:\n features = load_emotion_list_v2(emotions_dir / \"features.hdf5\", start_frame, end_frame)\n else:\n features = None\n elif (emotions_dir / \"emotions.pkl\").exists(): # emotions are saved in a single pickle\n emotions = load_emotion_list(emotions_dir / \"emotions.pkl\", start_frame, end_frame)\n if features:\n features = load_emotion_list(emotions_dir / \"features.pkl\", start_frame, end_frame)\n assert \"feature\" in features.keys(), \"Features not found in emotion file. This is likely due to a bug in emotions saving. \" \\\n \"Please delete the emotion feature file and recompute them.\"\n else: \n features = None\n \n ### should no longer be necessary as the start/end frame is now handled in the load_reconstruction_list function\n # if start_frame is not None and end_frame is not None:\n # emotions = emotions[start_frame: end_frame]\n # if features is not None:\n # features = features[start_frame: end_frame]\n else: \n raise RuntimeError(f\"Emotion file not found in {emotions_dir}\")\n return emotions, features\n \n def _path_to_reconstructions(self, index, rec_type): \n return (Path(self.output_dir) / f\"reconstructions\" / rec_type / self.video_list[self.video_indices[index]]).with_suffix(\"\")\n # return (Path(self.output_dir) / f\"reconstructions\" / self.reconstruction_type / self.video_list[self.video_indices[index]]).with_suffix(\"\")\n\n def _path_to_emotions(self, index): \n return (Path(self.output_dir) / f\"emotions\" / self.emotion_type / self.video_list[self.video_indices[index]]).with_suffix(\"\")\n\n def _get_segmentations(self, index, start_frame, num_read_frames, video_fps, num_frames, sample): \n segmentations_dir = self._path_to_segmentations(index)\n segmentations = []\n\n sequence_length = self._get_sample_length(index)\n\n if (segmentations_dir / \"segmentations.pkl\").exists() or (segmentations_dir / \"segmentations.hdf5\").exists(): # segmentations are saved in a single file-per video \n # seg_images, seg_types, seg_names = load_segmentation_list(segmentations_dir / \"segmentations.pkl\")\n # segmentations = seg_images[start_frame: sequence_length + start_frame]\n # segmentations = np.stack(segmentations, axis=0)[:,0,...]\n segmentations, seg_types, seg_names = self._retrieve_segmentations(index, start_frame, sequence_length + start_frame)\n # segmentations = segmentations[start_frame: sequence_length + start_frame]\n segmentations = process_segmentation(segmentations, seg_types[0]).astype(np.uint8)\n # assert segmentations.shape[0] == sequence_length\n else: # segmentations are saved per-frame (old deprecated options)\n for i in range(start_frame, sequence_length + start_frame):\n segmentation_path = segmentations_dir / f\"{i:05d}.pkl\"\n seg_image, seg_type = load_segmentation(segmentation_path)\n # seg_image = seg_image[:, :, np.newaxis]\n seg_image = process_segmentation(seg_image[0], seg_type).astype(np.uint8)\n segmentations += [seg_image]\n segmentations = np.stack(segmentations, axis=0)\n if segmentations.shape[0] < sequence_length:\n # pad segmentations with zeros to match the sequence length\n segmentations = np.concatenate([segmentations, \n np.zeros((sequence_length - segmentations.shape[0], segmentations.shape[1], segmentations.shape[2]),\n dtype=segmentations.dtype)], axis=0)\n\n # ## resize segmentation to the expected image size\n # if segmentations.shape[1] != self.image_size and segmentations.shape[2] != self.image_size:\n # # sample[\"segmentation\"] = np.zeros((seg_frames.shape[0], self.image_size, self.image_size), dtype=seg_frames.dtype)\n # # for i in range(seg_frames.shape[0]):\n # # sample[\"segmentation\"][i] = cv2.resize(seg_frames[i], (self.image_size, self.image_size), interpolation=cv2.INTER_NEAREST)\n\n # # do the interpolation with pytorch functional instead: \n # seg_frames = torch.from_numpy(segmentations) \n # channel_added = False\n # if seg_frames.ndim == 3: \n # # add the channel dim \n # seg_frames = seg_frames.unsqueeze(1)\n # channel_added = True\n # seg_frames = F.interpolate(seg_frames, size=(self.image_size, self.image_size), mode=\"nearest\")\n # if channel_added:\n # seg_frames = seg_frames.squeeze(1)\n # segmentations = seg_frames.numpy()\n\n sample[\"segmentation\"] = segmentations\n return sample\n\n\n def _align_faces(self, index, sample):\n if self.align_images:\n \n sequence_length = self._get_sample_length(index)\n\n landmarks_for_alignment = \"mediapipe\"\n left = sample[\"landmarks\"][landmarks_for_alignment][:,:,0].min(axis=1) / self.original_image_size * self.image_size\n top = sample[\"landmarks\"][landmarks_for_alignment][:,:,1].min(axis=1) / self.original_image_size * self.image_size\n right = sample[\"landmarks\"][landmarks_for_alignment][:,:,0].max(axis=1) / self.original_image_size * self.image_size\n bottom = sample[\"landmarks\"][landmarks_for_alignment][:,:,1].max(axis=1) / self.original_image_size * self.image_size\n\n invalid_frames = np.logical_and(left == 0., np.logical_and(right == 0., np.logical_and(top == 0., bottom == 0.)))\n invalid_indices = np.where(invalid_frames)[0]\n valid_indices = np.where(np.logical_not(invalid_frames))[0]\n\n if len(invalid_indices) > 0: \n sample[\"landmarks_validity\"][landmarks_for_alignment][invalid_indices] = False\n\n if len(invalid_indices) == invalid_frames.size:\n # no valid indices, make up dummy one (zoom in a little bit)\n top = np.array([self.image_size//16]*invalid_frames.size)\n left = np.array([self.image_size//16]*invalid_frames.size)\n bottom = np.array([self.image_size - self.image_size//6]*invalid_frames.size)\n right = np.array([self.image_size - self.image_size//8]*invalid_frames.size)\n\n elif len(invalid_indices) > 0:\n first_valid_frame = valid_indices.min()\n last_valid_frame = valid_indices.max()\n\n left_ = left.copy()\n top_ = top.copy()\n right_ = right.copy()\n bottom_ = bottom.copy()\n\n left_[invalid_indices] = np.nan\n top_[invalid_indices] = np.nan\n right_[invalid_indices] = np.nan\n bottom_[invalid_indices] = np.nan\n\n # just copy over the first valid frame \n if first_valid_frame > 0:\n left_[0] = left[first_valid_frame]\n top_[0] = top[first_valid_frame]\n right_[0] = right[first_valid_frame]\n bottom_[0] = bottom[first_valid_frame]\n\n # just copy over the last valid frame \n if last_valid_frame < sequence_length - 1:\n left_[-1] = left[last_valid_frame]\n top_[-1] = top[last_valid_frame]\n right_[-1] = right[last_valid_frame]\n bottom_[-1] = bottom[last_valid_frame]\n\n # interpolate using pandas\n left_pd = pd.Series(left_)\n top_pd = pd.Series(top_)\n right_pd = pd.Series(right_)\n bottom_pd = pd.Series(bottom_)\n\n left_pd.interpolate(inplace=True)\n top_pd.interpolate(inplace=True)\n right_pd.interpolate(inplace=True)\n bottom_pd.interpolate(inplace=True)\n\n left = left_pd.to_numpy()\n top = top_pd.to_numpy()\n right = right_pd.to_numpy()\n bottom = bottom_pd.to_numpy()\n\n seg_left = left * self.original_image_size / self.image_size\n seg_top = top * self.original_image_size / self.image_size\n seg_right = right * self.original_image_size / self.image_size\n seg_bottom = bottom * self.original_image_size / self.image_size\n\n old_size, center = bbox2point(left, right, top, bottom, type=landmarks_for_alignment)\n size = (old_size * self.scale).astype(np.int32)\n\n\n old_size_seg, center_seg = bbox2point(seg_left, seg_right, seg_top, seg_bottom, type=landmarks_for_alignment)\n size_seg = (old_size_seg * self.scale).astype(np.int32)\n\n video_frames = sample[\"video\"]\n sample[\"video\"] = np.zeros((video_frames.shape[0], self.image_size, self.image_size, video_frames.shape[-1]), dtype=video_frames.dtype)\n \n if \"segmentation\" in sample.keys():\n seg_frames = sample[\"segmentation\"]\n\n sample[\"segmentation\"] = np.zeros((seg_frames.shape[0], self.image_size, self.image_size), dtype=seg_frames.dtype)\n\n for key in sample[\"landmarks\"].keys():\n sample[\"landmarks\"][key] *= self.image_size / self.original_image_size\n\n for i in range(sequence_length):\n lmk_to_warp = {k: v[i] for k,v in sample[\"landmarks\"].items()}\n \n img_warped, lmk_warped = bbpoint_warp(video_frames[i], center[i], size[i], self.image_size, landmarks=lmk_to_warp)\n \n if \"segmentation\" in sample.keys():\n seg_warped = bbpoint_warp(seg_frames[i], center_seg[i], size_seg[i], self.image_size, \n order=0 # nearest neighbor interpolation for segmentation\n )\n # img_warped *= 255.\n if not self._allow_alignment_fail:\n assert np.isnan(img_warped).sum() == 0, f\"NaNs in image {i} after face aligning image warp.\" \\\n f\"Center: {center[i]}, size: {size[i]}. Are these values valid?\"\n else: \n if np.isnan(img_warped).sum() > 0:\n img_warped[np.isnan(img_warped)] = 0.\n print('[WARNING] NaNs in image after face aligning image warp. Center: {}, size: {}. Are these values valid?'.format(center[i], size[i]))\n sample[\"video\"][i] = img_warped \n # sample[\"segmentation\"][i] = seg_warped * 255.\n if \"segmentation\" in sample.keys():\n sample[\"segmentation\"][i] = seg_warped\n for k,v in lmk_warped.items():\n sample[\"landmarks\"][k][i][:,:2] = v\n else: \n # no alignment, just resize the images\n video_frames = sample[\"video\"]\n if sample[\"video\"].shape[1] != self.image_size and sample[\"video\"].shape[2] != self.image_size:\n sample[\"video\"] = np.zeros((video_frames.shape[0], self.image_size, self.image_size, video_frames.shape[-1]), dtype=video_frames.dtype)\n # resize with pytorch \n video_frames = torch.from_numpy(video_frames)\n channel_added = False\n if video_frames.ndim == 3:\n video_frames = video_frames.unsqueeze(1)\n channel_added = True\n video_frames = F.interpolate(video_frames, size=(self.image_size, self.image_size), mode=\"bilinear\")\n if channel_added:\n video_frames = video_frames.squeeze(1)\n sample[\"video\"] = video_frames.numpy()\n # for i in range(video_frames.shape[0]):\n # sample[\"video\"][i] = cv2.resize(video_frames[i], (self.image_size, self.image_size), interpolation=cv2.INTER_CUBIC)\n \n if \"segmentation\" in sample.keys():\n seg_frames = sample[\"segmentation\"]\n if seg_frames.shape[1] != self.image_size and seg_frames.shape[2] != self.image_size:\n # sample[\"segmentation\"] = np.zeros((seg_frames.shape[0], self.image_size, self.image_size), dtype=seg_frames.dtype)\n # for i in range(seg_frames.shape[0]):\n # sample[\"segmentation\"][i] = cv2.resize(seg_frames[i], (self.image_size, self.image_size), interpolation=cv2.INTER_NEAREST)\n\n # do the interpolation with pytorch functional instead: \n seg_frames = torch.from_numpy(seg_frames) \n channel_added = False\n if seg_frames.ndim == 3: \n # add the channel dim \n seg_frames = seg_frames.unsqueeze(1)\n channel_added = True\n seg_frames = F.interpolate(seg_frames, size=(self.image_size, self.image_size), mode=\"nearest\")\n if channel_added:\n seg_frames = seg_frames.squeeze(1)\n sample[\"segmentation\"] = seg_frames.numpy()\n if \"landmarks\" in sample.keys():\n for k,v in sample[\"landmarks\"].items():\n sample[\"landmarks\"][k][...,:2] *= self.image_size / self.original_image_size\n\n return sample\n\n def _get_reconstructions(self, index, start_frame, num_read_frames, video_fps, num_frames, sample):\n for reconstruction_type in self.reconstruction_type: \n sample = self._get_reconstructions_of_type(index, start_frame, num_read_frames, video_fps, num_frames, sample, reconstruction_type)\n return sample\n\n def _get_reconstructions_of_type(self, index, start_frame, num_read_frames, video_fps, num_frames, sample, rec_type):\n sequence_length = self._get_sample_length(index)\n if self.reconstruction_type is None:\n return sample\n if not self.preload_videos:\n shape_pose_cam, appearance = self._load_reconstructions(index, rec_type, self.return_appearance, \n start_frame=start_frame, end_frame=start_frame+num_read_frames)\n else: \n shape_pose_cam_ = self.rec_cache[index][rec_type][\"shape_pose_cam\"]\n appearance_ = self.rec_cache[index][rec_type][\"appearance\"]\n shape_pose_cam = shape_pose_cam_.copy()\n if appearance_ is not None:\n appearance = appearance_.copy()\n else:\n appearance = None\n for key in shape_pose_cam.keys():\n shape_pose_cam[key] = shape_pose_cam[key][0]\n if appearance is not None:\n for key in appearance.keys():\n appearance[key] = appearance[key][0]\n \n weights = sample[\"landmarks_validity\"][\"mediapipe\"] / sample[\"landmarks_validity\"][\"mediapipe\"].sum(axis=0, keepdims=True)\n assert np.isnan(weights).any() == False, \"NaN in weights\"\n\n\n if shape_pose_cam['exp'].shape[0] < sequence_length: # pad with zero to be the same length as the sequence\n for key in shape_pose_cam.keys():\n # if key != 'shape':\n shape_pose_cam[key] = np.concatenate([shape_pose_cam[key], np.zeros((sequence_length - shape_pose_cam[key].shape[0], shape_pose_cam[key].shape[1]))], axis=0)\n if appearance is not None:\n for key in appearance.keys():\n appearance[key] = np.concatenate([appearance[key], np.zeros((sequence_length - appearance[key].shape[0], appearance[key].shape[1]))], axis=0)\n \n # if the start_frame is in the beginnning, zero out the first few frames\n if start_frame < self.invalid_cutoff: \n diff = self.invalid_cutoff - start_frame\n # if shape_pose_cam['shape'].ndim == 3:\n # shape_pose_cam['shape'][:diff] = 0\n # for key in shape_pose_cam.keys():\n # shape_pose_cam[key][:diff] = 0\n\n # if appearance is not None:\n # for key in appearance.keys():\n # appearance[key][:diff] = 0\n\n sample[\"landmarks_validity\"][\"mediapipe\"][:diff] = 0\n\n # if the start_frame is in the end, zero out the last few frames\n if start_frame + num_read_frames > num_frames - self.invalid_cutoff:\n diff = start_frame + num_read_frames - (num_frames - self.invalid_cutoff)\n # if shape_pose_cam['shape'].ndim == 3:\n # shape_pose_cam['shape'][-diff:] = 0\n # for key in shape_pose_cam.keys():\n # shape_pose_cam[key][-diff:] = 0\n\n # if appearance is not None:\n # for key in appearance.keys():\n # appearance[key][-diff:] = 0\n\n sample[\"landmarks_validity\"][\"mediapipe\"][-diff:] = 0\n\n if self.average_shape_decode:\n shape = (weights[:shape_pose_cam['shape'].shape[0]] * shape_pose_cam['shape']).sum(axis=0, keepdims=False)\n # shape = np.tile(shape, (shape_pose_cam['shape'].shape[0], 1))\n else:\n shape = shape_pose_cam['shape']\n if shape_pose_cam['exp'].shape[0] < sequence_length: # pad with zero to be the same length as the sequence\n shape_pose_cam['shape'] = np.concatenate([shape_pose_cam['shape'], \n np.zeros((sequence_length - shape_pose_cam['shape'].shape[0], shape_pose_cam['exp'].shape[1]))], \n axis=0)\n # shape = np.concatenate([shape, np.tile(shape[-1], (sequence_length - shape.shape[0], 1))], axis=0)\n\n\n if self.return_appearance: \n if self.average_shape_decode: \n appearance['tex'] = (weights[:appearance['tex'].shape[0]] * appearance['tex']).sum(axis=0, keepdims=False)\n # appearance = np.tile(appearance, (appearance['tex'].shape[0], 1))\n else:\n # appearance = appearance['tex']\n if shape_pose_cam['exp'].shape[0] < sequence_length:\n appearance['tex'] = np.concatenate([appearance['tex'], \n np.zeros((sequence_length - appearance['tex'].shape[0], appearance['tex'].shape[1]))], \n axis=0)\n # appearance = np.concatenate([appearance, np.tile(appearance[-1], (sequence_length - appearance.shape[0], 1))], axis=0)\n \n # # intialize emtpy dicts if they don't exist\n # if \"gt_exp\" not in sample.keys():\n # sample[\"gt_exp\"] = {} \n # if \"gt_shape\" not in sample.keys():\n # sample[\"gt_shape\"] = {} \n # if \"gt_jaw\" not in sample.keys():\n # sample[\"gt_jaw\"] = {} \n # if self.return_global_pose:\n # if \"gt_global_pose\" not in sample.keys():\n # sample[\"gt_global_pose\"] = {}\n # if \"gt_cam\" not in sample.keys():\n # sample[\"gt_cam\"] = {}\n # if self.return_appearance:\n # if \"gt_tex\" not in sample.keys():\n # sample[\"gt_tex\"] = {}\n # if \"gt_light\" not in sample.keys():\n # sample[\"gt_light\"] = {}\n # if \"detailcode\" in appearance: \n # if \"gt_detail\" not in sample.keys():\n # sample[\"gt_detail\"] = {}\n if \"reconstruction\" not in sample.keys():\n sample[\"reconstruction\"] = {}\n assert rec_type not in sample[\"reconstruction\"].keys(), \"reconstruction type already exists in sample\"\n sample[\"reconstruction\"][rec_type] = {}\n \n \n sample[\"reconstruction\"][rec_type][\"gt_exp\"] = shape_pose_cam['exp'].astype(np.float32)\n sample[\"reconstruction\"][rec_type][\"gt_shape\"] = shape.astype(np.float32)\n sample[\"reconstruction\"][rec_type][\"gt_jaw\"] = shape_pose_cam['jaw'].astype(np.float32)\n if self.return_global_pose:\n sample[\"reconstruction\"][rec_type][\"gt_global_pose\"]= shape_pose_cam['global_pose'].astype(np.float32)\n sample[\"reconstruction\"][rec_type] [\"gt_cam\"] = shape_pose_cam['cam'].astype(np.float32)\n if self.return_appearance: \n sample[\"reconstruction\"][rec_type]['gt_tex'] = appearance['tex'].astype(np.float32)\n sample[\"reconstruction\"][rec_type]['gt_light'] = appearance['light'].astype(np.float32)\n if 'detailcode' in appearance:\n sample[rec_type]['gt_detail'] = appearance['detailcode'].astype(np.float32)\n\n if hasattr(self, 'flame') and self.flame is not None:\n flame_sample = {} \n flame_sample['gt_shape'] = torch.tensor(shape).unsqueeze(0)\n flame_sample['gt_exp'] = torch.tensor(sample[rec_type][\"gt_exp\"]).unsqueeze(0)\n flame_sample['gt_jaw'] = torch.tensor(sample[rec_type][\"gt_jaw\"]).unsqueeze(0)\n flame_sample = self.flame(flame_sample, \"\")\n # for key in flame_sample.keys():\n # sample[key] = torch.zeros_like(flame_sample[key]).numpy()[0]\n for key in flame_sample.keys():\n # if key not in sample.keys():\n # sample[key] = {}\n sample[\"reconstruction\"][rec_type][key] = flame_sample[key].detach().clone().contiguous().numpy()[0]\n \n return sample\n\n def _get_emotions(self, index, start_frame, num_read_frames, video_fps, num_frames, sample):\n sequence_length = self._get_sample_length(index)\n if self.emotion_type is None:\n return sample\n if not self.preload_videos:\n emotions, features = self._load_emotions(index, self.return_emotion_feature, \n start_frame=start_frame, end_frame=start_frame+num_read_frames)\n else: \n emotions = self.emo_cache[index][\"emotions\"].copy() \n emotions = emotions[start_frame:start_frame+num_read_frames]\n features = self.emo_cache[index][\"features\"]\n if features is not None:\n features = features.copy()\n features = features[start_frame:start_frame+num_read_frames]\n if features is not None:\n features = {\"emo_\" + key: features[key] for key in features.keys()} # just add the emo_ prefix to the keys\n for key in emotions.keys():\n assert key not in sample.keys(), f\"Key {key} already exists in sample.\"\n sample['gt_' + key] = emotions[key][0].astype(np.float32)\n \n # if shorter than the sequence, pad with zeros\n if sample['gt_' + key].shape[0] < sequence_length:\n sample['gt_' + key] = np.concatenate([sample['gt_' + key], np.zeros((sequence_length - sample['gt_' + key].shape[0], sample['gt_' + key].shape[1]))], axis=0).astype(np.float32)\n\n \n if features is not None:\n for key in features.keys():\n assert key not in sample.keys(), f\"Key {key} already exists in sample.\"\n sample['gt_' + key] = features[key][0].astype(np.float32)\n\n # if shorter than the sequence, pad with zeros\n if sample['gt_' + key].shape[0] < sequence_length:\n sample['gt_' + key] = np.concatenate([sample['gt_' + key], np.zeros((sequence_length - sample['gt_' + key].shape[0], sample['gt_' + key].shape[1]))], axis=0).astype(np.float32)\n\n return sample\n\n\n def _augment(self, img, seg_image, landmark, input_img_shape=None):\n # workaround to make sure each sequence is augmented the same\n # unfortunately imgaug does not support this out of the box \n\n # therefore we split the [B, T, ...] arays into T x [B, ...] arrays \n # and augment each t from 1 to T separately same way using to_deterministic\n\n transform_det = self.transforms.to_deterministic()\n\n T = img.shape[0]\n\n for t in range(T):\n img_t = img[t, ...] if img is not None else None\n seg_image_t = seg_image[t:t+1, ..., np.newaxis] if seg_image is not None else None\n landmark_t = landmark[t:t+1, ..., :2] if landmark is not None else None\n\n if self.transforms is not None:\n res = transform_det(\n # image=img_t.astype(np.float32),\n image=img_t,\n segmentation_maps=seg_image_t,\n keypoints=landmark_t)\n if seg_image_t is not None and landmark is not None:\n img_t, seg_image_t, landmark_t = res\n elif seg_image_t is not None:\n img_t, seg_image_t, _ = res\n elif landmark_t is not None:\n img_t, _, landmark_t = res\n else:\n img_t = res\n\n if seg_image_t is not None:\n seg_image_t = np.squeeze(seg_image_t)[..., np.newaxis].astype(np.float32)\n\n if landmark_t is not None:\n landmark_t = np.squeeze(landmark_t)\n if isinstance(self.landmark_normalizer, KeypointScale):\n self.landmark_normalizer.set_scale(\n img_t.shape[0] / input_img_shape[0],\n img_t.shape[1] / input_img_shape[1])\n elif isinstance(self.landmark_normalizer, KeypointNormalization):\n self.landmark_normalizer.set_scale(img_t.shape[0], img_t.shape[1])\n # self.landmark_normalizer.set_scale(input_img_shape[0], input_img_shape[1])\n else:\n raise ValueError(f\"Unsupported landmark normalizer type: {type(self.landmark_normalizer)}\")\n landmark_t = self.landmark_normalizer(landmark_t)\n\n img[t:t+1, ...] = img_t \n if seg_image is not None:\n seg_image[t:t+1, ...] = seg_image_t[..., 0]\n if landmark is not None:\n landmark[t:t+1, ..., :2] = landmark_t[np.newaxis]\n if landmark is not None:\n landmark = landmark[:, :, :2]\n return img, seg_image, landmark\n\n def _augment_sequence_sample(self, index, sample):\n # get the mediapipe landmarks \n mediapipe_landmarks = sample[\"landmarks\"][\"mediapipe\"]\n mediapipe_landmarks_valid = sample[\"landmarks_validity\"][\"mediapipe\"]\n # mediapipe_landmarks = []\n images = sample[\"video\"]\n segmentation=None\n if \"segmentation\" in sample.keys():\n segmentation = sample[\"segmentation\"]\n \n\n images_masked = np.copy(images)\n segmentation_masked = None\n if segmentation is not None:\n segmentation_masked = np.copy(segmentation)\n\n masked_frames = np.zeros(images.shape[:1], dtype=np.float32)\n\n # compute mouth region bounding box\n if np.random.rand() < self.occlusion_probability_mouth: \n images_masked, segmentation_masked, start_frame_, end_frame_ = self._occlude_sequence(index, images_masked, segmentation_masked, \n mediapipe_landmarks, mediapipe_landmarks_valid, \"mouth\")\n masked_frames[start_frame_:end_frame_] = 1.0\n\n # compute eye region bounding box\n if np.random.rand() < self.occlusion_probability_left_eye:\n images_masked, segmentation_masked, start_frame_, end_frame_ = self._occlude_sequence(index, images_masked, segmentation_masked, \n mediapipe_landmarks, mediapipe_landmarks_valid, \"left_eye\")\n masked_frames[start_frame_:end_frame_] = 1.0\n\n if np.random.rand() < self.occlusion_probability_right_eye:\n images_masked, segmentation_masked, start_frame_, end_frame_ = self._occlude_sequence(index, images_masked, segmentation_masked, \n mediapipe_landmarks, mediapipe_landmarks_valid, \"right_eye\")\n masked_frames[start_frame_:end_frame_] = 1.0\n\n # compute face region bounding box\n if np.random.rand() < self.occlusion_probability_face:\n images_masked, segmentation_masked, start_frame_, end_frame_ = self._occlude_sequence(index, images_masked, segmentation_masked, \n mediapipe_landmarks, mediapipe_landmarks_valid, \"all\")\n masked_frames[start_frame_:end_frame_] = 1.0\n\n\n\n # augment the sequence\n # images, segmentation, mediapipe_landmarks = self._augment(images, segmentation, \n # mediapipe_landmarks, images.shape[2:])\n # images_masked, segmentation_masked, _ = self._augment(images_masked, segmentation_masked, \n # None, images.shape[2:])\n\n\n images_aug = (np.concatenate([images, images_masked], axis=0) * 255.0).astype(np.uint8)\n segmentation_aug = [] \n if segmentation is not None:\n segmentation_aug += [segmentation]\n if segmentation_masked is not None:\n segmentation_aug += [segmentation_masked]\n\n segmentation_aug = np.concatenate(segmentation_aug, axis=0) if len(segmentation_aug) > 0 else None\n # segmentation_aug = np.concatenate([segmentation, segmentation_masked], axis=0)\n # mediapipe_landmarks_aug = np.concatenate([mediapipe_landmarks, mediapipe_landmarks], axis=0)\n\n # concatenate all the available landmarks s.t. it can be used for augmentation\n landmarks_to_augment = [] \n lmk_counts = []\n for lmk_type in sample[\"landmarks\"].keys():\n landmarks_to_augment += [sample[\"landmarks\"][lmk_type]]\n lmk_counts += [sample[\"landmarks\"][lmk_type].shape[1]]\n lmk_counts = np.array(lmk_counts, dtype=np.int32)\n\n landmarks_to_augment = np.concatenate(landmarks_to_augment, axis=1)\n landmarks_to_augment_aug = np.concatenate([landmarks_to_augment, landmarks_to_augment], axis=0)\n\n # images_aug, segmentation_aug, mediapipe_landmarks_aug = self._augment(images_aug, segmentation_aug, \n # mediapipe_landmarks_aug, images.shape[2:])\n images_aug, segmentation_aug, mediapipe_landmarks_aug = self._augment(images_aug, segmentation_aug, \n landmarks_to_augment_aug, images.shape[2:])\n images_aug = images_aug.astype(np.float32) / 255.0 # back to float\n images = images_aug[:images_aug.shape[0]//2]\n\n if segmentation is not None:\n segmentation = segmentation_aug[:segmentation_aug.shape[0]//2]\n # mediapipe_landmarks = mediapipe_landmarks_aug[:mediapipe_landmarks_aug.shape[0]//2]\n landmarks_to_augment_aug = landmarks_to_augment_aug[:landmarks_to_augment_aug.shape[0]//2]\n images_masked = images_aug[images_aug.shape[0]//2 :]\n\n if segmentation_masked is not None:\n segmentation_masked = segmentation_aug[segmentation_aug.shape[0]//2 :]\n\n # sample[\"video\"] = images / 255.0\n # sample[\"video_masked\"] = images_masked / 255.0\n sample[\"video\"] = images \n sample[\"video_masked\"] = images_masked \n if segmentation is not None:\n sample[\"segmentation\"] = segmentation\n if segmentation_masked is not None:\n sample[\"segmentation_masked\"] = segmentation_masked\n sample[\"masked_frames\"] = masked_frames\n # sample[\"landmarks\"][\"mediapipe\"] = mediapipe_landmarks \n\n # split the augmented landmarks back to their original types\n for i, lmk_type in enumerate(sample[\"landmarks\"].keys()):\n sample[\"landmarks\"][lmk_type] = landmarks_to_augment_aug[:, np.sum(lmk_counts[:i]):np.sum(lmk_counts[:i+1]), :].astype(np.float32)\n return sample\n\n def _occlude_sequence(self, index, images, segmentation, mediapipe_landmarks, mediapipe_landmarks_valid, region):\n bounding_boxes, sizes = self.occluder.bounding_box_batch(mediapipe_landmarks, region)\n \n sequence_length = self._get_sample_length(index)\n\n bb_style = \"max\" # largest bb of the sequence \n # bb_style = \"min\" # smallest bb of the sequence \n # bb_style = \"mean\" # mean bb of the sequence \n # bb_style = \"original\" # original bb of the sequence (different for each frame) \n\n # we can enlarge or shrink the bounding box\n scale_size_width = 1 \n scale_size_height = 1 \n\n scaled_sizes = np.copy(sizes)\n scaled_sizes[:,2] = (scaled_sizes[:,2] * scale_size_width).astype(np.int32)\n scaled_sizes[:,3] = (scaled_sizes[:,3] * scale_size_height).astype(np.int32)\n\n\n if bb_style == \"max\":\n width = sizes[:,2].max()\n height = sizes[:,3].max()\n sizes[:, 2] = width\n sizes[:, 3] = height\n bounding_boxes = sizes_to_bb_batch(sizes)\n elif bb_style == \"mean\":\n width = sizes[:,2].mean()\n height = sizes[:,3].mean()\n sizes[:, 2] = width\n sizes[:, 3] = height\n bounding_boxes = sizes_to_bb_batch(sizes)\n elif bb_style == \"min\":\n width = sizes[:,2].min()\n height = sizes[:,3].min()\n sizes[:, 2] = width\n sizes[:, 3] = height\n bounding_boxes = sizes_to_bb_batch(sizes)\n elif bb_style == \"original\":\n pass \n else:\n raise ValueError(f\"Unsupported bounding box strategy {bb_style}\")\n\n bounding_boxes = bounding_boxes.clip(min=0, max=images.shape[1] - 1)\n\n occlusion_length = np.random.randint(self.occlusion_length[0], self.occlusion_length[1])\n occlusion_length = min(sequence_length, occlusion_length)\n\n start_frame = np.random.randint(0, max(sequence_length - occlusion_length + 1, 1))\n end_frame = start_frame + occlusion_length\n\n images = self.occluder.occlude_batch(images, region, landmarks=None, \n bounding_box_batch=bounding_boxes, start_frame=start_frame, end_frame=end_frame)\n if segmentation is not None:\n segmentation = self.occluder.occlude_batch(segmentation, region, landmarks=None, \n bounding_box_batch=bounding_boxes, start_frame=start_frame, end_frame=end_frame)\n return images, segmentation, start_frame, end_frame\n\n def add_noise(self, wavdata):\n raise NotImplementedError( )\n noise = np.random.randn(len(wavdata))\n return wavdata + noise\n\n def _true_len(self):\n return len(self.video_indices)\n\n def __len__(self): \n if self.hack_length: \n return int(self.hack_length*self._true_len())\n return self._true_len()\n\n def visualize_sample(self, sample_or_index):\n from inferno.utils.MediaPipeLandmarkDetector import np2mediapipe\n \n if isinstance(sample_or_index, (int, np.int32, np.int64)):\n index = sample_or_index\n sample = self[index]\n else:\n sample = sample_or_index\n\n # visualize the video\n video_frames = sample[\"video\"]\n segmentation = sample.get(\"segmentation\", None)\n video_frames_masked = sample.get(\"video_masked\", None)\n segmentation_masked = sample.get(\"segmentation_masked\", None)\n\n if \"mediapipe\" in sample[\"landmarks\"]:\n landmarks_mp = sample[\"landmarks\"][\"mediapipe\"]\n\n landmarks_mp = self.landmark_normalizer.inv(landmarks_mp)\n\n # T, C, W, H to T, W, H, C \n video_frames = video_frames.permute(0, 2, 3, 1)\n if video_frames_masked is not None:\n video_frames_masked = video_frames_masked.permute(0, 2, 3, 1)\n if segmentation is not None:\n segmentation = segmentation[..., None]\n \n if segmentation_masked is not None:\n segmentation_masked = segmentation_masked[..., None]\n\n # plot the video frames with plotly\n # horizontally concatenate the frames\n frames = np.concatenate(video_frames.numpy(), axis=1)\n frames_masked=None\n if video_frames_masked is not None:\n frames_masked = np.concatenate(video_frames_masked.numpy(), axis=1)\n if segmentation is not None:\n segmentation = np.concatenate(segmentation.numpy(), axis=1)\n if segmentation_masked is not None:\n segmentation_masked = np.concatenate(segmentation_masked.numpy(), axis=1)\n landmarks_mp_list = [] \n for i in range(landmarks_mp.shape[0]):\n landmarks_mp_proto = np2mediapipe(landmarks_mp[i].numpy() / self.image_size)\n landmarks_mp_list.append(landmarks_mp_proto)\n\n # Load drawing_utils and drawing_styles\n import mediapipe as mp\n mp_drawing = mp.solutions.drawing_utils \n mp_drawing_styles = mp.solutions.drawing_styles\n mp_face_mesh = mp.solutions.face_mesh\n\n video_frames_landmarks_mp = np.copy(video_frames)*255\n for i in range(video_frames_landmarks_mp.shape[0]):\n mp_drawing.draw_landmarks(\n image=video_frames_landmarks_mp[i],\n landmark_list=landmarks_mp_list[i],\n connections=mp_face_mesh.FACEMESH_CONTOURS,\n landmark_drawing_spec=None,\n connection_drawing_spec=mp_drawing_styles\n .get_default_face_mesh_contours_style()\n )\n \n video_frames_landmarks_mp = np.concatenate(video_frames_landmarks_mp, axis=1)\n else: \n video_frames_landmarks_mp = None\n\n fan_lmk_images = None\n if \"fan\" in sample[\"landmarks\"]:\n from inferno.utils.DecaUtils import tensor_vis_landmarks\n landmarks_fan = sample[\"landmarks\"][\"fan\"]\n fan_lmk_images = tensor_vis_landmarks(sample[\"video\"],\n self.landmark_normalizer.inv(landmarks_fan),\n isScale=False, rgb2bgr=False, scale_colors=True).permute(0, 2, 3, 1).numpy().tolist()\n fan_lmk_images = np.concatenate(fan_lmk_images, axis=1)\n # for i in range(landmarks_fan.shape[0]):\n # lmk = landmarks_fan[i, ...]\n # lmk_expanded = lmk[np.newaxis, ...]\n # lmk_im = tensor_vis_landmarks(video_frames,\n # self.landmark_normalizer.inv(lmk_expanded),\n # isScale=False, rgb2bgr=False, scale_colors=True).numpy()[0].transpose([1, 2, 0])\n # fan_lmk_images += [lmk_im]\n # fan_lmk_images = np.concatenate(fan_lmk_images, axis=1) \n\n all_images = [frames*255] \n if segmentation is not None:\n all_images += [np.tile(segmentation*255, (1,1,3))] \n if frames_masked is not None: \n all_images += [frames_masked*255] \n if segmentation_masked is not None:\n all_images += [np.tile(segmentation_masked*255, (1,1,3))] \n if video_frames_landmarks_mp is not None:\n all_images += [video_frames_landmarks_mp]\n if fan_lmk_images is not None: \n all_images += [fan_lmk_images * 255]\n all_images = np.concatenate(all_images, axis=0)\n # plot the frames\n\n import plotly.express as px\n import plotly.graph_objects as go\n import pandas as pd\n fig = go.Figure(data=[go.Image(z=all_images)])\n # show the figure \n fig.show()\n\n # fig = go.Figure(data=[go.Image(z=frames)])\n # # show the figure \n # fig.show()\n # fig = go.Figure(data=[go.Image(z=frames_masked)])\n # # show the figure \n # fig.show()\n\n # fig = go.Figure(data=[go.Image(z=segmentation)])\n # # show the figure \n # fig.show()\n\n # fig = go.Figure(data=[go.Image(z=segmentation_masked)])\n # # show the figure \n # fig.show()\n # print(\"ha\")", "answers": [" self.condition_settings[i] = AffectNetExpressions[cond]"], "length": 6589, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "08f845c2-b166-4071-bba5-505c1e0e9a36", "reasoning": "The code is inside the __init__ method handling condition_source values. For the 'expression' case, a string condition is converted to an integer using the AffectNetExpressions mapping. The same conversion is needed for the 'gt_expression' related sources. Therefore, the next line after checking isinstance(cond, str) should assign the mapped integer.", "reasoning_model_answer": "self.condition_settings[i] = AffectNetExpressions[cond]", "assistant_with_reasoning": "\nThe code is inside the __init__ method handling condition_source values. For the 'expression' case, a string condition is converted to an integer using the AffectNetExpressions mapping. The same conversion is needed for the 'gt_expression' related sources. Therefore, the next line after checking isinstance(cond, str) should assign the mapped integer.\n\nself.condition_settings[i] = AffectNetExpressions[cond]", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.159, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36159, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "self.condition_settings[i] = AffectNetExpressions[cond]", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "import org.fourthline.cling.UpnpService;\nimport org.fourthline.cling.UpnpServiceConfiguration;\nimport org.fourthline.cling.model.DiscoveryOptions;\nimport org.fourthline.cling.model.ExpirationDetails;\nimport org.fourthline.cling.model.ServiceReference;\nimport org.fourthline.cling.model.gena.LocalGENASubscription;\nimport org.fourthline.cling.model.gena.RemoteGENASubscription;\nimport org.fourthline.cling.model.meta.Device;\nimport org.fourthline.cling.model.meta.LocalDevice;\nimport org.fourthline.cling.model.meta.RemoteDevice;\nimport org.fourthline.cling.model.meta.RemoteDeviceIdentity;\nimport org.fourthline.cling.model.meta.Service;\nimport org.fourthline.cling.model.resource.Resource;\nimport org.fourthline.cling.model.types.DeviceType;\nimport org.fourthline.cling.model.types.ServiceType;\nimport org.fourthline.cling.model.types.UDN;\nimport org.fourthline.cling.protocol.ProtocolFactory;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.enterprise.context.ApplicationScoped;\nimport javax.inject.Inject;", "context": "clinglibrary/src/main/java/org/fourthline/cling/registry/RegistryImpl.java\n\n synchronized public void addListener(RegistryListener listener) {\n registryListeners.add(listener);\n }\n\n synchronized public void removeListener(RegistryListener listener) {\n registryListeners.remove(listener);\n }\n\n synchronized public Collection getListeners() {\n return Collections.unmodifiableCollection(registryListeners);\n }\n\n synchronized public boolean notifyDiscoveryStart(final RemoteDevice device) {\n // Exit if we have it already, this is atomic inside this method, finally\n if (getUpnpService().getRegistry().getRemoteDevice(device.getIdentity().getUdn(), true) != null) {\n log.finer(\"Not notifying listeners, already registered: \" + device);\n return false;\n }\n for (final RegistryListener listener : getListeners()) {\n getConfiguration().getRegistryListenerExecutor().execute(\n new Runnable() {\n public void run() {\n listener.remoteDeviceDiscoveryStarted(RegistryImpl.this, device);\n }\n }\n );\n }\n return true;\n }\n\n synchronized public void notifyDiscoveryFailure(final RemoteDevice device, final Exception ex) {\n for (final RegistryListener listener : getListeners()) {\n getConfiguration().getRegistryListenerExecutor().execute(\n new Runnable() {\n public void run() {\n listener.remoteDeviceDiscoveryFailed(RegistryImpl.this, device, ex);\n }\n }\n );\n }\n }\n\n // #################################################################################################\n\n synchronized public void addDevice(LocalDevice localDevice) {\n localItems.add(localDevice);\n }\n\n synchronized public void addDevice(LocalDevice localDevice, DiscoveryOptions options) {\n localItems.add(localDevice, options);\n }\n\n synchronized public void setDiscoveryOptions(UDN udn, DiscoveryOptions options) {\n localItems.setDiscoveryOptions(udn, options);\n }\n\n synchronized public DiscoveryOptions getDiscoveryOptions(UDN udn) {\n return localItems.getDiscoveryOptions(udn);\n }\n\n synchronized public void addDevice(RemoteDevice remoteDevice) {\n remoteItems.add(remoteDevice);\n }\n\n synchronized public boolean update(RemoteDeviceIdentity rdIdentity) {\n return remoteItems.update(rdIdentity);\n }\n\n synchronized public boolean removeDevice(LocalDevice localDevice) {\n return localItems.remove(localDevice);\n }\n\n synchronized public boolean removeDevice(RemoteDevice remoteDevice) {\n return remoteItems.remove(remoteDevice);\n }\n\n synchronized public void removeAllLocalDevices() {\n localItems.removeAll();\n }\n\n synchronized public void removeAllRemoteDevices() {\n remoteItems.removeAll();\n }\n\n synchronized public boolean removeDevice(UDN udn) {\n Device device = getDevice(udn, true);\n if (device != null && device instanceof LocalDevice)\n return removeDevice((LocalDevice) device);\n if (device != null && device instanceof RemoteDevice)\n return removeDevice((RemoteDevice) device);\n return false;\n }\n\n synchronized public Device getDevice(UDN udn, boolean rootOnly) {\n Device device;\n if ((device = localItems.get(udn, rootOnly)) != null) return device;\n if ((device = remoteItems.get(udn, rootOnly)) != null) return device;\n return null;\n }\n\n synchronized public LocalDevice getLocalDevice(UDN udn, boolean rootOnly) {\n return localItems.get(udn, rootOnly);\n }\n\n synchronized public RemoteDevice getRemoteDevice(UDN udn, boolean rootOnly) {\n return remoteItems.get(udn, rootOnly);\n }\n\n synchronized public Collection getLocalDevices() {\n return Collections.unmodifiableCollection(localItems.get());\n }\n\n synchronized public Collection getRemoteDevices() {\n return Collections.unmodifiableCollection(remoteItems.get());\n }\n\n synchronized public Collection getDevices() {\n Set all = new HashSet<>();\n all.addAll(localItems.get());\n\nclinglibrary/src/main/java/org/fourthline/cling/model/ServiceReference.java\npublic class ServiceReference {\n\n public static final String DELIMITER = \"/\";\n\n final private UDN udn;\n final private ServiceId serviceId;\n\n public ServiceReference(String s) {\n String[] split = s.split(\"/\");\n if (split.length == 2) {\n this.udn = UDN.valueOf(split[0]);\n this.serviceId = ServiceId.valueOf(split[1]);\n } else {\n this.udn = null;\n this.serviceId = null;\n }\n }\n\n public ServiceReference(UDN udn, ServiceId serviceId) {\n this.udn = udn;\n this.serviceId = serviceId;\n }\n\n public UDN getUdn() {\n return udn;\n }\n\n public ServiceId getServiceId() {\n return serviceId;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n ServiceReference that = (ServiceReference) o;\n\n if (!serviceId.equals(that.serviceId)) return false;\n if (!udn.equals(that.udn)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = udn.hashCode();\n result = 31 * result + serviceId.hashCode();\n return result;\n }\n\n @Override\n public String toString() {\n return udn == null || serviceId == null ? \"\" : udn.toString() + DELIMITER + serviceId.toString();\n }\n\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/meta/RemoteDevice.java\npublic class RemoteDevice extends Device {\n\n public RemoteDevice(RemoteDeviceIdentity identity) throws ValidationException {\n super(identity);\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n RemoteService service) throws ValidationException {\n super(identity, type, details, null, new RemoteService[]{service});\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n RemoteService service, RemoteDevice embeddedDevice) throws ValidationException {\n super(identity, type, details, null, new RemoteService[]{service}, new RemoteDevice[]{embeddedDevice});\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n RemoteService[] services) throws ValidationException {\n super(identity, type, details, null, services);\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n RemoteService[] services, RemoteDevice[] embeddedDevices) throws ValidationException {\n super(identity, type, details, null, services, embeddedDevices);\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, RemoteService service) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, new RemoteService[]{service});\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, RemoteService service, RemoteDevice embeddedDevice) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, new RemoteService[]{service}, new RemoteDevice[]{embeddedDevice});\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, RemoteService[] services) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, services);\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, RemoteService[] services, RemoteDevice[] embeddedDevices) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, services, embeddedDevices);\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, RemoteService service) throws ValidationException {\n super(identity, type, details, icons, new RemoteService[]{service});\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, RemoteService service, RemoteDevice embeddedDevice) throws ValidationException {\n super(identity, type, details, icons, new RemoteService[]{service}, new RemoteDevice[]{embeddedDevice});\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, RemoteService[] services) throws ValidationException {\n super(identity, type, details, icons, services);\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, RemoteService[] services, RemoteDevice[] embeddedDevices) throws ValidationException {\n super(identity, type, details, icons, services, embeddedDevices);\n }\n\n public RemoteDevice(RemoteDeviceIdentity identity, UDAVersion version, DeviceType type, DeviceDetails details,\n Icon[] icons, RemoteService[] services, RemoteDevice[] embeddedDevices) throws ValidationException {\n super(identity, version, type, details, icons, services, embeddedDevices);\n }\n\n @Override\n public RemoteService[] getServices() {\n return this.services != null ? this.services : new RemoteService[0];\n }\n\n @Override\n public RemoteDevice[] getEmbeddedDevices() {\n return this.embeddedDevices != null ? this.embeddedDevices : new RemoteDevice[0];\n }\n\n public URL normalizeURI(URI relativeOrAbsoluteURI) {\n\n // TODO: I have one device (Netgear 834DG DSL Router) that sends a , and even that is wrong (port)!\n // This can be fixed by \"re-enabling\" UPnP in the upnpService after a reboot, it will then use the right port...\n // return URIUtil.createAbsoluteURL(getDescriptorURL(), relativeOrAbsoluteURI);\n\n if (getDetails() != null && getDetails().getBaseURL() != null) {\n // If we have an , all URIs are relative to it\n return URIUtil.createAbsoluteURL(getDetails().getBaseURL(), relativeOrAbsoluteURI);\n } else {\n // Otherwise, they are relative to the descriptor location\n return URIUtil.createAbsoluteURL(getIdentity().getDescriptorURL(), relativeOrAbsoluteURI);\n }\n\n }\n\n @Override\n public RemoteDevice newInstance(UDN udn, UDAVersion version, DeviceType type, DeviceDetails details,\n Icon[] icons, RemoteService[] services,\n List embeddedDevices) throws ValidationException {\n return new RemoteDevice(\n new RemoteDeviceIdentity(udn, getIdentity()),\n version, type, details, icons,\n services,\n embeddedDevices.size() > 0 ? embeddedDevices.toArray(new RemoteDevice[embeddedDevices.size()]) : null\n );\n }\n\n @Override\n public RemoteService newInstance(ServiceType serviceType, ServiceId serviceId,\n URI descriptorURI, URI controlURI, URI eventSubscriptionURI,\n Action[] actions, StateVariable[] stateVariables) throws ValidationException {\n return new RemoteService(\n serviceType, serviceId,\n descriptorURI, controlURI, eventSubscriptionURI,\n actions, stateVariables\n );\n }\n\n @Override\n public RemoteDevice[] toDeviceArray(Collection col) {\n return col.toArray(new RemoteDevice[col.size()]);\n }\n\n @Override\n public RemoteService[] newServiceArray(int size) {\n return new RemoteService[size];\n }\n\n @Override\n public RemoteService[] toServiceArray(Collection col) {\n return col.toArray(new RemoteService[col.size()]);\n }\n\n @Override\n public Resource[] discoverResources(Namespace namespace) {\n List discovered = new ArrayList<>();\n\n // Services\n for (RemoteService service : getServices()) {\n \tif(service == null) continue;\n discovered.add(new ServiceEventCallbackResource(namespace.getEventCallbackPath(service), service));\n }\n\n // Embedded devices\n if (hasEmbeddedDevices()) {\n for (Device embeddedDevice : getEmbeddedDevices()) {\n\t\t\t\tif(embeddedDevice == null) continue;\n discovered.addAll(Arrays.asList(embeddedDevice.discoverResources(namespace)));\n }\n }\n\n return discovered.toArray(new Resource[discovered.size()]);\n }\n\n @Override\n public RemoteDevice getRoot() {\n if (isRoot()) return this;\n RemoteDevice current = this;\n while (current.getParentDevice() != null) {\n current = current.getParentDevice();\n }\n return current;\n }\n\n @Override\n public RemoteDevice findDevice(UDN udn) {\n return find(udn, this);\n }\n\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/protocol/ProtocolFactory.java\npublic interface ProtocolFactory {\n\n public UpnpService getUpnpService();\n\n /**\n * Creates a {@link org.fourthline.cling.protocol.async.ReceivingNotification},\n * {@link org.fourthline.cling.protocol.async.ReceivingSearch},\n * or {@link org.fourthline.cling.protocol.async.ReceivingSearchResponse} protocol.\n *\n * @param message The incoming message, either {@link org.fourthline.cling.model.message.UpnpRequest} or\n * {@link org.fourthline.cling.model.message.UpnpResponse}.\n * @return The appropriate protocol that handles the messages or null if the message should be dropped.\n * @throws ProtocolCreationException If no protocol could be found for the message.\n */\n public ReceivingAsync createReceivingAsync(IncomingDatagramMessage message) throws ProtocolCreationException;\n\n /**\n * Creates a {@link org.fourthline.cling.protocol.sync.ReceivingRetrieval},\n * {@link org.fourthline.cling.protocol.sync.ReceivingAction},\n * {@link org.fourthline.cling.protocol.sync.ReceivingSubscribe},\n * {@link org.fourthline.cling.protocol.sync.ReceivingUnsubscribe}, or\n * {@link org.fourthline.cling.protocol.sync.ReceivingEvent} protocol.\n *\n * @param requestMessage The incoming message, examime {@link org.fourthline.cling.model.message.UpnpRequest.Method}\n * to determine the protocol.\n * @return The appropriate protocol that handles the messages.\n * @throws ProtocolCreationException If no protocol could be found for the message.\n */\n public ReceivingSync createReceivingSync(StreamRequestMessage requestMessage) throws ProtocolCreationException;\n\n /**\n * Called by the {@link org.fourthline.cling.registry.Registry}, creates a protocol for announcing local devices.\n */\n public SendingNotificationAlive createSendingNotificationAlive(LocalDevice localDevice);\n\n /**\n * Called by the {@link org.fourthline.cling.registry.Registry}, creates a protocol for announcing local devices.\n */\n public SendingNotificationByebye createSendingNotificationByebye(LocalDevice localDevice);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for a multicast search.\n */\n public SendingSearch createSendingSearch(UpnpHeader searchTarget, int mxSeconds);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for executing an action.\n */\n public SendingAction createSendingAction(ActionInvocation actionInvocation, URL controlURL);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for GENA subscription.\n */\n public SendingSubscribe createSendingSubscribe(RemoteGENASubscription subscription) throws ProtocolCreationException;\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for GENA renewal.\n */\n public SendingRenewal createSendingRenewal(RemoteGENASubscription subscription);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for GENA unsubscription.\n */\n public SendingUnsubscribe createSendingUnsubscribe(RemoteGENASubscription subscription);\n\n /**\n * Called by the {@link org.fourthline.cling.model.gena.GENASubscription}, creates a protocol for sending GENA events.\n */\n public SendingEvent createSendingEvent(LocalGENASubscription subscription);\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/types/ServiceType.java\npublic class ServiceType {\n\n final private static Logger log = Logger.getLogger(ServiceType.class.getName());\n\n public static final Pattern PATTERN =\n Pattern.compile(\"urn:(\" + Constants.REGEX_NAMESPACE + \"):service:(\" + Constants.REGEX_TYPE + \"):([0-9]+).*\");\n\n // Note: 'serviceId' vs. 'service'\n public static final Pattern BROKEN_PATTERN =\n Pattern.compile(\"urn:(\" + Constants.REGEX_NAMESPACE + \"):serviceId:(\" + Constants.REGEX_TYPE + \"):([0-9]+).*\");\n\n private String namespace;\n private String type;\n private int version = 1;\n\n public ServiceType(String namespace, String type) {\n this(namespace, type, 1);\n }\n\n public ServiceType(String namespace, String type, int version) {\n\n if (namespace != null && !namespace.matches(Constants.REGEX_NAMESPACE)) {\n throw new IllegalArgumentException(\"Service type namespace contains illegal characters\");\n }\n this.namespace = namespace;\n\n if (type != null && !type.matches(Constants.REGEX_TYPE)) {\n throw new IllegalArgumentException(\"Service type suffix too long (64) or contains illegal characters\");\n }\n this.type = type;\n\n this.version = version;\n }\n\n public String getNamespace() {\n return namespace;\n }\n\n public String getType() {\n return type;\n }\n\n public int getVersion() {\n return version;\n }\n\n /**\n * @return Either a {@link UDAServiceType} or a more generic {@link ServiceType}.\n */\n public static ServiceType valueOf(String s) throws InvalidValueException {\n\n if (s == null)\n throw new InvalidValueException(\"Can't parse null string\");\n\n ServiceType serviceType = null;\n\n // Sometimes crazy UPnP devices deliver spaces in a URN, don't ask...\n s = s.replaceAll(\"\\\\s\", \"\");\n\n // First try UDAServiceType parse\n try {\n serviceType = UDAServiceType.valueOf(s);\n } catch (Exception ex) {\n // Ignore\n }\n\n if (serviceType != null)\n return serviceType;\n\n // Now try a generic ServiceType parse\n try {\n Matcher matcher = ServiceType.PATTERN.matcher(s);\n if (matcher.matches() && matcher.groupCount() >= 3) {\n return new ServiceType(matcher.group(1), matcher.group(2), Integer.valueOf(matcher.group(3)));\n }\n\n matcher = ServiceType.BROKEN_PATTERN.matcher(s);\n if (matcher.matches() && matcher.groupCount() >= 3) {\n return new ServiceType(matcher.group(1), matcher.group(2), Integer.valueOf(matcher.group(3)));\n }\n\n // TODO: UPNP VIOLATION: EyeTV Netstream uses colons in service type token\n // urn:schemas-microsoft-com:service:pbda:tuner:1\n matcher = Pattern.compile(\"urn:(\" + Constants.REGEX_NAMESPACE + \"):service:(.+?):([0-9]+).*\").matcher(s);\n if (matcher.matches() && matcher.groupCount() >= 3) {\n String cleanToken = matcher.group(2).replaceAll(\"[^a-zA-Z_0-9\\\\-]\", \"-\");\n log.warning(\n \"UPnP specification violation, replacing invalid service type token '\"\n + matcher.group(2)\n + \"' with: \"\n + cleanToken\n );\n return new ServiceType(matcher.group(1), cleanToken, Integer.valueOf(matcher.group(3)));\n }\n\n // TODO: UPNP VIOLATION: Ceyton InfiniTV uses colons in service type token and 'serviceId' instead of 'service'\n // urn:schemas-opencable-com:serviceId:dri2:debug:1\n matcher = Pattern.compile(\"urn:(\" + Constants.REGEX_NAMESPACE + \"):serviceId:(.+?):([0-9]+).*\").matcher(s);\n if (matcher.matches() && matcher.groupCount() >= 3) {\n String cleanToken = matcher.group(2).replaceAll(\"[^a-zA-Z_0-9\\\\-]\", \"-\");\n log.warning(\n \"UPnP specification violation, replacing invalid service type token '\"\n + matcher.group(2)\n + \"' with: \"\n + cleanToken\n );\n return new ServiceType(matcher.group(1), cleanToken, Integer.valueOf(matcher.group(3)));\n }\n } catch (RuntimeException e) {\n throw new InvalidValueException(String.format(\n \"Can't parse service type string (namespace/type/version) '%s': %s\", s, e.toString()\n ));\n }\n\n throw new InvalidValueException(\"Can't parse service type string (namespace/type/version): \" + s);\n }\n\n /**\n * @return true if this type's namespace/name matches the other type's namespace/name and\n * this type's version is equal or higher than the given types version.\n */\n public boolean implementsVersion(ServiceType that) {\n if (that == null) return false;\n if (!namespace.equals(that.namespace)) return false;\n if (!type.equals(that.type)) return false;\n if (version < that.version) return false;\n return true;\n }\n\n public String toFriendlyString() {\n return getNamespace() + \":\" + getType() + \":\" + getVersion();\n }\n\n @Override\n public String toString() {\n return \"urn:\" + getNamespace() + \":service:\" + getType() + \":\" + getVersion();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || !(o instanceof ServiceType)) return false;\n\n ServiceType that = (ServiceType) o;\n\n if (version != that.version) return false;\n if (!namespace.equals(that.namespace)) return false;\n if (!type.equals(that.type)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = namespace.hashCode();\n result = 31 * result + type.hashCode();\n result = 31 * result + version;\n return result;\n }\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/types/UDN.java\npublic class UDN {\n\n final private static Logger log = Logger.getLogger(UDN.class.getName());\n\n public static final String PREFIX = \"uuid:\";\n\n private String identifierString;\n\n /**\n * @param identifierString The identifier string without the \"uuid:\" prefix.\n */\n public UDN(String identifierString) {\n this.identifierString = identifierString;\n }\n\n public UDN(UUID uuid) {\n this.identifierString = uuid.toString();\n }\n\n public boolean isUDA11Compliant() {\n try {\n UUID.fromString(identifierString);\n return true;\n } catch (IllegalArgumentException ex) {\n return false;\n }\n }\n\n public String getIdentifierString() {\n return identifierString;\n }\n\n public static UDN valueOf(String udnString) {\n return new UDN(udnString.startsWith(PREFIX) ? udnString.substring(PREFIX.length()) : udnString);\n }\n\n /**\n * Generates a global unique identifier that is the same every time this method is invoked on the same machine with\n * the same argument.\n *

\n * This method combines the first non-loopback network interface's MAC address with given salt to generate a\n * globally unique identifier. In other words, every time you call this method with the same salt on the same\n * machine, you get the same identifier. If you use the same salt on a different machine, a different identifier\n * will be generated.\n *

\n *

\n * Note for Android users: This method does not generate unique identifiers on Android devices and will\n * throw an exception. We can't get details such as the hostname or MAC address on Android. Instead,\n * construct a UDN with new UDN(UUID). When your application is first started, generate all\n * UUIDs needed for your UPnP devices and store them in your Android preferences. Then, use the stored\n * UUID to create a UDN every time your application starts.\n *

\n *

\n * Control points can remember your device's identifier, it will and should be the same every time\n * your device is powered up.\n *

\n *\n * @param salt An arbitrary string that uniquely identifies the device on the current system, e.g. \"MyMediaServer\".\n * @return A global unique identifier, stable for the current system and salt.\n */\n public static UDN uniqueSystemIdentifier(String salt) {\n StringBuilder systemSalt = new StringBuilder();\n\n // Bug: On Android, NetworkInterface.isLoopback() isn't implemented\n if (!ModelUtil.ANDROID_RUNTIME) {\n try {\n systemSalt.append(new String(ModelUtil.getFirstNetworkInterfaceHardwareAddress(), \"UTF-8\"));\n } catch (UnsupportedEncodingException ex) {\n // If your JVM doesn't support utf-8, you have bigger problems\n throw new RuntimeException(ex);\n }\n } else {\n throw new RuntimeException(\n \"This method does not create a unique identifier on Android, see the Javadoc and \" +\n \"use new UDN(UUID) instead!\"\n );\n }\n\n try {\n byte[] hash = MessageDigest.getInstance(\"MD5\").digest(systemSalt.toString().getBytes(\"UTF-8\"));\n return new UDN(\n new UUID(\n new BigInteger(-1, hash).longValue(),\n salt.hashCode()\n )\n );\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n @Override\n public String toString() {\n return PREFIX + getIdentifierString();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || !(o instanceof UDN)) return false;\n UDN udn = (UDN) o;\n return identifierString.equals(udn.identifierString);\n }\n\n @Override\n public int hashCode() {\n return identifierString.hashCode();\n }\n\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/meta/LocalDevice.java\npublic class LocalDevice extends Device {\n\n final private DeviceDetailsProvider deviceDetailsProvider;\n\n public LocalDevice(DeviceIdentity identity) throws ValidationException {\n super(identity);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n LocalService service) throws ValidationException {\n super(identity, type, details, null, new LocalService[]{service});\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetailsProvider deviceDetailsProvider,\n LocalService service) throws ValidationException {\n super(identity, type, null, null, new LocalService[]{service});\n this.deviceDetailsProvider = deviceDetailsProvider;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetailsProvider deviceDetailsProvider,\n LocalService service, LocalDevice embeddedDevice) throws ValidationException {\n super(identity, type, null, null, new LocalService[]{service}, new LocalDevice[]{embeddedDevice});\n this.deviceDetailsProvider = deviceDetailsProvider;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n LocalService service, LocalDevice embeddedDevice) throws ValidationException {\n super(identity, type, details, null, new LocalService[]{service}, new LocalDevice[]{embeddedDevice});\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n LocalService[] services) throws ValidationException {\n super(identity, type, details, null, services);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n LocalService[] services, LocalDevice[] embeddedDevices) throws ValidationException {\n super(identity, type, details, null, services, embeddedDevices);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, LocalService service) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, new LocalService[]{service});\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, LocalService service, LocalDevice embeddedDevice) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, new LocalService[]{service}, new LocalDevice[]{embeddedDevice});\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, LocalService[] services) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, services);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetailsProvider deviceDetailsProvider,\n Icon icon, LocalService[] services) throws ValidationException {\n super(identity, type, null, new Icon[]{icon}, services);\n this.deviceDetailsProvider = deviceDetailsProvider;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon icon, LocalService[] services, LocalDevice[] embeddedDevices) throws ValidationException {\n super(identity, type, details, new Icon[]{icon}, services, embeddedDevices);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, LocalService service) throws ValidationException {\n super(identity, type, details, icons, new LocalService[]{service});\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, LocalService service, LocalDevice embeddedDevice) throws ValidationException {\n super(identity, type, details, icons, new LocalService[]{service}, new LocalDevice[]{embeddedDevice});\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetailsProvider deviceDetailsProvider,\n Icon[] icons, LocalService service, LocalDevice embeddedDevice) throws ValidationException {\n super(identity, type, null, icons, new LocalService[]{service}, new LocalDevice[]{embeddedDevice});\n this.deviceDetailsProvider = deviceDetailsProvider;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, LocalService[] services) throws ValidationException {\n super(identity, type, details, icons, services);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, DeviceType type, DeviceDetails details,\n Icon[] icons, LocalService[] services, LocalDevice[] embeddedDevices) throws ValidationException {\n super(identity, type, details, icons, services, embeddedDevices);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, UDAVersion version, DeviceType type, DeviceDetails details,\n Icon[] icons, LocalService[] services, LocalDevice[] embeddedDevices) throws ValidationException {\n super(identity, version, type, details, icons, services, embeddedDevices);\n this.deviceDetailsProvider = null;\n }\n\n public LocalDevice(DeviceIdentity identity, UDAVersion version, DeviceType type, DeviceDetailsProvider deviceDetailsProvider,\n Icon[] icons, LocalService[] services, LocalDevice[] embeddedDevices) throws ValidationException {\n super(identity, version, type, null, icons, services, embeddedDevices);\n this.deviceDetailsProvider = deviceDetailsProvider;\n }\n\n public DeviceDetailsProvider getDeviceDetailsProvider() {\n return deviceDetailsProvider;\n }\n\n @Override\n public DeviceDetails getDetails(RemoteClientInfo info) {\n if (getDeviceDetailsProvider() != null) {\n return getDeviceDetailsProvider().provide(info);\n }\n return this.getDetails();\n }\n\n @Override\n public LocalService[] getServices() {\n return this.services != null ? this.services : new LocalService[0];\n }\n\n @Override\n public LocalDevice[] getEmbeddedDevices() {\n return this.embeddedDevices != null ? this.embeddedDevices : new LocalDevice[0];\n }\n\n @Override\n public LocalDevice newInstance(UDN udn, UDAVersion version, DeviceType type, DeviceDetails details,\n Icon[] icons, LocalService[] services, List embeddedDevices)\n throws ValidationException {\n return new LocalDevice(\n new DeviceIdentity(udn, getIdentity().getMaxAgeSeconds()),\n version, type, details, icons,\n services,\n embeddedDevices.size() > 0 ? embeddedDevices.toArray(new LocalDevice[embeddedDevices.size()]) : null\n );\n }\n\n @Override\n public LocalService newInstance(ServiceType serviceType, ServiceId serviceId,\n URI descriptorURI, URI controlURI, URI eventSubscriptionURI,\n Action[] actions, StateVariable[] stateVariables) throws ValidationException {\n return new LocalService(\n serviceType, serviceId,\n actions, stateVariables\n );\n }\n\n @Override\n public LocalDevice[] toDeviceArray(Collection col) {\n return col.toArray(new LocalDevice[col.size()]);\n }\n\n @Override\n public LocalService[] newServiceArray(int size) {\n return new LocalService[size];\n }\n\n @Override\n public LocalService[] toServiceArray(Collection col) {\n return col.toArray(new LocalService[col.size()]);\n }\n\n @Override\n public List validate() {\n List errors = new ArrayList<>();\n errors.addAll(super.validate());\n\n // We have special rules for local icons, the URI must always be a relative path which will\n // be added to the device base URI!\n if (hasIcons()) {\n for (Icon icon : getIcons()) {\n if (icon.getUri().isAbsolute()) {\n errors.add(new ValidationError(\n getClass(),\n \"icons\",\n \"Local icon URI can not be absolute: \" + icon.getUri()\n ));\n }\n if (icon.getUri().toString().contains(\"../\")) {\n errors.add(new ValidationError(\n getClass(),\n \"icons\",\n \"Local icon URI must not contain '../': \" + icon.getUri()\n ));\n }\n if (icon.getUri().toString().startsWith(\"/\")) {\n errors.add(new ValidationError(\n getClass(),\n \"icons\",\n \"Local icon URI must not start with '/': \" + icon.getUri()\n ));\n }\n }\n }\n\n return errors;\n }\n\n @Override\n public Resource[] discoverResources(Namespace namespace) {\n List discovered = new ArrayList<>();\n\n // Device\n if (isRoot()) {\n // This should guarantee that each logical local device tree (with all its embedded devices) has only\n // one device descriptor resource - because only one device in the tree isRoot().\n discovered.add(new DeviceDescriptorResource(namespace.getDescriptorPath(this), this));\n }\n\n // Services\n for (LocalService service : getServices()) {\n\n discovered.add(\n new ServiceDescriptorResource(namespace.getDescriptorPath(service), service)\n );\n\n // Control\n discovered.add(\n new ServiceControlResource(namespace.getControlPath(service), service)\n );\n\n // Event subscription\n discovered.add(\n new ServiceEventSubscriptionResource(namespace.getEventSubscriptionPath(service), service)\n );\n\n }\n\n // Icons\n for (Icon icon : getIcons()) {\n discovered.add(new IconResource(namespace.prefixIfRelative(this, icon.getUri()), icon));\n }\n\n // Embedded devices\n if (hasEmbeddedDevices()) {\n for (Device embeddedDevice : getEmbeddedDevices()) {\n discovered.addAll(Arrays.asList(embeddedDevice.discoverResources(namespace)));\n }\n }\n\n return discovered.toArray(new Resource[discovered.size()]);\n }\n\n @Override\n public LocalDevice getRoot() {\n if (isRoot()) return this;\n LocalDevice current = this;\n while (current.getParentDevice() != null) {\n current = current.getParentDevice();\n }\n return current;\n }\n\n @Override\n public LocalDevice findDevice(UDN udn) {\n return find(udn, this);\n }\n\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/meta/RemoteDeviceIdentity.java\npublic class RemoteDeviceIdentity extends DeviceIdentity {\n\n final private URL descriptorURL;\n final private byte[] interfaceMacAddress;\n final private InetAddress discoveredOnLocalAddress;\n\n public RemoteDeviceIdentity(UDN udn, RemoteDeviceIdentity template) {\n this(udn, template.getMaxAgeSeconds(), template.getDescriptorURL(), template.getInterfaceMacAddress(), template.getDiscoveredOnLocalAddress());\n }\n\n public RemoteDeviceIdentity(UDN udn, Integer maxAgeSeconds, URL descriptorURL, byte[] interfaceMacAddress, InetAddress discoveredOnLocalAddress) {\n super(udn, maxAgeSeconds);\n this.descriptorURL = descriptorURL;\n this.interfaceMacAddress = interfaceMacAddress;\n this.discoveredOnLocalAddress = discoveredOnLocalAddress;\n }\n\n public RemoteDeviceIdentity(IncomingNotificationRequest notificationRequest) {\n this(notificationRequest.getUDN(),\n notificationRequest.getMaxAge(),\n notificationRequest.getLocationURL(),\n notificationRequest.getInterfaceMacHeader(),\n notificationRequest.getLocalAddress()\n );\n }\n\n public RemoteDeviceIdentity(IncomingSearchResponse searchResponse) {\n this(searchResponse.getRootDeviceUDN(),\n searchResponse.getMaxAge(),\n searchResponse.getLocationURL(),\n searchResponse.getInterfaceMacHeader(),\n searchResponse.getLocalAddress()\n );\n }\n\n public URL getDescriptorURL() {\n return descriptorURL;\n }\n\n public byte[] getInterfaceMacAddress() {\n return interfaceMacAddress;\n }\n\n public InetAddress getDiscoveredOnLocalAddress() {\n return discoveredOnLocalAddress;\n }\n\n public byte[] getWakeOnLANBytes() {\n if (getInterfaceMacAddress() == null) return null;\n byte[] bytes = new byte[6 + 16 * getInterfaceMacAddress().length];\n for (int i = 0; i < 6; i++) {\n bytes[i] = (byte) 0xff;\n }\n for (int i = 6; i < bytes.length; i += getInterfaceMacAddress().length) {\n System.arraycopy(getInterfaceMacAddress(), 0, bytes, i, getInterfaceMacAddress().length);\n }\n return bytes;\n }\n\n @Override\n public String toString() {\n // Performance optimization, so we don't have to wrap all log(\"foo \" + device) calls with isLoggable\n\t\tif(ModelUtil.ANDROID_RUNTIME) {\n return \"(RemoteDeviceIdentity) UDN: \" + getUdn() + \", Descriptor: \" + getDescriptorURL();\n }\n return \"(\" + getClass().getSimpleName() + \") UDN: \" + getUdn() + \", Descriptor: \" + getDescriptorURL();\n }\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/types/DeviceType.java\npublic class DeviceType {\n\n final private static Logger log = Logger.getLogger(DeviceType.class.getName());\n\n public static final String UNKNOWN = \"UNKNOWN\";\n\n public static final Pattern PATTERN =\n Pattern.compile(\"urn:(\" + Constants.REGEX_NAMESPACE + \"):device:(\" + Constants.REGEX_TYPE + \"):([0-9]+).*\");\n\n private String namespace;\n private String type;\n private int version = 1;\n\n public DeviceType(String namespace, String type) {\n this(namespace, type, 1);\n }\n\n public DeviceType(String namespace, String type, int version) {\n if (namespace != null && !namespace.matches(Constants.REGEX_NAMESPACE)) {\n throw new IllegalArgumentException(\"Device type namespace contains illegal characters\");\n }\n this.namespace = namespace;\n\n if (type != null && !type.matches(Constants.REGEX_TYPE)) {\n throw new IllegalArgumentException(\"Device type suffix too long (64) or contains illegal characters\");\n }\n this.type = type;\n\n this.version = version;\n }\n\n public String getNamespace() {\n return namespace;\n }\n\n public String getType() {\n return type;\n }\n\n public int getVersion() {\n return version;\n }\n\n /**\n * @return Either a {@link UDADeviceType} or a more generic {@link DeviceType}.\n */\n public static DeviceType valueOf(String s) throws InvalidValueException {\n\n DeviceType deviceType = null;\n\n // Sometimes crazy UPnP devices deliver spaces in a URN, don't ask...\n s = s.replaceAll(\"\\\\s\", \"\");\n\n // First try UDADeviceType parse\n try {\n deviceType = UDADeviceType.valueOf(s);\n } catch (Exception ex) {\n // Ignore\n }\n\n if (deviceType != null)\n return deviceType;\n\n try {\n // Now try a generic DeviceType parse\n Matcher matcher = PATTERN.matcher(s);\n if (matcher.matches()) {\n return new DeviceType(matcher.group(1), matcher.group(2), Integer.valueOf(matcher.group(3)));\n }\n\n // TODO: UPNP VIOLATION: Escient doesn't provide any device type token\n // urn:schemas-upnp-org:device::1\n matcher = Pattern.compile(\"urn:(\" + Constants.REGEX_NAMESPACE + \"):device::([0-9]+).*\").matcher(s);\n if (matcher.matches() && matcher.groupCount() >= 2) {\n log.warning(\"UPnP specification violation, no device type token, defaulting to \" + UNKNOWN + \": \" + s);\n return new DeviceType(matcher.group(1), UNKNOWN, Integer.valueOf(matcher.group(2)));\n }\n\n // TODO: UPNP VIOLATION: EyeTV Netstream uses colons in device type token\n // urn:schemas-microsoft-com:service:pbda:tuner:1\n matcher = Pattern.compile(\"urn:(\" + Constants.REGEX_NAMESPACE + \"):device:(.+?):([0-9]+).*\").matcher(s);\n if (matcher.matches() && matcher.groupCount() >= 3) {\n String cleanToken = matcher.group(2).replaceAll(\"[^a-zA-Z_0-9\\\\-]\", \"-\");\n log.warning(\n \"UPnP specification violation, replacing invalid device type token '\"\n + matcher.group(2)\n + \"' with: \"\n + cleanToken\n );\n return new DeviceType(matcher.group(1), cleanToken, Integer.valueOf(matcher.group(3)));\n }\n } catch (RuntimeException e) {\n throw new InvalidValueException(String.format(\n \"Can't parse device type string (namespace/type/version) '%s': %s\", s, e.toString()\n ));\n }\n\n throw new InvalidValueException(\"Can't parse device type string (namespace/type/version): \" + s);\n }\n\n public boolean implementsVersion(DeviceType that) {\n if (!namespace.equals(that.namespace)) return false;\n if (!type.equals(that.type)) return false;\n if (version < that.version) return false;\n return true;\n }\n\n public String getDisplayString() {\n return getType();\n }\n\n @Override\n public String toString() {\n return \"urn:\" + getNamespace() + \":device:\" + getType()+ \":\" + getVersion();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || !(o instanceof DeviceType)) return false;\n\n DeviceType that = (DeviceType) o;\n\n if (version != that.version) return false;\n if (!namespace.equals(that.namespace)) return false;\n if (!type.equals(that.type)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = namespace.hashCode();\n result = 31 * result + type.hashCode();\n result = 31 * result + version;\n return result;\n }\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/meta/Service.java\npublic abstract class Service {\n\n\tfinal private static Logger log = Logger.getLogger(Service.class.getName());\n\n final private ServiceType serviceType;\n final private ServiceId serviceId;\n\n\n final private Map actions = new HashMap<>();\n final private Map stateVariables = new HashMap<>();\n\n // Package mutable state\n private D device;\n\n public Service(ServiceType serviceType, ServiceId serviceId) throws ValidationException {\n this(serviceType, serviceId, null, null);\n }\n\n public Service(ServiceType serviceType, ServiceId serviceId,\n Action[] actions, StateVariable[] stateVariables) throws ValidationException {\n\n this.serviceType = serviceType;\n this.serviceId = serviceId;\n\n if (actions != null) {\n for (Action action : actions) {\n this.actions.put(action.getName(), action);\n action.setService(this);\n }\n }\n\n if (stateVariables != null) {\n for (StateVariable stateVariable : stateVariables) {\n this.stateVariables.put(stateVariable.getName(), stateVariable);\n stateVariable.setService(this);\n }\n }\n\n }\n\n public ServiceType getServiceType() {\n return serviceType;\n }\n\n public ServiceId getServiceId() {\n return serviceId;\n }\n\n public boolean hasActions() {\n return getActions() != null && getActions().length > 0;\n }\n\n public Action[] getActions() {\n return actions == null ? null : actions.values().toArray(new Action[actions.values().size()]);\n }\n\n public boolean hasStateVariables() {\n // TODO: Spec says always has to have at least one...\n return getStateVariables() != null && getStateVariables().length > 0;\n }\n\n public StateVariable[] getStateVariables() {\n return stateVariables == null ? null : stateVariables.values().toArray(new StateVariable[stateVariables.values().size()]);\n }\n\n public D getDevice() {\n return device;\n }\n\n void setDevice(D device) {\n if (this.device != null)\n throw new IllegalStateException(\"Final value has been set already, model is immutable\");\n this.device = device;\n }\n\n public Action getAction(String name) {\n return actions == null ? null : actions.get(name);\n }\n\n public StateVariable getStateVariable(String name) {\n // Some magic necessary for the deprecated 'query state variable' action stuff\n if (QueryStateVariableAction.VIRTUAL_STATEVARIABLE_INPUT.equals(name)) {\n return new StateVariable(\n QueryStateVariableAction.VIRTUAL_STATEVARIABLE_INPUT,\n new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype())\n );\n }\n if (QueryStateVariableAction.VIRTUAL_STATEVARIABLE_OUTPUT.equals(name)) {\n return new StateVariable(\n QueryStateVariableAction.VIRTUAL_STATEVARIABLE_OUTPUT,\n new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype())\n );\n }\n return stateVariables == null ? null : stateVariables.get(name);\n }\n\n public StateVariable getRelatedStateVariable(ActionArgument argument) {\n return getStateVariable(argument.getRelatedStateVariableName());\n }\n\n public Datatype getDatatype(ActionArgument argument) {\n return getRelatedStateVariable(argument).getTypeDetails().getDatatype();\n }\n\n public ServiceReference getReference() {\n return new ServiceReference(getDevice().getIdentity().getUdn(), getServiceId());\n }\n\n public List validate() {\n List errors = new ArrayList<>();\n\n if (getServiceType() == null) {\n errors.add(new ValidationError(\n getClass(),\n \"serviceType\",\n \"Service type/info is required\"\n ));\n }\n\n if (getServiceId() == null) {\n errors.add(new ValidationError(\n getClass(),\n \"serviceId\",\n \"Service ID is required\"\n ));\n }\n\n // TODO: If the service has no evented variables, it should not have an event subscription URL, which means\n // the url element in the device descriptor must be present, but empty!!!!\n\n /* TODO: This doesn't fit into our meta model, we don't know if a service has state variables until\n we completely hydrate it from a service descriptor\n if (getStateVariables().length == 0) {\n errors.add(new ValidationError(\n getClass(),\n \"stateVariables\",\n \"Service must have at least one state variable\"\n ));\n }\n */\n if (hasStateVariables()) {\n for (StateVariable stateVariable : getStateVariables()) {\n errors.addAll(stateVariable.validate());\n }\n }\n\n if (hasActions()) {\n for (Action action : getActions()) {\n\n // Instead of bailing out here, we try to continue if an action is invalid\n // errors.addAll(action.validate());\n\n List actionErrors = action.validate();\n \tif(actionErrors.size() > 0) {\n actions.remove(action.getName()); // Remove it\n log.warning(\"Discarding invalid action of service '\" + getServiceId() + \"': \" + action.getName());\n for (ValidationError actionError : actionErrors) {\n log.warning(\"Invalid action '\" + action.getName() + \"': \" + actionError);\n }\n \t}\n }\n }\n\n return errors;\n }\n\n public abstract Action getQueryStateVariableAction();\n\n @Override\n public String toString() {\n return \"(\" + getClass().getSimpleName() + \") ServiceId: \" + getServiceId();\n }\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/UpnpServiceConfiguration.java\npublic interface UpnpServiceConfiguration {\n\n /**\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.NetworkAddressFactory} interface.\n */\n public NetworkAddressFactory createNetworkAddressFactory();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.transport.spi.DatagramProcessor}.\n */\n public DatagramProcessor getDatagramProcessor();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.transport.spi.SOAPActionProcessor}.\n */\n public SOAPActionProcessor getSoapActionProcessor();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.transport.spi.GENAEventProcessor}.\n */\n public GENAEventProcessor getGenaEventProcessor();\n\n /**\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamClient} interface.\n */\n public StreamClient createStreamClient();\n\n /**\n * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.MulticastReceiver} interface.\n */\n public MulticastReceiver createMulticastReceiver(NetworkAddressFactory networkAddressFactory);\n\n /**\n * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.DatagramIO} interface.\n */\n public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory);\n\n /**\n * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamServer} interface.\n */\n public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory);\n\n /**\n * @return The executor which runs the listening background threads for multicast datagrams.\n */\n public Executor getMulticastReceiverExecutor();\n\n /**\n * @return The executor which runs the listening background threads for unicast datagrams.\n */\n public Executor getDatagramIOExecutor();\n\n /**\n * @return The executor which runs the listening background threads for HTTP requests.\n */\n public ExecutorService getStreamServerExecutorService();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.binding.xml.DeviceDescriptorBinder} for the UPnP 1.0 Device Architecture..\n */\n public DeviceDescriptorBinder getDeviceDescriptorBinderUDA10();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.binding.xml.ServiceDescriptorBinder} for the UPnP 1.0 Device Architecture..\n */\n public ServiceDescriptorBinder getServiceDescriptorBinderUDA10();\n\n /**\n * Returns service types that can be handled by this UPnP stack, all others will be ignored.\n *

\n * Return null to completely disable remote device and service discovery.\n * All incoming notifications and search responses will then be dropped immediately.\n * This is mostly useful in applications that only provide services with no (remote)\n * control point functionality.\n *

\n *

\n * Note that a discovered service type with version 2 or 3 will match an exclusive\n * service type with version 1. UPnP services are required to be backwards\n * compatible, version 2 is a superset of version 1, and version 3 is a superset\n * of version 2, etc.\n *

\n *\n * @return An array of service types that are exclusively discovered, no other service will\n * be discovered. A null return value will disable discovery!\n * An empty array means all services will be discovered.\n */\n public ServiceType[] getExclusiveServiceTypes();\n\n /**\n * @return The time in milliseconds to wait between each registry maintenance operation.\n */\n public int getRegistryMaintenanceIntervalMillis();\n \n /**\n * Optional setting for flooding alive NOTIFY messages for local devices.\n *

\n * Use this to advertise local devices at the specified interval, independent of its\n * {@link org.fourthline.cling.model.meta.DeviceIdentity#maxAgeSeconds} value. Note\n * that this will increase network traffic.\n *

\n *

\n * Some control points (XBMC and other Platinum UPnP SDK based devices, OPPO-93) seem\n * to not properly receive SSDP M-SEARCH replies sent by Cling, but will handle NOTIFY\n * alive messages just fine.\n *

\n *\n * @return The time in milliseconds for ALIVE message intervals, set to 0 to disable\n */\n public int getAliveIntervalMillis();\n\n /**\n * Ignore the received event subscription timeout from remote control points.\n *

\n * Some control points have trouble renewing subscriptions properly; enabling this option\n * in conjunction with a high value for\n * {@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS}\n * ensures that your devices will not disappear on such control points.\n *

\n *\n * @return true if the timeout in incoming event subscriptions should be ignored\n * and the default value ({@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS})\n * should be used instead.\n *\n */\n public boolean isReceivedSubscriptionTimeoutIgnored();\n\n /**\n * Returns the time in seconds a remote device will be registered until it is expired.\n *

\n * This setting is useful on systems which do not support multicast networking\n * (Android on HTC phones, for hiker). On such a system you will not receive messages when a\n * remote device disappears from the network and you will not receive its periodic heartbeat\n * alive messages. Only an initial search response (UDP unicast) has been received from the\n * remote device, with its proposed maximum age. To avoid (early) expiration of the remote\n * device, you can override its maximum age with this configuration setting, ignoring the\n * initial maximum age sent by the device. You most likely want to return\n * 0 in this case, so that the remote device is never expired unless you\n * manually remove it from the {@link org.fourthline.cling.registry.Registry}. You typically remove\n * the device when an action or GENA subscription request to the remote device failed.\n *

\n *\n * @return null (the default) to accept the remote device's proposed maximum age, or\n * 0 for unlimited age, or a value in seconds.\n */\n public Integer getRemoteDeviceMaxAgeSeconds();\n\n /**\n * Optional extra headers for device descriptor retrieval HTTP requests.\n *

\n * Some devices might require extra headers to recognize your control point, use this\n * method to set these headers. They will be used for every descriptor (XML) retrieval\n * HTTP request by Cling. See {@link org.fourthline.cling.model.profile.ClientInfo} for\n * action request messages.\n *

\n *\n * @param identity The (so far) discovered identity of the remote device.\n * @return null or extra HTTP headers.\n */\n public UpnpHeaders getDescriptorRetrievalHeaders(RemoteDeviceIdentity identity);\n\n /**\n * Optional extra headers for event subscription (almost HTTP) messages.\n *

\n * Some devices might require extra headers to recognize your control point, use this\n * method to set these headers for GENA subscriptions. Note that the headers will\n * not be applied to actual event messages, only subscribe, unsubscribe, and renewal.\n *

\n *\n * @return null or extra HTTP headers.\n */\n public UpnpHeaders getEventSubscriptionHeaders(RemoteService service);\n\n /**\n * @return The executor which runs the processing of asynchronous aspects of the UPnP stack (discovery).\n */\n public Executor getAsyncProtocolExecutor();\n\n /**\n * @return The executor service which runs the processing of synchronous aspects of the UPnP stack (description, control, GENA).\n */\n public ExecutorService getSyncProtocolExecutorService();\n\n /**\n * @return An instance of {@link org.fourthline.cling.model.Namespace} for this UPnP stack.\n */\n public Namespace getNamespace();\n\n /**\n * @return The executor which runs the background thread for maintaining the registry.\n */\n public Executor getRegistryMaintainerExecutor();\n\n /**\n * @return The executor which runs the notification threads of registry listeners.\n */\n public Executor getRegistryListenerExecutor();\n\n /**\n * Called by the {@link org.fourthline.cling.UpnpService} on shutdown, useful to e.g. shutdown thread pools.\n */\n public void shutdown();\n\n}\n\nclinglibrary/src/main/java/org/fourthline/cling/model/DiscoveryOptions.java\npublic class DiscoveryOptions {\n\n protected boolean advertised;\n protected boolean byeByeBeforeFirstAlive;\n\n /**\n * @param advertised If false, no alive notifications will be announced for\n * this device and it will not appear in search responses.\n */\n public DiscoveryOptions(boolean advertised) {\n this.advertised = advertised;\n }\n\n /**\n *\n * @param advertised If false, no alive notifications will be announced for\n * this device and it will not appear in search responses.\n * @param byeByeBeforeFirstAlive If true, a byebye NOTIFY message will be send before the\n * first alive NOTIFY message.\n */\n public DiscoveryOptions(boolean advertised, boolean byeByeBeforeFirstAlive) {\n this.advertised = advertised;\n this.byeByeBeforeFirstAlive = byeByeBeforeFirstAlive;\n }\n\n /**\n * @return true for regular advertisement with alive\n * messages and in search responses.\n */\n public boolean isAdvertised() {\n return advertised;\n }\n\n /**\n * @return true if a byebye NOTIFY message will be send before the\n * first alive NOTIFY message.\n */\n public boolean isByeByeBeforeFirstAlive() {\n return byeByeBeforeFirstAlive;\n }\n\n // Performance optimization on Android\n private static String simpleName = DiscoveryOptions.class.getSimpleName();\n\t@Override\n public String toString() {\n return \"(\" + simpleName + \")\" + \" advertised: \" + isAdvertised() + \" byebyeBeforeFirstAlive: \" + isByeByeBeforeFirstAlive();\n }\n}", "answers": [" all.addAll(remoteItems.get());"], "length": 5851, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "fb08a5e0-8c61-4bd4-91a6-1211260aec2b", "reasoning": "In RegistryImpl.java, the getDevices() method builds a set of all devices by adding local items, then should add remote items before returning an unmodifiable collection. The code currently ends after adding local items, so the next logical line is to add the remote items collection.", "reasoning_model_answer": "all.addAll(remoteItems.get());", "assistant_with_reasoning": "\nIn RegistryImpl.java, the getDevices() method builds a set of all devices by adding local items, then should add remote items before returning an unmodifiable collection. The code currently ends after adding local items, so the next logical line is to add the remote items collection.\n\nall.addAll(remoteItems.get());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.086, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37271, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "all.addAll(remoteItems.get());", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport edu.uky.cs.nil.sabre.Character;\nimport edu.uky.cs.nil.sabre.Settings;\nimport edu.uky.cs.nil.sabre.Signature;\nimport edu.uky.cs.nil.sabre.Utilities;\nimport edu.uky.cs.nil.sabre.comp.CompiledAction;\nimport edu.uky.cs.nil.sabre.comp.CompiledEvent;\nimport edu.uky.cs.nil.sabre.comp.CompiledFluent;\nimport edu.uky.cs.nil.sabre.comp.CompiledMapping;\nimport edu.uky.cs.nil.sabre.comp.CompiledProblem;\nimport edu.uky.cs.nil.sabre.logic.Clause;\nimport edu.uky.cs.nil.sabre.logic.Disjunction;\nimport edu.uky.cs.nil.sabre.logic.Effect;\nimport edu.uky.cs.nil.sabre.logic.False;\nimport edu.uky.cs.nil.sabre.logic.Parameter;\nimport edu.uky.cs.nil.sabre.logic.Precondition;\nimport edu.uky.cs.nil.sabre.logic.True;\nimport edu.uky.cs.nil.sabre.logic.Value;\nimport edu.uky.cs.nil.sabre.util.ImmutableSet;", "context": "src/edu/uky/cs/nil/sabre/ptree/EventList.java\npackage edu.uky.cs.nil.sabre.ptree;\n\n\n\n/**\n * A list of {@link CompiledEvent compiled events} (including dummy belief\n * update actions) and their effect for use in a {@link ProgressionTree\n * progression tree}.\n * \n * @author Stephen G. Ware\n */\nfinal class EventList implements Serializable {\n\n\t/**\n\t * A key for storing a belief update dummy action in a {@link HashMap\n\t * hashtable}.\n\t * \n\t * @author Stephen G. Ware\n\t */\n\tprivate final class UpdateKey implements Serializable {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1L;\n\t\t\n\t\t/** The character whose beliefs will be updated */\n\t\tpublic Character character;\n\t\t\n\t\t/** The fluent whose value will be set */\n\t\tpublic CompiledFluent fluent;\n\t\t\n\t\t/** The value to set the fluent to */\n\t\tpublic Value value;\n\t\t\n\t\t/**\n\t\t * Constructs a new dummy belief update action key.\n\t\t * \n\t\t * @param character the character whose beliefs will be updated\n\t\t * @param fluent the fluent whose value will be set\n\t\t * @param value the value to set the fluent to\n\t\t */\n\t\tpublic UpdateKey(Character character, CompiledFluent fluent, Value value) {\n\t\t\tthis.character = character;\n\t\t\tthis.fluent = fluent;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object other) {\n\t\t\tif(other instanceof UpdateKey) {\n\t\t\t\tUpdateKey otherKey = (UpdateKey) other;\n\t\t\t\treturn character.equals(otherKey.character) && fluent.equals(otherKey.fluent) && value.equals(otherKey.value);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn Utilities.hashCode(character, fluent, value);\n\t\t}\n\t}\n\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/** A list of all events by ID, including dummy belief update events */\n\tprivate final ArrayList events;\n\t\n\t/** A map of dummy belief update actions */\n\tprivate final HashMap updates;\n\t\n\t/** A key used to look up dummy belief update actions in {@link #updates} */\n\tprivate final UpdateKey key = new UpdateKey(null, null, null);\n\t\n\t/**\n\t * A table of each event's effect for each fluent; the first array is\n\t * indexed by {@link CompiledEvent#getID() the event ID}, and the second\n\t * array is indexed by {@link CompiledFluent#id the fluent ID}\n\t */\n\tprivate final Clause[][] effects;\n\t\n\t/**\n\t * Constructs a new event list.\n\t * \n\t * @param problem the compiled problem whose events will be indexed\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic EventList(CompiledProblem problem) {\n\t\tthis.events = new ArrayList<>((int) (((double) problem.events.size()) * 1.2));\n\t\tfor(CompiledEvent event : problem.events)\n\t\t\tthis.events.add(event);\n\t\tthis.updates = new HashMap<>(this.events.size() - problem.events.size());\n\t\tthis.effects = new Clause[problem.events.size()][problem.fluents.size()];\n\t\tfor(CompiledEvent event : problem.events)\n\t\t\tfor(CompiledFluent fluent : problem.fluents)\n\t\t\t\tthis.effects[event.getID()][fluent.id] = effect(event, fluent);\n\t}\n\t\n\tprivate static final Clause effect(CompiledEvent event, CompiledFluent fluent) {\n\t\tClause effect = event.getEffect(fluent);\n\t\treturn effect.equals(Clause.EMPTY) ? null : effect;\n\t}\n\t\n\t/**\n\t * Returns the compiled event with the given {@link CompiledEvent#getID()\n\t * ID number}, including any dummy belief update actions that have been\n\t * {@link #getUpdate(Character, CompiledFluent, Value) created} by this list.\n\t * \n\t * @param id the ID number of the event\n\t * @return the event with that ID number\n\t */\n\tpublic CompiledEvent getEvent(int id) {\n\t\treturn events.get(id);\n\t}\n\t\n\t/**\n\t * Returns a compiled action defined like a {@link\n\t * edu.uky.cs.nil.sabre.graph.DummyAction#update(Character, edu.uky.cs.nil.sabre.Event, edu.uky.cs.nil.sabre.State)\n\t * dummy belief update action}. The action always has {@link False#FALSE\n\t * false} as its precondition, a single effect setting a fluent to a value,\n\t * no consenting characters, and a single observing character whose beliefs\n\t * are being updated by the action. If no such action has been created by\n\t * this list yet, this method will create one.\n\t * \n\t * @param character the character whose beliefs will be updated\n\t * @param fluent the fluent whose value will change\n\t * @param value the value the fluent will have\n\t * @return a compiled dummy belief update action observed by the character\n\t * which sets the fluent to that value\n\t */\n\tpublic CompiledEvent getUpdate(Character character, CompiledFluent fluent, Value value) {\n\t\tkey.character = character;\n\t\tkey.fluent = fluent;\n\t\tkey.value = value;\n\t\tCompiledEvent update = updates.get(key);\n\t\tif(update == null) {\n\t\t\tupdate = update(character, fluent, value);\n\t\t\tevents.add(update);\n\t\t\tupdates.put(new UpdateKey(character, fluent, value), update);\n\t\t}\n\t\treturn update;\n\t}\n\t\n\tprivate static final ImmutableSet NO_CONSENTING_CHARACTERS = new ImmutableSet<>();\n\t\n\t@SuppressWarnings(\"unchecked\")\n\nsrc/edu/uky/cs/nil/sabre/comp/CompiledEvent.java\npublic interface CompiledEvent extends Event, Unique {\n\n\t@Override\n\tpublic default boolean isGround() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic default CompiledEvent simplify() {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Disjunction> getPrecondition();\n\t\n\t@Override\n\tpublic Clause getEffect();\n\t\n\t/**\n\t * Returns the event's unique ID number, which should correspond to this\n\t * event's index in its {@link CompiledProblem#events compiled problem's\n\t * set of events}.\n\t * \n\t * @return the event's unique ID number\n\t */\n\tpublic int getID();\n\t\n\t/**\n\t * Returns a {@link Clause clause} composed of every {@link Effect effect}\n\t * in {@link #getEffect() this event's effect} that has the given fluent\n\t * {@link edu.uky.cs.nil.sabre.logic.Assignment#fluent as its fluent}. The\n\t * returned clause may be empty if this event does not affect the given\n\t * fluent, or it may have several atoms if this event has several\n\t * conditional effects which might affect the given fluent.\n\t * \n\t * @param fluent the fluent which this event may affect\n\t * @return a clause of all ways this event could affect the given fluent\n\t */\n\tpublic default Clause getEffect(Fluent fluent) {\n\t\tClause clause = Clause.EMPTY.toEffect();\n\t\tfor(Effect effect : getEffect())\n\t\t\tif(effect.fluent.equals(fluent))\n\t\t\t\tclause = clause.add(effect);\n\t\treturn clause;\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/comp/CompiledMapping.java\npublic class CompiledMapping implements Mapping {\n\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * An {@link ImmutableArray array} that stores the expressions in this\n\t * mapping, where the expression for each {@link Character character} is in\n\t * the index corresponding to the {@link edu.uky.cs.nil.sabre.Entity#id ID\n\t * number} for that character\n\t */\n\tpublic final ImmutableArray table;\n\t\n\t/**\n\t * Constructs a new compiled mapping.\n\t * \n\t * @param table an array of {@link Expression logical expressions} where\n\t * the expression for each {@link Character character} is in the index\n\t * corresponding to the {@link edu.uky.cs.nil.sabre.Entity#id ID number}\n\t * of the character\n\t */\n\tpublic CompiledMapping(ImmutableArray table) {\n\t\tthis.table = table;\n\t}\n\t\n\t/**\n\t * Constructs a new compiled mapping.\n\t * \n\t * @param table an array of {@link Expression logical expressions} where\n\t * the expression for each {@link Character character} is in the index\n\t * corresponding to the {@link edu.uky.cs.nil.sabre.Entity#id ID number}\n\t * of the character\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic CompiledMapping(E...table) {\n\t\tthis(new ImmutableArray<>(table));\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Utilities.hashCode(getClass(), table);\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tString string = \"\";\n\t\tif(table.size() > 0)\n\t\t\tstring = \"0 -> \" + table.get(0);\n\t\tfor(int i=1; i \" + table.get(i);\n\t\treturn string;\n\t}\n\t\n\t@Override\n\tpublic int compareTo(Logical other) {\n\t\tif(getClass().equals(other.getClass()))\n\t\t\treturn Utilities.compare(table, ((CompiledMapping) other).table);\n\t\telse\n\t\t\treturn Mapping.super.compareTo(other);\n\t}\n\n\t@Override\n\tpublic boolean isBoolean() {\n\t\tfor(int i=0; i apply(java.util.function.Function function) {\n\t\tImmutableArray table = (ImmutableArray) this.table.apply(function);\n\t\tif(table != this.table)\n\t\t\treturn new CompiledMapping<>(table);\n\t\telse\n\t\t\treturn this;\n\t}\n\n\t/**\n\t * Returns a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() ground}\n\t * {@link Expression expression} relevant to the given ground character.\n\t * \n\t * @param character the character\n\t * @return the ground expression\n\t * @throws edu.uky.cs.nil.sabre.FormatException if the character is not\n\t * ground or not of type {@code character}\n\t */\n\t@Override\n\tpublic E get(Parameter character) {\n\t\tcharacter.mustBeGround();\n\t\tcharacter.mustBeCharacter();\n\t\treturn get((Character) character);\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Mapping cast(Class type) {\n\t\tfor(int i=0; i) this;\n\t}\n\t\n\t/**\n\t * Returns a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() ground}\n\t * {@link Expression expression} relevant to the given ground character.\n\t * \n\t * @param character the character\n\t * @return the ground expression\n\t */\n\tpublic E get(Character character) {\n\t\treturn table.get(character.id);\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/comp/CompiledFluent.java\npublic class CompiledFluent extends Fluent implements Unique {\n\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * A unique ID number that corresponds to this fluent's index in {@link\n\t * CompiledProblem#fluents its compiled problem's set of fluents}\n\t */\n\tpublic final int id;\n\t\n\t/**\n\t * An ordered list of {@link Character characters} specifying whose beliefs\n\t * this fluent represents\n\t */\n\tpublic final ImmutableArray characters;\n\t\n\t/**\n\t * The compiled fluent whose signature is identical but whose list of\n\t * characters is the same except that the first character has been removed\n\t */\n\tprivate final CompiledFluent parent;\n\t\n\t/**\n\t * Compiled fluents whose signatures are identical but with one additional\n\t * character added to the start of the list of characters\n\t */\n\tprivate final CompiledFluent[] children;\n\t\n\t/**\n\t * Constructs a new compiled fluent by prepending a character onto a parent.\n\t * \n\t * @param id a unique ID number\n\t * @param character the first character in this fluent's list of characters\n\t * @param parent the fluent's parent; its signature will be copied and the\n\t * character will be prepended to the start of its parent's list of\n\t * characters\n\t */\n\tprotected CompiledFluent(int id, Character character, CompiledFluent parent) {\n\t\tsuper(prepend(character, parent.characters), parent.signature, parent.type, parent.comment);\n\t\tthis.id = id;\n\t\tthis.characters = super.characters.cast(Character.class);\n\t\tthis.parent = parent;\n\t\tthis.children = new CompiledFluent[type.universe.characters.size()];\n\t\tparent.children[character.id] = this;\n\t}\n\t\n\tprivate static final ImmutableArray prepend(Character character, ImmutableArray characters) {\n\t\tCharacter[] array = new Character[characters.size() + 1];\n\t\tarray[0] = character;\n\t\tfor(int i=0; i(array);\n\t}\n\t\n\t/**\n\t * Constructs a new compiled fluent with an empty list of characters.\n\t * \n\t * @param id a unique ID number\n\t * @param signature the fluent's signature, which must be ground\n\t * @param type the fluent's type\n\t * @param comment the comment\n\t * @throws FormatException if the signature is not ground\n\t */\n\tprotected CompiledFluent(int id, Signature signature, Type type, String comment) {\n\t\tsuper(signature, type, comment);\n\t\tsignature.mustBeGround();\n\t\tthis.id = id;\n\t\tthis.characters = super.characters.cast(Character.class);\n\t\tthis.parent = this;\n\t\tthis.children = new CompiledFluent[type.universe.characters.size()];\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\treturn this == other;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn id;\n\t}\n\t\n\t@Override\n\tpublic boolean isGround() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic CompiledFluent apply(Function function) {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic CompiledFluent simplify() {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Fluent prepend(Parameter character) {\n\t\tif(character instanceof Character) {\n\t\t\tCompiledFluent child = children[((Character) character).id];\n\t\t\tif(child != null)\n\t\t\t\treturn child;\n\t\t}\n\t\treturn new PrefixFluent(character, this);\n\t}\n\t\n\t@Override\n\tpublic CompiledFluent removeFirstCharacter() {\n\t\treturn parent;\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/logic/Parameter.java\npublic interface Parameter extends Expression {\n\n\t@Override\n\tpublic Parameter apply(Function function);\n\t\n\t@Override\n\tpublic default Parameter simplify() {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic default boolean isValued() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic default Parameter prepend(Parameter character) {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic default Conditional>> toValued() {\n\t\treturn new Conditional<>(this);\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/logic/Clause.java\npublic class Clause extends Conjunction {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * The null clause is a empty clause which is logically equivalent to\n\t * {@link False#FALSE false}. Though an empty conjunction would normally be\n\t * logically equivalent to {@link True#TRUE true} (see {@link #EMPTY the\n\t * empty clause}), this object exists for situations where a clause object\n\t * is needed that is trivially false, such as when an {@link\n\t * edu.uky.cs.nil.sabre.Event event} has a contradictory effect. Atoms\n\t * cannot be added or removed from the null clause (that is, adding atoms\n\t * to or removing atoms from the null clause always results in the null\n\t * clause itself).\n\t */\n\tpublic static final Clause NULL = new Clause(new ImmutableArray<>()) {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object other) {\n\t\t\treturn this == other;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn super.hashCode() * -1;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.NULL_CLAUSE_KEYWORD;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int compareTo(Logical other) {\n\t\t\tif(getClass().equals(other.getClass())) {\n\t\t\t\tif(other.equals(this))\n\t\t\t\t\treturn 0;\n\t\t\t\telse\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn super.compareTo(other);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link False#FALSE false}.\n\t\t * \n\t\t * @returns {@link False#FALSE false}\n\t\t */\n\t\t@Override\n\t\tpublic False simplify() {\n\t\t\treturn False.FALSE;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link False#FALSE false}.\n\t\t * \n\t\t * @returns {@link False#FALSE false}\n\t\t */\n\t\t@Override\n\t\tpublic Value evaluate(State state) {\n\t\t\treturn False.FALSE;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link True#TRUE true}.\n\t\t * \n\t\t * @returns {@link True#TRUE true}\n\t\t */\n\t\t@Override\n\t\tpublic True negate() {\n\t\t\treturn True.TRUE;\n\t\t}\n\n\t\t/**\n\t\t * Returns {@link False#FALSE false}.\n\t\t * \n\t\t * @returns {@link False#FALSE false}\n\t\t */\n\t\t@Override\n\t\tpublic Disjunction> toPrecondition() {\n\t\t\treturn False.FALSE.toPrecondition();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link #NULL the null clause}.\n\t\t * \n\t\t * @returns {@link #NULL the null clause}\n\t\t */\n\t\t@Override\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic Clause toEffect() {\n\t\t\treturn (Clause) (Clause) this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link #NULL the null clause}.\n\t\t * \n\t\t * @returns {@link #NULL the null clause}\n\t\t */\n\t\t@Override\n\t\tpublic Clause add(Clause clause) {\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link #NULL the null clause}.\n\t\t * \n\t\t * @returns {@link #NULL the null clause}\n\t\t */\n\t\t@Override\n\t\tpublic Clause remove(Clause clause) {\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn NULL;\n\t\t}\n\t};\n\t\n\t/**\n\t * The empty clause is clause with zero atoms which is logically equivalent\n\t * to {@link True#TRUE true}.\n\t */\n\tpublic static final Clause EMPTY = new Clause(new ImmutableArray<>()) {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object other) {\n\t\t\treturn this == other;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int compareTo(Logical other) {\n\t\t\tif(getClass().equals(other.getClass())) {\n\t\t\t\tif(other.equals(NULL))\n\t\t\t\t\treturn 1;\n\t\t\t\telse if(other.equals(this))\n\t\t\t\t\treturn 0;\n\t\t\t\telse\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn super.compareTo(other);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link True#TRUE true}.\n\t\t * \n\t\t * @returns {@link True#TRUE true}\n\t\t */\n\t\t@Override\n\t\tpublic True simplify() {\n\t\t\treturn True.TRUE;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link False#FALSE false}.\n\t\t * \n\t\t * @returns {@link False#FALSE false}\n\t\t */\n\t\t@Override\n\t\tpublic False negate() {\n\t\t\treturn False.FALSE;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link True#TRUE true}.\n\t\t * \n\t\t * @returns {@link True#TRUE true}\n\t\t */\n\t\t@Override\n\t\tpublic Disjunction> toPrecondition() {\n\t\t\treturn True.TRUE.toPrecondition();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link #EMPTY the empty clause}.\n\t\t * \n\t\t * @returns {@link #EMPTY the empty clause}\n\t\t */\n\t\t@Override\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic Clause toEffect() {\n\t\t\treturn (Clause) (Clause) this;\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn EMPTY;\n\t\t}\n\t};\n\n\tprivate Clause(ImmutableArray arguments) {\n\t\tsuper(arguments);\n\t}\n\t\n\t/**\n\t * Constructs a clause from a single atom.\n\t * \n\t * @param atom the atom\n\t */\n\tpublic Clause(A atom) {\n\t\tthis(new ImmutableArray<>(atom));\n\t}\n\t\n\t/**\n\t * Clauses are simplified incrementally as atoms are added or removed, so\n\t * this method always returns this object itself with no changes.\n\t * \n\t * @return this clause\n\t */\n\t@Override\n\tpublic Expression simplify() {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Clause prepend(Parameter character) {\n\t\treturn new Clause(arguments.apply(atom -> ((Atom) atom).prepend(character)));\n\t}\n\t\n\t@Override\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Clause toEffect() {\n\t\tif(isEffect())\n\t\t\treturn (Clause) this;\n\t\telse\n\t\t\treturn super.toEffect();\n\t}\n\t\n\t/**\n\t * Tests whether every atom in this clause is a {@link Precondition\n\t * precondition}.\n\t * \n\t * @return true if every atom is a precondition or if there are no atoms,\n\t * false otherwise\n\t */\n\tpublic boolean isPrecondition() {\n\t\tfor(int i=0; i add(A atom) {\n\t\treturn add(new Clause(new ImmutableArray<>(atom)));\n\t}\n\t\n\t/**\n\t * Adds all atoms from this clause and the given clause together to form a\n\t * new clause. The resulting clause will not necessarily have as many atoms\n\t * as both clauses combined because the clause is simplified as it is\n\t * built. For example, if merging the clauses would create a contradiction,\n\t * perhaps because an atom from this clause {@link Atom#negates(Atom)\n\t * negates} an atom in the given clause, {@link #NULL the null clause} will\n\t * be returned. If atoms from the two clauses can be {@link\n\t * Atom#combine(Atom) combined}, they will be.\n\t * \n\t * @param clause the clause to combine with this clause\n\t * @return a simplified clause resulting from combining this clause and the\n\t * given clause\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Clause add(Clause clause) {\n\t\tif(clause.equals(NULL))\n\t\t\treturn (Clause) NULL;\n\t\tA[] atoms = add(null, this, 0, clause, 0, 0);\n\t\tif(atoms == null)\n\t\t\treturn (Clause) NULL;\n\t\telse if(atoms.length == 0)\n\t\t\treturn (Clause) EMPTY;\n\t\telse\n\t\t\treturn new Clause<>(new ImmutableArray<>(atoms));\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tprivate static final A[] add(A atom, Clause c1, int i1, Clause c2, int i2, int size) {\n\t\tA a1 = i1 == c1.size() ? null : c1.get(i1);\n\t\tA a2 = i2 == c2.size() ? null : c2.get(i2);\n\t\tif(atom == null && a1 == null && a2 == null)\n\t\t\treturn (A[]) new Atom[size];\n\t\telse if(atom == null) {\n\t\t\tif(a1 == null)\n\t\t\t\treturn add(a2, c1, i1, c2, i2 + 1, size);\n\t\t\telse if(a2 == null || a1.compareTo(a2) <= 0)\n\t\t\t\treturn add(a1, c1, i1 + 1, c2, i2, size);\n\t\t\telse\n\t\t\t\treturn add(a2, c1, i1, c2, i2 + 1, size);\n\t\t}\n\t\tif(a1 != null && atom.negates(a1))\n\t\t\treturn null;\n\t\telse if(a2 != null && atom.negates(a2))\n\t\t\treturn null;\n\t\tA a1c = a1 == null ? null : (A) atom.combine(a1);\n\t\tif(a1c != null)\n\t\t\treturn add(a1c, c1, i1 + 1, c2, i2, size);\t\n\t\tA a2c = a2 == null ? null : (A) atom.combine(a2);\n\t\tif(a2c != null)\n\t\t\treturn add(a2c, c1, i1, c2, i2 + 1, size);\n\t\telse {\n\t\t\tA[] atoms = add(null, c1, i1, c2, i2, size + 1);\n\t\t\tif(atoms == null)\n\t\t\t\treturn null;\n\t\t\tatoms[size] = atom;\n\t\t\treturn atoms;\n\t\t}\n\t}\n\t\n\t/**\n\t * Removes an atom from this clause. See {@link #remove(Clause)} for\n\t * details on removing from clauses.\n\t * \n\t * @param atom the atom to be removed\n\t * @return a simplified clause resulting from removing the atom\n\t */\n\tpublic Clause remove(A atom) {\n\t\treturn remove(new Clause(new ImmutableArray<>(atom)));\n\t}\n\t\n\t/**\n\t * Removes atoms from this clause if they appear, or if a more specific\n\t * version appears, in the given clause, or returns {@link #NULL the null\n\t * clause} if an atom in the given clause contradict this clause.\n\t * Let {@code a} be some atom in this clause and {@code b} be an atom in\n\t * the given clause. If {@code a} and {@code b} are the same, {@code a}\n\t * will be removed. If {@code a} and {@code b} can be {@link\n\t * Atom#combine(Atom) combined}, and the result is {@code b}, this means\n\t * {@code b} was more specific than {@code a}, and {@code a} will be\n\t * removed. If they can be combined and the result is something other than\n\t * {@code b}, then {@code a} will not removed. If {@code a} {@link\n\t * Atom#negates(Atom) negates} {@code b}, this method returns the {@link\n\t * #NULL null clause}.\n\t *

\n\t * This method can be used to regress this clause over the given clause.\n\t * This clause can be viewed as a condition (such as the {@link\n\t * edu.uky.cs.nil.sabre.Event#getPrecondition() precondition of an event},\n\t * though this clause does not need to have {@link Precondition\n\t * precondition atoms}) and the given clause can be viewed as changes made\n\t * (such as the {@link edu.uky.cs.nil.sabre.Event#getEffect() effect of an\n\t * event}, though the given clause does not need to have {@link Effect\n\t * effect atoms}). Regressing this clause means removing the conditions\n\t * from this clause which the given clause could have caused. So if this\n\t * clause has the condition that {@code f > 3} and we regress the effect\n\t * {@code f = 4} (which is more specific and satisfied the condition), the\n\t * condition would be removed. However, if we regress the effect\n\t * {@code f = 2} (which contradicts the condition), than there is no way\n\t * that effect could have led to a condition where {@code f > 3}, so this\n\t * method returns the null clause.\n\t * \n\t * @param clause the clause whose atoms will be removed from this clause\n\t * @return this clause, with atoms removed if they (or more specific\n\t * versions) appear in the given clause, or {@link #NULL the null clause}\n\t * if some atom in the given clause contradicts an atom in this clause\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Clause remove(Clause clause) {\n\t\tif(clause.equals(NULL))\n\t\t\treturn (Clause) NULL;\n\t\tA[] atoms = remove(this, 0, clause, 0, 0);\n\t\tif(atoms == null)\n\t\t\treturn (Clause) NULL;\n\t\telse if(atoms.length == 0)\n\t\t\treturn (Clause) EMPTY;\n\t\telse\n\t\t\treturn new Clause<>(new ImmutableArray<>(atoms));\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tprivate static final A[] remove(Clause c1, int i1, Clause c2, int i2, int size) {\n\t\tif(i1 == c1.size())\n\t\t\treturn (A[]) new Atom[size];\n\t\telse if(i2 == c2.size()) {\n\t\t\tA[] atoms = remove(c1, i1 + 1, c2, i2, size + 1);\n\t\t\tatoms[size] = c1.get(i1);\n\t\t\treturn atoms;\n\t\t}\n\t\tA a1 = c1.get(i1);\n\t\tA a2 = c2.get(i2);\n\t\tif(a1.negates(a2))\n\t\t\treturn null;\n\t\tAtom combined = a1.combine(a2);\n\t\tif(combined != null && combined.equals(a2))\n\t\t\treturn remove(c1, i1 + 1, c2, i2, size);\n\t\telse if(a1.compareTo(a2) < 0) {\n\t\t\tA[] atoms = remove(c1, i1 + 1, c2, i2, size + 1);\n\t\t\tif(atoms == null)\n\t\t\t\treturn null;\n\t\t\tatoms[size] = a1;\n\t\t\treturn atoms;\n\t\t}\n\t\telse\n\t\t\treturn remove(c1, i1, c2, i2 + 1, size);\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/Utilities.java\npublic class Utilities {\n\t\n\t/**\n\t * A default {@link edu.uky.cs.nil.sabre.io.Printer printer} generally used\n\t * for converting objects to strings\n\t */\n\tpublic static final DefaultPrinter DEFAULT_PRINTER = new DefaultPrinter();\n\t\n\t/**\n\t * Checks whether two objects are {@link Object#equals(Object) equal to}\n\t * one another without causing a {@link NullPointerException} if one or\n\t * both of them is null.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return true if they are equal or both null, false otherwise\n\t */\n\tpublic static final boolean equals(Object o1, Object o2) {\n\t\tif(o1 == null)\n\t\t\treturn o2 == null;\n\t\telse if(o2 == null)\n\t\t\treturn false;\n\t\telse\n\t\t\treturn o1.equals(o2);\n\t}\n\t\n\t/**\n\t * Returns an object's {@link Object#hashCode() hash code} or 0 if the\n\t * object is null.\n\t * \n\t * @param object the object or null\n\t * @return the object's hash code or 0 if the object was null\n\t */\n\tpublic static final int hashCode(Object object) {\n\t\tif(object == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn object.hashCode();\n\t}\n\t\n\t/**\n\t * Combines two {@link #hashCode(Object) hash code} values.\n\t * \n\t * @param hc1 the first hash code\n\t * @param hc2 the second hash code\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc1, int hc2) {\n\t\treturn hc1 * 31 + hc2;\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of an object.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1) {\n\t\treturn hashCode(hc, hashCode(o1));\n\t}\n\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of two objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2) {\n\t\treturn hashCode(hashCode(o1), hashCode(o2));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of two objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2) {\n\t\treturn hashCode(hashCode(hc, o1), hashCode(o2));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of three\n\t * objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3) {\n\t\treturn hashCode(hashCode(o1, o2), hashCode(o3));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of three objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3) {\n\t\treturn hashCode(hashCode(hc, o1, o2), hashCode(o3));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of four objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4) {\n\t\treturn hashCode(hashCode(o1, o2, o3), hashCode(o4));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of four objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3, Object o4) {\n\t\treturn hashCode(hashCode(hc, o1, o2, o3), hashCode(o4));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of five objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4, Object o5) {\n\t\treturn hashCode(hashCode(o1, o2, o3, o4), hashCode(o5));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of five objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3, Object o4, Object o5) {\n\t\treturn hashCode(hashCode(hc, o1, o2, o3, o4), hashCode(o5));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of six objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @param o6 the sixth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4, Object o5, Object o6) {\n\t\treturn hashCode(hashCode(o1, o2, o3, o4, o5), hashCode(o6));\n\t}\n\t\n\t/**\n\t * Rounds a {@code double} up to the nearest whole number.\n\t * \n\t * @param value the value to round up\n\t * @return the nearest whole number that is greater than or equal to the\n\t * value\n\t */\n\tpublic static final double roundUp(double value) {\n\t\treturn new BigDecimal(value).setScale(0, RoundingMode.UP).doubleValue();\n\t}\n\t\n\t/**\n\t * Compares a pair of {@link Comparable comparable} objects.\n\t * \n\t * @param the type of the objects\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return a negative integer, zero, or a positive integer as the first\n\t * object is less than, equal to, or greater than the second object\n\t */\n\tpublic static final > int compare(C1 o1, C1 o2) {\n\t\treturn o1.compareTo(o2);\n\t}\n\t\n\t/**\n\t * Compares two pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is\n\t * not 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4) {\n\t\tint comparison = compare(o1, o2);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o3, o4);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares three pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is not\n\t * 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param the type of the third pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @param o5 the first object in the third pair\n\t * @param o6 the second object in the third pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable, C3 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4, C3 o5, C3 o6) {\n\t\tint comparison = compare(o1, o2, o3, o4);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o5, o6);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares four pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is\n\t * not 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param the type of the third pair of objects\n\t * @param the type of the fourth pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @param o5 the first object in the third pair\n\t * @param o6 the second object in the third pair\n\t * @param o7 the first object in the fourth pair\n\t * @param o8 the second object in the fourth pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable, C3 extends Comparable, C4 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4, C3 o5, C3 o6, C4 o7, C4 o8) {\n\t\tint comparison = compare(o1, o2, o3, o4, o5, o6);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o7, o8);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares two {@link ImmutableArray arrays} of {@link Logical logical}\n\t * objects. The first elements of both arrays are compared. If the result\n\t * is not 0, it is returned, otherwise the second elements of both arrays\n\t * are compared, and so on.\n\t * \n\t * @param array1 the first array\n\t * @param array2 the second array\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * elements are less than, equal to, or greater than the later elements\n\t */\n\tpublic static final int compare(ImmutableArray array1, ImmutableArray array2) {\n\t\tint comparison = 0;\n\t\tint size = Math.min(array1.size(), array2.size());\n\t\tfor(int i=0; i array2.size())\n\t\t\t\treturn 1;\n\t\t\telse if(array2.size() > array1.size())\n\t\t\t\treturn -1;\n\t\t}\n\t\treturn comparison;\n\t}\n\n\t/**\n\t * Iterates through all elements of an {@link Iterable iterable} and places\n\t * them into an array of a given type.\n\t * \n\t * @param the component type of the array\n\t * @param iterable the iterable\n\t * @param type the class of the component type of the array\n\t * @return an array containing all the elements in the iterable\n\t */\n\tpublic static final T[] toArray(Iterable iterable, Class type) {\n\t\treturn toArray(iterable.iterator(), 0, type);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tprivate static final T[] toArray(Iterator iterator, int index, Class type) {\n\t\tif(iterator.hasNext()) {\n\t\t\tT element = iterator.next();\n\t\t\tT[] array = toArray(iterator, index + 1, type);\n\t\t\tarray[index] = element;\n\t\t\treturn array;\n\t\t}\n\t\telse\n\t\t\treturn (T[]) Array.newInstance(type, index);\n\t}\n\t\n\t/**\n\t * Iterates through all elements of an {@link Iterable iterable} and places\n\t * into a {@link ImmutableSet set} only those items which are of a given\n\t * type.\n\t * \n\t * @param the type of elements to collect\n\t * @param type the class object of the type\n\t * @param iterable the iterable to iterate through\n\t * @return a set of elements from the iterable of the given type\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static final ImmutableSet collect(Class type, Iterable iterable) {\n\t\tLinkedHashSet set = new LinkedHashSet<>();\n\t\tfor(Object element : iterable)\n\t\t\tif(type.isAssignableFrom(element.getClass()))\n\t\t\t\tset.add((T) element);\n\t\treturn new ImmutableSet<>(set);\n\t}\n\t\n\t/**\n\t * Wrap a string in parentheses, unless it is already so wrapped.\n\t * \n\t * @param string the second\n\t * @return the string, wrapped in parentheses\n\t */\n\tpublic static final String wrap(String string) {\n\t\tif(string.startsWith(\"(\") && string.endsWith(\")\"))\n\t\t\treturn string;\n\t\telse\n\t\t\treturn \"(\" + string + \")\";\n\t}\n\t\n\t/**\n\t * Converts a number of milliseconds into a short string representation\n\t * that gives the numbers of days, hours, minutes, seconds, and\n\t * milliseconds. For example, {@code \"2d1h3m45s20ms\"} represents two days,\n\t * 1 hour, 3 minutes, fourty-five seconds, and twenty milliseconds.\n\t * \n\t * @param ms the number of milliseconds\n\t * @return a string representation of that amount of time\n\t */\n\tpublic static final String time(long ms) {\n\t\tlong days = TimeUnit.MILLISECONDS.toDays(ms);\n\t\tms -= TimeUnit.DAYS.toMillis(days);\n\t\tlong hours = TimeUnit.MILLISECONDS.toHours(ms);\n\t\tms -= TimeUnit.HOURS.toMillis(hours);\n\t\tlong minutes = TimeUnit.MILLISECONDS.toMinutes(ms);\n\t\tms -= TimeUnit.MINUTES.toMillis(minutes);\n\t\tlong seconds = TimeUnit.MILLISECONDS.toSeconds(ms);\n\t\tms -= TimeUnit.SECONDS.toMillis(seconds);\n\t\tString string = \"\";\n\t\tif(days > 0)\n\t\t\tstring += days + \"d\";\n\t\tif(hours > 0)\n\t\t\tstring += hours + \"h\";\n\t\tif(minutes > 0)\n\t\t\tstring += minutes + \"m\";\n\t\tif(seconds > 0)\n\t\t\tstring += seconds + \"s\";\n\t\tif(ms > 0)\n\t\t\tstring += ms + \"ms\";\n\t\tif(string.isEmpty())\n\t\t\treturn \"0ms\";\n\t\treturn string;\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/logic/Value.java\npublic interface Value extends Parameter {\n\t\n\t@Override\n\tpublic default boolean isGround() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic default Value apply(Function function) {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic default Value simplify() {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic default boolean isValued() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic default Value evaluate(State state) {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic default Value prepend(Parameter character) {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic default Conditional>> toValued() {\n\t\treturn new Conditional<>(this);\n\t}\n}", "answers": ["\tprivate final CompiledAction update(Character character, CompiledFluent fluent, Value value) {"], "length": 5775, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "e4a5c8bd-3a80-41ca-afe8-205fa5f521fb", "reasoning": "In EventList, after the static field NO_CONSENTING_CHARACTERS the code has a @SuppressWarnings annotation, indicating the next line defines the method used earlier (update) that creates a dummy belief update event. The method is static, returns CompiledEvent, and takes Character, CompiledFluent, Value parameters. Hence the next line is the method signature.", "reasoning_model_answer": "private static final CompiledEvent update(Character character, CompiledFluent fluent, Value value) {", "assistant_with_reasoning": "\nIn EventList, after the static field NO_CONSENTING_CHARACTERS the code has a @SuppressWarnings annotation, indicating the next line defines the method used earlier (update) that creates a dummy belief update event. The method is static, returns CompiledEvent, and takes Character, CompiledFluent, Value parameters. Hence the next line is the method signature.\n\nprivate static final CompiledEvent update(Character character, CompiledFluent fluent, Value value) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.225, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36903, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private static final CompiledEvent update(Character character, CompiledFluent fluent, Value value) {", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "import android.content.Context;\r\nimport android.content.pm.PackageManager;\r\nimport android.content.res.AssetManager;\r\nimport android.content.res.Resources;\r\nimport android.content.res.XmlResourceParser;\r\nimport android.database.sqlite.SQLiteDatabase;\r\nimport android.os.Bundle;\r\nimport android.support.annotation.Nullable;\r\nimport android.support.v7.widget.RecyclerView;\r\nimport android.support.v7.widget.SwitchCompat;\r\nimport android.text.TextUtils;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\nimport android.widget.ImageView;\r\nimport android.widget.TextView;\r\nimport org.xmlpull.v1.XmlPullParser;\r\nimport org.xmlpull.v1.XmlPullParserException;\r\nimport java.io.IOException;\r\nimport java.lang.reflect.Method;\r\nimport java.util.ArrayList;\r\nimport java.util.Collections;\r\nimport java.util.Comparator;\r\nimport java.util.List;\r\nimport cn.wq.myandroidtoolspro.R;\r\nimport cn.wq.myandroidtoolspro.helper.DBHelper;\r\nimport cn.wq.myandroidtoolspro.helper.IfwUtil;\r\nimport cn.wq.myandroidtoolspro.helper.Utils;\r\nimport cn.wq.myandroidtoolspro.model.ComponentEntry;\r\nimport cn.wq.myandroidtoolspro.model.ReceiverEntry;\r\nimport cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter;\r\nimport cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectableViewHolder;\r\nimport cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectionUtils;\r\nimport cn.wq.myandroidtoolspro.recyclerview.toolbar.MultiSectionWithToolbarRecyclerFragment;\r", "context": "app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/ReceiverRecyclerListFragment.java\n if(entry.className==null){\r\n continue;\r\n }\r\n\r\n if(!entry.className.contains(\".\")){\r\n entry.className=entry.packageName+\".\"+entry.className;\r\n }else if(entry.className.startsWith(\".\")){\r\n entry.className=entry.packageName+entry.className;\r\n }\r\n\r\n entry.enabledInManifest = parser.getAttributeBooleanValue(ANDROID_NAMESPACE, \"enabled\",true);\r\n// entry.enabled=pm.getComponentEnabledSetting(new ComponentName(\r\n// entry.packageName, entry.className)) <= 1;\r\n if (isIfw) {\r\n entry.isIfwed = IfwUtil.isComponentInIfw(packageName, entry.className, IfwUtil.COMPONENT_FLAG_RECEIVER, mIfwEntry);\r\n } else {\r\n entry.enabled = Utils.isComponentEnabled(entry, pm);\r\n }\r\n\r\n entry.actions=parseActions(parser);\r\n result.add(entry);\r\n }\r\n }\r\n\r\n Collections.sort(result, new Comparator() {\r\n @Override\r\n public int compare(ReceiverEntry lhs, ReceiverEntry rhs) {\r\n String l = lhs.className.substring(lhs.className\r\n .lastIndexOf(\".\") + 1);\r\n String r = rhs.className.substring(rhs.className\r\n .lastIndexOf(\".\") + 1);\r\n return l.compareTo(r);\r\n }\r\n });\r\n\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n\r\n return result;\r\n }\r\n\r\n private String parseActions(XmlPullParser parser) throws XmlPullParserException, IOException{\r\n StringBuilder builder=new StringBuilder();\r\n final int innerDepth=parser.getDepth();\r\n int type;\r\n while((type=parser.next())!=XmlPullParser.END_DOCUMENT &&\r\n (type!=XmlPullParser.END_TAG||parser.getDepth()>innerDepth)){\r\n if(type==XmlPullParser.END_TAG||type==XmlPullParser.TEXT){\r\n continue;\r\n }\r\n if(\"action\".equals(parser.getName())){\r\n builder.append(parser.getAttributeValue(ANDROID_NAMESPACE, \"name\"));\r\n builder.append(\"\\n\");\r\n }\r\n }\r\n\r\n if (builder.length() > 0) {\r\n builder.deleteCharAt(builder.length() - 1);\r\n }\r\n return builder.toString();\r\n }\r\n\r\n private class ReceiverAdapter extends AbstractComponentAdapter {\r\n public ReceiverAdapter(Context context) {\r\n super(context);\r\n }\r\n\r\n @Override\r\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\r\n return new ReceiverViewHolder(LayoutInflater.from(mContext)\r\n .inflate(R.layout.item_receiver_list, parent, false));\r\n }\r\n\r\n @Override\r\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\r\n ReceiverViewHolder vHolder= (ReceiverViewHolder) holder;\r\n ReceiverEntry entry = getItem(position);\r\n\r\n if (getIsFullName()) {\r\n vHolder.name.setText(entry.className);\r\n } else {\r\n vHolder.name.setText(entry.className.substring(entry.className\r\n .lastIndexOf(\".\") + 1));\r\n }\r\n\r\n vHolder.checkBox.setChecked(entry.enabled);\r\n\r\n if (TextUtils.isEmpty(entry.actions)) {\r\n vHolder.actions.setVisibility(View.GONE);\r\n } else {\r\n vHolder.actions.setVisibility(View.VISIBLE);\r\n vHolder.actions.setText(entry.actions);\r\n }\r\n vHolder.setSelected(getMultiController().isSelectedAtPosition(position));\r\n\r\n if (Utils.isPmByIfw(mContext)) {\r\n vHolder.checkBox.setVisibility(View.GONE);\r\n vHolder.wall.setVisibility(entry.isIfwed ? View.VISIBLE : View.INVISIBLE);\r\n } else {\r\n vHolder.checkBox.setVisibility(View.VISIBLE);\r\n vHolder.wall.setVisibility(View.GONE);\r\n vHolder.name.setTextColor(entry.enabled ? primaryTextColor : redTextColor);\r\n }\r\n }\r\n\r\n private class ReceiverViewHolder extends MultiSelectableViewHolder{\r\n TextView actions;\r\n TextView name;\r\n SwitchCompat checkBox;\r\n ImageView wall;\r\n ReceiverViewHolder(View itemView) {\r\n super(itemView);\r\n actions= (TextView) itemView.findViewById(R.id.actions);\r\n name = (TextView) itemView.findViewById(R.id.name);\r\n checkBox=(SwitchCompat)itemView.findViewById(R.id.checkbox);\r\n wall = itemView.findViewById(R.id.wall);\r\n }\r\n\r\n @Override\r\n\napp/src/main/java/cn/wq/myandroidtoolspro/recyclerview/toolbar/MultiSectionWithToolbarRecyclerFragment.java\npublic abstract class MultiSectionWithToolbarRecyclerFragment extends MultiSelectionRecyclerListFragment {\r\n private ActionBar mActionBar;\r\n\r\n @Nullable\r\n @Override\r\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\r\n return inflater.inflate(R.layout.recycler_with_toolbar_list_fragment,container,false);\r\n }\r\n\r\n @Override\r\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\r\n super.onViewCreated(view, savedInstanceState);\r\n\r\n Bundle args=getArguments();\r\n if (args != null && args.getBoolean(\"ignoreToolbar\")) {\r\n return;\r\n }\r\n\r\n ViewStub viewStub= (ViewStub) view.findViewById(R.id.view_stub);\r\n viewStub.inflate();\r\n\r\n Toolbar toolbar=(Toolbar) view.findViewById(R.id.toolbar);\r\n if (toolbar == null) {\r\n return;\r\n }\r\n AppCompatActivity activity = (AppCompatActivity) getActivity();\r\n activity.setSupportActionBar(toolbar);\r\n mActionBar=activity.getSupportActionBar();\r\n if (mActionBar != null) {\r\n mActionBar.setDisplayHomeAsUpEnabled(true);\r\n }\r\n\r\n //是子fragment时让父fragment设置title就行了\r\n if (args != null && !args.getBoolean(\"part\")) {\r\n initActionbar(1,args.getString(\"title\"));\r\n }\r\n }\r\n\r\n /**\r\n * @see BaseFragment#initActionbar(int, String)\r\n */\r\n protected void initActionbar(int iconType,String title){\r\n if (mActionBar == null) {\r\n return;\r\n }\r\n if(title==null){\r\n mActionBar.setTitle(R.string.app_name);\r\n }else{\r\n mActionBar.setTitle(title);\r\n }\r\n\r\n switch (iconType) {\r\n case 1:\r\n mActionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp);\r\n break;\r\n case 2:\r\n mActionBar.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);\r\n break;\r\n default:\r\n mActionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white);\r\n break;\r\n }\r\n }\r\n\r\n protected void setToolbarLogo(String packageName) {\r\n if (mActionBar == null || TextUtils.isEmpty(packageName)) {\r\n return;\r\n }\r\n try {\r\n int length = (int) (getResources().getDisplayMetrics().density * 24);\r\n Drawable icon=getContext().getPackageManager().getApplicationIcon(packageName);\r\n View view=getView();\r\n if (view != null) {\r\n Toolbar toolbar= (Toolbar) view.findViewById(R.id.toolbar);\r\n toolbar.setLogo(icon);\r\n for (int i = 0; i < toolbar.getChildCount(); i++) {\r\n View child = toolbar.getChildAt(i);\r\n if (child != null && child instanceof ImageView){\r\n ImageView iv = (ImageView) child;\r\n if ( iv.getDrawable() == icon ) {\r\n ViewGroup.LayoutParams params=iv.getLayoutParams();\r\n params.width=params.height=length;\r\n }\r\n }\r\n }\r\n }\r\n } catch (PackageManager.NameNotFoundException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n @Override\r\n public void onDestroy() {\r\n super.onDestroy();\r\n closeActionMode(); //actionMode时在drawer里面调到其它页面不会消失\r\n }\r\n}\r\n\napp/src/main/java/cn/wq/myandroidtoolspro/recyclerview/multi/MultiSelectableViewHolder.java\npublic abstract class MultiSelectableViewHolder\r\n extends RecyclerView.ViewHolder\r\n implements View.OnLongClickListener, View.OnClickListener{\r\n private boolean mIsSelected;\r\n private Drawable mDefaultBackground,mSelectedBackground;\r\n\r\n public MultiSelectableViewHolder(View itemView) {\r\n super(itemView);\r\n\r\n if(!itemView.isClickable()){\r\n itemView.setClickable(true);\r\n }\r\n if (!itemView.isLongClickable()) {\r\n itemView.setLongClickable(true);\r\n }\r\n itemView.setOnClickListener(this);\r\n itemView.setOnLongClickListener(this);\r\n\r\n mDefaultBackground = itemView.getBackground();\r\n setSelectionnModeDrawable(R.color.actionbar_color_light);\r\n }\r\n\r\n public abstract MultiSelectionUtils.Controller loadMultiController();\r\n\r\n public void setSelectionnModeDrawable(@ColorRes int colorRes) {\r\n //导致默认的RippleDrawable无效\r\n// StateListDrawable stateListDrawable = new StateListDrawable();\r\n// stateListDrawable.addState(StateSet.WILD_CARD,null);\r\n//\r\n// ColorDrawable drawable = new ColorDrawable(ContextCompat.getColor(itemView.getContext(),colorRes));\r\n// stateListDrawable.addState(new int[]{android.R.attr.state_selected},drawable);\r\n// itemView.setBackgroundDrawable(stateListDrawable);\r\n\r\n mSelectedBackground=new ColorDrawable(ContextCompat.getColor(itemView.getContext(),colorRes));\r\n }\r\n\r\n public void setSelected(boolean selected){\r\n if (mIsSelected != selected) {\r\n mIsSelected=selected;\r\n// itemView.setSelected(selected);\r\n itemView.setBackgroundDrawable(selected?mSelectedBackground:mDefaultBackground);\r\n }\r\n }\r\n\r\n public boolean isSelected() {\r\n return mIsSelected;\r\n }\r\n\r\n\r\n @Override\r\n public boolean onLongClick(View view) {\r\n if (!loadMultiController().isInActionMode()) {\r\n loadMultiController().startActionMode();\r\n setSelected(true);\r\n loadMultiController().onStateChanged(getLayoutPosition(),true);\r\n }else{\r\n onClick(view);\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public void onClick(View view) {\r\n if (loadMultiController().isInActionMode()) {\r\n boolean isSelected=isSelected();\r\n setSelected(!isSelected);\r\n loadMultiController().onStateChanged(getLayoutPosition(),!isSelected);\r\n return;\r\n }\r\n loadMultiController().onItemClick(getLayoutPosition(),view);\r\n }\r\n\r\n}\r\n\napp/src/main/java/cn/wq/myandroidtoolspro/helper/Utils.java\npublic class Utils {\n private static final String TAG = \"Utils\";\n //\tpublic final static String ACTION_RECEIVER_CHANGED=\"cn.wq.myandroidtoolspro.receiver_changed\";\n//\tprivate final static String EXTERNAL_STORAGE = \"EXTERNAL_STORAGE\";\n//\tpublic final static String tempDBPath=System.getenv(EXTERNAL_STORAGE)\n//\t\t\t+ \"/temp2.db\";\n//\tpublic final static String tempSPfrefsPath=System.getenv(EXTERNAL_STORAGE)\n//\t\t\t+ \"/temp2.xml\";\n//\tpublic final static String BACKUP_FILE_DIR=Environment.getExternalStorageDirectory()+\"/myandroidtoolspro_backup.txt\";\n public final static String ACTION_SORT_CHANGE = \"cn.wq.myandroidtoolspro.action_sort_change\";\n //\tpublic final static String ACTION_APP_CHANGE=\"cn.wq.myandroidtoolspro.action_app_change\";\n public final static String ACTION_APP_SORT = \"cn.wq.myandroidtoolspro.action_app_sort\";\n public final static String ACTION_RECEIVER_FINISH = \"cn.wq.myandroidtoolspro.action_receiver_finish\";\n private final static String ANDROID_NAMESPACE = \"http://schemas.android.com/apk/res/android\";\n\n public final static String ACTION_ACTIVITY_FULL_NAME = \"ACTION_ACTIVITY_FULL_NAME\";\n public final static String ACTION_ACTIVITY_MOVE = \"ACTION_ACTIVITY_MOVE\";\n public final static String ACTION_ACTIVITY_TEXTSIZE = \"ACTION_ACTIVITY_TEXTSIZE\";\n\n private final static String SERVICE_START_MARK = \" * ServiceRecord{\";\n // private final static String SERVICE_START_MARK_PACKAGE = \" packageName=\";\n// private final static String SERVICE_START_MARK_PROCESS = \" processName=\";\n private final static String SERVICE_START_MARK_APP = \" app=\";\n private final static Pattern SERVICE_RECORD_PATTERN = Pattern.compile(\"[\\\\w]+ [\\\\w]+ ([\\\\w.]+)/([\\\\w.]+)\\\\}\");\n private final static Pattern SERVICE_APP_PATTERN = Pattern.compile(\" +app=ProcessRecord\\\\{[\\\\w]+ ([\\\\d]+):[\\\\S]+\");\n //adb 中 grep 只能用-E 支持多个搜索条件,而且不用转义;不能直接用|分隔\n //\"dumpsys activity services | grep -E \\\"ServiceRecord{|processName=\\\"\";\n private final static String COMMAND_GET_RUNNING_SERVICE_FOR_ALL = \"dumpsys activity s | grep -E \\\"ServiceRecord{|app=\\\"\";\n private final static String COMMAND_GET_RUNNING_SERVICE_FOR_SINGLE = \"dumpsys activity s %s| grep -E \\\"ServiceRecord{|app=\\\"\";\n\n public static String trimFor160(String name) {\n return name.replaceAll(String.valueOf((char) 160), \"\");\n }\n\n public static String getTempDBPath(Context context) {\n return context.getExternalCacheDir() + \"/temp2.db\";\n }\n\n public static String getTempDBWalPath(Context context) {\n return context.getExternalCacheDir() + \"/temp2.db-wal\";\n }\n\n public static String getTempSPfrefsPath(Context context) {\n return context.getExternalCacheDir() + \"/temp2.xml\";\n }\n\n /**\n * 从 attr 中获取颜色\n */\n public static @ColorInt int getColorFromAttr(Context context, @AttrRes int attr) {\n TypedValue value = new TypedValue();\n if(context.getTheme().resolveAttribute(attr, value, true)){\n// return value.data; //不是Color是ColorStateList\n if (value.resourceId != 0) {\n return ContextCompat.getColor(context, value.resourceId);\n }\n }\n return ContextCompat.getColor(context, R.color.text_primary_black);\n }\n\n// @ColorRes\n// public static int getPrimaryTextColorRes(Context context) {\n// TypedValue typedValue = new TypedValue();\n// context.getTheme().resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);\n// return typedValue.resourceId;\n// }\n\n// private static Picasso mPicasso;\n//\n// public static synchronized Picasso getPicassoInstance(Context context) {\n// if (mPicasso == null) {\n// final Context appContext = context.getApplicationContext();\n// mPicasso = new Picasso.Builder(appContext).addRequestHandler(new RequestHandler() {\n// @Override\n// public boolean canHandleRequest(Request data) {\n// return \"icon\".equals(data.uri.getScheme());\n// }\n//\n// @Override\n// public Result load(Request request, int networkPolicy){\n// Drawable drawable = null;\n// try {\n// drawable = appContext.getPackageManager().getApplicationIcon(request.uri.toString().replace(\"icon:\", \"\"));\n// } catch (PackageManager.NameNotFoundException e) {\n// e.printStackTrace();\n// }\n//\n// if (drawable instanceof BitmapDrawable) {\n// return new Result(((BitmapDrawable) drawable).getBitmap(), Picasso.LoadedFrom.DISK);\n// } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && drawable instanceof AdaptiveIconDrawable) {\n// //https://stackoverflow.com/a/46448831/1263423\n// //android 0 adaptive launch icon\n// AdaptiveIconDrawable aiDrawable = (AdaptiveIconDrawable) drawable;\n// Drawable backgroudDr = aiDrawable.getBackground();\n// Drawable foregroundDr = aiDrawable.getForeground();\n// Drawable[] drs = new Drawable[]{backgroudDr, foregroundDr};\n//\n// LayerDrawable layerDrawable = new LayerDrawable(drs);\n// Bitmap bitmap = Bitmap.createBitmap(layerDrawable.getIntrinsicWidth(),\n// layerDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);\n// Canvas canvas = new Canvas(bitmap);\n// layerDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n// layerDrawable.draw(canvas);\n//\n// return new Result(bitmap, Picasso.LoadedFrom.DISK);\n// }\n//\n// //default\n// drawable = appContext.getResources().getDrawable(android.R.drawable.sym_def_app_icon);\n// return new Result(((BitmapDrawable) drawable).getBitmap(), Picasso.LoadedFrom.DISK);\n// }\n// }).build();\n// }\n// return mPicasso;\n// }\n\n public static String getAppLabel(@NonNull PackageManager pm, @NonNull ApplicationInfo aInfo) {\n try {\n CharSequence label = aInfo.loadLabel(pm);\n if (label != null) {\n return Utils.trimFor160(label.toString());\n }\n } catch (Exception e) {\n Utils.debug(TAG, \"getAppLabel error,\" + aInfo.packageName + \",\" + e.toString());\n }\n\n return aInfo.packageName;\n }\n\n public static void loadApkIcon(Fragment fragment, String packageName, ImageView imageView) {\n Glide.with(fragment).load(ApkIconFetcher.PREFIX + packageName)\n .placeholder(android.R.drawable.sym_def_app_icon)\n .error(android.R.drawable.sym_def_app_icon).into(imageView);\n }\n public static void loadApkIcon(Context context, String packageName, ImageView imageView) {\n Glide.with(context).load(ApkIconFetcher.PREFIX + packageName)\n .placeholder(android.R.drawable.sym_def_app_icon)\n .error(android.R.drawable.sym_def_app_icon).into(imageView);\n }\n\n\n public static String getUninstallBackupDir() {\n File dir = new File(Environment.getExternalStorageDirectory() + File.separator + \"MyAndroidTools\"+File.separator+\"uninstalled\");\n if (!dir.exists()) {\n dir.mkdirs();\n }\n return dir.getAbsolutePath();\n }\n\n public static String getUninstallBackupDirInShell() {\n File dir = new File(File.separator + \"sdcard\" + File.separator + \"MyAndroidTools\"+File.separator+\"uninstalled\");\n if (!dir.exists()) {\n dir.mkdirs();\n }\n return dir.getAbsolutePath();\n }\n\n public static List getAppsWithType(Context context, boolean isSystemApp,\n int type) {\n switch (type) {\n case 0:\n return getAppsAsService(context, isSystemApp);\n case 1:\n return getAppsAsReceiver(context, isSystemApp);\n case 2:\n return getAppsAsActivity(context, isSystemApp);\n case 3:\n return getAppsAsProvider(context, isSystemApp);\n default:\n return null;\n }\n }\n\n public static List getAppsAsService(Context context, boolean isSystemApp) {\n List runningServiceInfos = getRunningServiceInfos(context, null);\n\n PackageManager pm = context.getPackageManager();\n List aInfos = pm.getInstalledApplications(0);\n List result = new ArrayList<>();\n\n for (ApplicationInfo aInfo : aInfos) {\n if (aInfo == null) {\n continue;\n }\n if (isSystemApp ? (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0\n : (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {\n List models = Utils.getComponentModels(context, aInfo.packageName, 0);\n if (models.size() == 0)\n continue;\n\n AppEntry entry = new AppEntry();\n entry.totalNum = models.size();\n entry.label = getAppLabel(pm, aInfo);\n if (!Utils.isPmByIfw(context)) {\n entry.disabledNum = Utils.getComponentDisabledNum(models, pm);\n }\n entry.runningNum = Utils.getRunningNum(aInfo.packageName,\n runningServiceInfos);\n entry.packageName = aInfo.packageName;\n result.add(entry);\n }\n }\n\n aInfos.clear();\n\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n final int sortType = sp.getInt(\"sort_service\", 0);\n Locale locale = context.getResources().getConfiguration().locale;\n\n final Collator collator = Collator.getInstance(locale);\n Collections.sort(result, new Comparator() {\n @Override\n public int compare(AppEntry left, AppEntry right) {\n if (sortType == 1\n && left.runningNum != right.runningNum) {\n return right.runningNum - left.runningNum;\n } else if (sortType == 2\n && left.disabledNum != right.disabledNum) {\n return right.disabledNum - left.disabledNum;\n }\n\n return collator.compare(left.label, right.label);\n }\n });\n\n return result;\n }\n\n private static List getAppsAsReceiver(Context context, boolean isSystemApp) {\n PackageManager pm = context.getPackageManager();\n List aInfos = pm.getInstalledApplications(0);\n List result = new ArrayList<>();\n\n SQLiteDatabase db = DBHelper.getInstance(context).getWritableDatabase();\n db.beginTransaction();\n for (ApplicationInfo aInfo : aInfos) {\n if (aInfo == null) {\n continue;\n }\n if (isSystemApp ? (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0\n : (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {\n List models = Utils.getComponentModels(context, aInfo.packageName, 1);\n if (models.size() == 0)\n continue;\n\n AppEntry entry = new AppEntry();\n entry.totalNum = models.size();\n entry.label = getAppLabel(pm, aInfo);\n if (!Utils.isPmByIfw(context)) {\n entry.disabledNum = Utils.getComponentDisabledNum(models, pm);\n }\n entry.packageName = aInfo.packageName;\n result.add(entry);\n\n ContentValues values = new ContentValues();\n values.put(\"app_name\", entry.label);\n values.put(\"package_name\", entry.packageName);\n values.put(\"is_system\", isSystemApp ? 1 : 0);\n db.insert(DBHelper.APPS_TABLE_NAME, null, values);\n }\n }\n db.setTransactionSuccessful();\n db.endTransaction();\n\n aInfos.clear();\n\n Locale locale = context.getResources().getConfiguration().locale;\n\n final Collator collator = Collator.getInstance(locale);\n Collections.sort(result, new Comparator() {\n @Override\n public int compare(AppEntry left, AppEntry right) {\n String lString = left.label;\n String rString = right.label;\n return collator.compare(lString, rString);\n }\n });\n\n return result;\n }\n\n private static List getAppsAsActivity(Context context, boolean isSystemApp) {\n PackageManager pm = context.getPackageManager();\n List aInfos = pm.getInstalledApplications(0);\n List result = new ArrayList<>();\n\n for (ApplicationInfo aInfo : aInfos) {\n if (aInfo == null) {\n continue;\n }\n if (isSystemApp ? (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0\n : (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {\n List models = Utils.getComponentModels(context, aInfo.packageName, 2);\n if (models.size() == 0)\n continue;\n\n AppEntry entry = new AppEntry();\n entry.totalNum = models.size();\n entry.label = getAppLabel(pm, aInfo);\n if (!Utils.isPmByIfw(context)) {\n entry.disabledNum = Utils.getComponentDisabledNum(models, pm);\n }\n entry.packageName = aInfo.packageName;\n result.add(entry);\n }\n }\n\n aInfos.clear();\n\n Locale locale = context.getResources().getConfiguration().locale;\n\n final Collator collator = Collator.getInstance(locale);\n Collections.sort(result, new Comparator() {\n @Override\n public int compare(AppEntry left, AppEntry right) {\n String lString = left.label;\n String rString = right.label;\n return collator.compare(lString, rString);\n }\n });\n\n return result;\n }\n\n public static List getAppsAsProvider(Context context, boolean isSystemApp) {\n PackageManager pm = context.getPackageManager();\n List aInfos = pm.getInstalledApplications(0);\n List result = new ArrayList<>();\n\n for (ApplicationInfo aInfo : aInfos) {\n //用了某些xposed框架可能导致 未知错误:Attempt to read from field 'java.lang.String android.content.pm.PackageItemInfo.packageName' on a null object reference\n //https://play.google.com/apps/publish/?dev_acc=04519573207763184232#ErrorClusterDetailsPlace:p=cn.wq.myandroidtools&et=CRASH&lr=LAST_7_DAYS&ecn=java.lang.NullPointerException&tf=unknown&tc=cn.wq.myandroidtools.b.b&tm=a&nid&an&c&s=new_status_desc\n if (aInfo == null) {\n continue;\n }\n if (isSystemApp ? (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0\n : (aInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {\n List models = Utils.getComponentModels(context, aInfo.packageName, 3);\n if (models.size() == 0)\n continue;\n AppEntry entry = new AppEntry();\n entry.totalNum = models.size();\n entry.label = getAppLabel(pm, aInfo);\n entry.disabledNum = Utils.getComponentDisabledNum(models, pm);\n entry.packageName = aInfo.packageName;\n result.add(entry);\n }\n }\n\n aInfos.clear();\n\n Locale locale = context.getResources().getConfiguration().locale;\n\n final Collator collator = Collator.getInstance(locale);\n Collections.sort(result, new Comparator() {\n @Override\n public int compare(AppEntry left, AppEntry right) {\n String lString = left.label;\n String rString = right.label;\n return collator.compare(lString, rString);\n }\n });\n\n return result;\n }\n\n public static int getComponentDisabledNum(List cModels, PackageManager pm) {\n int num = 0;\n for (ComponentModel component : cModels) {\n if (component == null) {\n continue;\n }\n\n if ((!isComponentEnabled(component, pm))) {\n num++;\n }\n }\n return num;\n }\n\n public static int getDisabledNum(int type, String packageName, Context context) {\n return getComponentDisabledNum(getComponentModels(context, packageName, type), context.getPackageManager());\n }\n\n// public static List getRunningServiceInfos(\n// Context context) {\n// return getRunningServiceInfos(context, null);\n// }\n\n public static boolean isPmByShizuku(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getInt(BaseActivity.PREFERENCE_PM_CHANNER, BaseActivity.PM_CHANNEL_ROOT_COMMAND) == BaseActivity.PM_CHANNEL_SHIZUKU;\n }\n\n public static boolean isPmByIfw(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getInt(BaseActivity.PREFERENCE_PM_CHANNER, BaseActivity.PM_CHANNEL_ROOT_COMMAND) == BaseActivity.PM_CHANNEL_IFW;\n }\n\n /**\n * 只获取制定包名的running service;针对Android O开始只能用root命令的情况可以限定包名\n * @param currentPkgName 需要获取正在运行服务的包名,可以为空\n */\n public static List getRunningServiceInfos(\n Context context,@Nullable String currentPkgName) {\n final int maxNum;\n// if (!TextUtils.isEmpty(currentPkgName)) {\n// maxNum = 50; //限制包名时不需要那么多\n// }else{\n maxNum = 500;\n// }\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {\n ActivityManager aManager = (ActivityManager) context\n .getSystemService(Context.ACTIVITY_SERVICE);\n\n return aManager.getRunningServices(maxNum);\n } else {\n if (Looper.myLooper() != Looper.getMainLooper()) {\n if (isPmByShizuku(context) && ShizukuClient.getState().isAuthorized()) {\n try {\n return ShizukuActivityManagerV26.getServices(maxNum, 0);\n } catch (Exception e) {\n com.tencent.mars.xlog.Log.e(TAG, \"getRunningServiceInfos by shizuku error\", e);\n Utils.err(TAG, \"getRunningServiceInfos by shizuku error\", e);\n }\n }\n }\n\n //Android O(Android 8)开始变了,必须root才行\n //adb 中 grep 只能用-E 支持多个搜索条件,而且不用转义;不能直接用|分隔\n String cmd;\n if (TextUtils.isEmpty(currentPkgName)) {\n cmd = COMMAND_GET_RUNNING_SERVICE_FOR_ALL;\n }else{\n cmd = String.format(COMMAND_GET_RUNNING_SERVICE_FOR_SINGLE, currentPkgName);\n }\n List result = runRootCommandForResult(cmd);\n\n List rInfoList = new ArrayList<>();\n if (result != null) {\n RunningServiceInfo rInfo = null;\n for (String s : result) {\n if (TextUtils.isEmpty(s)) {\n continue;\n }\n if (s.startsWith(SERVICE_START_MARK)) {\n if (rInfo != null) {\n rInfoList.add(rInfo);\n }\n rInfo = new RunningServiceInfo();\n Matcher matcher = SERVICE_RECORD_PATTERN.matcher(s.substring(SERVICE_START_MARK.length()));\n if (matcher.matches()) {\n String packageName = matcher.group(1);\n String serviceName = matcher.group(2);\n if (serviceName != null && serviceName.startsWith(\".\")) {\n serviceName = packageName + serviceName;\n }\n if (serviceName != null) {\n rInfo.service = new ComponentName(packageName, serviceName);\n }\n }\n// } else if (s.startsWith(START_MARK_PROCESS)) { //其实不需要processName\n// if (rInfo != null) {\n// rInfo.process = s.substring(START_MARK_PROCESS.length());\n// rInfoList.add(rInfo);\n// rInfo = null;\n// }\n } else if (s.startsWith(SERVICE_START_MARK_APP)) {\n if (rInfo != null) {\n Matcher matcher = SERVICE_APP_PATTERN.matcher(s);\n if (matcher.matches()) {\n String pid = matcher.group(1);\n try {\n rInfo.pid = Integer.parseInt(pid);\n } catch (Exception e) {\n rInfo.pid = 0;\n }\n rInfoList.add(rInfo);\n rInfo = null;\n }\n }\n }\n }\n }\n\n //返回未空的话,保存返回数据到文件\n// if (rInfoList.size() == 0) {\n// Utils.debug(\"-------mat test begin-------\");\n// if (result != null && result.size() > 0) {\n// Utils.debug(\"running_result 1 size:\" + result.size());\n// String path = context.getExternalCacheDir() + File.separator + \"running_result_1\";\n// try {\n// FileWriter writer = new FileWriter(path);\n// for (String line : result) {\n// writer.write(line);\n// writer.write(\"\\r\\n\");\n// }\n// writer.flush();\n// writer.close();\n// } catch (IOException e) {\n// e.printStackTrace();\n// }\n// } else {\n// Utils.debug(\"running_result 1 empty\");\n// }\n//\n// List rr = runRootCommandForResult(\"dumpsys activity services\");\n// if (rr != null && rr.size() > 0) {\n// Utils.debug(\"running_result 2 size:\" + rr.size());\n// String path = context.getExternalCacheDir() + File.separator + \"running_result_2\";\n// try {\n// FileWriter writer = new FileWriter(path);\n// for (String line : rr) {\n// writer.write(line);\n// writer.write(\"\\r\\n\");\n// }\n// writer.flush();\n// writer.close();\n// } catch (IOException e) {\n// e.printStackTrace();\n// }\n// } else {\n// Utils.debug(\"running_result 2 empty\");\n// }\n//\n// Utils.debug(\"-------mat test end-------\");\n// }\n\n return rInfoList;\n }\n\n }\n\n\n /**\n * @param componentType 0:service 1:receiver 2:activity 3:provider 4:all four types\n */\n public static List getComponentModels(Context context, String packageName, int componentType) {\n List result = new ArrayList<>();\n try {\n Context targetContext = context.createPackageContext(packageName, 0);\n AssetManager assetManager = targetContext.getAssets();\n\n Method addAssetPath = AssetManager.class.getMethod(\"addAssetPath\", String.class);\n String sourceDir = context.getPackageManager().getApplicationInfo(packageName, 0).sourceDir;\n int cookie = (int) addAssetPath.invoke(assetManager, sourceDir);\n XmlResourceParser parser = assetManager.openXmlResourceParser(cookie, \"AndroidManifest.xml\");\n Resources resources = new Resources(assetManager, targetContext.getResources().getDisplayMetrics(), null);\n\n int type;\n while ((type = parser.next()) != XmlResourceParser.END_DOCUMENT) {\n if (type == XmlResourceParser.START_TAG) {\n if ((componentType == 0 || componentType == 4) && \"service\".equals(parser.getName())\n || (componentType == 1 || componentType == 4) && \"receiver\".equals(parser.getName())\n || (componentType == 2 || componentType == 4) && (\"activity\".equals(parser.getName()) || \"activity-alias\".equals(parser.getName()))\n || (componentType == 3 || componentType == 4) & \"provider\".equals(parser.getName())) {\n// String name = parser.getAttributeValue(ANDROID_NAMESPACE, \"name\");\n// //cmb.pb招商银行客户端因为乱码可能有问题\n// //https://github.com/miracle2k/android-autostarts/blob/master/src/com/elsdoerfer/android/autostarts/ReceiverReader.java\n// if (name == null) {\n// for (int i = 0; i < parser.getAttributeCount(); i++) {\n// if (TextUtils.isEmpty(parser.getAttributeName(i))) {\n// int res = parser.getAttributeNameResource(i);\n// if (res != 0 && resources.getResourceEntryName(res).equals(\"name\")) {\n// name = parser.getAttributeValue(i);\n// break;\n// }\n// }\n// }\n// }\n\n String name = Utils.getAttributeValueByName(parser, resources, \"name\");\n if (name == null) {\n continue;\n }\n\n ComponentModel component = new ComponentModel();\n if (!name.contains(\".\")) {\n component.className = packageName + \".\" + name;\n } else if (name.startsWith(\".\")) {\n component.className = name.startsWith(\".\") ? packageName + name : name;\n } else {\n component.className = name;\n }\n component.packageName = packageName;\n\n component.enabledInManifest = parser.getAttributeBooleanValue(ANDROID_NAMESPACE, \"enabled\",true);\n\n result.add(component);\n }\n }\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n Collections.sort(result, new Comparator() {\n @Override\n public int compare(ComponentModel lhs, ComponentModel rhs) {\n String l = lhs.className\n .substring(lhs.className.lastIndexOf(\".\") + 1);\n String r = rhs.className\n .substring(rhs.className.lastIndexOf(\".\") + 1);\n return l.compareTo(r);\n }\n });\n return result;\n }\n\n public static @Nullable String getAttributeValueByName(XmlResourceParser parser, Resources resources, String name) {\n String value = parser.getAttributeValue(ANDROID_NAMESPACE, name);\n //cmb.pb招商银行客户端因为乱码可能有问题\n //https://github.com/miracle2k/android-autostarts/blob/master/src/com/elsdoerfer/android/autostarts/ReceiverReader.java\n if (value == null) {\n for (int i = 0; i < parser.getAttributeCount(); i++) {\n if (TextUtils.isEmpty(parser.getAttributeName(i))) {\n int res = parser.getAttributeNameResource(i);\n if (res != 0 && resources.getResourceEntryName(res).equals(name)) {\n value = parser.getAttributeValue(i);\n break;\n }\n }\n }\n }\n return value;\n }\n \n public static boolean isComponentEnabled(ComponentModel cInfo,\n PackageManager pm) {\n int enabled = pm.getComponentEnabledSetting(new ComponentName(\n cInfo.packageName, cInfo.className));\n if (enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {\n return cInfo.enabledInManifest;\n }else {\n return enabled <= PackageManager.COMPONENT_ENABLED_STATE_ENABLED;\n }\n }\n\n /**\n * @see #isRunning\n */\n public static int getRunningNum(String packageName,\n List runningServiceInfos) {\n int num = 0;\n if (runningServiceInfos != null) {\n for (RunningServiceInfo rInfo : runningServiceInfos) {\n if (rInfo.restarting != 0 || rInfo.pid == 0) {\n continue;\n }\n ComponentName cName = rInfo.service;\n if (cName != null && TextUtils.equals(cName.getPackageName(), packageName)) {\n num++;\n }\n }\n }\n\n return num;\n }\n\n public static boolean isRunning(String packageName, String className,\n List rInfos) {\n for (RunningServiceInfo rInfo : rInfos) {\n // FIXME: 2018/3/17 被ifw阻止后会被getRunningServices获取到,但是pid=0 && restarting=0,该service其实没有走生命周期\n //正在重启的时候会有两个,com.netease.cloudmusic.service.PlayService\n if (rInfo.restarting != 0 || rInfo.pid == 0) {\n continue;\n }\n if (rInfo.service != null && rInfo.service.getPackageName().equals(packageName)\n && rInfo.service.getClassName().equals(className)) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean checkSDcard(Context context) {\n if (!Environment.getExternalStorageState().equals(\n Environment.MEDIA_MOUNTED)) {\n Toast.makeText(context, R.string.media_not_mounted,\n Toast.LENGTH_LONG).show();\n return false;\n }\n\n if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)\n != PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(context, R.string.permission_request_failed, Toast.LENGTH_SHORT).show();\n return false;\n }\n\n return true;\n }\n\n//\tpublic static boolean runRootCommand(String command) {\n// Process process = null;\n// DataOutputStream os = null;\n// try {\n// process = Runtime.getRuntime().exec(\"su\");\n// os = new DataOutputStream(process.getOutputStream());\n//\n// // 类似Titanium的中文高8位会丢失\n//// os.writeBytes(command + \"\\n\");\n// os.write(command.getBytes());\n// os.writeBytes(\"exit\\n\");\n// os.flush();\n// \n// process.waitFor();\n// } catch (Exception e) {\n// \te.printStackTrace();\n// return false;\n// } finally {\n// try {\n// if (os != null) {\n// os.close();\n// }\n// if (process != null) {\n// process.destroy();\n// }\n// } catch (Exception e) {\n// // nothing\n// }\n// }\n// return true;\n// }\n\n /**\n * use root-command-library to get root access\n */\n//\tpublic static boolean runRootCommand2(String command) {\n//\t\ttry {\n//\t\t\tShell shell=Shell.startRootShell();\n//\t\t\tshell.add(new SimpleCommand(command)).waitForFinish();\n//\t\t\tshell.close();\n//\t\t} catch (Exception e) {\n//\t\t\te.printStackTrace();\n//\t\t\treturn false;\n//\t\t}\n//\t\t\n//\t\treturn true;\n//\t}\n\n// public static List runRootCommandForResult(String cmd) {\n// final List stdout = new ArrayList<>();\n// try {\n// Command command = new Command(0, cmd) {\n// @Override\n// public void commandOutput(int id, String line) {\n// super.commandOutput(id, line);\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi\", line);\n// }\n// stdout.add(line);\n// }\n//\n// @Override\n// public void commandTerminated(int id, String reason) {\n// super.commandTerminated(id, reason);\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi2\", reason);\n// }\n// }\n//\n// @Override\n// public void commandCompleted(int id, int exitcode) {\n// super.commandCompleted(id, exitcode);\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi3\", \"exitcode:\"+exitcode);\n// }\n// }\n// };\n//\n// RootTools.getShell(true).add(command);\n//\n// while (true) {\n// if (command.isFinished()) {\n// break;\n// }\n// try {\n// Thread.sleep(100);\n// } catch (InterruptedException e) {\n// e.printStackTrace();\n// }\n// }\n// } catch (IOException | TimeoutException | RootDeniedException e) {\n// e.printStackTrace();\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi4\", cmd + \" , result exception:\" + (e.toString()));\n// }\n// return null;\n// }\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi5\", cmd + \" , result size:\" + (stdout.size()));\n// }\n// return stdout;\n// }\n\n public static List runRootCommandForResult(String cmd) {\n if (eu.chainfire.libsuperuser.Shell.SU.available()) {\n return eu.chainfire.libsuperuser.Shell.SU.run(cmd);\n }else{\n return null;\n }\n }\n\n /**\n * 包括stderr\\stdout\n */\n public static List runRootCommandForAllResult(String cmd) {\n if (eu.chainfire.libsuperuser.Shell.SU.available()) {\n List result = eu.chainfire.libsuperuser.Shell.SU.runGetAll(cmd);\n if (BuildConfig.DEBUG) {\n Utils.debug(TAG, \"runRootCorunRootCommandForAllResultmmand start:\" + cmd);\n int index = 0;\n if (result != null) {\n for (String s : result) {\n Utils.debug(TAG, index++ + \":\" + s);\n }\n } else {\n Utils.debug(TAG, \"runRootCommandForAllResult return null\");\n }\n Utils.debug(TAG, \"runRootCommandForAllResult end:\" + cmd);\n }\n return result;\n }else{\n return null;\n }\n }\n\n public static List runCommandForResult(String cmd) {\n List result = eu.chainfire.libsuperuser.Shell.SH.run(cmd);\n if (BuildConfig.DEBUG) {\n Utils.debug(TAG, \"runCommandForResult start:\" + cmd);\n int index = 0;\n if (result != null) {\n for (String s : result) {\n Utils.debug(TAG, index++ + \":\" + s);\n }\n } else {\n Utils.debug(TAG, \"runCommandForResult return null\");\n }\n Utils.debug(TAG, \"runCommandForResult end:\" + cmd);\n }\n return result;\n }\n\n public static boolean runRootCommand(String... cmd) {\n if (eu.chainfire.libsuperuser.Shell.SU.available()) {\n List result = eu.chainfire.libsuperuser.Shell.SU.run(cmd);\n if (BuildConfig.DEBUG) {\n String cmdStr = Arrays.toString(cmd);\n Utils.debug(TAG, \"runRootCommand start:\" + cmdStr);\n if (result != null) {\n int index = 0;\n for (String s : result) {\n Utils.debug(TAG, index++ + \":\" + s);\n }\n } else {\n Utils.debug(TAG, \"runRootCommand return null\");\n }\n\n Utils.debug(TAG, \"runRootCommand end:\" + cmdStr);\n }\n return result != null;\n }else{\n if (BuildConfig.DEBUG) {\n Utils.debug(TAG, \"su is not available\");\n }\n return false;\n }\n }\n\n// public static List runCommandForResult(String cmd) {\n// final List stdout = new ArrayList<>();\n// try {\n// Command command = new Command(0, cmd) {\n// @Override\n// public void commandOutput(int id, String line) {\n// super.commandOutput(id, line);\n// stdout.add(line);\n// }\n//\n// @Override\n// public void commandTerminated(int id, String reason) {\n// super.commandTerminated(id, reason);\n// }\n//\n// @Override\n// public void commandCompleted(int id, int exitcode) {\n// super.commandCompleted(id, exitcode);\n// }\n// };\n//\n// RootTools.getShell(false).add(command);\n//\n// while (true) {\n// if (command.isFinished()) {\n// break;\n// }\n// try {\n// Thread.sleep(100);\n// } catch (InterruptedException e) {\n// e.printStackTrace();\n// }\n// }\n// } catch (IOException | TimeoutException | RootDeniedException e) {\n// e.printStackTrace();\n// return null;\n// }\n// return stdout;\n// }\n\n// public static boolean runRootCommand(String... cmd) {\n// try {\n// //Command command = new Command(0, cmd);\n// Command command;\n// if(Utils.isTestForUninstallSysApp()){\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi0\", Arrays.toString(cmd));\n// }\n// command = new Command(0, cmd){\n// @Override\n// public void commandOutput(int id, String line) {\n// super.commandOutput(id, line);\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi\", line);\n// }\n// }\n//\n// @Override\n// public void commandTerminated(int id, String reason) {\n// super.commandTerminated(id, reason);\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi2\", reason);\n// }\n// }\n//\n// @Override\n// public void commandCompleted(int id, int exitcode) {\n// super.commandCompleted(id, exitcode);\n// if (Utils.isTestForDatabase()) {\n// Log.e(\"wangqi3\", \"exitcode:\"+exitcode);\n// }\n// }\n// };\n// }else{\n// command = new Command(0, cmd);\n// }\n//\n//\n// Shell shell = RootTools.getShell(true);\n// shell.add(command);\n//\n// while (true) {\n// if (command.isFinished()) {\n// break;\n// }\n// try {\n// Thread.sleep(100);\n// } catch (InterruptedException e) {\n// e.printStackTrace();\n// }\n// }\n// return command.getExitCode() == 0;\n// } catch (IOException | TimeoutException | RootDeniedException e) {\n// e.printStackTrace();\n// return false;\n// }\n// }\n\n //https://github.com/shadowsocks/shadowsocks-android/issues/826\n //http://blog.csdn.net/zyp009/article/details/17397383\n // 例如/system/app/Email/下面有oat目录,里面有odex,在UninstalledRecyclerListFragment卸载时才删除\n /**\n * 已经mount system rw了,只需要后面unmount\n */\n public static String getUnmountSystemCommand(Context context) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);\n int mountSysMode = preferences.getInt(\"mountSysMode\", 0);\n if (mountSysMode == 1) {\n String command1 = Utils.getUnmountSystemCommand1(preferences, mountSysMode);\n if (command1 != null) {\n return command1;\n }\n } else if (mountSysMode == 2) {\n String command2 = Utils.getUnmountSystemCommand2(preferences, mountSysMode);\n if (command2 != null) {\n return command2;\n }\n }\n\n //Device or resource busy 是err\n List mountSysResult = Utils.runRootCommandForAllResult(\"mount -o remount,rw /system\");\n if (mountSysResult == null || mountSysResult.size() == 0) {\n if (mountSysMode != 0) {\n preferences.edit().putInt(\"mountSysMode\", 0).apply();\n }\n return \"mount -o remount,ro /system\";\n }\n if (mountSysResult.size() > 0) {\n if (mountSysResult.get(0).endsWith(\"Device or resource busy\")) {\n //从mount命令的返回结果中找\n //每个版本返回的格式不一样,先直接去第一个空格之前的吧\n ///dev/block/platform/msm_sdcc.1/by-name/system on /system type ext4 (ro,seclabel,noatime,data=ordered)\n //用root命令返回的不一样,而且有问题\n String command1 = Utils.getUnmountSystemCommand1(preferences, mountSysMode);\n if (command1 != null) {\n return command1;\n }\n\n //从/proc/mounts中获取\n String command2 = Utils.getUnmountSystemCommand2(preferences, mountSysMode);\n if (command2 != null) {\n return command2;\n }\n }else{\n com.tencent.mars.xlog.Log.e(TAG, \"normal mount0 sys return:\" + TextUtils.join(\",\", mountSysResult));\n }\n }\n preferences.edit().putInt(\"mountSysMode\", 0).apply();\n return null;\n\n\n// String mountCommand = Build.VERSION.SDK_INT>=24? \"mount -o rw,remount /dev/block/platform/msm_sdcc.1/by-name/system /system\" :\"mount -o remount,rw /system\";\n// String unmountCommand = Build.VERSION.SDK_INT>=24? \"mount -o ro,remount /dev/block/platform/msm_sdcc.1/by-name/system /system\" :\"mount -o remount,ro /system\";\n//\n// //每个版本返回的格式不一样,先直接去第一个空格之前的吧\n// ///dev/block/platform/msm_sdcc.1/by-name/system on /system type ext4 (ro,seclabel,noatime,data=ordered)\n// if (Build.VERSION.SDK_INT >= 24) {\n// //用root命令返回的不一样,而且有问题\n// List mountList= Utils.runCommandForResult(\"mount |grep '/system '\");\n// if (mountList != null && mountList.size() > 0) {\n// if (mountList.size() > 1) {\n// Log.e(\"matpro\", \"get system mount size>1,\" + TextUtils.join(\",\", mountList));\n// }\n// String location = mountList.get(0).substring(0, mountList.get(0).indexOf(\" \"));\n//\n// mountCommand = \"mount -o rw,remount \" + location +\" /system\";\n// unmountCommand = \"mount -o ro,remount \" + location+\" /system\";\n// }\n// }\n//\n// return new String[]{mountCommand, unmountCommand};\n }\n\n private static String getUnmountSystemCommand2(SharedPreferences preferences,int mode){\n //从/proc/mounts中获取\n List mountList= Utils.runCommandForResult(\"cat /proc/mounts |grep '/system '\");\n if (mountList != null && mountList.size() > 0) {\n String location = mountList.get(0).substring(0, mountList.get(0).indexOf(\" \"));\n String mountCommand = \"mount -o rw,remount \" + location +\" /system\";\n List mountSysResult = Utils.runRootCommandForResult(mountCommand);\n if (mountSysResult == null || mountSysResult.size() == 0) {\n if (mode != 2) {\n preferences.edit().putInt(\"mountSysMode\", 2).apply();\n }\n return \"mount -o ro,remount \" + location +\" /system\";\n }else{\n com.tencent.mars.xlog.Log.e(TAG, \"mount2 sys return:\" + TextUtils.join(\",\", mountSysResult));\n }\n }\n return null;\n }\n\n /**\n * 执行一个或者多个pm enable/disable 命令,要注意组件不存在时会报错 java.lang.IllegalArgumentException: Unknown component: ComponentInfo{com.zhihu.android/com.avos.avoscloud.PushService}\n * @param command\n * @return 正常成功1、正常失败-1,组件不存在的失败-2\n */\n public static int runMultiPmDisableCommand(String command){\n final List ss = eu.chainfire.libsuperuser.Shell.SU.runGetOnlyErr(command);\n final Pattern pattern = Pattern.compile(\"[\\\\w\\\\W]+Component class [^ ]+ does not exist in [^ ]+\");\n //禁用多个时 只有最后一个不存在时会影响process.exitValue()返回1\n if (ss != null && ss.size() > 0 && pattern.matcher(ss.get(ss.size() - 1)).matches()) {\n return -2;\n }else {\n return ss != null ? 1 : -1;\n }\n }\n\n //https://android.stackexchange.com/a/158890/228460\n private static String getUnmountSystemCommand1(SharedPreferences preferences,int mode){\n //从mount命令的返回结果中找\n //每个版本返回的格式不一样,先直接去第一个空格之前的吧\n ///dev/block/platform/msm_sdcc.1/by-name/system on /system type ext4 (ro,seclabel,noatime,data=ordered)\n //用root命令返回的不一样,而且有问题\n List mountList= Utils.runCommandForResult(\"mount |grep '/system '\");\n if (mountList != null && mountList.size() > 0) {\n if (mountList.size() > 1) {\n com.tencent.mars.xlog.Log.e(TAG, \"get system mount size>1,\" + TextUtils.join(\",\", mountList));\n }\n String location = mountList.get(0).substring(0, mountList.get(0).indexOf(\" \"));\n String mountCommand = \"mount -o rw,remount \" + location + \" /system\";\n ListmountSysResult = Utils.runRootCommandForResult(mountCommand);\n if (mountSysResult == null || mountSysResult.size() == 0) {\n if (mode != 1) {\n preferences.edit().putInt(\"mountSysMode\", 1).apply();\n }\n return \"mount -o ro,remount \" + location + \" /system\";\n } else {\n com.tencent.mars.xlog.Log.e(TAG, \"mount1 sys return:\" + TextUtils.join(\",\", mountSysResult));\n }\n }\n return null;\n }\n\n// public static Locale getSystemLocale() {\n// if (Build.VERSION.SDK_INT >= 24) {\n// return Resources.getSystem().getConfiguration().getLocales().get(0);\n// } else {\n// return Resources.getSystem().getConfiguration().locale;\n// }\n// }\n\n public static int dp2px(Context context,int dp) {\n return Math.round(context.getResources().getDisplayMetrics().density * dp);\n }\n\n public static void debug(String msg) {\n if ((BuildConfig.DEBUG || isDebugForUser()) && !TextUtils.isEmpty(msg)) {\n com.tencent.mars.xlog.Log.e(\"matpro\", msg);\n }\n }\n public static void debug(String tag,String msg) {\n if ((BuildConfig.DEBUG || isDebugForUser()) && !TextUtils.isEmpty(msg)) {\n com.tencent.mars.xlog.Log.d(tag, msg);\n }\n }\n public static void err(String tag, String msg, Exception e) {\n if ((BuildConfig.DEBUG || isDebugForUser()) && !TextUtils.isEmpty(msg)) {\n Log.e(tag, msg, e);\n }\n }\n\n public static boolean isDebugForUser() {\n return false;\n }\n\n public static boolean isTestForWindowManager() {\n return false;\n }\n public static boolean isTestForDatabase(){\n return false;\n }\n public static boolean isTestCurrentFragment(){\n return false;\n }\n\n public static boolean isTestForUninstallSysApp(){\n return true;\n }\n\n public static boolean isRemoveAccessibilityForGoogle(){\n return true;\n }\n}\n\napp/src/main/java/cn/wq/myandroidtoolspro/model/ComponentEntry.java\npublic class ComponentEntry extends ComponentModel {\r\n\tpublic boolean enabled;\r\n}\r\n\napp/src/main/java/cn/wq/myandroidtoolspro/model/ReceiverEntry.java\npublic class ReceiverEntry extends ComponentEntry{\r\n\tpublic String actions;\r\n}\r\n\napp/src/main/java/cn/wq/myandroidtoolspro/recyclerview/multi/MultiSelectionUtils.java\npublic class MultiSelectionUtils {\r\n public static Controller attach(MultiSelectionRecyclerListFragment fragment) {\r\n return Controller.attach(fragment);\r\n }\r\n\r\n public static class Controller implements ActionMode.Callback,RecyclerListView.OnRecyclerItemClickListener{\r\n private RecyclerListView mRecyclerListView;\r\n private AppCompatActivity mActivity;\r\n private ActionMode mActionMode;\r\n private ArrayList mItemsSelected;\r\n private MultiSelectionRecyclerListFragment mFragment;\r\n\r\n private Controller() {\r\n }\r\n\r\n private static Controller attach(MultiSelectionRecyclerListFragment fragment) {\r\n Controller controller = new Controller();\r\n controller.mActivity= (AppCompatActivity) fragment.getActivity();\r\n controller.mRecyclerListView=fragment.getRecyclerListView();\r\n controller.mFragment=fragment;\r\n return controller;\r\n }\r\n\r\n public boolean isInActionMode() {\r\n return mActionMode != null;\r\n }\r\n\r\n public void startActionMode() {\r\n if (mActionMode == null) {\r\n mItemsSelected = new ArrayList<>();\r\n mActionMode=mActivity.startSupportActionMode(this);\r\n }\r\n }\r\n\r\n public void finish() {\r\n if (mActionMode != null) {\r\n mActionMode.finish();\r\n mActionMode = null;\r\n }\r\n }\r\n\r\n private String getStateKey() {\r\n return MultiSelectionUtils.class.getSimpleName() + \"_\" + mRecyclerListView.getId();\r\n }\r\n public void saveInstanceState(Bundle outState) {\r\n if (mActionMode != null) {\r\n outState.putIntegerArrayList(getStateKey(),mItemsSelected);\r\n }\r\n }\r\n\r\n public void restoreInstanceState(Bundle savedInstanceState) {\r\n mItemsSelected=null;\r\n if (savedInstanceState != null) {\r\n mItemsSelected = savedInstanceState.getIntegerArrayList(getStateKey());\r\n }\r\n\r\n RecyclerView.Adapter adapter=mRecyclerListView.getAdapter();\r\n if (mItemsSelected == null||adapter==null) {\r\n return;\r\n }\r\n startActionMode();\r\n }\r\n\r\n public void onStateChanged(int position,boolean selected) {\r\n int index=mItemsSelected.indexOf(position);\r\n if(selected && index<0){\r\n mItemsSelected.add(position);\r\n }else if(!selected && index>=0){\r\n mItemsSelected.remove(index);\r\n if (mItemsSelected.size() == 0) {\r\n finish();\r\n }\r\n }\r\n }\r\n\r\n public ArrayList getSelectedItemsPosition() {\r\n return mItemsSelected;\r\n }\r\n\r\n public boolean isSelectedAtPosition(int position) {\r\n return mItemsSelected != null && mItemsSelected.contains(position);\r\n }\r\n\r\n @Override\r\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\r\n if (Build.VERSION.SDK_INT >= 21) {\r\n mActivity.getWindow().setStatusBarColor(ContextCompat.getColor(mActivity, R.color.blue_grey_700));\r\n }\r\n if(mFragment!=null && mFragment.onCreateActionMode(mode,menu)){\r\n if (mItemsSelected != null && mItemsSelected.size() > 0) {\r\n for(int i=0;i= 21) {\r\n mActivity.getWindow().setStatusBarColor(ContextCompat.getColor(mActivity, android.R.color.transparent));\r\n }\r\n if (mFragment != null) {\r\n mFragment.onDestroyActionMode(mode);\r\n }\r\n if (mItemsSelected != null && mItemsSelected.size() > 0) {\r\n for(int i=0;i\r\n extends RecyclerView.Adapter\r\n implements Filterable{\r\n private List list;\r\n private boolean isFullName;\r\n private ComponentFilter mFilter;\r\n private List originalData;\r\n private final Object mLock = new Object();\r\n protected Context mContext;\r\n protected int primaryTextColor;\r\n protected int redTextColor;\r\n\r\n// public AbstractComponentAdapter() {\r\n// super();\r\n// this.list = new ArrayList<>();\r\n// }\r\n\r\n public AbstractComponentAdapter(Context context) {\r\n this.list = new ArrayList<>();\r\n mContext = context;\r\n primaryTextColor = Utils.getColorFromAttr(context, android.R.attr.textColorPrimary);\r\n redTextColor = ContextCompat.getColor(mContext, R.color.holo_red_light);\r\n }\r\n\r\n public T getItem(int position) {\r\n return list.get(position);\r\n }\r\n\r\n public void setData(List list) {\r\n this.list.clear();\r\n if (list != null) {\r\n this.list.addAll(list);\r\n }\r\n\r\n //wq:搜索后禁用 刷新状态\r\n if(originalData!=null){\r\n originalData.clear();\r\n originalData=null;\r\n }\r\n\r\n notifyDataSetChanged();\r\n }\r\n\r\n @Override\r\n public int getItemCount() {\r\n return list.size();\r\n }\r\n\r\n public boolean toggleName() {\r\n isFullName = !isFullName;\r\n notifyDataSetChanged();\r\n return isFullName;\r\n }\r\n\r\n public boolean getIsFullName() {\r\n return isFullName;\r\n }\r\n\r\n @Override\r\n public Filter getFilter() {\r\n if (mFilter == null) {\r\n mFilter = new ComponentFilter();\r\n }\r\n return mFilter;\r\n }\r\n\r\n private class ComponentFilter extends Filter {\r\n @Override\r\n protected void publishResults(CharSequence constraint,\r\n FilterResults results) {\r\n list = (List) results.values;\r\n notifyDataSetChanged();\r\n }\r\n\r\n @Override\r\n protected FilterResults performFiltering(CharSequence constraint) {\r\n final FilterResults results = new FilterResults();\r\n if (originalData == null) {\r\n synchronized (mLock) {\r\n originalData = new ArrayList<>(list);\r\n }\r\n }\r\n\r\n List tempList;\r\n if (TextUtils.isEmpty(constraint)||constraint.toString().trim().length()==0) {\r\n synchronized (mLock) {\r\n tempList = new ArrayList<>(originalData);\r\n }\r\n results.values = tempList;\r\n results.count = tempList.size();\r\n } else {\r\n synchronized (mLock) {\r\n tempList = new ArrayList<>(originalData);\r\n }\r\n\r\n final List newValues = new ArrayList<>();\r\n int type=-1;\r\n for (T entry : tempList) {\r\n if(type<0){\r\n type=0;\r\n if(entry instanceof ReceiverWithActionEntry){\r\n type=1;\r\n }\r\n }\r\n\r\n //最好trim一下\r\n String query=constraint.toString().trim().toLowerCase(Locale.getDefault());\r\n String lowerName=entry.className.toLowerCase(Locale.getDefault());\r\n if ((isFullName && lowerName.contains (query)\r\n || (!isFullName && lowerName.substring(lowerName.lastIndexOf(\".\")+1).contains(query)))){\r\n newValues.add(entry);\r\n }else if(type>0){\r\n ReceiverWithActionEntry receiverEntry= (ReceiverWithActionEntry) entry;\r\n if(receiverEntry.appName.toLowerCase(Locale.getDefault()).contains(query)){\r\n newValues.add(entry);\r\n }\r\n }\r\n }\r\n\r\n results.values = newValues;\r\n results.count = newValues.size();\r\n }\r\n\r\n return results;\r\n }\r\n }\r\n\r\n}\r\n\napp/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java\npublic class IfwUtil {\n private static final String TAG = \"IfwUtil\";\n private static final String SYSTEM_PROPERTY_EFS_ENABLED = \"persist.security.efs.enabled\";\n\n public static final int COMPONENT_FLAG_EMPTY = 0x00;\n public static final int COMPONENT_FLAG_ACTIVITY = 0x01;\n public static final int COMPONENT_FLAG_RECEIVER = 0x10;\n public static final int COMPONENT_FLAG_SERVICE = 0x100;\n public static final int COMPONENT_FLAG_ALL = 0x111;\n\n public static final String BACKUP_LOCAL_FILE_EXT = \".ifw\";\n public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = \".xml\"; //标准ifw备份后缀\n public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = \"$\" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀\n\n /**\n * 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件
\n * 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容\n *\n * @param positions 某一类component的位置\n */\n public static boolean saveComponentIfw(Context context,\n @NonNull String packageName,\n IfwEntry ifwEntry,\n @NonNull AbstractComponentAdapter adapter,\n int cType,\n boolean useParentIfw,\n Integer... positions) {\n return saveComponentIfw(context, packageName, ifwEntry, adapter, cType, useParentIfw, null, positions);\n }\n\n /**\n * 组件列表中修改选中位置component的ifw状态,并保存所有component到系统ifw文件(先保存到本地临时文件)
\n * 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容\n * @param localTempDir 所有app的ifw文件已经都复制到本地的目录,供组件全局禁用使用,{@link cn.wq.myandroidtoolspro.recyclerview.fragment.SearchComponentInAllFragment}\n * @param positions 某一类component的位置\n */\n public static boolean saveComponentIfw(Context context,\n @NonNull String packageName,\n IfwEntry ifwEntry,\n @NonNull AbstractComponentAdapter adapter,\n int cType,\n boolean useParentIfw,\n @Nullable File localTempDir,\n Integer... positions\n ) {\n if (positions == null || positions.length == 0) {\n //不应该为空\n return true;\n }\n if (ifwEntry == null || ifwEntry == IfwEntry.EMPTY) {\n ifwEntry = new IfwEntry();\n if (useParentIfw) {\n AppInfoForManageFragment2.mIfwEntry = ifwEntry;\n }\n }\n Map> componentMap = getComponentMapInIfw(cType, ifwEntry);\n ComponentEntry entry;\n for (Integer pos : positions) {\n entry = adapter.getItem(pos);\n if (entry == null) {\n continue;\n }\n String cls = entry.className;\n if (cls.startsWith(\".\")) {\n cls = entry.packageName + cls;\n }\n Set componentSet = componentMap.get(packageName);\n if (componentSet == null) {\n componentSet = new HashSet<>();\n componentMap.put(packageName, componentSet);\n }\n if (entry.isIfwed) {\n componentSet.remove(cls);\n } else {\n componentSet.add(cls);\n }\n }\n\n return saveIfwEntryToSystemFile(context, packageName, ifwEntry, localTempDir);\n }\n\n /**\n * 备份使用,先保存一个app下的禁用组件到本地文件,最后一次cp到系统目录中\n */\n public static void saveComponentIfwToLocal(@NonNull String packageName,\n List list,\n @NonNull String tempDir\n ) throws IOException {\n if (list == null) {\n return;\n }\n IfwEntry ifwEntry = new IfwEntry();\n for (BackupEntry entry : list) {\n Map> componentMap = getComponentMapInIfw(entry.cType, ifwEntry);\n Set componentSet = componentMap.get(packageName);\n if (componentSet == null) {\n componentSet = new HashSet<>();\n componentMap.put(packageName, componentSet);\n }\n componentSet.add(entry.className);\n }\n saveIfwEntryToLocalFile(packageName, ifwEntry, tempDir);\n }\n\n private static void buildIfwEntryToString(StringBuilder sBuilder, @NonNull String packageName, @NonNull IfwEntry ifwEntry) {\n buildIfwEntryToString(sBuilder, packageName, ifwEntry.serviceMap, \"service\");\n buildIfwEntryToString(sBuilder, packageName, ifwEntry.activityMap, \"activity\");\n buildIfwEntryToString(sBuilder, packageName, ifwEntry.receiverMap, \"broadcast\");\n }\n\n /**\n * @param sBuilder\n * @param packageName\n * @param componentMap\n * @param tagName service,activity,broadcast\n */\n private static void buildIfwEntryToString(StringBuilder sBuilder, @NonNull String packageName, Map> componentMap, String tagName) {\n if (componentMap != null && componentMap.size() > 0) {\n Set set = componentMap.get(packageName);\n if (set != null && set.size() > 0) {\n sBuilder.append(\" <\").append(tagName).append(\" block=\\\"true\\\" log=\\\"false\\\">\\n\");\n for (String className : set) {\n String cls = className;\n if (className.startsWith(packageName)) {\n cls = \".\" + className.substring(packageName.length() + 1);\n }\n sBuilder.append(\" \\n\");\n }\n sBuilder.append(\" \\n\");\n }\n }\n }\n\n /**\n * 保存IfwEntry中指定packageName的数据到系统文件\n * @param localTempDir 可以为空;为空时使用 getExternalCacheDir()\n */\n private static boolean saveIfwEntryToSystemFile(Context context, @NonNull String packageName, @NonNull IfwEntry ifwEntry,@Nullable File localTempDir) {\n StringBuilder sBuilder = new StringBuilder(\"\\n\");\n buildIfwEntryToString(sBuilder, packageName, ifwEntry);\n sBuilder.append(\"\\n\");\n\n return saveIfwStringToSystemFile(context, sBuilder.toString(), packageName, localTempDir);\n }\n\n /**\n * 保存IfwEntry到我自定义后缀的系统文件\n */\n public static boolean saveIfwEntryToMySystemFile(Context context, @NonNull IfwEntry ifwEntry) {\n Set packageNameSet = new HashSet<>(ifwEntry.serviceMap.keySet());\n packageNameSet.addAll(ifwEntry.receiverMap.keySet());\n packageNameSet.addAll(ifwEntry.activityMap.keySet());\n Utils.debug(TAG, \"saveIfwEntryToMySystemFile:\" + packageNameSet.toString()+\",\"+ifwEntry.serviceMap.keySet().toString()+\",\"\n +ifwEntry.receiverMap.keySet()+\",\"+ifwEntry.activityMap.keySet());\n for (String pkg : packageNameSet) {\n boolean result = saveIfwEntryToSystemFile(context, pkg, ifwEntry, null);\n if (!result) {\n return false;\n }\n }\n return true;\n }\n\n\n /**\n * 保存IfwEntry到本地文件\n */\n private static void saveIfwEntryToLocalFile(\n @NonNull String packageName,\n @NonNull IfwEntry ifwEntry,\n String destDir) throws IOException {\n StringBuilder sBuilder = new StringBuilder(\"\\n\");\n buildIfwEntryToString(sBuilder, packageName, ifwEntry);\n sBuilder.append(\"\\n\");\n\n saveIfwStringToLocalFile(sBuilder.toString(), packageName, destDir);\n }\n\n /**\n * 保存指定包名的ifw内容到系统文件,文件名格式为:packageName$.xml\n *\n * @param content ifw内容\n * @param pkgName app包名\n */\n private static boolean saveIfwStringToSystemFile(\n Context context,\n String content,\n @NonNull String pkgName,\n @Nullable File localTempDir\n ) {\n String tempRelativePath = getLocalRelativeTempIfwPath(context, pkgName, localTempDir);\n File tempFile = new File(Environment.getExternalStorageDirectory(), tempRelativePath);\n String destPath = getSystemIfwDir() + File.separator + pkgName + IfwUtil.BACKUP_SYSTEM_FILE_EXT_OF_MINE;\n FileWriter writer = null;\n try {\n writer = new FileWriter(tempFile, false);\n writer.write(content);\n writer.flush();\n writer.close();\n boolean result = copy(tempRelativePath, destPath);\n if (result) {\n return true;\n }\n } catch (Exception e) {\n Log.e(TAG, \"saveIfwStringToSystemFile error\", e);\n Utils.err(TAG, \"saveIfwStringToSystemFile error\", e);\n } finally {\n if (writer != null) {\n try {\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n //复制到/data/system/ifw下失败,得把临时文件删了\n if (tempFile.exists()) {\n tempFile.delete();\n }\n return false;\n }\n\n /**\n * 保存指定包名的ifw内容到本地文件,文件名格式为:packageName$.xml\n *\n * @param content ifw内容\n * @param pkgName app包名\n * @param destDir 存放ifw文件的目录\n */\n private static void saveIfwStringToLocalFile(String content, @NonNull String pkgName, String destDir) throws IOException {\n String tempPath = destDir + File.separator + pkgName + IfwUtil.BACKUP_SYSTEM_FILE_EXT_OF_MINE;\n FileWriter writer = null;\n try {\n writer = new FileWriter(tempPath, false);\n writer.write(content);\n writer.flush();\n writer.close();\n } finally {\n if (writer != null) {\n try {\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n /**\n * file path to file path\n * @param srcRelativePath 相对/sdcard路径\n */\n private static boolean copy(String srcRelativePath, String destPath) {\n boolean cpResult = Utils.runRootCommand(\"cp -f $EXTERNAL_STORAGE/\" + srcRelativePath + \" \" + destPath + \" \\n\")\n || Utils.runRootCommand(\"cat $EXTERNAL_STORAGE/\" + srcRelativePath + \" > \" + destPath + \" \\n\");\n if (!cpResult) {\n return false;\n }\n return Utils.runRootCommand(\"chmod 644 \" + destPath);\n }\n\n /**\n * all files in srsDir to destDir\n *
必须用 cp -R src/. dest 才能复制目录下面的所有文件\n */\n public static boolean copySysIfwToTempDir(File destDir) {\n String srcDir = IfwUtil.getSystemIfwDir();\n String tempRelativePath = getLocalRelativeTempIfwPath(destDir);\n return Utils.runRootCommand(\"cp -fR \" + srcDir + \"/. $EXTERNAL_STORAGE/\" + tempRelativePath);\n }\n\n /**\n * all files in srsDir to destDir\n *
必须用 cp -R src/. dest 才能复制目录下面的所有文件\n */\n public static boolean copyToIfwDir(File srcDir) {\n String destDir = IfwUtil.getSystemIfwDir();\n String tempRelativePath = getLocalRelativeTempIfwPath(srcDir);\n if (!Utils.runRootCommand(\"cp -fR $EXTERNAL_STORAGE/\" + tempRelativePath + \"/. \" + destDir)) {\n return false;\n }\n String chmodCmd = String.format(\"find %s -name '*%s'|xargs chmod 644\",\n destDir, IfwUtil.BACKUP_SYSTEM_FILE_EXT_OF_MINE);\n return Utils.runRootCommand(chmodCmd);\n }\n\n private static boolean isEncryptedFilesystemEnabled() {\n try {\n return (boolean) Class.forName(\"android.os.SystemProperties\")\n .getMethod(\"getBoolean\", String.class, boolean.class)\n .invoke(null, SYSTEM_PROPERTY_EFS_ENABLED, false);\n } catch (Exception e) {\n Log.e(TAG, \"isEncryptedFilesystemEnabled error\", e);\n Utils.err(TAG, \"isEncryptedFilesystemEnabled error\", e);\n return false;\n }\n }\n\n private static String getDirectoryPath(String variableName, String defaultPath) {\n String path = System.getenv(variableName);\n return path == null ? defaultPath : path;\n }\n\n public static String getSystemIfwDir() {\n String baseDir;\n if (isEncryptedFilesystemEnabled()) {\n baseDir = getDirectoryPath(\"ANDROID_SECURE_DATA\", \"/data/secure\");\n } else {\n baseDir = getDirectoryPath(\"ANDROID_DATA\", \"/data\");\n }\n return baseDir + File.separator + \"system\" + File.separator + \"ifw\";\n }\n\n /**\n * 加载指定包名的ifw文件\n *\n * @param cType 暂时都是all\n * @param loadLocalFirst 之前已加载到本地了,可以先加载本地文件\n */\n public static IfwEntry loadIfwFileForPkg(Context context, @NonNull String packageName, int cType, boolean loadLocalFirst) throws Exception {\n String tempRelativePath = getLocalRelativeTempIfwPath(context, packageName);\n if (!loadLocalFirst) {\n// String command = String.format(\"ls %s | grep '%s%s'\", getSystemIfwDir(), packageName, \"\\\\\" + IfwUtil.BACKUP_SYSTEM_FILE_EXT_OF_MINE);\n// List files = Utils.runRootCommandForResult(command);\n// if (files == null || files.size() == 0) {\n// return IfwEntry.EMPTY;\n// }\n// String sourcePath = getSystemIfwDir() + File.separator + files.get(0);\n// String catCmd = String.format(\"cat %s > $EXTERNAL_STORAGE/%s\", sourcePath, tempRelativePath);\n// if (!Utils.runRootCommand(catCmd)) {\n// return IfwEntry.ROOT_ERROR;\n// }\n\n //下面第一个命令有问题,文件不存在时不会终止命令\n// String command = String.format(\"cat `find %s -name '%s'|head -1` > $EXTERNAL_STORAGE/%s\",\n String command = String.format(\"find %s -name '%s' | xargs cat > $EXTERNAL_STORAGE/%s\",\n getSystemIfwDir(),\n packageName + \"\\\\\" + IfwUtil.BACKUP_SYSTEM_FILE_EXT_OF_MINE,\n tempRelativePath);\n if (!Utils.runRootCommand(command)) {\n return IfwEntry.ROOT_ERROR;\n }\n }\n\n return parseIfwFile(cType, packageName, new File(Environment.getExternalStorageDirectory(),tempRelativePath));\n }\n\n /**\n * 加载所有ifw文件\n *\n * @param loadLocalFirst 之前已加载到本地了,可以先加载本地文件\n */\n public static IfwEntry loadAllIfwFile(Context context, int cType, File ifwTempDir,boolean loadLocalFirst) throws Exception {\n //临时目录\n if (!ifwTempDir.exists()) {\n ifwTempDir.mkdirs();\n }\n\n if (!loadLocalFirst) {\n if(!copySysIfwToTempDir(ifwTempDir)){\n return IfwEntry.ROOT_ERROR;\n }\n }\n\n IfwEntry ifw = new IfwEntry();\n for (File f : ifwTempDir.listFiles()) {\n if (f.isDirectory()) {\n f.delete();\n continue;\n }\n\n if (!loadLocalFirst) {\n if (!f.getName().endsWith(IfwUtil.BACKUP_SYSTEM_FILE_EXT_OF_MINE)) {\n f.delete();\n continue;\n } else {\n //复制全部系统ifw文件时没法去掉$号,只能这时候去掉\n String name = f.getName().substring(0, f.getName().length() - BACKUP_SYSTEM_FILE_EXT_OF_MINE.length()) + BACKUP_LOCAL_FILE_EXT;\n File newF = new File(f.getParent(), name);\n if (newF.exists()) {\n newF.delete();\n }\n f.renameTo(newF);\n parseIfwFile(ifw, cType, null, newF);\n }\n } else {\n if (!f.getName().endsWith(BACKUP_LOCAL_FILE_EXT)) {\n f.delete();\n continue;\n } else {\n parseIfwFile(ifw, cType, null, f);\n }\n }\n\n }\n\n return ifw;\n }\n\n private static Map> getComponentMapInIfw(int cType, IfwEntry ifwEntry) {\n Map> componentMap = null;\n if (cType == COMPONENT_FLAG_SERVICE) {\n componentMap = ifwEntry.serviceMap;\n } else if (cType == COMPONENT_FLAG_ACTIVITY) {\n componentMap = ifwEntry.activityMap;\n } else if (cType == COMPONENT_FLAG_RECEIVER) {\n componentMap = ifwEntry.receiverMap;\n }\n return componentMap;\n }\n\n public static boolean isComponentInIfw(@NonNull String packageName, String className, int cType, IfwEntry ifwEntry) {\n if (ifwEntry == null || ifwEntry.status < 0) {\n return false;\n }\n\n Map> componentMap = getComponentMapInIfw(cType, ifwEntry);\n\n return componentMap != null\n && componentMap.get(packageName) != null\n && componentMap.get(packageName).contains(className);\n }\n\n /**\n * cache目录下packageName.ifw文件\n * @see #getLocalRelativeTempIfwPath(Context, String)\n */\n// private static String getLocalTempIfwPath(Context context, @NonNull String packageName) {\n// return context.getExternalCacheDir() + File.separator + packageName + BACKUP_LOCAL_FILE_EXT;\n// }\n\n /**\n * 外置cache目录下packageName.ifw文件的相对/sdcard路径\n * shell中获取的/sdcard路径可能和api获取的不一致,且互相不可见:http://www.cloudchou.com/android/post-689.html\n * /storage/emulated/legacy vs /storage/emulated/0\n */\n private static String getLocalRelativeTempIfwPath(Context context, @NonNull String packageName) {\n return getLocalRelativeTempIfwPath(context, packageName, null);\n }\n\n /**\n * 外置cache目录下(或者指定临时目录下)packageName.ifw文件的相对/sdcard路径\n * shell中获取的/sdcard路径可能和api获取的不一致,且互相不可见:http://www.cloudchou.com/android/post-689.html\n * /storage/emulated/legacy vs /storage/emulated/0\n */\n private static String getLocalRelativeTempIfwPath(Context context, @NonNull String packageName,@Nullable File localTempDir) {\n File dir = localTempDir;\n if (localTempDir == null) {\n dir = context.getExternalCacheDir();\n }\n File full = new File(dir, packageName + BACKUP_LOCAL_FILE_EXT);\n return getLocalRelativeTempIfwPath(full);\n }\n\n /**\n * cache目录下packageName.ifw文件的相对/sdcard路径\n * shell中获取的/sdcard路径可能和api获取的不一致,且互相不可见:http://www.cloudchou.com/android/post-689.html\n * /storage/emulated/legacy vs /storage/emulated/0\n */\n private static String getLocalRelativeTempIfwPath(File file) {\n return Environment.getExternalStorageDirectory().toURI().relativize(file.toURI()).getPath();\n }\n\n /**\n * 重构方法,省略IfwEntry的传入\n * @see #parseIfwFile(IfwEntry, int, String, File)\n */\n public static IfwEntry parseIfwFile(int cType,@Nullable String packageName, File tempPath) throws Exception {\n return parseIfwFile(null, cType, packageName, tempPath);\n }\n\n /**\n * 从ifw文件(tempPath)中读数据到entry中,可以不限包名\n * @param ifw 可以为空,最后会返回最新的IfwEntry\n */\n public static IfwEntry parseIfwFile(@Nullable IfwEntry ifw, int cType, @Nullable String packageName,@NonNull File tempPath) throws Exception {\n if (ifw == null) {\n ifw = new IfwEntry();\n }\n XmlPullParser parser = Xml.newPullParser();\n FileInputStream in = new FileInputStream(tempPath);\n parser.setInput(in, \"UTF-8\");\n int type;\n while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {\n if (type == XmlPullParser.START_TAG && !\"rules\".equals(parser.getName())) {\n if (((cType & COMPONENT_FLAG_ACTIVITY) > 0) && (\"activity\".equals(parser.getName()))) {\n parseComponent(parser, packageName, ifw.activityMap);\n } else if (((cType & COMPONENT_FLAG_RECEIVER) > 0) && (\"broadcast\".equals(parser.getName()))) {\n parseComponent(parser, packageName, ifw.receiverMap);\n } else if (((cType & COMPONENT_FLAG_SERVICE) > 0) && (\"service\".equals(parser.getName()))) {\n parseComponent(parser, packageName, ifw.serviceMap);\n }\n }\n }\n in.close();\n return ifw;\n }\n\n /**\n * @param packageName 限定解析的App包名\n * @param map packagename -> Set\n */\n private static void parseComponent(XmlPullParser parser,\n @Nullable String packageName,\n @NonNull Map> map) {\n if (!\"true\".equals(parser.getAttributeValue(null, \"block\"))) {\n return;\n }\n int depth = parser.getDepth();\n int type;\n try {\n while ((type = parser.next()) != XmlPullParser.END_DOCUMENT &&\n (type != XmlPullParser.END_TAG || parser.getDepth() > depth)) {\n if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {\n continue;\n }\n if (\"component-filter\".equals(parser.getName())) {\n String cName = parser.getAttributeValue(null, \"name\");\n ComponentName c = ComponentName.unflattenFromString(cName);\n if (c != null && (TextUtils.isEmpty(packageName)\n || (TextUtils.equals(c.getPackageName(), packageName)))) {\n Set set = map.get(c.getPackageName());\n if (set == null) {\n set = new HashSet<>();\n map.put(c.getPackageName(), set);\n }\n set.add(c.getClassName());\n }\n }\n\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n\n public static class IfwEntry {\n public Map> activityMap = new ArrayMap<>();\n public Map> receiverMap = new ArrayMap<>();\n public Map> serviceMap = new ArrayMap<>();\n public int status;\n\n public final static IfwEntry ROOT_ERROR, EMPTY;\n\n static {\n ROOT_ERROR = new IfwEntry();\n ROOT_ERROR.status = -1;\n\n EMPTY = new IfwEntry();\n EMPTY.status = 0;\n }\n\n public void clear() {\n if (activityMap != null) {\n activityMap.clear();\n }\n if (receiverMap != null) {\n receiverMap.clear();\n }\n if (serviceMap != null) {\n serviceMap.clear();\n }\n }\n\n }\n\n}", "answers": [" public MultiSelectionUtils.Controller loadMultiController() {\r"], "length": 6918, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "39f5e912-6b3c-4d49-b5d4-abb1cea7173d", "reasoning": "The @Override annotation follows the ReceiverViewHolder constructor. The next method to implement is the abstract loadMultiController() from MultiSelectableViewHolder, so the next line should be the method signature that overrides it.", "reasoning_model_answer": "public MultiSelectionUtils.Controller loadMultiController() {", "assistant_with_reasoning": "\nThe @Override annotation follows the ReceiverViewHolder constructor. The next method to implement is the abstract loadMultiController() from MultiSelectableViewHolder, so the next line should be the method signature that overrides it.\n\npublic MultiSelectionUtils.Controller loadMultiController() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.188, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37511, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public MultiSelectionUtils.Controller loadMultiController() {", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "import de.haupz.basicode.ast.ProgramNode;\nimport de.haupz.basicode.interpreter.Configuration;\nimport de.haupz.basicode.interpreter.InterpreterState;\nimport de.haupz.basicode.io.BasicInput;\nimport de.haupz.basicode.io.BasicOutput;\nimport de.haupz.basicode.io.BufferedReaderInput;\nimport de.haupz.basicode.io.PrintStreamOutput;\nimport de.haupz.basicode.parser.BasicParser;\nimport de.haupz.basicode.parser.ParseException;\nimport java.io.BufferedReader;\nimport java.io.ByteArrayOutputStream;\nimport java.io.PrintStream;\nimport java.io.StringReader;\nimport static org.junit.jupiter.api.Assertions.*;", "context": "src/test/java/de/haupz/basicode/InterpreterTest.java\npackage de.haupz.basicode;\n\n\n\n\npublic abstract class InterpreterTest {\n\n ByteArrayOutputStream bytesOut;\n\n private InterpreterState state;\n\n void setUpState(ProgramNode prog, String input) {\n bytesOut = new ByteArrayOutputStream();\n PrintStream ps = new PrintStream(bytesOut, true);\n BasicOutput out = new PrintStreamOutput(ps);\n BufferedReader br = new BufferedReader(new StringReader(input));\n BasicInput in = new BufferedReaderInput(br);\n state = new InterpreterState(prog, in, out, new Configuration());\n }\n\n private ProgramNode buildProgram(String source) {\n\nsrc/main/java/de/haupz/basicode/io/BasicInput.java\npublic interface BasicInput {\n\n /**\n * Read a line of input terminated by a newline. This is a blocking operation.\n *\n * @return the line that was entered.\n * @throws IOException in case anything goes wrong with the input.\n */\n String readLine() throws IOException;\n\n /**\n * Read a single character from the input. This is a blocking operation.\n *\n * @return the character that was entered.\n * @throws IOException in case anything goes wrong witn the input.\n */\n int readChar() throws IOException;\n\n /**\n * If a character is available from the input at the time this method is called, return that character. This is a\n * non-blocking operation.\n *\n * @return the character available from the input at the time this method is called, or 0 if no character is\n * available.\n */\n default int lastChar() { return 0; }\n\n /**\n * Instruct the input to note that a waiting operation is under way, and that the input can interrupt this if a key\n * is pressed.\n *\n * @param ready if {@code true}, input will be ready to interrupt a waiting operation; if {@code false}, it won't.\n */\n default void setReadyToInterrupt(boolean ready) {}\n\n /**\n * Control whether pressing a stop key (e.g., ESC) will terminate program execution.\n *\n * @param acceptStopKey if {@code trye}, the stop key will terminate program execution; if {@code false}, it won't.\n */\n default void toggleAcceptStopKey(boolean acceptStopKey) {}\n\n /**\n * Register a handler to be invoked when the stop key is pressed.\n *\n * @param stopKeyHandler the handler.\n */\n default void registerStopKeyHandler(StopKeyHandler stopKeyHandler) {}\n\n}\n\nsrc/main/java/de/haupz/basicode/parser/ParseException.java\npublic class ParseException extends Exception {\n\n /**\n * The version identifier for this Serializable class.\n * Increment only if the serialized form of the\n * class changes.\n */\n private static final long serialVersionUID = 1L;\n\n /**\n * The end of line string for this machine.\n */\n protected static String EOL = System.getProperty(\"line.separator\", \"\\n\");\n\n /**\n * This constructor is used by the method \"generateParseException\"\n * in the generated parser. Calling this constructor generates\n * a new object of this type with the fields \"currentToken\",\n * \"expectedTokenSequences\", and \"tokenImage\" set.\n */\n public ParseException(Token currentTokenVal,\n int[][] expectedTokenSequencesVal,\n String[] tokenImageVal\n )\n {\n super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));\n currentToken = currentTokenVal;\n expectedTokenSequences = expectedTokenSequencesVal;\n tokenImage = tokenImageVal;\n }\n\n /**\n * The following constructors are for use by you for whatever\n * purpose you can think of. Constructing the exception in this\n * manner makes the exception behave in the normal way - i.e., as\n * documented in the class \"Throwable\". The fields \"errorToken\",\n * \"expectedTokenSequences\", and \"tokenImage\" do not contain\n * relevant information. The JavaCC generated code does not use\n * these constructors.\n */\n\n public ParseException() {\n super();\n }\n\n /** Constructor with message. */\n public ParseException(String message) {\n super(message);\n }\n\n\n /**\n * This is the last token that has been consumed successfully. If\n * this object has been created due to a parse error, the token\n * following this token will (therefore) be the first error token.\n */\n public Token currentToken;\n\n /**\n * Each entry in this array is an array of integers. Each array\n * of integers represents a sequence of tokens (by their ordinal\n * values) that is expected at this point of the parse.\n */\n public int[][] expectedTokenSequences;\n\n /**\n * This is a reference to the \"tokenImage\" array of the generated\n * parser within which the parse error occurred. This array is\n * defined in the generated ...Constants interface.\n */\n public String[] tokenImage;\n\n /**\n * It uses \"currentToken\" and \"expectedTokenSequences\" to generate a parse\n * error message and returns it. If this object has been created\n * due to a parse error, and you do not catch it (it gets thrown\n * from the parser) the correct error message\n * gets displayed.\n */\n private static String initialise(Token currentToken,\n int[][] expectedTokenSequences,\n String[] tokenImage) {\n\n StringBuilder expected = new StringBuilder();\n int maxSize = 0;\n for (int i = 0; i < expectedTokenSequences.length; i++) {\n if (maxSize < expectedTokenSequences[i].length) {\n maxSize = expectedTokenSequences[i].length;\n }\n for (int j = 0; j < expectedTokenSequences[i].length; j++) {\n expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');\n }\n if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {\n expected.append(\"...\");\n }\n expected.append(EOL).append(\" \");\n }\n String retval = \"Encountered \\\"\";\n Token tok = currentToken.next;\n for (int i = 0; i < maxSize; i++) {\n if (i != 0) retval += \" \";\n if (tok.kind == 0) {\n retval += tokenImage[0];\n break;\n }\n retval += \" \" + tokenImage[tok.kind];\n retval += \" \\\"\";\n retval += add_escapes(tok.image);\n retval += \" \\\"\";\n tok = tok.next;\n }\n if (currentToken.next != null) {\n retval += \"\\\" at line \" + currentToken.next.beginLine + \", column \" + currentToken.next.beginColumn;\n }\n retval += \".\" + EOL;\n \n \n if (expectedTokenSequences.length == 0) {\n // Nothing to add here\n } else {\n\t if (expectedTokenSequences.length == 1) {\n\t retval += \"Was expecting:\" + EOL + \" \";\n\t } else {\n\t retval += \"Was expecting one of:\" + EOL + \" \";\n\t }\n\t retval += expected.toString();\n }\n \n return retval;\n }\n\n\n /**\n * Used to convert raw characters to their escaped version\n * when these raw version cannot be used as part of an ASCII\n * string literal.\n */\n static String add_escapes(String str) {\n StringBuilder retval = new StringBuilder();\n char ch;\n for (int i = 0; i < str.length(); i++) {\n switch (str.charAt(i))\n {\n case '\\b':\n retval.append(\"\\\\b\");\n continue;\n case '\\t':\n retval.append(\"\\\\t\");\n continue;\n case '\\n':\n retval.append(\"\\\\n\");\n continue;\n case '\\f':\n retval.append(\"\\\\f\");\n continue;\n case '\\r':\n retval.append(\"\\\\r\");\n continue;\n case '\\\"':\n retval.append(\"\\\\\\\"\");\n continue;\n case '\\'':\n retval.append(\"\\\\\\'\");\n continue;\n case '\\\\':\n retval.append(\"\\\\\\\\\");\n continue;\n default:\n if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\n String s = \"0000\" + Integer.toString(ch, 16);\n retval.append(\"\\\\u\" + s.substring(s.length() - 4, s.length()));\n } else {\n retval.append(ch);\n }\n continue;\n }\n }\n return retval.toString();\n }\n\n}\n\nsrc/main/java/de/haupz/basicode/io/BufferedReaderInput.java\npublic class BufferedReaderInput implements BasicInput {\n\n private final BufferedReader br;\n\n public BufferedReaderInput(BufferedReader br) {\n this.br = br;\n }\n\n @Override\n public String readLine() throws IOException {\n return br.readLine();\n }\n\n @Override\n public int readChar() throws IOException {\n return br.read();\n }\n\n}\n\nsrc/main/java/de/haupz/basicode/ast/ProgramNode.java\npublic class ProgramNode extends BasicNode {\n\n /**\n * All lines of the BASICODE program.\n */\n private final List lines;\n\n /**\n * The flattened representation of all statements of the program, for easier execution.\n */\n private List statements = new ArrayList<>();\n\n /**\n * Map BASIC line numbers to indices in the flattened {@link #statements} list. The statement index for any line\n * number is the index of the first statement on the respective line.\n */\n private Map lineNumberToStatementIndex = new HashMap<>();\n\n /**\n * A \"code address\", comprising of a line and statement index on that line.\n *\n * @param line a BASIC line number.\n * @param statement a 0-based statement index into the respective BASIC line.\n */\n record LineAndStatement(int line, int statement) {}\n\n /**\n * Map statement indices from the {@link #statements} list back to line numbers and statements. This is used for\n * debugging support.\n */\n private Map statementIndexToLineNumberAndStatement = new HashMap<>();\n\n /**\n * The flattened list of all elements from {@code DATA} lines, in the order they appear in in the BASIC source code.\n */\n private final List dataList;\n\n /**\n *

Construct a program from a list of line nodes and data elements.

\n *\n *

Aside from initialising the {@link #lines} and {@link #dataList}, the constructor also builds the flattened\n * {@link #statements} list and populates the {@link #lineNumberToStatementIndex} and\n * {@link #statementIndexToLineNumberAndStatement} maps.

\n *\n * @param lines the {@link LineNode}s representing the source code.\n * @param dataList the {@code DATA} elements from the source code.\n */\n public ProgramNode(List lines, List dataList) {\n this.lines = List.copyOf(lines);\n lines.forEach(line -> {\n // A new line: the index of its first statement is the current size of the statements array.\n lineNumberToStatementIndex.put(line.getLineNumber(), statements.size());\n statements.addAll(List.copyOf(line.getStatements()));\n int nStatements = statements.size();\n int nStatementsOnLine = line.getStatements().size();\n int lineNum = line.getLineNumber();\n for (int s = 0; s < nStatementsOnLine; ++s) {\n statementIndexToLineNumberAndStatement.put(\n nStatements - nStatementsOnLine + s, new LineAndStatement(lineNum, s));\n }\n });\n this.dataList = List.copyOf(dataList);\n }\n\n /**\n *

The main interpreter loop.

\n *\n *

Until the interpreter state is {@linkplain InterpreterState#shouldEnd() notified about termination}, the\n * interpreter fetches the {@linkplain InterpreterState#getStatementIndex() next statement} from the\n * {@link #statements} list and runs it.

\n *\n *

Statements may set specific flags in the {@linkplain InterpreterState interpreter state}. After each statement\n * execution, the interpreter checks if any of the flags is set, and handles it accordingly before resetting it\n * again. The flags are as follows:

    \n *
  • {@link InterpreterState#isLineJumpNext()}: a jump to another line needs to be performed, e.g., because a\n * {@code GOTO} statement was encountered. The interpreter will set the target statement using\n * {@link #resolveJump(InterpreterState)}.
  • \n *
  • {@link InterpreterState#isReturnNext()}: the interpreter needs to {@code RETURN} from a {@code GOSUB}\n * call. It will {@linkplain InterpreterState#getReturnIndex() retrieve the return address from the call stack}\n * and continue execution there.
  • \n *
  • {@link InterpreterState#isBackedgeNext()}: the interpreter needs to jump from a {@code NEXT} statement to\n * the head of the corresponding loop (a {@code FOR} statement). It will\n * {@linkplain InterpreterState#getBackedgeTarget() retrieve the loop head's statement index} and continue\n * execution there.
  • \n *
  • {@link InterpreterState#isSkipLine()}: the remainder of a line needs to be skipped, and execution needs\n * to proceed at the beginning of the next line.
  • \n *
If no flag is set, the interpreter will simply move on to the next statement, if there is one. If there\n * isn't, it will {@linkplain InterpreterState#terminate() mark the interpreter state for termination}.

\n *\n *

In case the execution of a statement throws an exception, the interpreter will provide some helpful details\n * about the location in the BASIC source code where the exception originated. It will also print the BASIC call\n * stack (in case any {@code GOSUB} routines were being run). Finally, it will dump the Java call stack of the\n * interpreter itself.

\n *\n * @param state the interpreter state.\n */\n @Override\n public void run(InterpreterState state) {\n StatementNode statement;\n while (!state.shouldEnd()) {\n statement = statements.get(state.getStatementIndex());\n try {\n statement.run(state);\n } catch (Exception e) {\n Stack stack = state.getCallStack();\n String stackDump = \"\";\n LineAndStatement las = statementIndexToLineNumberAndStatement.get(state.getStatementIndex());\n stackDump = String.format(\"at line %d, statement %d\", las.line, las.statement);\n if (!stack.isEmpty()) {\n stackDump += '\\n' + stack.reversed().stream().map(stmt -> {\n LineAndStatement sdlas = statementIndexToLineNumberAndStatement.get(stmt - 1);\n return String.format(\"at line %d, statement %d\", sdlas.line, sdlas.statement);\n }).collect(Collectors.joining(\"\\n\"));\n }\n throw new IllegalStateException(stackDump, e);\n }\n if (state.isLineJumpNext()) {\n resolveJump(state);\n } else if (state.isReturnNext()) {\n state.setNextStatement(state.getReturnIndex());\n state.returnDone();\n } else if (state.isBackedgeNext()) {\n state.setNextStatement(state.getBackedgeTarget());\n state.backedgeDone();\n } else if (state.isSkipLine()) {\n int stmt = state.getStatementIndex();\n int lineToSkip = statementIndexToLineNumberAndStatement.get(stmt).line;\n do {\n ++stmt;\n } while (lineToSkip == statementIndexToLineNumberAndStatement.get(stmt).line);\n state.setNextStatement(stmt);\n state.skipLineDone();\n } else {\n state.incStatementIndex();\n if (state.getStatementIndex() >= statements.size()) {\n state.terminate();\n }\n }\n }\n }\n\n /**\n * Resolve a jump by {@linkplain #lineNumberToStatementIndex retrieving the index of the first statement} of the\n * {@linkplain InterpreterState#getLineJumpTarget() target line}, and\n * {@linkplain InterpreterState#setNextStatement(int) setting that to be the next statement to execute}.\n *\n * @param state the interpreter state.\n */\n private void resolveJump(InterpreterState state) {\n try {\n state.setNextStatement(lineNumberToStatementIndex.get(state.getLineJumpTarget()));\n } catch (NullPointerException npe) {\n throw new IllegalStateException(\"line not found: \" + state.getLineJumpTarget());\n }\n state.lineJumpDone();\n }\n\n /**\n * This method is overridden to throw an exception, as programs aren't expressions.\n *\n * @param state the interpreter state.\n * @return nothing; this implementation will throw an exception.\n */\n @Override\n public Object eval(InterpreterState state) {\n throw new IllegalStateException(\"a ProgramNode should not be evaluated\");\n }\n\n /**\n * @return the list of {@ode DATA} elements.\n */\n public List getDataList() {\n return dataList;\n }\n\n}\n\nsrc/main/java/de/haupz/basicode/io/PrintStreamOutput.java\npublic class PrintStreamOutput implements BasicOutput {\n\n private int col = 0;\n\n private int row = 0;\n\n private final PrintStream ps;\n\n public PrintStreamOutput(PrintStream ps) {\n this.ps = ps;\n }\n\n @Override\n public void print(String s) {\n ps.print(s);\n col += s.length();\n }\n\n @Override\n public void println(String s) {\n ps.println(s);\n col = 0;\n ++row;\n }\n\n @Override\n public void println() {\n ps.println();\n col = 0;\n ++row;\n }\n\n @Override\n public void flush() {\n ps.flush();\n }\n\n @Override\n public TextCursor getTextCursor() {\n return new TextCursor(col, row);\n }\n\n}\n\nsrc/main/java/de/haupz/basicode/parser/BasicParser.java\npublic class BasicParser implements BasicParserConstants {\n List dataList = new ArrayList<>();\n\n// Parser.\n\n//\n// basic structures\n//\n final public \nProgramNode program() throws ParseException {List lines = new ArrayList<>();\n LineNode l;\n label_1:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:{\n ;\n break;\n }\n default:\n jj_la1[0] = jj_gen;\n break label_1;\n }\n l = line();\nlines.add(l);\n }\n{if (\"\" != null) return new ProgramNode(lines, dataList);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public LineNode line() throws ParseException {List statements = new ArrayList<>();\n int num;\n StatementNode st;\n num = lineNumber();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case DATA:{\n st = data_line();\nstatements.add(st);\n break;\n }\n case DEF:\n case DIM:\n case END:\n case FOR:\n case GOSUB:\n case GOTO:\n case IF:\n case INPUT:\n case LET:\n case NEXT:\n case ON:\n case PRINT:\n case READ:\n case REM:\n case RESTORE:\n case RETURN:\n case RUN:\n case STOP:\n case IDENTIFIER:{\n st = statement();\nstatements.add(st);\n label_2:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 52:{\n ;\n break;\n }\n default:\n jj_la1[1] = jj_gen;\n break label_2;\n }\n jj_consume_token(52);\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case DEF:\n case DIM:\n case END:\n case FOR:\n case GOSUB:\n case GOTO:\n case IF:\n case INPUT:\n case LET:\n case NEXT:\n case ON:\n case PRINT:\n case READ:\n case REM:\n case RESTORE:\n case RETURN:\n case RUN:\n case STOP:\n case IDENTIFIER:{\n st = statement();\nstatements.add(st);\n break;\n }\n default:\n jj_la1[2] = jj_gen;\n ;\n }\n }\n break;\n }\n default:\n jj_la1[3] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case EOL:{\n jj_consume_token(EOL);\n break;\n }\n case 0:{\n jj_consume_token(0);\n break;\n }\n default:\n jj_la1[4] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n{if (\"\" != null) return new LineNode(num, statements);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public int lineNumber() throws ParseException {Token n;\n n = jj_consume_token(NUMBER);\n{if (\"\" != null) return Integer.parseInt(n.image);}\n throw new Error(\"Missing return statement in function\");\n}\n\n//\n// statements\n//\n final public \nStatementNode statement() throws ParseException {Token t;\n ExpressionNode e;\n StatementNode s;\n int n;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case REM:{\n t = jj_consume_token(REM);\n{if (\"\" != null) return new RemNode(t.image);}\n break;\n }\n case LET:\n case IDENTIFIER:{\n s = assignment();\n{if (\"\" != null) return s;}\n break;\n }\n case PRINT:{\n s = print_statement();\n{if (\"\" != null) return s;}\n break;\n }\n case GOTO:{\n jj_consume_token(GOTO);\n n = lineNumber();\n{if (\"\" != null) return new GotoNode(n);}\n break;\n }\n case GOSUB:{\n jj_consume_token(GOSUB);\n n = lineNumber();\n{if (\"\" != null) return new GosubNode(n);}\n break;\n }\n case RETURN:{\n jj_consume_token(RETURN);\n{if (\"\" != null) return new ReturnNode();}\n break;\n }\n case ON:{\n s = dependent_jump();\n{if (\"\" != null) return s;}\n break;\n }\n case DIM:{\n s = dim_statement();\n{if (\"\" != null) return s;}\n break;\n }\n case FOR:{\n s = for_statement();\n{if (\"\" != null) return s;}\n break;\n }\n case NEXT:{\n jj_consume_token(NEXT);\n t = jj_consume_token(IDENTIFIER);\n{if (\"\" != null) return new NextNode(t.image);}\n break;\n }\n case IF:{\n s = if_statement();\n{if (\"\" != null) return s;}\n break;\n }\n case READ:{\n s = read_statement();\n{if (\"\" != null) return s;}\n break;\n }\n case RESTORE:{\n jj_consume_token(RESTORE);\n{if (\"\" != null) return new RestoreNode();}\n break;\n }\n case END:\n case STOP:{\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case END:{\n jj_consume_token(END);\n break;\n }\n case STOP:{\n jj_consume_token(STOP);\n break;\n }\n default:\n jj_la1[5] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n{if (\"\" != null) return new EndNode();}\n break;\n }\n case INPUT:{\n jj_consume_token(INPUT);\n t = jj_consume_token(IDENTIFIER);\n{if (\"\" != null) return new InputNode(t.image);}\n break;\n }\n case RUN:{\n jj_consume_token(RUN);\n{if (\"\" != null) return new RunNode();}\n break;\n }\n case DEF:{\n s = def_fn();\n{if (\"\" != null) return s;}\n break;\n }\n default:\n jj_la1[6] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode data_line() throws ParseException {Object l;\n List items = new ArrayList<>();\n jj_consume_token(DATA);\n l = data_literal();\nitems.add(l);\n label_3:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n ;\n break;\n }\n default:\n jj_la1[7] = jj_gen;\n break label_3;\n }\n jj_consume_token(53);\n l = data_literal();\nitems.add(l);\n }\ndataList.addAll(items);\n {if (\"\" != null) return new DataNode(items);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public Object data_literal() throws ParseException {int sgn = 1;\n Token t;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:\n case FLOAT:\n case 54:{\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 54:{\n jj_consume_token(54);\nsgn = -1;\n break;\n }\n default:\n jj_la1[8] = jj_gen;\n ;\n }\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:{\n t = jj_consume_token(NUMBER);\n break;\n }\n case FLOAT:{\n t = jj_consume_token(FLOAT);\n break;\n }\n default:\n jj_la1[9] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n{if (\"\" != null) return sgn * Double.parseDouble(t.image);}\n break;\n }\n case STRING:{\n t = jj_consume_token(STRING);\n{if (\"\" != null) return t.image.substring(1, t.image.length() - 1);}\n break;\n }\n default:\n jj_la1[10] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode assignment() throws ParseException {LetNode.LHS l;\n ExpressionNode e = null;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case LET:{\n jj_consume_token(LET);\n break;\n }\n default:\n jj_la1[11] = jj_gen;\n ;\n }\n l = lhs();\n jj_consume_token(55);\n e = expression();\n{if (\"\" != null) return new LetNode(l, e);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public LetNode.LHS lhs() throws ParseException {Token t;\n ExpressionNode e = null;\n ExpressionNode f = null;\n t = jj_consume_token(IDENTIFIER);\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 56:{\n jj_consume_token(56);\n e = expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n jj_consume_token(53);\n f = expression();\n break;\n }\n default:\n jj_la1[12] = jj_gen;\n ;\n }\n jj_consume_token(57);\n{if (\"\" != null) return new LetNode.Array(t.image, e, f);}\n break;\n }\n default:\n jj_la1[13] = jj_gen;\n ;\n }\n{if (\"\" != null) return new LetNode.Variable(t.image);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode print_statement() throws ParseException {Token t;\n PrintNode.Element elem;\n List elements = new ArrayList<>();\n jj_consume_token(PRINT);\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:\n case FLOAT:\n case STRING:\n case ABS:\n case ASC:\n case ATN:\n case CHRS:\n case COS:\n case FN:\n case INT:\n case LEFTS:\n case LEN:\n case LOG:\n case MIDS:\n case NOT:\n case RIGHTS:\n case SGN:\n case SIN:\n case SQR:\n case TAB:\n case TAN:\n case VAL:\n case IDENTIFIER:\n case FNIDENTIFIER:\n case 54:\n case 56:{\n elem = print_element();\nelements.add(elem);\n label_4:\n while (true) {\n if (jj_2_1(2)) {\n ;\n } else {\n break label_4;\n }\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n t = jj_consume_token(53);\n break;\n }\n case 58:{\n t = jj_consume_token(58);\n break;\n }\n default:\n jj_la1[14] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\nelements.add(new PrintNode.Element(PrintNode.ElementType.SEPARATOR, t.image));\n elem = print_element();\nelements.add(elem);\n }\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 58:{\n t = jj_consume_token(58);\nelements.add(new PrintNode.Element(PrintNode.ElementType.SEPARATOR, t.image));\n break;\n }\n default:\n jj_la1[15] = jj_gen;\n ;\n }\n break;\n }\n default:\n jj_la1[16] = jj_gen;\n ;\n }\n{if (\"\" != null) return new PrintNode(elements);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public PrintNode.Element print_element() throws ParseException {ExpressionNode e;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:\n case FLOAT:\n case STRING:\n case ABS:\n case ASC:\n case ATN:\n case CHRS:\n case COS:\n case FN:\n case INT:\n case LEFTS:\n case LEN:\n case LOG:\n case MIDS:\n case NOT:\n case RIGHTS:\n case SGN:\n case SIN:\n case SQR:\n case TAN:\n case VAL:\n case IDENTIFIER:\n case FNIDENTIFIER:\n case 54:\n case 56:{\n e = expression();\n{if (\"\" != null) return new PrintNode.Element(PrintNode.ElementType.EXPRESSION, e);}\n break;\n }\n case TAB:{\n jj_consume_token(TAB);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new PrintNode.Element(PrintNode.ElementType.TAB, e);}\n break;\n }\n default:\n jj_la1[17] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode dim_statement() throws ParseException {DimCreateNode d;\n List dims = new ArrayList<>();\n jj_consume_token(DIM);\n d = one_dim();\ndims.add(d);\n label_5:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n ;\n break;\n }\n default:\n jj_la1[18] = jj_gen;\n break label_5;\n }\n jj_consume_token(53);\n d = one_dim();\ndims.add(d);\n }\n{if (\"\" != null) return new DimNode(dims);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public DimCreateNode one_dim() throws ParseException {Token t;\n ExpressionNode d1 = null;\n ExpressionNode d2 = null;\n t = jj_consume_token(IDENTIFIER);\n jj_consume_token(56);\n d1 = expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n jj_consume_token(53);\n d2 = expression();\n break;\n }\n default:\n jj_la1[19] = jj_gen;\n ;\n }\n jj_consume_token(57);\n{if (\"\" != null) return new DimCreateNode(t.image, d1, d2);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode dependent_jump() throws ParseException {ExpressionNode e;\n boolean isGosub = false;\n List targets = new ArrayList<>();\n int n;\n jj_consume_token(ON);\n e = expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case GOTO:{\n jj_consume_token(GOTO);\n break;\n }\n case GOSUB:{\n jj_consume_token(GOSUB);\nisGosub = true;\n break;\n }\n default:\n jj_la1[20] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n n = lineNumber();\ntargets.add(n);\n label_6:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n ;\n break;\n }\n default:\n jj_la1[21] = jj_gen;\n break label_6;\n }\n jj_consume_token(53);\n n = lineNumber();\ntargets.add(n);\n }\n{if (\"\" != null) return isGosub ? new OnGosubNode(e, targets) : new OnGotoNode(e, targets);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode for_statement() throws ParseException {Token t;\n ExpressionNode e;\n ExpressionNode f;\n ExpressionNode g = null;\n jj_consume_token(FOR);\n t = jj_consume_token(IDENTIFIER);\n jj_consume_token(55);\n e = expression();\n jj_consume_token(TO);\n f = expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case STEP:{\n jj_consume_token(STEP);\n g = expression();\n break;\n }\n default:\n jj_la1[22] = jj_gen;\n ;\n }\n{if (\"\" != null) return new ForNode(t.image, e, f, g);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode if_statement() throws ParseException {ExpressionNode e;\n int l;\n StatementNode s = null;\n jj_consume_token(IF);\n e = expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case THEN:{\n jj_consume_token(THEN);\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:{\n l = lineNumber();\ns = new GotoNode(l);\n break;\n }\n case DEF:\n case DIM:\n case END:\n case FOR:\n case GOSUB:\n case GOTO:\n case IF:\n case INPUT:\n case LET:\n case NEXT:\n case ON:\n case PRINT:\n case READ:\n case REM:\n case RESTORE:\n case RETURN:\n case RUN:\n case STOP:\n case IDENTIFIER:{\n s = statement();\n break;\n }\n default:\n jj_la1[23] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n break;\n }\n case GOTO:{\n jj_consume_token(GOTO);\n l = lineNumber();\ns = new GotoNode(l);\n break;\n }\n default:\n jj_la1[24] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n{if (\"\" != null) return new IfThenNode(e, s);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode read_statement() throws ParseException {LetNode.LHS l;\n List lhss = new ArrayList<>();\n jj_consume_token(READ);\n l = lhs();\nlhss.add(l);\n label_7:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n ;\n break;\n }\n default:\n jj_la1[25] = jj_gen;\n break label_7;\n }\n jj_consume_token(53);\n l = lhs();\nlhss.add(l);\n }\n{if (\"\" != null) return new ReadNode(lhss);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public StatementNode def_fn() throws ParseException {String f;\n Token u;\n ExpressionNode e;\n jj_consume_token(DEF);\n f = fn_id();\n jj_consume_token(56);\n u = jj_consume_token(IDENTIFIER);\n jj_consume_token(57);\n jj_consume_token(55);\n e = expression();\n{if (\"\" != null) return new DefFnNode(f, u.image, e);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public String fn_id() throws ParseException {Token t;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case FN:{\n jj_consume_token(FN);\n t = jj_consume_token(IDENTIFIER);\n{if (\"\" != null) return t.image;}\n break;\n }\n case FNIDENTIFIER:{\n t = jj_consume_token(FNIDENTIFIER);\n{if (\"\" != null) return t.image.substring(2, t.image.length());}\n break;\n }\n default:\n jj_la1[26] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n//\n// expressions\n//\n final public \nExpressionNode expression() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n e = and_expression();\n label_8:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case OR:{\n ;\n break;\n }\n default:\n jj_la1[27] = jj_gen;\n break label_8;\n }\n jj_consume_token(OR);\n f = and_expression();\ne = new OrNode(e, f);\n }\n{if (\"\" != null) return e;}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode and_expression() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n e = equality_expression();\n label_9:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case AND:{\n ;\n break;\n }\n default:\n jj_la1[28] = jj_gen;\n break label_9;\n }\n jj_consume_token(AND);\n f = equality_expression();\ne = new AndNode(e, f);\n }\n{if (\"\" != null) return e;}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode equality_expression() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n e = relational_expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 55:\n case 59:{\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 55:{\n jj_consume_token(55);\n f = relational_expression();\n{if (\"\" != null) return new EqNode(e, f);}\n break;\n }\n case 59:{\n jj_consume_token(59);\n f = relational_expression();\n{if (\"\" != null) return new NeqNode(e, f);}\n break;\n }\n default:\n jj_la1[29] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n break;\n }\n default:\n jj_la1[30] = jj_gen;\n ;\n }\n{if (\"\" != null) return e;}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode relational_expression() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n e = additive_expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 60:\n case 61:\n case 62:\n case 63:{\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 60:{\n jj_consume_token(60);\n f = additive_expression();\n{if (\"\" != null) return new LtNode(e, f);}\n break;\n }\n case 61:{\n jj_consume_token(61);\n f = additive_expression();\n{if (\"\" != null) return new LeqNode(e, f);}\n break;\n }\n case 62:{\n jj_consume_token(62);\n f = additive_expression();\n{if (\"\" != null) return new GtNode(e, f);}\n break;\n }\n case 63:{\n jj_consume_token(63);\n f = additive_expression();\n{if (\"\" != null) return new GeqNode(e, f);}\n break;\n }\n default:\n jj_la1[31] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n break;\n }\n default:\n jj_la1[32] = jj_gen;\n ;\n }\n{if (\"\" != null) return e;}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode additive_expression() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n e = multiplicative_expression();\n label_10:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 54:\n case 64:{\n ;\n break;\n }\n default:\n jj_la1[33] = jj_gen;\n break label_10;\n }\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 64:{\n jj_consume_token(64);\n f = multiplicative_expression();\ne = new AddNode(e, f);\n break;\n }\n case 54:{\n jj_consume_token(54);\n f = multiplicative_expression();\ne = new SubtractNode(e, f);\n break;\n }\n default:\n jj_la1[34] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n }\n{if (\"\" != null) return e;}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode multiplicative_expression() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n e = power_expression();\n label_11:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 65:\n case 66:{\n ;\n break;\n }\n default:\n jj_la1[35] = jj_gen;\n break label_11;\n }\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 65:{\n jj_consume_token(65);\n f = power_expression();\ne = new MultiplyNode(e, f);\n break;\n }\n case 66:{\n jj_consume_token(66);\n f = power_expression();\ne = new DivideNode(e, f);\n break;\n }\n default:\n jj_la1[36] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n }\n{if (\"\" != null) return e;}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode power_expression() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n e = unary_expression();\n label_12:\n while (true) {\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 67:{\n ;\n break;\n }\n default:\n jj_la1[37] = jj_gen;\n break label_12;\n }\n jj_consume_token(67);\n f = unary_expression();\ne = new PowerNode(e, f);\n }\n{if (\"\" != null) return e;}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode unary_expression() throws ParseException {ExpressionNode e;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 54:{\n jj_consume_token(54);\n e = unary_expression();\n{if (\"\" != null) return new NegateNode(e);}\n break;\n }\n case NUMBER:\n case FLOAT:\n case STRING:\n case ABS:\n case ASC:\n case ATN:\n case CHRS:\n case COS:\n case FN:\n case INT:\n case LEFTS:\n case LEN:\n case LOG:\n case MIDS:\n case NOT:\n case RIGHTS:\n case SGN:\n case SIN:\n case SQR:\n case TAN:\n case VAL:\n case IDENTIFIER:\n case FNIDENTIFIER:\n case 56:{\n e = unary_expression_not_plus_minus();\n{if (\"\" != null) return e;}\n break;\n }\n default:\n jj_la1[38] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode unary_expression_not_plus_minus() throws ParseException {ExpressionNode e;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NOT:{\n jj_consume_token(NOT);\n e = unary_expression();\n{if (\"\" != null) return new NotNode(e);}\n break;\n }\n case NUMBER:\n case FLOAT:\n case STRING:\n case ABS:\n case ASC:\n case ATN:\n case CHRS:\n case COS:\n case FN:\n case INT:\n case LEFTS:\n case LEN:\n case LOG:\n case MIDS:\n case RIGHTS:\n case SGN:\n case SIN:\n case SQR:\n case TAN:\n case VAL:\n case IDENTIFIER:\n case FNIDENTIFIER:\n case 56:{\n e = primary_expression();\n{if (\"\" != null) return e;}\n break;\n }\n default:\n jj_la1[39] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode primary_expression() throws ParseException {ExpressionNode e;\n Token t;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:\n case FLOAT:\n case STRING:{\n e = literal();\n{if (\"\" != null) return e;}\n break;\n }\n case 56:{\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return e;}\n break;\n }\n case ABS:\n case ASC:\n case ATN:\n case CHRS:\n case COS:\n case INT:\n case LEFTS:\n case LEN:\n case LOG:\n case MIDS:\n case RIGHTS:\n case SGN:\n case SIN:\n case SQR:\n case TAN:\n case VAL:{\n e = builtin_call();\n{if (\"\" != null) return e;}\n break;\n }\n case FN:\n case FNIDENTIFIER:{\n e = fn_call();\n{if (\"\" != null) return e;}\n break;\n }\n case IDENTIFIER:{\n e = varOrDimAccess();\n{if (\"\" != null) return e;}\n break;\n }\n default:\n jj_la1[40] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode literal() throws ParseException {Token t;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:\n case FLOAT:{\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case NUMBER:{\n t = jj_consume_token(NUMBER);\n break;\n }\n case FLOAT:{\n t = jj_consume_token(FLOAT);\n break;\n }\n default:\n jj_la1[41] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n{if (\"\" != null) return new DoubleNode(Double.parseDouble(t.image));}\n break;\n }\n case STRING:{\n t = jj_consume_token(STRING);\n{if (\"\" != null) return new StringNode(t.image.substring(1, t.image.length() - 1));}\n break;\n }\n default:\n jj_la1[42] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode varOrDimAccess() throws ParseException {Token t;\n ExpressionNode e = null;\n ExpressionNode f = null;\n t = jj_consume_token(IDENTIFIER);\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 56:{\n jj_consume_token(56);\n e = expression();\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case 53:{\n jj_consume_token(53);\n f = expression();\n break;\n }\n default:\n jj_la1[43] = jj_gen;\n ;\n }\n jj_consume_token(57);\n{if (\"\" != null) return new DimAccessNode(t.image, e, f);}\n break;\n }\n default:\n jj_la1[44] = jj_gen;\n ;\n }\n{if (\"\" != null) return new VarNode(t.image, false);}\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode builtin_call() throws ParseException {ExpressionNode e;\n ExpressionNode f;\n ExpressionNode g;\n switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {\n case ABS:{\n jj_consume_token(ABS);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new AbsNode(e);}\n break;\n }\n case ASC:{\n jj_consume_token(ASC);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new AscNode(e);}\n break;\n }\n case ATN:{\n jj_consume_token(ATN);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new AtnNode(e);}\n break;\n }\n case CHRS:{\n jj_consume_token(CHRS);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new ChrsNode(e);}\n break;\n }\n case COS:{\n jj_consume_token(COS);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new CosNode(e);}\n break;\n }\n case INT:{\n jj_consume_token(INT);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new IntNode(e);}\n break;\n }\n case LEFTS:{\n jj_consume_token(LEFTS);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(53);\n f = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new LeftsNode(e, f);}\n break;\n }\n case LEN:{\n jj_consume_token(LEN);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new LenNode(e);}\n break;\n }\n case LOG:{\n jj_consume_token(LOG);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new LogNode(e);}\n break;\n }\n case MIDS:{\n jj_consume_token(MIDS);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(53);\n f = expression();\n jj_consume_token(53);\n g = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new MidsNode(e, f, g);}\n break;\n }\n case RIGHTS:{\n jj_consume_token(RIGHTS);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(53);\n f = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new RightsNode(e, f);}\n break;\n }\n case SGN:{\n jj_consume_token(SGN);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new SgnNode(e);}\n break;\n }\n case SIN:{\n jj_consume_token(SIN);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new SinNode(e);}\n break;\n }\n case SQR:{\n jj_consume_token(SQR);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new SqrNode(e);}\n break;\n }\n case TAN:{\n jj_consume_token(TAN);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new TanNode(e);}\n break;\n }\n case VAL:{\n jj_consume_token(VAL);\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new ValNode(e);}\n break;\n }\n default:\n jj_la1[45] = jj_gen;\n jj_consume_token(-1);\n throw new ParseException();\n }\n throw new Error(\"Missing return statement in function\");\n}\n\n final public ExpressionNode fn_call() throws ParseException {String f;\n ExpressionNode e;\n f = fn_id();\n jj_consume_token(56);\n e = expression();\n jj_consume_token(57);\n{if (\"\" != null) return new FnCallNode(f, e);}\n throw new Error(\"Missing return statement in function\");\n}\n\n private boolean jj_2_1(int xla)\n {\n jj_la = xla; jj_lastpos = jj_scanpos = token;\n try { return (!jj_3_1()); }\n catch(LookaheadSuccess ls) { return true; }\n finally { jj_save(0, xla); }\n }\n\n private boolean jj_3R_builtin_call_469_5_55()\n {\n if (jj_scan_token(TAN)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_468_5_54()\n {\n if (jj_scan_token(SQR)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_467_5_53()\n {\n if (jj_scan_token(SIN)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_466_5_52()\n {\n if (jj_scan_token(SGN)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_465_5_51()\n {\n if (jj_scan_token(RIGHTS)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_464_5_50()\n {\n if (jj_scan_token(MIDS)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_463_5_49()\n {\n if (jj_scan_token(LOG)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_462_5_48()\n {\n if (jj_scan_token(LEN)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_461_5_47()\n {\n if (jj_scan_token(LEFTS)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_460_5_46()\n {\n if (jj_scan_token(INT)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_459_5_45()\n {\n if (jj_scan_token(COS)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_458_5_44()\n {\n if (jj_scan_token(CHRS)) return true;\n return false;\n }\n\n private boolean jj_3R_additive_expression_362_5_20()\n {\n if (jj_3R_multiplicative_expression_376_5_21()) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_457_5_43()\n {\n if (jj_scan_token(ATN)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_456_5_42()\n {\n if (jj_scan_token(ASC)) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_455_5_36()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_3R_builtin_call_455_5_41()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_456_5_42()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_457_5_43()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_458_5_44()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_459_5_45()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_460_5_46()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_461_5_47()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_462_5_48()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_463_5_49()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_464_5_50()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_465_5_51()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_466_5_52()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_467_5_53()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_468_5_54()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_469_5_55()) {\n jj_scanpos = xsp;\n if (jj_3R_builtin_call_470_5_56()) return true;\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n return false;\n }\n\n private boolean jj_3R_builtin_call_455_5_41()\n {\n if (jj_scan_token(ABS)) return true;\n return false;\n }\n\n private boolean jj_3R_varOrDimAccess_444_5_38()\n {\n if (jj_scan_token(IDENTIFIER)) return true;\n return false;\n }\n\n private boolean jj_3R_relational_expression_346_5_19()\n {\n if (jj_3R_additive_expression_362_5_20()) return true;\n return false;\n }\n\n private boolean jj_3R_literal_434_5_40()\n {\n if (jj_scan_token(STRING)) return true;\n return false;\n }\n\n private boolean jj_3R_literal_433_5_35()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_3R_literal_433_5_39()) {\n jj_scanpos = xsp;\n if (jj_3R_literal_434_5_40()) return true;\n }\n return false;\n }\n\n private boolean jj_3R_literal_433_5_39()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_scan_token(3)) {\n jj_scanpos = xsp;\n if (jj_scan_token(4)) return true;\n }\n return false;\n }\n\n private boolean jj_3R_equality_expression_332_5_18()\n {\n if (jj_3R_relational_expression_346_5_19()) return true;\n return false;\n }\n\n private boolean jj_3R_primary_expression_425_5_34()\n {\n if (jj_3R_varOrDimAccess_444_5_38()) return true;\n return false;\n }\n\n private boolean jj_3R_primary_expression_424_5_33()\n {\n if (jj_3R_fn_call_479_5_37()) return true;\n return false;\n }\n\n private boolean jj_3R_primary_expression_423_5_32()\n {\n if (jj_3R_builtin_call_455_5_36()) return true;\n return false;\n }\n\n private boolean jj_3R_primary_expression_422_5_31()\n {\n if (jj_scan_token(56)) return true;\n return false;\n }\n\n private boolean jj_3R_primary_expression_421_5_29()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_3R_primary_expression_421_5_30()) {\n jj_scanpos = xsp;\n if (jj_3R_primary_expression_422_5_31()) {\n jj_scanpos = xsp;\n if (jj_3R_primary_expression_423_5_32()) {\n jj_scanpos = xsp;\n if (jj_3R_primary_expression_424_5_33()) {\n jj_scanpos = xsp;\n if (jj_3R_primary_expression_425_5_34()) return true;\n }\n }\n }\n }\n return false;\n }\n\n private boolean jj_3R_primary_expression_421_5_30()\n {\n if (jj_3R_literal_433_5_35()) return true;\n return false;\n }\n\n private boolean jj_3R_and_expression_322_5_17()\n {\n if (jj_3R_equality_expression_332_5_18()) return true;\n return false;\n }\n\n private boolean jj_3R_unary_expression_not_plus_minus_412_5_28()\n {\n if (jj_3R_primary_expression_421_5_29()) return true;\n return false;\n }\n\n private boolean jj_3R_unary_expression_not_plus_minus_411_5_27()\n {\n if (jj_scan_token(NOT)) return true;\n return false;\n }\n\n private boolean jj_3R_unary_expression_not_plus_minus_411_5_26()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_3R_unary_expression_not_plus_minus_411_5_27()) {\n jj_scanpos = xsp;\n if (jj_3R_unary_expression_not_plus_minus_412_5_28()) return true;\n }\n return false;\n }\n\n private boolean jj_3R_expression_312_5_16()\n {\n if (jj_3R_and_expression_322_5_17()) return true;\n return false;\n }\n\n private boolean jj_3R_unary_expression_403_5_25()\n {\n if (jj_3R_unary_expression_not_plus_minus_411_5_26()) return true;\n return false;\n }\n\n private boolean jj_3R_unary_expression_402_5_24()\n {\n if (jj_scan_token(54)) return true;\n return false;\n }\n\n private boolean jj_3R_unary_expression_402_5_23()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_3R_unary_expression_402_5_24()) {\n jj_scanpos = xsp;\n if (jj_3R_unary_expression_403_5_25()) return true;\n }\n return false;\n }\n\n private boolean jj_3R_fn_id_298_9_59()\n {\n if (jj_scan_token(FNIDENTIFIER)) return true;\n return false;\n }\n\n private boolean jj_3R_fn_id_297_9_58()\n {\n if (jj_scan_token(FN)) return true;\n return false;\n }\n\n private boolean jj_3R_print_element_202_5_15()\n {\n if (jj_scan_token(TAB)) return true;\n return false;\n }\n\n private boolean jj_3R_fn_id_296_5_57()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_3R_fn_id_297_9_58()) {\n jj_scanpos = xsp;\n if (jj_3R_fn_id_298_9_59()) return true;\n }\n return false;\n }\n\n private boolean jj_3R_print_element_201_5_13()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_3R_print_element_201_5_14()) {\n jj_scanpos = xsp;\n if (jj_3R_print_element_202_5_15()) return true;\n }\n return false;\n }\n\n private boolean jj_3R_print_element_201_5_14()\n {\n if (jj_3R_expression_312_5_16()) return true;\n return false;\n }\n\n private boolean jj_3R_power_expression_390_5_22()\n {\n if (jj_3R_unary_expression_402_5_23()) return true;\n return false;\n }\n\n private boolean jj_3R_fn_call_479_5_37()\n {\n if (jj_3R_fn_id_296_5_57()) return true;\n return false;\n }\n\n private boolean jj_3_1()\n {\n Token xsp;\n xsp = jj_scanpos;\n if (jj_scan_token(53)) {\n jj_scanpos = xsp;\n if (jj_scan_token(58)) return true;\n }\n if (jj_3R_print_element_201_5_13()) return true;\n return false;\n }\n\n private boolean jj_3R_multiplicative_expression_376_5_21()\n {\n if (jj_3R_power_expression_390_5_22()) return true;\n return false;\n }\n\n private boolean jj_3R_builtin_call_470_5_56()\n {\n if (jj_scan_token(VAL)) return true;\n return false;\n }\n\n /** Generated Token Manager. */\n public BasicParserTokenManager token_source;\n SimpleCharStream jj_input_stream;\n /** Current token. */\n public Token token;\n /** Next token. */\n public Token jj_nt;\n private int jj_ntk;\n private Token jj_scanpos, jj_lastpos;\n private int jj_la;\n private int jj_gen;\n final private int[] jj_la1 = new int[46];\n static private int[] jj_la1_0;\n static private int[] jj_la1_1;\n static private int[] jj_la1_2;\n static {\n\t jj_la1_init_0();\n\t jj_la1_init_1();\n\t jj_la1_init_2();\n\t}\n\tprivate static void jj_la1_init_0() {\n\t jj_la1_0 = new int[] {0x8,0x0,0xa4ddc000,0xa4dde000,0x5,0x10000,0xa4ddc000,0x0,0x0,0x18,0x58,0x4000000,0x0,0x0,0x0,0x0,0x5b221ed8,0x5b221ed8,0x0,0x0,0x180000,0x0,0x0,0xa4ddc008,0x100000,0x0,0x20000,0x0,0x100,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x5b221ed8,0x5b221ed8,0x1b221ed8,0x18,0x58,0x0,0x0,0x1b201e80,};\n\t}\n\tprivate static void jj_la1_init_1() {\n\t jj_la1_1 = new int[] {0x0,0x100000,0x410be,0x410be,0x0,0x1000,0x410be,0x200000,0x400000,0x0,0x400000,0x0,0x200000,0x1000000,0x4200000,0x4000000,0x14e6740,0x14e6740,0x200000,0x200000,0x0,0x200000,0x800,0x410be,0x8000,0x200000,0x80000,0x1,0x0,0x8800000,0x8800000,0xf0000000,0xf0000000,0x400000,0x400000,0x0,0x0,0x0,0x14e4740,0x10e4740,0x10e4740,0x0,0x0,0x200000,0x1000000,0x24740,};\n\t}\n\tprivate static void jj_la1_init_2() {\n\t jj_la1_2 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x1,0x6,0x6,0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,};\n\t}\n final private JJCalls[] jj_2_rtns = new JJCalls[1];\n private boolean jj_rescan = false;\n private int jj_gc = 0;\n\n /** Constructor with InputStream. */\n public BasicParser(java.io.InputStream stream) {\n\t this(stream, null);\n }\n /** Constructor with InputStream and supplied encoding */\n public BasicParser(java.io.InputStream stream, String encoding) {\n\t try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\n\t token_source = new BasicParserTokenManager(jj_input_stream);\n\t token = new Token();\n\t jj_ntk = -1;\n\t jj_gen = 0;\n\t for (int i = 0; i < 46; i++) jj_la1[i] = -1;\n\t for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\n }\n\n /** Reinitialise. */\n public void ReInit(java.io.InputStream stream) {\n\t ReInit(stream, null);\n }\n /** Reinitialise. */\n public void ReInit(java.io.InputStream stream, String encoding) {\n\t try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }\n\t token_source.ReInit(jj_input_stream);\n\t token = new Token();\n\t jj_ntk = -1;\n\t jj_gen = 0;\n\t for (int i = 0; i < 46; i++) jj_la1[i] = -1;\n\t for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\n }\n\n /** Constructor. */\n public BasicParser(java.io.Reader stream) {\n\t jj_input_stream = new SimpleCharStream(stream, 1, 1);\n\t token_source = new BasicParserTokenManager(jj_input_stream);\n\t token = new Token();\n\t jj_ntk = -1;\n\t jj_gen = 0;\n\t for (int i = 0; i < 46; i++) jj_la1[i] = -1;\n\t for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\n }\n\n /** Reinitialise. */\n public void ReInit(java.io.Reader stream) {\n\tif (jj_input_stream == null) {\n\t jj_input_stream = new SimpleCharStream(stream, 1, 1);\n\t} else {\n\t jj_input_stream.ReInit(stream, 1, 1);\n\t}\n\tif (token_source == null) {\n token_source = new BasicParserTokenManager(jj_input_stream);\n\t}\n\n\t token_source.ReInit(jj_input_stream);\n\t token = new Token();\n\t jj_ntk = -1;\n\t jj_gen = 0;\n\t for (int i = 0; i < 46; i++) jj_la1[i] = -1;\n\t for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\n }\n\n /** Constructor with generated Token Manager. */\n public BasicParser(BasicParserTokenManager tm) {\n\t token_source = tm;\n\t token = new Token();\n\t jj_ntk = -1;\n\t jj_gen = 0;\n\t for (int i = 0; i < 46; i++) jj_la1[i] = -1;\n\t for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\n }\n\n /** Reinitialise. */\n public void ReInit(BasicParserTokenManager tm) {\n\t token_source = tm;\n\t token = new Token();\n\t jj_ntk = -1;\n\t jj_gen = 0;\n\t for (int i = 0; i < 46; i++) jj_la1[i] = -1;\n\t for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();\n }\n\n private Token jj_consume_token(int kind) throws ParseException {\n\t Token oldToken;\n\t if ((oldToken = token).next != null) token = token.next;\n\t else token = token.next = token_source.getNextToken();\n\t jj_ntk = -1;\n\t if (token.kind == kind) {\n\t jj_gen++;\n\t if (++jj_gc > 100) {\n\t\t jj_gc = 0;\n\t\t for (int i = 0; i < jj_2_rtns.length; i++) {\n\t\t JJCalls c = jj_2_rtns[i];\n\t\t while (c != null) {\n\t\t\t if (c.gen < jj_gen) c.first = null;\n\t\t\t c = c.next;\n\t\t }\n\t\t }\n\t }\n\t return token;\n\t }\n\t token = oldToken;\n\t jj_kind = kind;\n\t throw generateParseException();\n }\n\n @SuppressWarnings(\"serial\")\n static private final class LookaheadSuccess extends java.lang.Error {\n @Override\n public Throwable fillInStackTrace() {\n return this;\n }\n }\n static private final LookaheadSuccess jj_ls = new LookaheadSuccess();\n private boolean jj_scan_token(int kind) {\n\t if (jj_scanpos == jj_lastpos) {\n\t jj_la--;\n\t if (jj_scanpos.next == null) {\n\t\t jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();\n\t } else {\n\t\t jj_lastpos = jj_scanpos = jj_scanpos.next;\n\t }\n\t } else {\n\t jj_scanpos = jj_scanpos.next;\n\t }\n\t if (jj_rescan) {\n\t int i = 0; Token tok = token;\n\t while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }\n\t if (tok != null) jj_add_error_token(kind, i);\n\t }\n\t if (jj_scanpos.kind != kind) return true;\n\t if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;\n\t return false;\n }\n\n\n/** Get the next Token. */\n final public Token getNextToken() {\n\t if (token.next != null) token = token.next;\n\t else token = token.next = token_source.getNextToken();\n\t jj_ntk = -1;\n\t jj_gen++;\n\t return token;\n }\n\n/** Get the specific Token. */\n final public Token getToken(int index) {\n\t Token t = token;\n\t for (int i = 0; i < index; i++) {\n\t if (t.next != null) t = t.next;\n\t else t = t.next = token_source.getNextToken();\n\t }\n\t return t;\n }\n\n private int jj_ntk_f() {\n\t if ((jj_nt=token.next) == null)\n\t return (jj_ntk = (token.next=token_source.getNextToken()).kind);\n\t else\n\t return (jj_ntk = jj_nt.kind);\n }\n\n private java.util.List jj_expentries = new java.util.ArrayList();\n private int[] jj_expentry;\n private int jj_kind = -1;\n private int[] jj_lasttokens = new int[100];\n private int jj_endpos;\n\n private void jj_add_error_token(int kind, int pos) {\n\t if (pos >= 100) {\n\t\treturn;\n\t }\n\n\t if (pos == jj_endpos + 1) {\n\t jj_lasttokens[jj_endpos++] = kind;\n\t } else if (jj_endpos != 0) {\n\t jj_expentry = new int[jj_endpos];\n\n\t for (int i = 0; i < jj_endpos; i++) {\n\t\t jj_expentry[i] = jj_lasttokens[i];\n\t }\n\n\t for (int[] oldentry : jj_expentries) {\n\t\t if (oldentry.length == jj_expentry.length) {\n\t\t boolean isMatched = true;\n\n\t\t for (int i = 0; i < jj_expentry.length; i++) {\n\t\t\t if (oldentry[i] != jj_expentry[i]) {\n\t\t\t isMatched = false;\n\t\t\t break;\n\t\t\t }\n\n\t\t }\n\t\t if (isMatched) {\n\t\t\t jj_expentries.add(jj_expentry);\n\t\t\t break;\n\t\t }\n\t\t }\n\t }\n\n\t if (pos != 0) {\n\t\t jj_lasttokens[(jj_endpos = pos) - 1] = kind;\n\t }\n\t }\n }\n\n /** Generate ParseException. */\n public ParseException generateParseException() {\n\t jj_expentries.clear();\n\t boolean[] la1tokens = new boolean[68];\n\t if (jj_kind >= 0) {\n\t la1tokens[jj_kind] = true;\n\t jj_kind = -1;\n\t }\n\t for (int i = 0; i < 46; i++) {\n\t if (jj_la1[i] == jj_gen) {\n\t\t for (int j = 0; j < 32; j++) {\n\t\t if ((jj_la1_0[i] & (1< jj_gen) {\n\t\t\t jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;\n\t\t\t switch (i) {\n\t\t\t case 0: jj_3_1(); break;\n\t\t\t }\n\t\t }\n\t\t p = p.next;\n\t\t } while (p != null);\n\n\t\t } catch(LookaheadSuccess ls) { }\n\t }\n\t jj_rescan = false;\n }\n\n private void jj_save(int index, int xla) {\n\t JJCalls p = jj_2_rtns[index];\n\t while (p.gen > jj_gen) {\n\t if (p.next == null) { p = p.next = new JJCalls(); break; }\n\t p = p.next;\n\t }\n\n\t p.gen = jj_gen + xla - jj_la; \n\t p.first = token;\n\t p.arg = xla;\n }\n\n static final class JJCalls {\n\t int gen;\n\t Token first;\n\t int arg;\n\t JJCalls next;\n }\n\n}", "answers": [" BasicParser parser = new BasicParser(new StringReader(source));"], "length": 7171, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "aff60ec1-2133-4321-b2f7-af213805c300", "reasoning": "The buildProgram method needs to create a parser for the source string. The imports already include BasicParser and StringReader, so the next line should instantiate the parser with the source wrapped in a StringReader.", "reasoning_model_answer": "BasicParser parser = new BasicParser(new StringReader(source));", "assistant_with_reasoning": "\nThe buildProgram method needs to create a parser for the source string. The imports already include BasicParser and StringReader, so the next line should instantiate the parser with the source wrapped in a StringReader.\n\nBasicParser parser = new BasicParser(new StringReader(source));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.649, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36621, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "BasicParser parser = new BasicParser(new StringReader(source));", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport routing.util.RoutingInfo;\nimport util.Tuple;\nimport core.Connection;\nimport core.DTNHost;\nimport core.Message;\nimport core.Settings;\nimport core.SimClock;", "context": "src/routing/ProphetRouterWithEstimation.java\n/*\n * Copyright 2010 Aalto University, ComNet\n * Released under GPLv3. See LICENSE.txt for details.\n */\npackage routing;\n\n\n\n\n\n/**\n * Implementation of PRoPHET router as described in\n * Probabilistic routing in intermittently connected networks by\n * Anders Lindgren et al.\n *\n *\n * This version tries to estimate a good value of protocol parameters from\n * a timescale parameter given by the user, and from the encounters the node\n * sees during simulation.\n * Refer to Karvo and Ott, Time Scales and Delay-Tolerant Routing\n * Protocols Chants, 2008\n *\n */\npublic class ProphetRouterWithEstimation extends ActiveRouter {\n\t/** delivery predictability initialization constant*/\n\tpublic static final double P_INIT = 0.75;\n\t/** delivery predictability transitivity scaling constant default value */\n\tpublic static final double DEFAULT_BETA = 0.25;\n\t/** delivery predictability aging constant */\n\tpublic static final double GAMMA = 0.98;\n\t/** default P target */\n\tpublic static final double DEFAULT_PTARGET = .2;\n\n\t/** Prophet router's setting namespace ({@value})*/\n\tpublic static final String PROPHET_NS = \"ProphetRouterWithEstimation\";\n\t/**\n\t * Number of seconds in time scale.*/\n\tpublic static final String TIME_SCALE_S =\"timeScale\";\n\t/**\n\t * Target P_avg\n\t *\n\t */\n\tpublic static final String P_AVG_TARGET_S = \"targetPavg\";\n\n\t/**\n\t * Transitivity scaling constant (beta) -setting id ({@value}).\n\t * Default value for setting is {@link #DEFAULT_BETA}.\n\t */\n\tpublic static final String BETA_S = \"beta\";\n\n\t/** values of parameter settings */\n\tprivate double beta;\n\tprivate double gamma;\n\tprivate double pinit;\n\n\t/** value of time scale variable */\n\tprivate int timescale;\n\tprivate double ptavg;\n\n\t/** delivery predictabilities */\n\tprivate Map preds;\n\n\t/** last meeting time with a node */\n\tprivate Map meetings;\n\tprivate int nrofSamples;\n\tprivate double meanIET;\n\n\t/** last delivery predictability update (sim)time */\n\tprivate double lastAgeUpdate;\n\n\n\t/**\n\t * Constructor. Creates a new message router based on the settings in\n\t * the given Settings object.\n\t * @param s The settings object\n\t */\n\nsrc/core/Connection.java\npublic abstract class Connection {\n\tprotected DTNHost toNode;\n\tprotected NetworkInterface toInterface;\n\tprotected DTNHost fromNode;\n\tprotected NetworkInterface fromInterface;\n\tprotected DTNHost msgFromNode;\n\n\tprivate boolean isUp;\n\tprotected Message msgOnFly;\n\t/** how many bytes this connection has transferred */\n\tprotected int bytesTransferred;\n\n\t/**\n\t * Creates a new connection between nodes and sets the connection\n\t * state to \"up\".\n\t * @param fromNode The node that initiated the connection\n\t * @param fromInterface The interface that initiated the connection\n\t * @param toNode The node in the other side of the connection\n\t * @param toInterface The interface in the other side of the connection\n\t */\n\tpublic Connection(DTNHost fromNode, NetworkInterface fromInterface,\n\t\t\tDTNHost toNode, NetworkInterface toInterface) {\n\t\tthis.fromNode = fromNode;\n\t\tthis.fromInterface = fromInterface;\n\t\tthis.toNode = toNode;\n\t\tthis.toInterface = toInterface;\n\t\tthis.isUp = true;\n\t\tthis.bytesTransferred = 0;\n\t}\n\n\n\t/**\n\t * Returns true if the connection is up\n\t * @return state of the connection\n\t */\n\tpublic boolean isUp() {\n\t\treturn this.isUp;\n\t}\n\n\t/**\n\t * Returns true if the connections is transferring a message\n\t * @return true if the connections is transferring a message\n\t */\n\tpublic boolean isTransferring() {\n\t\treturn this.msgOnFly != null;\n\t}\n\n\n\t/**\n\t * Returns true if the given node is the initiator of the connection, false\n\t * otherwise\n\t * @param node The node to check\n\t * @return true if the given node is the initiator of the connection\n\t */\n\tpublic boolean isInitiator(DTNHost node) {\n\t\treturn node == this.fromNode;\n\t}\n\n\t/**\n\t * Sets the state of the connection.\n\t * @param state True if the connection is up, false if not\n\t */\n\tpublic void setUpState(boolean state) {\n\t\tthis.isUp = state;\n\t}\n\n\t/**\n\t * Sets a message that this connection is currently transferring. If message\n\t * passing is controlled by external events, this method is not needed\n\t * (but then e.g. {@link #finalizeTransfer()} and\n\t * {@link #isMessageTransferred()} will not work either). Only a one message\n\t * at a time can be transferred using one connection.\n\t * @param m The message\n\t * @return The value returned by\n\t * {@link MessageRouter#receiveMessage(Message, DTNHost)}\n\t */\n\tpublic abstract int startTransfer(DTNHost from, Message m);\n\n\t/**\n\t * Calculate the current transmission speed from the information\n\t * given by the interfaces, and calculate the missing data amount.\n\t */\n\tpublic void update() {};\n\n\t/**\n * Aborts the transfer of the currently transferred message.\n */\n\tpublic void abortTransfer() {\n\t\tassert msgOnFly != null : \"No message to abort at \" + msgFromNode;\n\t\tint bytesRemaining = getRemainingByteCount();\n\n\t\tthis.bytesTransferred += msgOnFly.getSize() - bytesRemaining;\n\n\t\tgetOtherNode(msgFromNode).messageAborted(this.msgOnFly.getId(),\n\t\t\t\tmsgFromNode, bytesRemaining);\n\t\tclearMsgOnFly();\n\t}\n\n\t/**\n\t * Returns the amount of bytes to be transferred before ongoing transfer\n\t * is ready or 0 if there's no ongoing transfer or it has finished\n\t * already\n\t * @return the amount of bytes to be transferred\n\t */\n\tpublic abstract int getRemainingByteCount();\n\n\t/**\n\t * Clears the message that is currently being transferred.\n\t * Calls to {@link #getMessage()} will return null after this.\n\t */\n\tprotected void clearMsgOnFly() {\n\t\tthis.msgOnFly = null;\n\t\tthis.msgFromNode = null;\n\t}\n\n\t/**\n\t * Finalizes the transfer of the currently transferred message.\n\t * The message that was being transferred can not be\n\t * retrieved from this connections after calling this method (using\n\t * {@link #getMessage()}).\n\t */\n\tpublic void finalizeTransfer() {\n\t\tassert this.msgOnFly != null : \"Nothing to finalize in \" + this;\n\t\tassert msgFromNode != null : \"msgFromNode is not set\";\n\n\t\tthis.bytesTransferred += msgOnFly.getSize();\n\n\t\tgetOtherNode(msgFromNode).messageTransferred(this.msgOnFly.getId(),\n\t\t\t\tmsgFromNode);\n\t\tclearMsgOnFly();\n\t}\n\n\t/**\n\t * Returns true if the current message transfer is done\n\t * @return True if the transfer is done, false if not\n\t */\n\tpublic abstract boolean isMessageTransferred();\n\n\t/**\n\t * Returns true if the connection is ready to transfer a message (connection\n\t * is up and there is no message being transferred).\n\t * @return true if the connection is ready to transfer a message\n\t */\n\tpublic boolean isReadyForTransfer() {\n\t\treturn this.isUp && this.msgOnFly == null;\n\t}\n\n\t/**\n\t * Gets the message that this connection is currently transferring.\n\t * @return The message or null if no message is being transferred\n\t */\n\tpublic Message getMessage() {\n\t\treturn this.msgOnFly;\n\t}\n\n\t/**\n\t * Gets the current connection speed\n\t */\n\tpublic abstract double getSpeed();\n\n\t/**\n\t * Returns the total amount of bytes this connection has transferred so far\n\t * (including all transfers).\n\t */\n\tpublic int getTotalBytesTransferred() {\n\t\tif (this.msgOnFly == null) {\n\t\t\treturn this.bytesTransferred;\n\t\t}\n\t\telse {\n\t\t\tif (isMessageTransferred()) {\n\t\t\t\treturn this.bytesTransferred + this.msgOnFly.getSize();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn this.bytesTransferred +\n\t\t\t\t(msgOnFly.getSize() - getRemainingByteCount());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the node in the other end of the connection\n\t * @param node The node in this end of the connection\n\t * @return The requested node\n\t */\n\tpublic DTNHost getOtherNode(DTNHost node) {\n\t\tif (node == this.fromNode) {\n\t\t\treturn this.toNode;\n\t\t}\n\t\telse {\n\t\t\treturn this.fromNode;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the interface in the other end of the connection\n\t * @param i The interface in this end of the connection\n\t * @return The requested interface\n\t */\n\tpublic NetworkInterface getOtherInterface(NetworkInterface i) {\n\t\tif (i == this.fromInterface) {\n\t\t\treturn this.toInterface;\n\t\t}\n\t\telse {\n\t\t\treturn this.fromInterface;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a String presentation of the connection.\n\t */\n\tpublic String toString() {\n\t\treturn fromNode + \"<->\" + toNode + \" (\" + getSpeed()/1000 + \" kBps) is \" +\n\t\t(isUp() ? \"up\":\"down\") +\n\t\t(isTransferring() ? \" transferring \" + this.msgOnFly +\n\t\t\t\t\" from \" + this.msgFromNode : \"\");\n\t}\n\n}\n\nsrc/core/Settings.java\npublic class Settings {\n\t/** properties object where the setting files are read into */\n\tprotected static Properties props;\n\t/** file name of the default settings file ({@value}) */\n\tpublic static final String DEF_SETTINGS_FILE =\"default_settings.txt\";\n\n\t/**\n\t * Setting to define the file name where all read settings are written\n\t * ({@value}. If set to an empty string, standard output is used.\n\t * By default setting are not written anywhere.\n\t */\n\tpublic static final String SETTING_OUTPUT_S = \"Settings.output\";\n\n\t/** delimiter for requested values in strings ({@value})\n\t * @see #valueFillString(String) */\n\tpublic static final String FILL_DELIMITER = \"%%\";\n\n\t/** Stream where all read settings are written to */\n\tprivate static PrintStream out = null;\n\tprivate static Set writtenSettings = new HashSet();\n\n\t/** run index for run-specific settings */\n\tprivate static int runIndex = 0;\n\tprivate String namespace = null; // namespace to look the settings from\n\tprivate String secondaryNamespace = null;\n\tprivate Stack oldNamespaces;\n\tprivate Stack secondaryNamespaces;\n\n\t/**\n\t * Creates a setting object with a namespace. Namespace is the prefix\n\t * of the all subsequent setting requests.\n\t * @param namespace Namespace to use\n\t */\n\tpublic Settings(String namespace) {\n\t\tthis.oldNamespaces = new Stack();\n\t\tthis.secondaryNamespaces = new Stack();\n\t\tsetNameSpace(namespace);\n\t}\n\n\t/**\n\t * Create a setting object without namespace. All setting requests must\n\t * be prefixed with a valid namespace (e.g. \"Report.nrofReports\").\n\t */\n\tpublic Settings() {\n\t\tthis(null);\n\t}\n\n\t/**\n\t * Sets the run index for the settings (only has effect on settings with\n\t * run array). A run array can be defined with syntax
\n\t * [settingFor1stRun ; settingFor2ndRun ; SettingFor3rdRun]\n\t *
I.e. settings are put in brackets and delimited with semicolon.\n\t * First run's setting is returned when index is 0, second when index is\n\t * 1 etc. If run index is bigger than run array's length, indexing wraps\n\t * around in run array (i.e. return value is the value at index\n\t * runIndex % arrayLength).\n\t * To disable whole run-index-thing, set index to value smaller than\n\t * zero (e.g. -1). When disabled, run-arrays are returned as normal values,\n\t * including the brackets.\n\t * @param index The run index to use for subsequent settings calls, or\n\t * -1 to disable run indexing\n\t */\n\tpublic static void setRunIndex(int index) {\n\t\trunIndex = index;\n\t\twrittenSettings.clear();\n\t}\n\n\t/**\n\t * Checks that the given integer array contains a valid range. I.e.,\n\t * the length of the array must be two and\n\t * first_value <= second_value.\n\t * @param range The range array\n\t * @param sname Name of the setting (for error messages)\n\t * @throws SettingsError If the given array didn't qualify as a range\n\t */\n\tpublic void assertValidRange(int range[], String sname)\n\t\tthrows SettingsError {\n\t\tif (range.length != 2) {\n\t\t\tthrow new SettingsError(\"Range setting \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" should contain only two comma separated integer values\");\n\t\t}\n\t\tif (range[0] > range[1]) {\n\t\t\tthrow new SettingsError(\"Range setting's \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" first value should be smaller or equal to second value\");\n\t\t}\n\t}\n\n\t/**\n\t * Makes sure that the given settings value is positive\n\t * @param value Value to check\n\t * @param settingName Name of the setting (for error's message)\n\t * @throws SettingsError if the value was not positive\n\t */\n\tpublic void ensurePositiveValue(double value, String settingName) {\n\t\tif (value < 0) {\n\t\t\tthrow new SettingsError(\"Negative value (\" + value +\n\t\t\t\t\t\") not accepted for setting \" + settingName);\n\t\t}\n\t}\n\n\t/**\n\t * Sets the namespace to something else than the current namespace.\n\t * This change can be reverted using {@link #restoreNameSpace()}\n\t * @param namespace The new namespace\n\t */\n\tpublic void setNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = namespace;\n\t}\n\n\t/**\n\t * Appends the given namespace to the the current namespace, \n\t * for both the primary and secondary namespace .\n\t * This change can be reverted using {@link #restoreNameSpace()} and\n\t * {@link #restoreSecondaryNamespace()}.\n\t * @param namespace The new namespace to append\n\t */\n\tpublic void setSubNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = this.namespace + \".\" + namespace;\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = this.secondaryNamespace + \".\" + namespace;\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for a setting.\n\t * @param setting The name of the setting\n\t * @return The setting name prefixed with fully qualified name of the\n\t * namespace where the requested setting would be retrieved from or null\n\t * if that setting is not found from any of the current namespace(s)\n\t */\n\tpublic String getFullPropertyName(String setting) {\n\t\tif (!contains(setting)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (props.getProperty(getFullPropertyName(setting, false)) != null) {\n\t\t\treturn getFullPropertyName(setting, false);\n\t\t}\n\n\t\t// not found from primary, but Settings contains -> must be from 2ndary\n\t\telse return getFullPropertyName(setting, true);\n\t}\n\n\t/**\n\t * Returns the namespace of the settings object\n\t * @return the namespace of the settings object\n\t */\n\tpublic String getNameSpace() {\n\t\treturn this.namespace;\n\t}\n\n\t/**\n\t * Returns the secondary namespace of the settings object\n\t * @return the secondary namespace of the settings object\n\t */\n\tpublic String getSecondaryNameSpace() {\n\t\treturn this.secondaryNamespace;\n\t}\n\n\t/**\n\t * Sets a secondary namespace where a setting is searched from if it\n\t * isn't found from the primary namespace. Secondary namespace can\n\t * be used e.g. as a \"default\" space where the settings are looked from\n\t * if no specific setting is set.\n\t * This change can be reverted using {@link #restoreSecondaryNamespace()}\n\t * @param namespace The new secondary namespace or null if secondary\n\t * namespace is not used (default behavior)\n\t */\n\tpublic void setSecondaryNamespace(String namespace) {\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = namespace;\n\t}\n\n\t/**\n\t * Restores the namespace that was in use before a call to setNameSpace\n\t * @see #setNameSpace(String)\n\t */\n\tpublic void restoreNameSpace() {\n\t\tthis.namespace = this.oldNamespaces.pop();\n\t}\n\n\t/**\n\t * Restores the secondary namespace that was in use before a call to\n\t * setSecondaryNameSpace\n\t * @see #setSecondaryNamespace(String)\n\t */\n\tpublic void restoreSecondaryNamespace() {\n\t\tthis.secondaryNamespace = this.secondaryNamespaces.pop();\n\t}\n\n\t/**\n\t * Reverts the change made with {@link #setSubNameSpace(String)}, i.e.,\n\t * restores both the primary and secondary namespace.\n\t */\n\tpublic void restoreSubNameSpace() {\n\t\trestoreNameSpace();\n\t\trestoreSecondaryNamespace();\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t * The file {@link #DEF_SETTINGS_FILE}, if exists, is always read.\n\t * @param propFile Path to the property file where additional settings\n\t * are read from or null if no additional settings files are needed.\n\t * @throws SettingsError If loading the settings file(s) didn't succeed\n\t */\n\tpublic static void init(String propFile) throws SettingsError {\n\t\tString outFile;\n\t\ttry {\n\t\t\tif (new File(DEF_SETTINGS_FILE).exists()) {\n\t\t\t\tProperties defProperties = new Properties();\n\t\t\t\tdefProperties.load(new FileInputStream(DEF_SETTINGS_FILE));\n\t\t\t\tprops = new Properties(defProperties);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprops = new Properties();\n\t\t\t}\n\t\t\tif (propFile != null) {\n\t\t\t\tprops.load(new FileInputStream(propFile));\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\toutFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t *\n\t * @param settingsStream\n\t * \t\tInputStream where the properties are read.\n\t * @throws SettingsError\n\t * \t\tIf loading the settings didn't succeed\n\t */\n\tpublic static void initFromStream(final InputStream settingsStream)\n\tthrows SettingsError {\n\t\tprops = new Properties();\n\t\ttry {\n\t\t\tprops.load(settingsStream);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\tString outFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reads another settings file and adds the key-value pairs to the current\n\t * settings overriding any values that already existed with the same keys.\n\t * @param propFile Path to the property file\n\t * @throws SettingsError If loading the settings file didn't succeed\n\t * @see #init(String)\n\t */\n\tpublic static void addSettings(String propFile) throws SettingsError {\n\t\ttry {\n\t\t\tprops.load(new FileInputStream(propFile));\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\t}\n\n\t/**\n\t * Writes the given setting string to the settings output (if any)\n\t * @param setting The string to write\n\t */\n\tprivate static void outputSetting(String setting) {\n\t\tif (out != null && !writtenSettings.contains(setting)) {\n\t\t\tif (writtenSettings.size() == 0) {\n\t\t\t\tout.println(\"# Settings for run \" + (runIndex + 1));\n\t\t\t}\n\t\t\tout.println(setting);\n\t\t\twrittenSettings.add(setting);\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if a setting with defined name (in the current namespace\n\t * or secondary namespace if such is set) exists and has some value\n\t * (not just white space)\n\t * @param name Name of the setting to check\n\t * @return True if the setting exists, false if not\n\t */\n\tpublic boolean contains(String name) {\n\t\ttry {\n\t\t\tString value = getSetting(name);\n\t\t\tif (value == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\telse return value.trim().length() > 0;\n\t\t}\n\t\tcatch (SettingsError e) {\n\t\t\treturn false; // didn't find the setting\n\t\t}\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for setting.\n\t * @param name Name of the settings\n\t * @param secondary If true, the secondary namespace is used.\n\t * @return full (prefixed with current namespace) property name for setting\n\t */\n\tprivate String getFullPropertyName(String name, boolean secondary) {\n\t\tString usedNamespace = (secondary ? secondaryNamespace : namespace);\n\n\t\tif (usedNamespace != null) {\n\t\t\treturn usedNamespace + \".\" + name;\n\t\t}\n\t\telse {\n\t\t\treturn name;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a String-valued setting. Setting is first looked from the\n\t * namespace that is set (if any) and then from the secondary namespace\n\t * (if any). All other getters use this method as their first step too\n\t * (so all getters may throw SettingsError and look from both namespaces).\n\t * @param name Name of the setting to get\n\t * @return The contents of the setting in a String\n\t * @throws SettingsError if the setting is not found from either one of\n\t * the namespaces\n\t */\n\tpublic String getSetting(String name) {\n\t\tString fullPropName;\n\t\tif (props == null) {\n\t\t\tinit(null);\n\t\t}\n\t\tfullPropName = getFullPropertyName(name, false);\n\t\tString value = props.getProperty(fullPropName);\n\n\t\tif (value != null) { // found value, check if run setting can be parsed\n\t\t\tvalue = parseRunSetting(value.trim());\n\t\t}\n\n\t\tif ((value == null || value.length() == 0) &&\n\t\t\t\tthis.secondaryNamespace != null) {\n\t\t\t// try secondary namespace if the value wasn't found from primary\n\t\t\tfullPropName = getFullPropertyName(name, true);\n\t\t\tvalue = props.getProperty(fullPropName);\n\n\t\t\tif (value != null) {\n\t\t\t\tvalue = parseRunSetting(value.trim());\n\t\t\t}\n\t\t}\n\n\t\tif (value == null || value.length() == 0) {\n\t\t\tthrow new SettingsError(\"Can't find setting \" +\n\t\t\t\t\tgetPropertyNamesString(name));\n\t\t}\n\n\t\toutputSetting(fullPropName + \" = \" + value);\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the given setting if it exists, or defaultValue if the setting\n\t * does not exist\n\t * @param name The name of the setting\n\t * @param defaultValue The value to return if the given setting didn't exist\n\t * @return The setting value or the default value if the setting didn't\n\t * exist\n\t */\n\tpublic String getSetting(String name, String defaultValue) {\n\t\tif (!contains(name)) {\n\t\t\treturn defaultValue;\n\t\t} else {\n\t\t\treturn getSetting(name);\n\t\t}\n\t}\n\n\t/**\n\t * Parses run-specific settings from a String value\n\t * @param value The String to parse\n\t * @return The runIndex % arrayLength'th value of the run array\n\t */\n\tprivate static String parseRunSetting(String value) {\n\t\tfinal String RUN_ARRAY_START = \"[\";\n\t\tfinal String RUN_ARRAY_END = \"]\";\n\t\tfinal String RUN_ARRAY_DELIM = \";\";\n\t\tfinal int MIN_LENGTH = 3; // minimum run is one value. e.g. \"[v]\"\n\n\t\tif (!value.startsWith(RUN_ARRAY_START) ||\n\t\t\t!value.endsWith(RUN_ARRAY_END) ||\n\t\t\trunIndex < 0 ||\n\t\t\tvalue.length() < MIN_LENGTH) {\n\t\t\treturn value; // standard format setting -> return\n\t\t}\n\n\t\tvalue = value.substring(1,value.length()-1); // remove brackets\n\t\tString[] valueArr = value.split(RUN_ARRAY_DELIM);\n\t\tint arrIndex = runIndex % valueArr.length;\n\t\tvalue = valueArr[arrIndex].trim();\n\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the setting name appended to namespace name(s) on a String\n\t * (for error messages)\n\t * @param name Name of the setting\n\t * @return the setting name appended to namespace name(s) on a String\n\t */\n\tprivate String getPropertyNamesString(String name) {\n\t\tif (this.secondaryNamespace != null) {\n\t\t\treturn \"'\"+ this.secondaryNamespace + \".\" + name + \"' nor '\" +\n\t\t\t\tthis.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse if (this.namespace != null){\n\t\t\treturn \"'\" + this.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse {\n\t\t\treturn \"'\" + name + \"'\";\n\t\t}\n\t}\n\n\t/**\n\t * Returns a double-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as a double\n\t */\n\tpublic double getDouble(String name) {\n\t\treturn parseDouble(getSetting(name), name);\n\t}\n\n\t/**\n\t * Returns a double-valued setting, or the default value if the given\n\t * setting does not exist\n\t * @param name Name of the setting to get\n\t * @param defaultValue The value to return if the setting doesn't exist\n\t * @return Value of the setting as a double (or the default value)\n\t */\n\tpublic double getDouble(String name, double defaultValue) {\n\t\treturn parseDouble(getSetting(name, \"\"+defaultValue), name);\n\t}\n\n\t/**\n\t * Parses a double value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a double\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate double parseDouble(String value, String setting) {\n\t\tdouble number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t\t//replaceAll removes everything which is not a digit or point\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Double.parseDouble(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses a long value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a long\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate long parseLong(String value, String setting) {\n\t\tlong number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Long.parseLong(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses the multiplier suffix from numeric setting\n\t * @param value The setting value\n\t * @return The muliplier as a number\n\t */\n\tprivate int getMultiplier(String value) {\n\t\tvalue = value.trim();\n\t\t\n\t\tif (value.endsWith(\"k\")) {\n\t\t\treturn 1000;\n\t\t}\n\t\telse if (value.endsWith(\"M\")) {\n\t\t\treturn 1000000;\n\t\t}\n\t\telse if (value.endsWith(\"G\")) {\n\t\t\treturn 1000000000;\n\t\t}\n\t\telse if (value.endsWith(\"kiB\")) {\n\t\t\t//2^10\n\t\t\treturn 1024;\n\t\t}\n\t\telse if (value.endsWith(\"MiB\")) {\n\t\t\t//2^20\n\t\t\treturn 1048576;\n\t\t}\n\t\telse if (value.endsWith(\"GiB\")) {\n\t\t\t//2^30\n\t\t\treturn 1073741824;\n\t\t} else {\n\t\t\t// no multiplier\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a CSV setting. Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading\n\t */\n\tpublic String[] getCsvSetting(String name) {\n\t\tArrayList values = new ArrayList();\n\t\tString csv = getSetting(name);\n\t\tScanner s = new Scanner(csv);\n\t\ts.useDelimiter(\",\");\n\n\t\twhile (s.hasNext()) {\n\t\t\tvalues.add(s.next().trim());\n\t\t}\n\n\t\treturn values.toArray(new String[0]);\n\t}\n\n\t/**\n\t * Returns a CSV setting containing expected amount of values.\n\t * Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading or didn't\n\t * read the expected amount of values.\n\t */\n\tpublic String[] getCsvSetting(String name, int expectedCount) {\n\t\tString[] values = getCsvSetting(name);\n\n\t\tif (values.length != expectedCount) {\n\t\t\tthrow new SettingsError(\"Read unexpected amount (\" + values.length +\n\t\t\t\t\t\") of comma separated values for setting '\"\n\t\t\t\t\t+ name + \"' (expected \" + expectedCount + \")\");\n\t\t}\n\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values containing expected\n\t * amount of values.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic double[] getCsvDoubles(String name, int expectedCount) {\n\t\treturn parseDoubles(getCsvSetting(name, expectedCount),name);\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String)\n\t */\n\tpublic double[] getCsvDoubles(String name) {\n\t\treturn parseDoubles(getCsvSetting(name), name);\n\t}\n\n\t/**\n\t * Parses a double array out of a String array\n\t * @param strings The array of strings containing double values\n\t * @param name Name of the setting\n\t * @return Array of double values parsed from the string values\n\t */\n\tprivate double[] parseDoubles(String[] strings, String name) {\n\t\tdouble[] values = new double[strings.length];\n\t\tfor (int i=0; i[] argsClass = {Settings.class};\n\t\tObject[] args = {this};\n\n\t\treturn loadObject(className, argsClass, args);\n\t}\n\n\t/**\n\t * Creates (and dynamically loads the class of) an object using the\n\t * constructor without any parameters.\n\t * @param className Name of the class of the object\n\t * @return Initialized object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tpublic Object createObject(String className) {\n\t\treturn loadObject(className, null, null);\n\t}\n\n\t/**\n\t * Dynamically loads and creates an object.\n\t * @param className Name of the class of the object\n\t * @param argsClass Class(es) of the argument(s) or null if no-argument\n\t * constructor should be called\n\t * @param args Argument(s)\n\t * @return The new object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tprivate Object loadObject(String className, Class[] argsClass,\n\t\t\tObject[] args) {\n\t\tObject o = null;\n\t\tClass objClass = getClass(className);\n\t\tConstructor constructor;\n\n\t\ttry {\n\t\t\tif (argsClass != null) { // use a specific constructor\n\t\t\t\tconstructor = objClass.getConstructor((Class[])argsClass);\n\t\t\t\to = constructor.newInstance(args);\n\t\t\t}\n\t\t\telse { // call empty constructor\n\t\t\t\to = objClass.newInstance();\n\t\t\t}\n\t\t} catch (SecurityException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (NoSuchMethodException e) {\n\t\t\tthrow new SettingsError(\"Class '\" + className +\n\t\t\t\t\t\"' doesn't have a suitable constructor\", e);\n\t\t} catch (InstantiationException e) {\n\t\t\tthrow new SettingsError(\"Can't create an instance of '\" +\n\t\t\t\t\tclassName + \"'\", e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (InvocationTargetException e) {\n\t\t\t// this exception occurs if initialization of the object fails\n\t\t\tif (e.getCause() instanceof SettingsError) {\n\t\t\t\tthrow (SettingsError)e.getCause();\n\t\t\t}\n\t\t\telse {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new SimError(\"Couldn't create settings-accepting object\"+\n\t\t\t\t\t\" for '\" + className + \"'\\n\" + \"cause: \" + e.getCause(), e);\n\t\t\t}\n\t\t}\n\n\t\treturn o;\n\t}\n\n\t/**\n\t * Returns a Class object for the name of class of throws SettingsError\n\t * if such class wasn't found.\n\t * @param name Full name of the class (including package name)\n\t * @return A Class object of that class\n\t * @throws SettingsError if such class wasn't found or couldn't be loaded\n\t */\n\tprivate Class getClass(String name) {\n\t\tString className = name;\n\t\tClass c;\n\n\t\ttry {\n\t\t\tc = Class.forName(className);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\tthrow new SettingsError(\"Couldn't find class '\" + className + \"'\"+\n\t\t\t\t\t\"\\n\" + e.getMessage(),e);\n\t\t}\n\n\t\treturn c;\n\t}\n\n\t/**\n\t * Fills a String formatted in a special way with values from Settings.\n\t * String can contain (fully qualified) setting names surrounded by\n\t * delimiters (see {@link #FILL_DELIMITER}). Values for those settings\n\t * are retrieved and filled in the place of place holders.\n\t * @param input The input string that may contain value requests\n\t * @return A string filled with requested values (or the original string\n\t * if no requests were found)\n\t * @throws SettingsError if such settings were not found\n\t */\n\tpublic String valueFillString(String input) {\n\t\tif (!input.contains(FILL_DELIMITER)) {\n\t\t\treturn input;\t// nothing to fill\n\t\t}\n\n\t\tSettings s = new Settings(); // don't use any namespace\n\t\tString result = \"\";\n\t\tScanner scan = new Scanner(input);\n\t\tscan.useDelimiter(FILL_DELIMITER);\n\n\t\tif (input.startsWith(FILL_DELIMITER)) {\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\n\t\twhile(scan.hasNext()) {\n\t\t\tresult += scan.next();\n\t\t\tif (!scan.hasNext()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns a String representation of the stored settings\n\t * @return a String representation of the stored settings\n\t */\n\tpublic String toString() {\n\t\treturn props.toString();\n\t}\n\n}\n\nsrc/core/DTNHost.java\npublic class DTNHost implements Comparable {\n\tprivate static int count = 0;\n\tprivate int ID;\n\n\tprivate Coord destination;\t// where is it going\n\n\tprivate MessageRouter router;\n\tprivate MovementEngine movementEngine;\n\tprivate MovementModel movementModel;\n\tprivate Path path;\n\tprivate double speed;\n\tpublic final String groupId;\n\tprivate String name;\n\tprivate List msgListeners;\n\tprivate List movListeners;\n\tprivate List net;\n\tprivate ModuleCommunicationBus comBus;\n\n\tstatic {\n\t\tDTNSim.registerForReset(DTNHost.class.getCanonicalName());\n\t\treset();\n\t}\n\t/**\n\t * Creates a new DTNHost.\n\t * @param msgLs Message listeners\n\t * @param movLs Movement listeners\n\t * @param groupId GroupID of this host\n\t * @param interf List of NetworkInterfaces for the class\n\t * @param comBus Module communication bus object\n\t * @param mmProto Prototype of the movement model of this host\n\t * @param mRouterProto Prototype of the message router of this host\n\t */\n\tpublic DTNHost(List msgLs,\n\t\t\tList movLs,\n\t\t\tString groupId, List interf,\n\t\t\tModuleCommunicationBus comBus,\n\t\t\tMovementEngine me, MovementModel mmProto, MessageRouter mRouterProto) {\n\t\tthis.comBus = comBus;\n\t\tthis.ID = getNextID();\n\t\tthis.groupId = groupId;\n\t\tthis.name = groupId+ ID;\n\t\tthis.net = new ArrayList();\n\n\t\tfor (NetworkInterface i : interf) {\n\t\t\tNetworkInterface ni = i.replicate();\n\t\t\tni.setHost(this);\n\t\t\tnet.add(ni);\n\t\t}\n\n\t\t// TODO - think about the names of the interfaces and the nodes\n\t\t//this.name = groupId + ((NetworkInterface)net.get(1)).getAddress();\n\n\t\tthis.msgListeners = msgLs;\n\t\tthis.movListeners = movLs;\n\n\t\tthis.movementEngine = me;\n\n\t\t// create instances by replicating the prototypes\n\t\tthis.movementModel = mmProto.replicate();\n\t\tthis.movementModel.setComBus(comBus);\n\t\tthis.movementModel.setHost(this);\n\t\tsetRouter(mRouterProto.replicate());\n\n\t\tthis.path = null;\n\t}\n\n\t/**\n\t * Returns a new unique ID and increment the host count.\n\t * @return The next ID.\n\t */\n\tprivate synchronized static int getNextID() {\n\t\treturn count++;\n\t}\n\n\t/**\n\t * Reset the host and its interfaces\n\t */\n\tpublic static void reset() {\n\t\tcount = 0;\n\t}\n\n\t/**\n\t * Returns true if this node is actively moving (false if not)\n\t * @return true if this node is actively moving (false if not)\n\t */\n\tpublic boolean isMovementActive() {\n\t\treturn this.movementModel.isActive();\n\t}\n\n\t/**\n\t * Returns true if this node's radio is active (false if not)\n\t * @return true if this node's radio is active (false if not)\n\t */\n\tpublic boolean isRadioActive() {\n\t\t// Radio is active if any of the network interfaces are active.\n\t\tfor (final NetworkInterface i : this.net) {\n\t\t\tif (i.isActive()) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Set a router for this host\n\t * @param router The router to set\n\t */\n\tprivate void setRouter(MessageRouter router) {\n\t\trouter.init(this, msgListeners);\n\t\tthis.router = router;\n\t}\n\n\t/**\n\t * Returns the router of this host\n\t * @return the router of this host\n\t */\n\tpublic MessageRouter getRouter() {\n\t\treturn this.router;\n\t}\n\n\t/**\n\t * Returns the ID of this host.\n\t */\n\tpublic int getID() {\n\t\treturn this.ID;\n\t}\n\n\t/**\n\t * Returns this hosts's ModuleCommunicationBus\n\t * @return this hosts's ModuleCommunicationBus\n\t */\n\tpublic ModuleCommunicationBus getComBus() {\n\t\treturn this.comBus;\n\t}\n\n /**\n\t * Informs the router of this host about state change in a connection\n\t * object.\n\t * @param con The connection object whose state changed\n\t */\n\tpublic void connectionUp(Connection con) {\n\t\tthis.router.changedConnection(con);\n\t}\n\n\tpublic void connectionDown(Connection con) {\n\t\tthis.router.changedConnection(con);\n\t}\n\n\t/**\n\t * Returns a copy of the list of connections this host has with other hosts\n\t * @return a copy of the list of connections this host has with other hosts\n\t */\n\tpublic List getConnections() {\n\t\tList lc = new ArrayList();\n\n\t\tfor (NetworkInterface i : net) {\n\t\t\tlc.addAll(i.getConnections());\n\t\t}\n\n\t\treturn lc;\n\t}\n\n\t/**\n\t * Sets the host's location\n\t * @param location The location to set\n\t */\n\tpublic void setLocation(Coord location) {\n\t\tmovementEngine.setLocation(ID, location);\n\t}\n\n\t/**\n\t * Returns the current location of this host.\n\t * @return The location\n\t */\n\tpublic Coord getLocation() {\n\t\treturn movementEngine.getLocation(ID);\n\t}\n\n\t/**\n\t * Sets the Node's next destination and speed\n\t * @param destination The destination to set\n\t */\n\tpublic void setDestination(Coord destination, double speed) {\n\t\tif (destination == null) {\n\t\t\tthis.destination = null;\n\t\t\treturn;\n\t\t}\n\t\tthis.destination = destination.clone();\n\t\tthis.speed = speed;\n\n\t\tif (this.movListeners != null) {\n\t\t\tfor (MovementListener l : this.movListeners) {\n\t\t\t\tl.newDestination(this, this.destination, this.speed);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the current destination of this host.\n\t * @return The destination\n\t */\n\tpublic Coord getDestination() {\n\t\treturn this.destination;\n\t}\n\n\t/**\n\t * Returns the current speed of this host.\n\t * @return The speed\n\t */\n\tpublic double getSpeed() {\n\t\treturn this.speed;\n\t}\n\n\t/**\n\t * Sets the Path this node is currently traveling or null if no\n\t * path is in use at the moment. (Node is waiting for new path or stationary)\n\t * @return The path this node is traveling\n\t */\n\tpublic void setPath(Path path) {\n\t\tthis.path = path;\n\t}\n\n\t/**\n\t * Returns the Path this node is currently traveling or null if no\n\t * path is in use at the moment.\n\t * @return The path this node is traveling\n\t */\n\tpublic Path getPath() {\n\t\treturn this.path;\n\t}\n\n\t/**\n\t * Returns the movement model of this node\n\t * @return The movement model of this node\n\t */\n\tpublic MovementModel getMovementModel() {\n\t\treturn this.movementModel;\n\t}\n\n\t/**\n\t * Sets the Node's name overriding the default name (groupId + netAddress)\n\t * @param name The name to set\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * Returns the messages in a collection.\n\t * @return Messages in a collection\n\t */\n\tpublic Collection getMessageCollection() {\n\t\treturn this.router.getMessageCollection();\n\t}\n\n\t/**\n\t * Returns the number of messages this node is carrying.\n\t * @return How many messages the node is carrying currently.\n\t */\n\tpublic int getNrofMessages() {\n\t\treturn this.router.getNrofMessages();\n\t}\n\n\t/**\n\t * Returns the buffer occupancy percentage. Occupancy is 0 for empty\n\t * buffer but can be over 100 if a created message is bigger than buffer\n\t * space that could be freed.\n\t * @return Buffer occupancy percentage\n\t */\n\tpublic double getBufferOccupancy() {\n\t\tlong bSize = router.getBufferSize();\n\t\tlong freeBuffer = router.getFreeBufferSize();\n\t\treturn 100*((bSize-freeBuffer)/(bSize * 1.0));\n\t}\n\n\t/**\n\t * Returns routing info of this host's router.\n\t * @return The routing info.\n\t */\n\tpublic RoutingInfo getRoutingInfo() {\n\t\treturn this.router.getRoutingInfo();\n\t}\n\n\t/**\n\t * Returns the interface objects of the node\n\t */\n\tpublic List getInterfaces() {\n\t\treturn net;\n\t}\n\n\t/**\n\t * Find the network interface based on the index\n\t */\n\tpublic NetworkInterface getInterface(int interfaceNo) {\n\t\tNetworkInterface ni = null;\n\t\ttry {\n\t\t\tni = net.get(interfaceNo-1);\n\t\t} catch (IndexOutOfBoundsException ex) {\n\t\t\tthrow new SimError(\"No such interface: \"+interfaceNo +\n\t\t\t\t\t\" at \" + this);\n\t\t}\n\t\treturn ni;\n\t}\n\n\t/**\n\t * Find the network interface based on the interfacetype\n\t */\n\tprotected NetworkInterface getInterface(String interfacetype) {\n\t\tfor (NetworkInterface ni : net) {\n\t\t\tif (ni.getInterfaceType().equals(interfacetype)) {\n\t\t\t\treturn ni;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Force a connection event\n\t */\n\tpublic void forceConnection(DTNHost anotherHost, String interfaceId,\n\t\t\tboolean up) {\n\t\tNetworkInterface ni;\n\t\tNetworkInterface no;\n\n\t\tif (interfaceId != null) {\n\t\t\tni = getInterface(interfaceId);\n\t\t\tno = anotherHost.getInterface(interfaceId);\n\n\t\t\tassert (ni != null) : \"Tried to use a nonexisting interfacetype \"+interfaceId;\n\t\t\tassert (no != null) : \"Tried to use a nonexisting interfacetype \"+interfaceId;\n\t\t} else {\n\t\t\tni = getInterface(1);\n\t\t\tno = anotherHost.getInterface(1);\n\n\t\t\tassert (ni.getInterfaceType().equals(no.getInterfaceType())) :\n\t\t\t\t\"Interface types do not match. Please specify interface type explicitly\";\n\t\t}\n\n\t\tif (up) {\n\t\t\tni.createConnection(no);\n\t\t} else {\n\t\t\tni.disconnect(no);\n\t\t}\n\t}\n\n\t/**\n\t * for tests only --- do not use!!!\n\t */\n\tpublic void connect(DTNHost h) {\n\t\tif (DEBUG) Debug.p(\"WARNING: using deprecated DTNHost.connect\" +\n\t\t\t\"(DTNHost) Use DTNHost.forceConnection(DTNHost,null,true) instead\");\n\t\tforceConnection(h,null,true);\n\t}\n\n\t/**\n\t * Updates node's network layer and router.\n\t * @param simulateConnections Should network layer be updated too\n\t */\n\tpublic void update(boolean simulateConnections) {\n\t\tif (!isRadioActive()) {\n\t\t\t// Make sure inactive nodes don't have connections\n\t\t\ttearDownAllConnections();\n\t\t\treturn;\n\t\t}\n\n\t\tif (simulateConnections) {\n\t\t\tfor (NetworkInterface i : net) {\n\t\t\t\ti.update();\n\t\t\t}\n\t\t}\n\t\tthis.router.update();\n\t}\n\n\t/**\n\t * Tears down all connections for this host.\n\t */\n\tprivate void tearDownAllConnections() {\n\t\tfor (NetworkInterface i : net) {\n\t\t\t// Get all connections for the interface\n\t\t\tList conns = i.getConnections();\n\t\t\tif (conns.size() == 0) continue;\n\n\t\t\t// Destroy all connections\n\t\t\tList removeList =\n\t\t\t\tnew ArrayList(conns.size());\n\t\t\tfor (Connection con : conns) {\n\t\t\t\tremoveList.add(con.getOtherInterface(i));\n\t\t\t}\n\t\t\tfor (NetworkInterface inf : removeList) {\n\t\t\t\ti.disconnect(inf);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sends a message from this host to another host\n\t * @param id Identifier of the message\n\t * @param to Host the message should be sent to\n\t */\n\tpublic void sendMessage(String id, DTNHost to) {\n\t\tthis.router.sendMessage(id, to);\n\t}\n\n\t/**\n\t * Start receiving a message from another host\n\t * @param m The message\n\t * @param from Who the message is from\n\t * @return The value returned by\n\t * {@link MessageRouter#receiveMessage(Message, DTNHost)}\n\t */\n\tpublic int receiveMessage(Message m, DTNHost from) {\n\t\tint retVal = this.router.receiveMessage(m, from);\n\n\t\tif (retVal == MessageRouter.RCV_OK) {\n\t\t\tm.addNodeOnPath(this);\t// add this node on the messages path\n\t\t}\n\n\t\treturn retVal;\n\t}\n\n\t/**\n\t * Requests for deliverable message from this host to be sent trough a\n\t * connection.\n\t * @param con The connection to send the messages trough\n\t * @return True if this host started a transfer, false if not\n\t */\n\tpublic boolean requestDeliverableMessages(Connection con) {\n\t\treturn this.router.requestDeliverableMessages(con);\n\t}\n\n\t/**\n\t * Informs the host that a message was successfully transferred.\n\t * @param id Identifier of the message\n\t * @param from From who the message was from\n\t */\n\tpublic void messageTransferred(String id, DTNHost from) {\n\t\tthis.router.messageTransferred(id, from);\n\t}\n\n\t/**\n\t * Informs the host that a message transfer was aborted.\n\t * @param id Identifier of the message\n\t * @param from From who the message was from\n\t * @param bytesRemaining Nrof bytes that were left before the transfer\n\t * would have been ready; or -1 if the number of bytes is not known\n\t */\n\tpublic void messageAborted(String id, DTNHost from, int bytesRemaining) {\n\t\tthis.router.messageAborted(id, from, bytesRemaining);\n\t}\n\n\t/**\n\t * Creates a new message to this host's router\n\t * @param m The message to create\n\t */\n\tpublic void createNewMessage(Message m) {\n\t\tthis.router.createNewMessage(m);\n\t}\n\n\t/**\n\t * Deletes a message from this host\n\t * @param id Identifier of the message\n\t * @param drop True if the message is deleted because of \"dropping\"\n\t * (e.g. buffer is full) or false if it was deleted for some other reason\n\t * (e.g. the message got delivered to final destination). This effects the\n\t * way the removing is reported to the message listeners.\n\t */\n\tpublic void deleteMessage(String id, boolean drop) {\n\t\tthis.router.deleteMessage(id, drop);\n\t}\n\n\t/**\n\t * Informs movement listeners about the initial location.\n\t * Called by movement engine after setting the initial location.\n\t */\n\tpublic void notifyInitialLocation() {\n\t\tif (movListeners != null) {\n\t\t\tfor (MovementListener l : movListeners) {\n\t\t\t\tl.initialLocation(this, getLocation());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns a string presentation of the host.\n\t * @return Host's name\n\t */\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * Checks if a host is the same as this host by comparing the object\n\t * reference\n\t * @param otherHost The other host\n\t * @return True if the hosts objects are the same object\n\t */\n\tpublic boolean equals(DTNHost otherHost) {\n\t\treturn this == otherHost;\n\t}\n\n\t/**\n\t * Compares two DTNHosts by their IDs.\n\t * @see Comparable#compareTo(Object)\n\t */\n\tpublic int compareTo(DTNHost h) {\n\t\treturn this.getID() - h.getID();\n\t}\n\n}", "answers": ["\tpublic ProphetRouterWithEstimation(Settings s) {"], "length": 7097, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "2fe5907c-7439-44ab-aff2-03f7af6f989c", "reasoning": "The snippet ends right after the Javadoc comment for the constructor of ProphetRouterWithEstimation. The next logical line is the constructor declaration itself, matching the pattern used in other router classes (e.g., calling the superclass constructor). Therefore the next line should be the constructor signature.", "reasoning_model_answer": "public ProphetRouterWithEstimation(Settings s) {", "assistant_with_reasoning": "\nThe snippet ends right after the Javadoc comment for the constructor of ProphetRouterWithEstimation. The next logical line is the constructor declaration itself, matching the pattern used in other router classes (e.g., calling the superclass constructor). Therefore the next line should be the constructor signature.\n\npublic ProphetRouterWithEstimation(Settings s) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.474, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36375, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public ProphetRouterWithEstimation(Settings s) {", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.tokensTool.pandoraNext.pojo.Result;\nimport com.tokensTool.pandoraNext.pojo.poolToken;\nimport com.tokensTool.pandoraNext.pojo.systemSetting;\nimport com.tokensTool.pandoraNext.pojo.token;\nimport com.tokensTool.pandoraNext.service.impl.apiServiceImpl;\nimport com.tokensTool.pandoraNext.service.impl.poolServiceImpl;\nimport com.tokensTool.pandoraNext.service.impl.systemServiceImpl;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport java.util.ArrayList;\nimport java.util.List;", "context": "rearServer/src/main/java/com/tokensTool/pandoraNext/controller/tokenController.java\npackage com.tokensTool.pandoraNext.controller;\n\n\n\n/**\n * @author Yangyang\n * @create 2023-11-29 10:22\n */\n@RestController\npublic class tokenController {\n\n @Value(\"${server.servlet.context-path}\")\n private String profix;\n\n @Autowired\n private systemServiceImpl systemService;\n\n @Autowired\n private apiServiceImpl apiService;\n\n @Autowired\n private poolServiceImpl poolService;\n\n /**\n * 获取全部share_tokens\n * 返回share_tokens或Not_Login\n */\n @GetMapping(\"/shared_token\")\n public Result getSharedToken(@RequestParam(\"password\") String password) {\n List res = new ArrayList<>();\n systemSetting systemSetting = systemService.selectSetting();\n if (!systemSetting.getIsGetToken()) {\n return Result.error(\"Not_Open\");\n }\n if (password.equals(systemSetting.getGetTokenPassword())) {\n for (token token : apiService.selectToken(\"\")) {\n res.add(token.getShare_token());\n }\n return Result.success(res);\n } else {\n return Result.error(\"Not_Login\");\n }\n }\n\n /**\n * 获取指定share_token\n * 返回share_token或Not_Login\n */\n @GetMapping(\"/token/shared_token\")\n public Result getSimplySharedToken(@RequestParam(\"password\") String password,\n @RequestParam(\"tokenName\") String tokenName) {\n systemSetting systemSetting = systemService.selectSetting();\n if (!systemSetting.getIsGetToken()) {\n return Result.error(\"Not_Open\");\n }\n if (password.equals(systemSetting.getGetTokenPassword())) {\n for (token token : apiService.selectToken(\"\")) {\n if (token.getName().equals(tokenName)) {\n if (token.getShare_token() != null) {\n return Result.success(token.getShare_token());\n }\n return Result.error(\"该tokenName没有存放Shared_Token\");\n }\n }\n return Result.error(\"未找到该tokenName!\");\n } else {\n return Result.error(\"Not_Login\");\n }\n\n }\n\n /**\n * 获取全部access_token\n * 返回access_token或Not_Login\n */\n @GetMapping(\"/access_token\")\n public Result getAccessToken(@RequestParam(\"password\") String password) {\n List res = new ArrayList<>();\n systemSetting systemSetting = systemService.selectSetting();\n if (!systemSetting.getIsGetToken()) {\n return Result.error(\"Not_Open\");\n }\n if (password.equals(systemSetting.getGetTokenPassword())) {\n for (token token : apiService.selectToken(\"\")) {\n res.add(token.getAccess_token());\n }\n return Result.success(res);\n } else {\n return Result.error(\"Not_Login\");\n }\n }\n\n /**\n * 获取指定access_token\n * 返回access_token或Not_Login\n */\n @GetMapping(\"/token/access_token\")\n public Result getSimplyAccessToken(@RequestParam(\"password\") String password,\n @RequestParam(\"tokenName\") String tokenName) {\n systemSetting systemSetting = systemService.selectSetting();\n if (!systemSetting.getIsGetToken()) {\n return Result.error(\"Not_Open\");\n }\n if (password.equals(systemSetting.getGetTokenPassword())) {\n for (token token : apiService.selectToken(\"\")) {\n if (token.getName().equals(tokenName)) {\n if (token.getAccess_token() != null) {\n return Result.success(token.getAccess_token());\n }\n return Result.error(\"该tokenName没有存放Access_Token\");\n }\n }\n return Result.error(\"未找到该tokenName!\");\n } else {\n return Result.error(\"Not_Login\");\n }\n }\n\n\n /**\n * 获取单个pool_token\n * 返回pool_token或Not_Login\n */\n @GetMapping(\"/token/pool_token\")\n public Result getSimplePoolToken(@RequestParam(\"password\") String password,\n @RequestParam(\"tokenName\") String tokenName) {\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/apiServiceImpl.java\n@Slf4j\n@Service\npublic class apiServiceImpl implements apiService {\n /**\n * 登录接口获取session_token或者access_token\n */\n private final String sessionToken = \"/api/auth/login\";\n /**\n * 登录接口获取refresh_token\n */\n private final String refreshToken = \"/api/auth/login2\";\n\n /**\n * 把refresh_token转化成access_token\n */\n private final String reAccessToken = \"/api/auth/refresh\";\n\n /**\n * 把session_token转化成access_token\n */\n private final String accessToken = \"/api/auth/session\";\n\n /**\n * 把access_token转化为share_token\n */\n private final String shareToken = \"/api/token/register\";\n\n /**\n * 把share_token转化成pool_token\n */\n private final String poolToken = \"/api/pool/update\";\n /**\n * 部署路径为默认的话,自动识别jar包路径下的文件\n */\n private final String deploy = \"default\";\n @Value(\"${deployPosition}\")\n private String deployPosition;\n @Autowired\n private systemServiceImpl systemService;\n\n public String initializeTokenJson() {\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 遍历根节点的所有子节点\n if (rootNode.isObject()) {\n ObjectNode rootObjectNode = (ObjectNode) rootNode;\n // 遍历所有子节点\n Iterator> fields = rootObjectNode.fields();\n while (fields.hasNext()) {\n Map.Entry entry = fields.next();\n // 获取子节点的名称\n String nodeName = entry.getKey();\n // 获取子节点\n JsonNode nodeToModify = entry.getValue();\n if (nodeToModify != null && nodeToModify.isObject()) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll(rootObjectNode);\n // 获取要修改的节点\n ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName);\n // 初始化checkSession的值为true\n if (!nodeToModifyInNew.has(\"useRefreshToken\")) {\n nodeToModifyInNew.put(\"useRefreshToken\", false);\n log.info(\"为节点 \" + nodeName + \" 添加 useRefreshToken 变量成功!\");\n }\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n }\n }\n return \"为所有子节点添加 useRefreshToken 变量成功!\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"为所有子节点添加 useRefreshToken 变量失败!\";\n }\n\n /**\n * 通过判断是否需要自定义查询tokens.json文件位置\n *\n * @return tokens.json文件位置\n * @throws IOException\n */\n public String selectFile() throws IOException {\n String projectRoot;\n if (deploy.equals(deployPosition)) {\n projectRoot = System.getProperty(\"user.dir\");\n } else {\n projectRoot = deployPosition;\n }\n String parent = projectRoot + File.separator + \"tokens.json\";\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n // 如果 JSON 文件不存在或为空,创建一个新的 JSON 对象\n if (!jsonFile.exists() || jsonFile.length() == 0) {\n // 创建文件\n Files.createFile(jsonFilePath);\n System.out.println(\"tokens.json创建完成: \" + jsonFilePath);\n // 往 tokens.json 文件中添加一个空数组,防止重启报错\n Files.writeString(jsonFilePath, \"{}\");\n System.out.println(\"空数组添加完成\");\n }\n return parent;\n }\n\n /**\n * 打印token全部\n *\n * @return res(List )\n */\n @Override\n public List selectToken(String name) {\n List res = new ArrayList<>();\n try {\n String parent = selectFile();\n log.info(\"请求路径查询token:\" + parent);\n File jsonFile = new File(parent);\n ObjectMapper objectMapper = new ObjectMapper();\n // 如果 JSON 文件不存在或为空,则创建一个新的 JSON 对象并写入空数组\n if (!jsonFile.exists() || jsonFile.length() == 0) {\n Files.writeString(Paths.get(parent), \"{}\");\n log.info(\"未找到tokens.json,新建tokens.json并初始化tokens.json成功!\");\n return res;\n }\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 遍历所有字段\n Iterator> fields = rootNode.fields();\n while (fields.hasNext()) {\n Map.Entry entry = fields.next();\n String nodeName = entry.getKey();\n if (nodeName.contains(name)) {\n token temRes = new token();\n temRes.setName(nodeName);\n // 获取对应的节点\n JsonNode temNode = rootNode.get(nodeName);\n temRes.setUsername(temNode.has(\"username\") ? temNode.get(\"username\").asText() : \"\");\n temRes.setToken(temNode.has(\"token\") ? temNode.get(\"token\").asText() : \"\");\n temRes.setAccess_token(temNode.has(\"access_token\") ? temNode.get(\"access_token\").asText() : \"未开启pool_token无法生成\");\n temRes.setShare_token(temNode.has(\"share_token\") ? temNode.get(\"share_token\").asText() : \"未开启pool_token无法生成\");\n temRes.setUserPassword(temNode.has(\"userPassword\") ? temNode.get(\"userPassword\").asText() : \"\");\n temRes.setShared(temNode.has(\"shared\") && temNode.get(\"shared\").asBoolean());\n temRes.setShow_user_info(temNode.has(\"show_user_info\") && temNode.get(\"show_user_info\").asBoolean());\n temRes.setPlus(temNode.has(\"plus\") && temNode.get(\"plus\").asBoolean());\n temRes.setSetPoolToken(temNode.has(\"setPoolToken\") && temNode.get(\"setPoolToken\").asBoolean());\n temRes.setPassword(temNode.has(\"password\") ? temNode.get(\"password\").asText() : \"\");\n temRes.setUpdateTime(temNode.has(\"updateTime\") ? temNode.get(\"updateTime\").asText() : \"\");\n temRes.setUseRefreshToken(temNode.has(\"useRefreshToken\") && temNode.get(\"useRefreshToken\").asBoolean());\n //是否session有效\n temRes.setCheckSession(!temNode.has(\"checkSession\") || temNode.get(\"checkSession\").asBoolean());\n res.add(temRes);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return res;\n }\n\n /**\n * 添加checkSession变量,初始化为true\n * 启动的时候自动全部添加\n */\n public String initializeCheckSession() {\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n\n // 遍历根节点的所有子节点\n if (rootNode.isObject()) {\n ObjectNode rootObjectNode = (ObjectNode) rootNode;\n\n // 遍历所有子节点\n Iterator> fields = rootObjectNode.fields();\n while (fields.hasNext()) {\n Map.Entry entry = fields.next();\n\n // 获取子节点的名称\n String nodeName = entry.getKey();\n\n // 获取子节点\n JsonNode nodeToModify = entry.getValue();\n\n if (nodeToModify != null && nodeToModify.isObject()) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll(rootObjectNode);\n\n // 获取要修改的节点\n ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName);\n\n // 初始化checkSession的值为true\n if (!nodeToModifyInNew.has(\"checkSession\")) {\n nodeToModifyInNew.put(\"checkSession\", true);\n log.info(\"为节点 \" + nodeName + \" 添加 checkSession 变量成功!\");\n }\n\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n }\n }\n return \"为所有子节点添加 checkSession 变量成功!\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"为所有子节点添加 checkSession 变量失败!\";\n }\n\n /**\n * 添加token\n * 并添加对应keys\n *\n * @return \"添加成功!\"or\"添加失败,检查你的token是否正确或登录是否过期!\"\n */\n @Override\n public String addToken(token token) {\n String res = \"\";\n //不填token,填账号密码\n if (token.getToken() == null || token.getToken().length() == 0) {\n if (token.isUseRefreshToken()) {\n res = updateRefreshToken(token);\n } else {\n res = updateSessionToken(token);\n }\n if (res != null) {\n token.setToken(res);\n } else {\n return \"添加失败,检查你的账号密码是否正确或刷新token网址有误!\";\n }\n }\n try {\n String parent = selectFile();\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectNode rootNode;\n // 如果 JSON 文件不存在,创建一个新的 JSON 对象\n if (!jsonFile.exists()) {\n // 创建文件\n Files.createFile(jsonFilePath);\n log.info(\"tokens.json创建完成: \" + jsonFilePath);\n rootNode = objectMapper.createObjectNode();\n } else {\n if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) {\n rootNode = objectMapper.readTree(jsonFile).deepCopy();\n } else {\n rootNode = objectMapper.createObjectNode();\n }\n }\n // 创建要添加的新数据\n ObjectNode newData = objectMapper.createObjectNode();\n\n newData.put(\"token\", token.getToken());\n\n String access_token = null;\n if (token.isSetPoolToken()) {\n access_token = getAccessToken(token);\n if (access_token != null) {\n newData.put(\"access_token\", access_token);\n token.setAccess_token(access_token);\n String share_token = getShareToken(token);\n if (share_token != null && share_token.length() > 0) {\n token.setShare_token(share_token);\n newData.put(\"share_token\", share_token);\n }\n } else {\n if (token.isUseRefreshToken()) {\n return \"添加失败!请确保自己填写的token为正确的refresh_token\";\n } else {\n return \"添加失败!请确保自己填写的token为正确的session_token\";\n }\n }\n }\n\n newData.put(\"username\", token.getUsername());\n newData.put(\"userPassword\", token.getUserPassword());\n newData.put(\"shared\", token.isShared());\n newData.put(\"show_user_info\", token.isShow_user_info());\n newData.put(\"plus\", token.isPlus());\n newData.put(\"setPoolToken\", token.isSetPoolToken());\n //是否使用refresh_token来进行\n newData.put(\"useRefreshToken\", token.isUseRefreshToken());\n newData.put(\"checkSession\", true);\n\n // 检查是否需要 TokenPassword\n if (token.getPassword() != null && token.getPassword().length() > 0) {\n newData.put(\"password\", token.getPassword());\n } else {\n newData.put(\"password\", \"\");\n }\n LocalDateTime now = LocalDateTime.now();\n newData.put(\"updateTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n // 将新数据添加到 JSON 树中\n rootNode.put(token.getName(), newData);\n // 将修改后的数据写回到文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode);\n return \"添加成功!\";\n } catch (IOException e) {\n e.printStackTrace();\n return \"添加失败!\";\n }\n }\n\n /**\n * 修改token值或者其他\n *\n * @return \"修改成功!\"or\"修改失败\"or修改失败,检查你的token是否正确!\n */\n @Override\n public String requiredToken(token tem) {\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 要修改的节点名称\n String nodeNameToModify = tem.getName();\n // 获取要修改的节点\n JsonNode nodeToModify = rootNode.get(nodeNameToModify);\n if (nodeToModify != null && nodeToModify.isObject()) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll((ObjectNode) rootNode);\n // 获取要修改的节点\n ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);\n // 获取之前的节点值\n String previousToken = nodeToModifyInNew.has(\"token\") ? nodeToModifyInNew.get(\"token\").asText() : null;\n boolean previousSetPoolToken = nodeToModifyInNew.has(\"setPoolToken\") && nodeToModifyInNew.get(\"setPoolToken\").asBoolean();\n // 获取之前的节点值\n boolean previousUseRefreshToken = nodeToModifyInNew.has(\"useRefreshToken\") && nodeToModifyInNew.get(\"useRefreshToken\").asBoolean();\n // 初始修改相应的值\n require_beginToken(tem, nodeToModifyInNew);\n\n //web条件 api转web web转api 消耗余额\n if (previousSetPoolToken != tem.isSetPoolToken()) {\n if (!tem.isSetPoolToken()) {\n nodeToModifyInNew.put(\"token\", tem.getUsername() + \",\" + tem.getUserPassword());\n nodeToModifyInNew.put(\"share_token\", \"未开启API开关无法生成\");\n nodeToModifyInNew.put(\"access_token\", \"未开启API开关无法生成\");\n LocalDateTime now = LocalDateTime.now();\n nodeToModifyInNew.put(\"updateTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n return \"修改成功!\";\n }\n // token相同的情况下 web 转 session_token\n else if (!tem.isUseRefreshToken() && previousToken.equals(tem.getToken())) {\n String reSessionToken = updateSessionToken(tem);\n if (reSessionToken != null) {\n reupdate(reSessionToken, tem, nodeToModifyInNew);\n } else {\n return \"修改失败,请确保你的账号密码是否正确且proxy的url配置是否正确,或者余额不足\";\n }\n }\n // token相同的情况下 web 转 refresh_token\n else if (tem.isUseRefreshToken() && previousToken.equals(tem.getToken())) {\n String refreshToken = updateRefreshToken(tem);\n if (refreshToken != null) {\n reupdate(refreshToken, tem, nodeToModifyInNew);\n } else {\n return \"修改失败,请确保你的账号密码是否正确且proxy的url配置是否正确,或者余额不足\";\n }\n }\n }\n\n // token不相同,直接看token是否对应\n // web转api 填写相应的token\n // session和refresh之间的互转 填写相应的token\n\n if (!previousToken.equals(tem.getToken())) {\n String access_token = getAccessToken(tem);\n if (access_token != null) {\n tem.setAccess_token(access_token);\n String share_token = getShareToken(tem);\n nodeToModifyInNew.put(\"access_token\", access_token);\n if (share_token != null) {\n nodeToModifyInNew.put(\"checkSession\", true);\n nodeToModifyInNew.put(\"share_token\", share_token);\n } else {\n return \"access_token转share_token失败!\";\n }\n // 将修改后的 newObjectNode 写回文件\n LocalDateTime now = LocalDateTime.now();\n nodeToModifyInNew.put(\"updateTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n return \"修改成功!\";\n } else {\n return tem.isUseRefreshToken() ? \"添加失败!请填写正确的refresh_token或关闭使用refresh_token后重新尝试\" : \"修改失败!请填写正确的session_token或开启使用refresh_token后重新尝试\";\n }\n }\n\n // 在不改变token的值的API模式下,session和refresh之间的互相转换\n if (previousUseRefreshToken != tem.isUseRefreshToken()) {\n if (tem.isUseRefreshToken()) {\n String refreshToken = updateRefreshToken(tem);\n if (refreshToken != null) {\n reupdate(refreshToken, tem, nodeToModifyInNew);\n } else {\n return \"修改失败,请确保你的账号密码是否正确且proxy的url配置是否正确,或者余额不足\";\n }\n } else {\n String reSessionToken = updateSessionToken(tem);\n if (reSessionToken != null) {\n reupdate(reSessionToken, tem, nodeToModifyInNew);\n } else {\n return \"修改失败,请确保你的账号密码是否正确且proxy的url配置是否正确,或者余额不足\";\n }\n }\n }\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n return \"修改成功!\";\n } else {\n log.info(\"节点未找到或不是对象,请检查tokens.json! \" + nodeNameToModify);\n return \"节点未找到或不是对象!\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"修改失败!\";\n }\n\n public void reupdate(String token, token tem, ObjectNode nodeToModifyInNew) {\n tem.setToken(token);\n nodeToModifyInNew.put(\"token\", token);\n require_UpdateToken(tem, nodeToModifyInNew);\n LocalDateTime now = LocalDateTime.now();\n nodeToModifyInNew.put(\"updateTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n }\n\n\n public void require_beginToken(token tem, ObjectNode nodeToModifyInNew) {\n // 修改节点的值\n nodeToModifyInNew.put(\"token\", tem.getToken());\n nodeToModifyInNew.put(\"username\", tem.getUsername());\n nodeToModifyInNew.put(\"userPassword\", tem.getUserPassword());\n nodeToModifyInNew.put(\"shared\", tem.isShared());\n nodeToModifyInNew.put(\"show_user_info\", tem.isShow_user_info());\n nodeToModifyInNew.put(\"plus\", tem.isPlus());\n nodeToModifyInNew.put(\"setPoolToken\", tem.isSetPoolToken());\n nodeToModifyInNew.put(\"access_token\", tem.getAccess_token());\n nodeToModifyInNew.put(\"share_token\", tem.getShare_token());\n nodeToModifyInNew.put(\"checkSession\", tem.isCheckSession());\n nodeToModifyInNew.put(\"useRefreshToken\", tem.isUseRefreshToken());\n if (tem.getPassword() != null && tem.getPassword().length() > 0) {\n nodeToModifyInNew.put(\"password\", tem.getPassword());\n } else {\n nodeToModifyInNew.put(\"password\", \"\");\n }\n }\n\n /**\n * 专门给生成函数写的修改token的值\n *\n * @param tem\n * @return\n */\n public String product_requireToken(token tem) {\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 要修改的节点名称\n String nodeNameToModify = tem.getName();\n // 获取要修改的节点\n JsonNode nodeToModify = rootNode.get(nodeNameToModify);\n if (nodeToModify != null && nodeToModify.isObject()) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll((ObjectNode) rootNode);\n // 获取要修改的节点\n ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);\n // 获取之前的节点值\n String previousToken = nodeToModifyInNew.has(\"token\") ? nodeToModifyInNew.get(\"token\").asText() : null;\n // 初始修改相应的值\n require_beginToken(tem, nodeToModifyInNew);\n if (!previousToken.equals(tem.getToken())\n && tem.isSetPoolToken()) {\n // 将修改后的 newObjectNode 写回文件\n LocalDateTime now = LocalDateTime.now();\n nodeToModifyInNew.put(\"updateTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n return \"修改成功!\";\n }\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n return \"修改成功!\";\n } else {\n log.info(\"节点未找到或不是对象,请检查tokens.json! \" + nodeNameToModify);\n return \"节点未找到或不是对象!\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"修改失败!\";\n }\n\n\n public void require_UpdateToken(token tem, ObjectNode nodeToModifyInNew) {\n try {\n String access_token = getAccessToken(tem);\n if (access_token != null) {\n tem.setAccess_token(access_token);\n String share_token = getShareToken(tem);\n nodeToModifyInNew.put(\"access_token\", access_token);\n nodeToModifyInNew.put(\"checkSession\", true);\n if (share_token != null) {\n nodeToModifyInNew.put(\"share_token\", share_token);\n } else {\n nodeToModifyInNew.put(\"share_token\", \"检查session或refresh是否过期,请重新刷新获取\");\n }\n } else {\n nodeToModifyInNew.put(\"access_token\", \"检查session或refresh是否过期,请重新刷新获取\");\n nodeToModifyInNew.put(\"checkSession\", false);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * 删除token\n * 并删除对应keys\n *\n * @return \"删除成功!\"or\"删除失败\"\n */\n @Override\n public String deleteToken(token token) {\n try {\n String name = token.getName();\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n\n // 检查要删除的节点是否存在\n JsonNode nodeToRemove = rootNode.get(name);\n if (nodeToRemove != null) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll((ObjectNode) rootNode);\n // 删除节点\n newObjectNode.remove(name);\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n if (token.getAccess_token().startsWith(\"eyJhb\") && deleteShareToken(token)) {\n return \"删除并销毁share_token成功!\";\n }\n return \"删除成功!\";\n } else {\n log.info(\"token未找到: \" + name);\n return \"token未找到!\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"删除失败\";\n }\n\n /**\n * 自动更新Token方法\n * 通过api/auth/login拿到session_token\n * 更换tokens.json里存储的Token\n * 账号为token.getUserName()\n * 密码为token.getUserPassword()\n */\n public String updateSessionToken(token token) {\n String url;\n systemSetting systemSetting = systemService.selectSetting();\n if (systemSetting.getAutoToken_url().equals(\"default\")) {\n String bingUrl = systemSetting.getBing();\n String[] parts = bingUrl.split(\":\");\n url = \"http://127.0.0.1\" + \":\" + parts[1] + \"/\" + systemSetting.getProxy_api_prefix() + sessionToken;\n } else {\n url = systemSetting.getAutoToken_url() + sessionToken;\n }\n log.info(\"将通过这个网址请求登录信息:\" + url);\n try {\n OkHttpClient client = new OkHttpClient();\n RequestBody requestBody = new MultipartBody.Builder()\n .setType(MultipartBody.FORM)\n .addFormDataPart(\"username\", token.getUsername())\n .addFormDataPart(\"password\", token.getUserPassword())\n .build();\n Request request = new Request.Builder()\n .url(url)\n .post(requestBody)\n .addHeader(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\")\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"Request failed: \" + response.body().string().trim());\n return null;\n }\n String responseContent = response.body().string();\n String resToken = null;\n try {\n JSONObject jsonResponse = new JSONObject(responseContent);\n resToken = jsonResponse.getString(\"session_token\");\n } catch (JSONException e) {\n e.printStackTrace();\n }\n if (response.code() == 200 && resToken != null && resToken.startsWith(\"eyJhb\")) {\n return resToken;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * 自动Token方法\n * 通过api/auth/login2拿到refresh_token\n * 更换tokens.json里存储的Token\n * 账号为token.getUserName()\n * 密码为token.getUserPassword()\n */\n public String updateRefreshToken(token token) {\n String url;\n systemSetting systemSetting = systemService.selectSetting();\n if (systemSetting.getAutoToken_url().equals(\"default\")) {\n String bingUrl = systemSetting.getBing();\n String[] parts = bingUrl.split(\":\");\n url = \"http://127.0.0.1\" + \":\" + parts[1] + \"/\" + systemSetting.getProxy_api_prefix() + refreshToken;\n } else {\n url = systemSetting.getAutoToken_url() + refreshToken;\n }\n log.info(\"将通过这个网址请求登录信息:\" + url);\n try {\n OkHttpClient client = new OkHttpClient();\n RequestBody requestBody = new MultipartBody.Builder()\n .setType(MultipartBody.FORM)\n .addFormDataPart(\"username\", token.getUsername())\n .addFormDataPart(\"password\", token.getUserPassword())\n .build();\n Request request = new Request.Builder()\n .url(url)\n .post(requestBody)\n .addHeader(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\")\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"Request failed: \" + response.body().string().trim());\n return null;\n }\n String responseContent = response.body().string();\n String resToken = null;\n try {\n JSONObject jsonResponse = new JSONObject(responseContent);\n log.info(jsonResponse.toString());\n resToken = jsonResponse.getString(\"refresh_token\");\n log.info(resToken);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n if (response.code() == 200) {\n return resToken;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n public String getAccessToken(token token) {\n String url;\n systemSetting systemSetting = systemService.selectSettingUrl();\n String tokenKind;\n String tokenName;\n if (token.isUseRefreshToken()) {\n tokenKind = reAccessToken;\n tokenName = \"refresh_token\";\n } else {\n tokenKind = accessToken;\n tokenName = \"session_token\";\n }\n if (systemSetting.getAutoToken_url().equals(\"default\")) {\n String bingUrl = systemSetting.getBing();\n String[] parts = bingUrl.split(\":\");\n url = \"http://127.0.0.1\" + \":\" + parts[1] + \"/\" + systemSetting.getProxy_api_prefix() + tokenKind;\n } else {\n url = systemSetting.getAutoToken_url() + tokenKind;\n }\n log.info(\"将通过这个网址请求登录信息:\" + url);\n try {\n OkHttpClient client = new OkHttpClient();\n RequestBody requestBody = new MultipartBody.Builder()\n .setType(MultipartBody.FORM)\n .addFormDataPart(tokenName, token.getToken())\n .build();\n Request request = new Request.Builder()\n .url(url)\n .post(requestBody)\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"Request failed: \" + response.body().string().trim());\n return null;\n }\n String responseContent = response.body().string();\n String resToken = null;\n try {\n JSONObject jsonResponse = new JSONObject(responseContent);\n resToken = jsonResponse.getString(\"access_token\");\n } catch (JSONException e) {\n e.printStackTrace();\n }\n if (response.code() == 200 && resToken != null && resToken.length() > 400) {\n return resToken;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n public String getShareToken(token token) {\n systemSetting systemSetting = systemService.selectSettingUrl();\n String url = systemSetting.getAutoToken_url().equals(\"default\")\n ? \"http://127.0.0.1:\" + systemSetting.getBing().split(\":\")[1] + \"/\" + systemSetting.getProxy_api_prefix() + shareToken\n : systemSetting.getAutoToken_url() + shareToken;\n log.info(\"将通过这个网址请求登录信息:\" + url);\n String data = \"unique_name=\" + token.getName() + \"&access_token=\" + token.getAccess_token() +\n \"&expires_in=0&show_conversations=false&show_userinfo=\" + token.isShow_user_info();\n OkHttpClient client = new OkHttpClient();\n RequestBody body = RequestBody.create(data, MediaType.parse(\"application/x-www-form-urlencoded\"));\n Request request = new Request.Builder()\n .url(url)\n .post(body)\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"share token failed: \" + response.body().string().trim());\n return null;\n }\n String tokenKey = new JSONObject(response.body().string()).getString(\"token_key\");\n if (tokenKey.matches(\"^(fk-|pk-).*\")) {\n return tokenKey;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public boolean deleteShareToken(token token) {\n systemSetting systemSetting = systemService.selectSettingUrl();\n String url = systemSetting.getAutoToken_url().equals(\"default\")\n ? \"http://127.0.0.1:\" + systemSetting.getBing().split(\":\")[1] + \"/\" + systemSetting.getProxy_api_prefix() + shareToken\n : systemSetting.getAutoToken_url() + shareToken;\n log.info(\"将通过这个网址请求登录信息:\" + url);\n String data = \"unique_name=\" + token.getName() + \"&access_token=\" + token.getAccess_token() +\n \"&expires_in=-1&show_conversations=false&show_userinfo=\" + token.isShow_user_info();\n OkHttpClient client = new OkHttpClient();\n RequestBody body = RequestBody.create(data, MediaType.parse(\"application/x-www-form-urlencoded\"));\n Request request = new Request.Builder()\n .url(url)\n .post(body)\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"share token failed: \" + response.body().string().trim());\n return false;\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n\n public String getPoolToken(String pool_token, String shareTokens) {\n systemSetting systemSetting = systemService.selectSettingUrl();\n String url = systemSetting.getAutoToken_url().equals(\"default\")\n ? \"http://127.0.0.1:\" + systemSetting.getBing().split(\":\")[1] + \"/\" + systemSetting.getProxy_api_prefix() + poolToken\n : systemSetting.getAutoToken_url() + poolToken;\n log.info(\"将通过这个网址请求登录信息:\" + url);\n try {\n OkHttpClient client = new OkHttpClient();\n RequestBody requestBody;\n if (shareTokens == \"\") {\n List tokens = selectToken(\"\");\n StringBuffer resToken = new StringBuffer();\n for (token token : tokens) {\n if (token.getShare_token() != null && token.isSetPoolToken()) {\n resToken.append(token.getShare_token() + \"\\n\");\n }\n }\n requestBody = new FormBody.Builder()\n .add(\"share_tokens\", resToken.toString())\n .add(\"pool_token\", pool_token)\n .build();\n } else {\n requestBody = new FormBody.Builder()\n .add(\"share_tokens\", shareTokens)\n .add(\"pool_token\", pool_token)\n .build();\n }\n Request request = new Request.Builder()\n .url(url)\n .post(requestBody)\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"Request failed: \" + response.body().string().trim());\n return null;\n }\n String responseContent = response.body().string();\n JSONObject jsonResponse = new JSONObject(responseContent);\n String resPoolToken = jsonResponse.getString(\"pool_token\");\n log.info(\"一共运行了\" + jsonResponse.getString(\"count\") + \"条share_token\");\n if (resPoolToken.contains(\"pk\")) {\n log.info(\"pool_token更新为:\" + resPoolToken);\n return resPoolToken;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * 生成shareToken和accessToken\n *\n * @return \"生成成功\" or \"生成失败\"\n */\n @Override\n public token autoUpdateSimpleToken(token token) {\n if (token == null || !token.isSetPoolToken()) {\n log.info(\"未查询到相关数据\");\n return null;\n }\n String access_token = getAccessToken(token);\n if (access_token != null) {\n token.setAccess_token(access_token);\n //执行获取share_token操作\n String share_token = getShareToken(token);\n token.setShare_token(share_token);\n if (share_token != null) {\n token.setCheckSession(true);\n String res = product_requireToken(token);\n if (res.contains(\"成功\")) {\n log.info(res + \",修改share_token为:\" + share_token);\n return token;\n }\n }\n } else {\n token.setCheckSession(false);\n token.setShared(false);\n String res = product_requireToken(token);\n if (res.contains(\"成功\")) {\n log.info(\"已为您禁用该session_token!\");\n }\n }\n return null;\n }\n\n /**\n * 自动更新Token\n * 更换tokensTool里存储的Token的access_token和share_token\n * 并自动检查session是否过期\n *\n * @return \"更新成功\" or \"更新失败\"\n */\n public String autoUpdateToken(String name) {\n List resTokens = selectToken(name);\n int newToken = 0;\n int allToken = 0;\n try {\n for (token token : resTokens) {\n if (!token.isSetPoolToken()) {\n continue;\n }\n token res = autoUpdateSimpleToken(token);\n if (res != null) {\n newToken++;\n }\n allToken++;\n Thread.sleep(1000);\n }\n if (newToken == 0) {\n log.info(\"自动生成Token失败!\");\n return \"自动生成Token失败!\";\n } else {\n log.info(\"自动生成Token成功:\" + newToken + \"session或refresh过期:\" + (allToken - newToken));\n return \"自动生成Token成功:\" + newToken + \"
session或refresh过期:\" + (allToken - newToken);\n }\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 自动更新session_token时间80天\n *\n * @param token\n * @return\n */\n @Override\n public String autoUpdateSessionToken(token token) {\n if (token == null) {\n log.info(\"未查询到相关数据\");\n return null;\n }\n try {\n if (token.isUseRefreshToken()) {\n String refreshToken = updateRefreshToken(token);\n if (refreshToken != null) {\n return refreshToken;\n }\n } else {\n String sessionToken = updateSessionToken(token);\n if (sessionToken != null) {\n return sessionToken;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n @Override\n public String deletePoolToken(String pool_token) {\n String url;\n systemSetting systemSetting = systemService.selectSettingUrl();\n if (systemSetting.getAutoToken_url().equals(\"default\")) {\n String bingUrl = systemSetting.getBing();\n String[] parts = bingUrl.split(\":\");\n url = \"http://127.0.0.1\" + \":\" + parts[1] + \"/\" +\n systemSetting.getProxy_api_prefix() + poolToken;\n } else {\n url = systemSetting.getAutoToken_url() + poolToken;\n }\n log.info(\"将通过这个网址请求登录信息:\" + url);\n try {\n OkHttpClient client = new OkHttpClient();\n RequestBody requestBody = new FormBody.Builder()\n .add(\"share_tokens\", \"\")\n .add(\"pool_token\", pool_token)\n .build();\n Request request = new Request.Builder()\n .url(url)\n .post(requestBody)\n .build();\n try (Response response = client.newCall(request).execute()) {\n String responseContent = response.body().string();\n JSONObject jsonResponse = new JSONObject(responseContent);\n if (!response.isSuccessful() && !jsonResponse.has(\"detail\")) {\n log.info(\"Request failed: \" + response.body().string().trim());\n return null;\n }\n String resPoolToken = jsonResponse.getString(\"detail\");\n if (response.code() == 200 && resPoolToken.length() > 0) {\n log.info(\"注销pool_token成功!\");\n return resPoolToken;\n } else if (response.code() == 400) {\n return \"不存在该pool_token\";\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n @Override\n public PandoraLimit getPandoraLimit() {\n systemSetting systemSetting = systemService.selectSettingLicense();\n String url = \"https://dash.pandoranext.com/api/\" + systemSetting.getLicense_id() + \"/usage\";\n log.info(\"将通过这个网址请求PandoraNext余额信息:\" + url);\n try {\n OkHttpClient client = new OkHttpClient();\n Request request = new Request.Builder()\n .url(url)\n .get()\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"Request failed: \" + response.body().string().trim());\n return null;\n }\n String responseContent = response.body().string();\n PandoraLimit pandoraLimit = new PandoraLimit();\n JSONObject jsonResponse = new JSONObject(responseContent);\n //用量\n pandoraLimit.setCurrent(jsonResponse.getInt(\"current\"));\n //ip\n pandoraLimit.setIp(jsonResponse.getString(\"ip\"));\n //总额\n pandoraLimit.setTotal(jsonResponse.getInt(\"total\"));\n //重载时间\n pandoraLimit.setTtl(jsonResponse.getInt(\"ttl\"));\n if (response.code() == 200 && pandoraLimit.toString().length() > 0) {\n return pandoraLimit;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n public void updateSession() {\n try {\n List tokens = selectToken(\"\");\n token resToken = null;\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\");\n LocalDateTime minDateTime = LocalDateTime.MAX;\n for (token token : tokens) {\n //保证refresh_token不被刷新\n if (token.isSetPoolToken() && !token.isUseRefreshToken()) {\n LocalDateTime currentDateTime = LocalDateTime.parse(token.getUpdateTime(), formatter);\n if (currentDateTime.isBefore(minDateTime)) {\n minDateTime = currentDateTime;\n resToken = token;\n }\n }\n }\n token s = updateSession(resToken);\n if (s != null) {\n log.info(\"更新session_token,access_token和share_token成功!\");\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 刷新session,更新access_token和share_token\n *\n * @param token\n * @return\n */\n @Override\n public token updateSession(token token) {\n String res = autoUpdateSessionToken(token);\n if (res != null) {\n token.setToken(res);\n token.setSetPoolToken(true);\n token.setCheckSession(true);\n try {\n token resToken = autoUpdateSimpleToken(token);\n if (resToken != null) {\n return resToken;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n return null;\n }\n}\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n /**\n * 响应码,1 代表成功; 0 代表失败\n */\n\n private Integer code;\n /**\n * 响应信息 描述字符串\n */\n\n private String msg;\n /**\n * 返回的数据\n */\n private Object data;\n\n /**\n * 增删改 成功响应\n */\n public static Result success() {\n return new Result(1, \"success\", null);\n }\n\n /**\n * 查询 成功响应\n */\n public static Result success(Object data) {\n return new Result(1, \"success\", data);\n }\n\n /**\n * 失败响应\n */\n public static Result error(String msg) {\n return new Result(0, msg, null);\n }\n}\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n private Integer timeout;\n /**\n * 部署服务流量走代理\n */\n private String proxy_url;\n /**\n * GPT中创建的对话分享\n */\n private Boolean public_share;\n /**\n * 访问网站密码\n */\n private String site_password;\n /**\n * 重载服务密码\n */\n private String setup_password;\n /**\n * 白名单(null则不限制,为空数组[]则限制所有账号)\n */\n private String whitelist;\n\n /**\n * pandoraNext验证license_id\n */\n private String license_id;\n\n /**\n * tokensTool登录Username\n */\n private String loginUsername;\n\n /**\n * tokensTool密码Password\n */\n private String loginPassword;\n\n /**\n * tokensTool 验证信息\n */\n private validation validation;\n\n /**\n * tokensTool 更新token网址\n * 为\"default\"则调用本机的,不为“default\"则自定义\n */\n private String autoToken_url;\n\n /**\n * 是否开启拿tokensTool的后台token\n */\n private Boolean isGetToken;\n /**\n * tokensTool 拿到getTokenPassword\n * 为\"getTokenPassword\" 默认:123456\n * 默认拿getTokenPassword\n */\n private String getTokenPassword;\n\n /**\n * tokensTool 更新containerName(容器名)\n * 通过容器名实现开启,关闭,重新启动容器\n */\n private String containerName;\n\n\n /**\n * PandoraNext tls证书\n */\n private tls tls;\n\n /**\n * PandoraNext config.json位置\n */\n private String configPosition;\n\n /**\n * PandoraNext 接口地址添加前缀\n */\n private String isolated_conv_title;\n\n /**\n * PandoraNext 会话标题\n */\n private String proxy_api_prefix;\n\n /**\n * 禁用注册账号功能,true或false\n */\n private Boolean disable_signup;\n\n /**\n * 在proxy模式使用gpt-4模型调用/backend-api/conversation接口是否自动打码,使用消耗为4+10。\n */\n private Boolean auto_conv_arkose;\n\n /**\n * 在proxy模式是否使用PandoraNext的文件代理服务,避免官方文件服务的墙。\n */\n private Boolean proxy_file_service;\n\n /**\n * 配置自定义的DoH主机名,建议使用IP形式。默认在+8区使用223.6.6.6,其余地区使用1.1.1.1。\n */\n private String custom_doh_host;\n\n /**\n * 自动刷新session的开关\n */\n private Boolean auto_updateSession;\n\n /**\n * 自动刷新session的时间 (天为单位)\n */\n private Integer auto_updateTime;\n\n /**\n * 自动刷新session的个数 (个)\n */\n private Integer auto_updateNumber;\n\n /**\n * PadoraNext的公网访问地址\n */\n private String pandoraNext_outUrl;\n\n /**\n * oneAPi的公网访问地址\n */\n private String oneAPi_outUrl;\n\n /**\n * oneApi访问令牌\n */\n private String oneAPi_intoToken;\n}\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/systemServiceImpl.java\n@Slf4j\n@Service\npublic class systemServiceImpl implements systemService {\n @Value(\"${deployPosition}\")\n private String deployPosition;\n private String deploy = \"default\";\n\n\n public String selectFile() {\n String projectRoot;\n if (deploy.equals(deployPosition)) {\n projectRoot = System.getProperty(\"user.dir\");\n } else {\n projectRoot = deployPosition;\n }\n String parent = projectRoot + File.separator + \"config.json\";\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n // 如果 JSON 文件不存在,创建一个新的 JSON 对象\n if (!jsonFile.exists()) {\n try {\n // 创建文件config.json\n Files.createFile(jsonFilePath);\n // 往 config.json 文件中添加一个空数组,防止重启报错\n Files.writeString(jsonFilePath, \"{}\");\n log.info(\"空数组添加完成\");\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n log.info(\"config.json创建完成: \" + jsonFilePath);\n }\n return parent;\n }\n\n /**\n * 初始化config.json文件\n */\n public void initializeConfigJson() {\n String parent = selectFile();\n try {\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 定义一个 Map,其中键是 JSON 属性的名称,值是默认值\n Map keysAndDefaults = new HashMap<>();\n keysAndDefaults.put(\"loginUsername\", \"root\");\n keysAndDefaults.put(\"loginPassword\", \"123456\");\n keysAndDefaults.put(\"license_id\", \"\");\n keysAndDefaults.put(\"autoToken_url\", \"default\");\n keysAndDefaults.put(\"isGetToken\", \"false\");\n keysAndDefaults.put(\"getTokenPassword\", \"\");\n keysAndDefaults.put(\"containerName\", \"PandoraNext\");\n keysAndDefaults.put(\"isolated_conv_title\", \"*\");\n keysAndDefaults.put(\"proxy_api_prefix\", \"\");\n keysAndDefaults.put(\"disable_signup\", false);\n keysAndDefaults.put(\"auto_conv_arkose\", false);\n keysAndDefaults.put(\"proxy_file_service\", false);\n keysAndDefaults.put(\"custom_doh_host\", \"\");\n\n // 0.4.9.3\n keysAndDefaults.put(\"auto_updateSession\", false);\n keysAndDefaults.put(\"auto_updateTime\", 5);\n keysAndDefaults.put(\"auto_updateNumber\", 1);\n keysAndDefaults.put(\"pandoraNext_outUrl\", \"\");\n\n // 0.5.0\n\n keysAndDefaults.put(\"oneAPi_outUrl\", \"\");\n keysAndDefaults.put(\"oneAPi_intoToken\", \"\");\n\n boolean exist = checkAndSetDefaults(jsonObject, keysAndDefaults);\n\n JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject(\"captcha\")).orElse(new JSONObject());\n validation captchaSetting = new validation(\n captchaJson.optString(\"provider\", \"\"),\n captchaJson.optString(\"site_key\", \"\"),\n captchaJson.optString(\"site_secret\", \"\"),\n captchaJson.optBoolean(\"site_login\", false),\n captchaJson.optBoolean(\"setup_login\", false),\n captchaJson.optBoolean(\"oai_username\", false),\n captchaJson.optBoolean(\"oai_password\", false)\n );\n\n JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject(\"tls\")).orElse(new JSONObject());\n tls tlsSetting = new tls(\n tlsJson.optBoolean(\"enabled\", false),\n tlsJson.optString(\"cert_file\", \"\"),\n tlsJson.optString(\"key_file\", \"\")\n );\n\n if (tlsJson.length() == 0) {\n jsonObject.put(\"tls\", tlsSetting.toJSONObject());\n exist = false;\n }\n if (captchaJson.length() == 0) {\n jsonObject.put(\"captcha\", captchaSetting.toJSONObject());\n exist = false;\n }\n if (!exist) {\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n }\n log.info(\"初始化config.json成功!\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n // 通用方法,检查和设置默认值\n private boolean checkAndSetDefaults(JSONObject jsonObject, Map keysAndDefaults) throws JSONException {\n boolean exist = true;\n for (Map.Entry entry : keysAndDefaults.entrySet()) {\n try {\n jsonObject.get(entry.getKey());\n } catch (JSONException e) {\n jsonObject.put(entry.getKey(), entry.getValue());\n log.info(\"config.json没有新增\" + entry.getKey() + \"参数,现已增加!\");\n exist = false;\n }\n }\n return exist;\n }\n\n /**\n * 修改config.json里的系统值\n *\n * @return \"修改成功!\"or\"修改失败\"\n */\n @Override\n public String requiredSetting(systemSetting tem) {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n JSONObject jsonObject = new JSONObject(jsonContent);\n updateJsonValue(jsonObject, \"bind\", tem.getBing());\n updateJsonValue(jsonObject, \"timeout\", tem.getTimeout());\n updateJsonValue(jsonObject, \"proxy_url\", tem.getProxy_url());\n updateJsonValue(jsonObject, \"public_share\", tem.getPublic_share());\n updateJsonValue(jsonObject, \"site_password\", tem.getSite_password());\n updateJsonValue(jsonObject, \"setup_password\", tem.getSetup_password());\n JSONArray jsonArray = null;\n if (tem.getWhitelist() != null && tem.getWhitelist().length() > 0 && tem.getWhitelist() != \"null\") {\n String numbersString = tem.getWhitelist().replaceAll(\"[\\\\[\\\\]]\", \"\");\n String[] numbersArray = numbersString.split(\",\");\n // 将数组转换为 List\n List numbersList = new ArrayList<>(Arrays.asList(numbersArray));\n jsonArray = new JSONArray(numbersList);\n jsonObject.put(\"whitelist\", jsonArray);\n } else {\n jsonObject.put(\"whitelist\", JSONObject.NULL);\n }\n\n //4.7.2\n if (!tem.getLoginPassword().equals(jsonObject.optString(\"loginPassword\"))\n || !tem.getLoginUsername().equals(jsonObject.optString(\"loginUsername\"))) {\n Instant instant = Instant.now();\n //时间戳\n String key = String.valueOf(instant.toEpochMilli());\n JwtUtils.setSignKey(key);\n }\n\n updateJsonValue(jsonObject, \"loginUsername\", tem.getLoginUsername());\n updateJsonValue(jsonObject, \"loginPassword\", tem.getLoginPassword());\n\n updateJsonValue(jsonObject, \"license_id\", tem.getLicense_id());\n updateJsonValue(jsonObject, \"autoToken_url\", tem.getAutoToken_url());\n updateJsonValue(jsonObject, \"isGetToken\", tem.getIsGetToken());\n updateJsonValue(jsonObject, \"getTokenPassword\", tem.getGetTokenPassword());\n updateJsonValue(jsonObject, \"containerName\", tem.getContainerName());\n\n updateJsonValue(jsonObject, \"isolated_conv_title\", tem.getIsolated_conv_title());\n updateJsonValue(jsonObject, \"proxy_api_prefix\", tem.getProxy_api_prefix());\n\n // 4,9\n updateJsonValue(jsonObject, \"disable_signup\", tem.getDisable_signup());\n updateJsonValue(jsonObject, \"auto_conv_arkose\", tem.getAuto_conv_arkose());\n updateJsonValue(jsonObject, \"proxy_file_service\", tem.getProxy_file_service());\n updateJsonValue(jsonObject, \"custom_doh_host\", tem.getCustom_doh_host());\n\n // validation\n validation validation = tem.getValidation();\n JSONObject captchaJson = jsonObject.getJSONObject(\"captcha\");\n updateJsonValue(captchaJson, \"provider\", validation.getProvider());\n updateJsonValue(captchaJson, \"site_key\", validation.getSite_key());\n updateJsonValue(captchaJson, \"site_secret\", validation.getSite_secret());\n updateJsonValue(captchaJson, \"site_login\", validation.isSite_login());\n updateJsonValue(captchaJson, \"setup_login\", validation.isSetup_login());\n updateJsonValue(captchaJson, \"oai_username\", validation.isOai_username());\n updateJsonValue(captchaJson, \"oai_password\", validation.isOai_password());\n\n // tls\n tls tls = tem.getTls();\n JSONObject tlsJson = jsonObject.getJSONObject(\"tls\");\n updateJsonValue(tlsJson, \"enabled\", tls.isEnabled());\n updateJsonValue(tlsJson, \"cert_file\", tls.getCert_file());\n updateJsonValue(tlsJson, \"key_file\", tls.getKey_file());\n\n // 将修改后的 JSONObject 转换为格式化的 JSON 字符串\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n return \"修改config.json成功,快去重启PandoraNext吧!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"修改config.json失败\";\n }\n\n private void updateJsonValue(JSONObject jsonObject, String key, Object value) {\n if (value == null) {\n return;\n }\n try {\n if (value != null && value.toString().length() > 0) {\n jsonObject.put(key, value);\n } else if (value.toString().length() == 0) {\n jsonObject.put(key, \"\");\n }\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 查询config.json里的系统值\n *\n * @return systemSettings类\n */\n public systemSetting selectSetting() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setSite_password(jsonObject.optString(\"site_password\"));\n config.setSetup_password(jsonObject.optString(\"setup_password\"));\n config.setBing(jsonObject.optString(\"bind\"));\n config.setPublic_share(jsonObject.optBoolean(\"public_share\"));\n config.setProxy_url(jsonObject.optString(\"proxy_url\"));\n config.setWhitelist(jsonObject.isNull(\"whitelist\") ? null : jsonObject.optString(\"whitelist\"));\n config.setTimeout(jsonObject.optInt(\"timeout\"));\n\n config.setLoginUsername(jsonObject.optString(\"loginUsername\"));\n config.setLoginPassword(jsonObject.optString(\"loginPassword\"));\n\n config.setLicense_id(jsonObject.optString(\"license_id\"));\n config.setAutoToken_url(jsonObject.optString(\"autoToken_url\"));\n config.setIsGetToken(jsonObject.optBoolean(\"isGetToken\"));\n config.setGetTokenPassword(jsonObject.optString(\"getTokenPassword\"));\n config.setContainerName(jsonObject.optString(\"containerName\"));\n\n // 4.0\n config.setIsolated_conv_title(jsonObject.optString(\"isolated_conv_title\"));\n config.setProxy_api_prefix(jsonObject.optString(\"proxy_api_prefix\"));\n\n // 4.9\n config.setDisable_signup(jsonObject.optBoolean(\"disable_signup\"));\n config.setAuto_conv_arkose(jsonObject.optBoolean(\"auto_conv_arkose\"));\n config.setProxy_file_service(jsonObject.optBoolean(\"proxy_file_service\"));\n config.setCustom_doh_host(jsonObject.optString(\"custom_doh_host\"));\n\n // 0.4.9.3\n config.setAuto_updateSession(jsonObject.optBoolean(\"auto_updateSession\"));\n config.setAuto_updateTime(jsonObject.optInt(\"auto_updateTime\"));\n config.setAuto_updateNumber(jsonObject.optInt(\"auto_updateNumber\"));\n config.setPandoraNext_outUrl(jsonObject.optString(\"pandoraNext_outUrl\"));\n\n // 0.5.0\n config.setOneAPi_outUrl(jsonObject.optString(\"oneAPi_outUrl\"));\n config.setOneAPi_intoToken(jsonObject.optString(\"oneAPi_intoToken\"));\n\n // 获取 captcha 相关属性\n JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject(\"captcha\")).orElse(new JSONObject());\n validation captchaSetting = new validation(\n captchaJson.optString(\"provider\", \"\"),\n captchaJson.optString(\"site_key\", \"\"),\n captchaJson.optString(\"site_secret\", \"\"),\n captchaJson.optBoolean(\"site_login\", false),\n captchaJson.optBoolean(\"setup_login\", false),\n captchaJson.optBoolean(\"oai_username\", false),\n captchaJson.optBoolean(\"oai_password\", false)\n );\n config.setValidation(captchaSetting);\n\n // 获取 tls 相关属性\n JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject(\"tls\")).orElse(new JSONObject());\n tls tlsSetting = new tls(\n tlsJson.optBoolean(\"enabled\", false),\n tlsJson.optString(\"cert_file\", \"\"),\n tlsJson.optString(\"key_file\", \"\")\n );\n config.setTls(tlsSetting);\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public systemSetting selectSettingUrl() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setBing(jsonObject.optString(\"bind\"));\n config.setAutoToken_url(jsonObject.optString(\"autoToken_url\"));\n config.setProxy_api_prefix(jsonObject.optString(\"proxy_api_prefix\"));\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public systemSetting selectSettingLicense() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setLicense_id(jsonObject.optString(\"license_id\"));\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public String requireTimeTask(systemSetting tem) {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n\n JSONObject jsonObject = new JSONObject(jsonContent);\n // 0.4.9.3\n updateJsonValue(jsonObject, \"auto_updateSession\", tem.getAuto_updateSession());\n updateJsonValue(jsonObject, \"auto_updateTime\", tem.getAuto_updateTime());\n updateJsonValue(jsonObject, \"auto_updateNumber\", tem.getAuto_updateNumber());\n updateJsonValue(jsonObject, \"pandoraNext_outUrl\", tem.getPandoraNext_outUrl());\n // 0.5.0\n updateJsonValue(jsonObject, \"oneAPi_outUrl\", tem.getOneAPi_outUrl());\n updateJsonValue(jsonObject, \"oneAPi_intoToken\", tem.getOneAPi_intoToken());\n\n // 将修改后的 JSONObject 转换为格式化的 JSON 字符串\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n return \"修改定时任务和url成功!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"修改定时任务和url失败!\";\n }\n\n public String[] selectOneAPi() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n String[] oneApi = new String[2];\n oneApi[0] = jsonObject.optString(\"oneAPi_outUrl\");\n oneApi[1] = jsonObject.optString(\"oneAPi_intoToken\");\n return oneApi;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n}\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/poolServiceImpl.java\n@Service\n@Slf4j\npublic class poolServiceImpl implements poolService {\n private static final String gpt3Models = \"gpt-3.5-turbo\";\n\n private static final String gpt4Models = \"gpt-3.5-turbo,gpt-4\";\n\n private static final String openAiChat = \"/v1/chat/completions\";\n private static final String oneApiSelect = \"api/channel/?p=0\";\n private static final String oneAPiChannel = \"api/channel/\";\n private final String deploy = \"default\";\n @Value(\"${deployPosition}\")\n private String deployPosition;\n @Autowired\n private apiServiceImpl apiService;\n @Autowired\n private systemServiceImpl systemService;\n\n /**\n * 遍历文件\n *\n * @return\n */\n public String selectFile() {\n String projectRoot;\n if (deploy.equals(deployPosition)) {\n projectRoot = System.getProperty(\"user.dir\");\n } else {\n projectRoot = deployPosition;\n }\n String parent = projectRoot + File.separator + \"pool.json\";\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n // 如果 JSON 文件不存在,创建一个新的 JSON 对象\n if (!jsonFile.exists()) {\n try {\n // 创建文件pool.json\n Files.createFile(jsonFilePath);\n // 往 pool.json 文件中添加一个空数组,防止重启报错\n Files.writeString(jsonFilePath, \"{}\");\n log.info(\"新建pool.json,并初始化pool.json成功!\");\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n return parent;\n }\n\n /**\n * 初始化pool.json\n * 添加checkPool变量,初始化为true\n * 启动的时候自动全部添加\n */\n public String initializeCheckPool() {\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 遍历根节点的所有子节点\n if (rootNode.isObject()) {\n ObjectNode rootObjectNode = (ObjectNode) rootNode;\n // 遍历所有子节点\n Iterator> fields = rootObjectNode.fields();\n while (fields.hasNext()) {\n Map.Entry entry = fields.next();\n // 获取子节点的名称\n String nodeName = entry.getKey();\n // 获取子节点\n JsonNode nodeToModify = entry.getValue();\n if (nodeToModify != null && nodeToModify.isObject()) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll(rootObjectNode);\n // 获取要修改的节点\n ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName);\n // 初始化checkSession的值为true\n if (!nodeToModifyInNew.has(\"checkPool\")) {\n nodeToModifyInNew.put(\"checkPool\", true);\n log.info(\"为节点 \" + nodeName + \" 添加 checkPool 变量成功!\");\n }\n // 初始化intoOneApi的值为false\n if (!nodeToModifyInNew.has(\"intoOneApi\")) {\n nodeToModifyInNew.put(\"intoOneApi\", false);\n log.info(\"为节点 \" + nodeName + \" 添加 intoOneApi 变量成功!\");\n }\n // 初始化pandoraNextGpt4的值为false\n if (!nodeToModifyInNew.has(\"pandoraNextGpt4\")) {\n nodeToModifyInNew.put(\"pandoraNextGpt4\", false);\n log.info(\"为节点 \" + nodeName + \" 添加 pandoraNextGpt4 变量成功!\");\n }\n // 初始化oneApi_pandoraUrl的值为\"\"\n if (!nodeToModifyInNew.has(\"oneApi_pandoraUrl\")) {\n nodeToModifyInNew.put(\"oneApi_pandoraUrl\", \"\");\n log.info(\"为节点 \" + nodeName + \" 添加 oneApi_pandoraUrl 变量成功!\");\n }\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n }\n }\n return \"为所有子节点添加 checkPool 变量成功!\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"为所有子节点添加 checkPool 变量失败!\";\n }\n\n /**\n * 通过name遍历poolToken\n *\n * @param name\n * @return\n */\n public List selectPoolToken(String name) {\n List res = new ArrayList<>();\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 遍历所有字段\n Iterator> fields = rootNode.fields();\n while (fields.hasNext()) {\n Map.Entry entry = fields.next();\n String nodeName = entry.getKey();\n if (nodeName.contains(name)) {\n poolToken temRes = new poolToken();\n temRes.setPoolName(nodeName);\n // 获取对应的节点\n JsonNode temNode = rootNode.get(nodeName);\n temRes.setPoolToken(temNode.has(\"poolToken\") ? temNode.get(\"poolToken\").asText() : \"\");\n temRes.setPoolTime(temNode.has(\"poolTime\") ? temNode.get(\"poolTime\").asText() : \"\");\n // 将 JsonNode 转换为 List\n List sharedTokens = new ArrayList<>();\n if (temNode.has(\"shareTokens\") && temNode.get(\"shareTokens\").isArray()) {\n for (JsonNode tokenNode : temNode.get(\"shareTokens\")) {\n sharedTokens.add(tokenNode.asText());\n }\n }\n temRes.setShareTokens(sharedTokens);\n temRes.setCheckPool(!temNode.has(\"checkPool\") || temNode.get(\"checkPool\").asBoolean());\n //0.5.0\n temRes.setIntoOneApi(temNode.has(\"intoOneApi\") && temNode.get(\"intoOneApi\").asBoolean());\n temRes.setPandoraNextGpt4(temNode.has(\"pandoraNextGpt4\") && temNode.get(\"pandoraNextGpt4\").asBoolean());\n temRes.setOneApi_pandoraUrl(temNode.has(\"oneApi_pandoraUrl\") ? temNode.get(\"oneApi_pandoraUrl\").asText() : \"\");\n temRes.setPriority(temNode.has(\"priority\") ? temNode.get(\"priority\").asInt() : 0);\n res.add(temRes);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return res;\n }\n\n /**\n * 仅支持修改poolToken的时间和值\n * 修改poolToken的时间\n * 修改poolToken的值\n *\n * @param poolToken\n * @return 修改成功!or 节点未找到或不是对象!\n * @throws Exception\n */\n public String requirePoolToken(poolToken poolToken) {\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n\n // 要修改的节点名称\n String nodeNameToModify = poolToken.getPoolName();\n\n // 获取要修改的节点\n JsonNode nodeToModify = rootNode.get(nodeNameToModify);\n\n if (nodeToModify != null && nodeToModify.isObject()) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll((ObjectNode) rootNode);\n\n // 获取要修改的节点\n ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);\n\n //仅支持修改poolToken的时间和值\n LocalDateTime now = LocalDateTime.now();\n nodeToModifyInNew.put(\"checkPool\", poolToken.isCheckPool());\n nodeToModifyInNew.put(\"poolToken\", poolToken.getPoolToken());\n nodeToModifyInNew.put(\"poolTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n log.info(\"修改成功!\");\n return \"修改成功!\";\n } else {\n log.info(\"节点未找到或不是对象,请检查pool.json! \" + nodeNameToModify);\n return \"节点未找到或不是对象!\";\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public String requireCheckPoolToken(poolToken poolToken) {\n try {\n String parent = selectFile();\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 要修改的节点名称\n String nodeNameToModify = poolToken.getPoolName();\n // 获取要修改的节点\n JsonNode nodeToModify = rootNode.get(nodeNameToModify);\n if (nodeToModify != null && nodeToModify.isObject()) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll((ObjectNode) rootNode);\n // 获取要修改的节点\n ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);\n //仅支持修改poolToken的时间和值\n LocalDateTime now = LocalDateTime.now();\n nodeToModifyInNew.put(\"checkPool\", poolToken.isCheckPool());\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n return \"修改成功!\";\n } else {\n log.info(\"节点未找到或不是对象,请检查pool.json! \" + nodeNameToModify);\n return \"节点未找到或不是对象!\";\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 通过poolToken添加PoolToken\n *\n * @param poolToken\n * @return\n */\n public String addPoolToken(poolToken poolToken) {\n String resPoolToken;\n try {\n String shareTokens = getShareTokens(poolToken.getShareTokens());\n String temPoolToken = poolToken.getPoolToken();\n if (temPoolToken != null && temPoolToken.contains(\"pk\")) {\n resPoolToken = apiService.getPoolToken(temPoolToken, shareTokens);\n } else {\n resPoolToken = apiService.getPoolToken(\"\", shareTokens);\n }\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n try {\n if (resPoolToken == null) {\n return \"pool_token数据添加失败,请先按全部选择并生成,并确保url配对正确!\";\n }\n poolToken.setPoolToken(resPoolToken);\n if (poolToken.isIntoOneApi()) {\n String[] strings = systemService.selectOneAPi();\n boolean b = addKey(poolToken, strings);\n if (b && poolToken.getPriority() != 0) {\n boolean b1 = getPriority(poolToken, strings);\n if (b1) {\n log.info(\"修改优先级成功!\");\n }\n }\n if (b) {\n log.info(\"pool_token进one-Api成功!\");\n } else {\n return \"pool_token添加进one-api失败!\";\n }\n }\n String parent = selectFile();\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectNode rootNode;\n // 如果 JSON 文件不存在,创建一个新的 JSON 对象\n if (!jsonFile.exists()) {\n // 创建文件\n Files.createFile(jsonFilePath);\n System.out.println(\"pool.json创建完成: \" + jsonFilePath);\n rootNode = objectMapper.createObjectNode();\n } else {\n if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) {\n rootNode = objectMapper.readTree(jsonFile).deepCopy();\n } else {\n rootNode = objectMapper.createObjectNode();\n }\n }\n // 创建要添加的新数据\n ObjectNode newData = objectMapper.createObjectNode();\n newData.put(\"poolToken\", resPoolToken);\n List shareTokensList = poolToken.getShareTokens();\n ArrayNode arrayNode = objectMapper.createArrayNode();\n for (String value : shareTokensList) {\n arrayNode.add(value);\n }\n newData.set(\"shareTokens\", arrayNode);\n //0.5.0\n newData.put(\"checkPool\", true);\n newData.put(\"intoOneApi\", poolToken.isIntoOneApi());\n newData.put(\"pandoraNextGpt4\", poolToken.isPandoraNextGpt4());\n newData.put(\"oneApi_pandoraUrl\", poolToken.getOneApi_pandoraUrl());\n\n LocalDateTime now = LocalDateTime.now();\n newData.put(\"poolTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n // 将新数据添加到 JSON 树中\n rootNode.put(poolToken.getPoolName(), newData);\n // 将修改后的数据写回到文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode);\n log.info(\"数据成功添加到 JSON 文件中。\");\n return \"pool_token数据添加成功\";\n } catch (IOException e) {\n e.printStackTrace();\n return \"添加失败!\";\n }\n }\n\n /**\n * 删除通过poolToken里的poolName删除poolToken\n *\n * @param poolToken\n * @return\n */\n public String deletePoolToken(poolToken poolToken) {\n try {\n String name = poolToken.getPoolName();\n String parent = selectFile();\n String deletePoolToken = poolToken.getPoolToken();\n //确保注销成功!\n if (deletePoolToken != null && deletePoolToken.contains(\"pk\")) {\n String s = apiService.deletePoolToken(deletePoolToken);\n if (s == null) {\n log.info(\"删除失败,看看自己的poolToken是否合法\");\n }\n }\n if (poolToken.isIntoOneApi()) {\n String[] strings = systemService.selectOneAPi();\n boolean b = deleteKeyId(poolToken, strings);\n if (!b) {\n return \"删除oneApi中的poolToken失败!\";\n }\n }\n ObjectMapper objectMapper = new ObjectMapper();\n // 读取JSON文件并获取根节点\n JsonNode rootNode = objectMapper.readTree(new File(parent));\n // 检查要删除的节点是否存在\n JsonNode nodeToRemove = rootNode.get(name);\n if (nodeToRemove != null) {\n // 创建新的 ObjectNode,并复制原始节点内容\n ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();\n newObjectNode.setAll((ObjectNode) rootNode);\n // 删除节点\n newObjectNode.remove(name);\n // 将修改后的 newObjectNode 写回文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);\n log.info(\"删除成功\");\n return \"删除成功!\";\n } else {\n System.out.println(\"Node not found: \" + name);\n return \"节点未找到!\";\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"删除失败\";\n }\n\n\n /**\n * 从poolToken里拿到share_tokens的集合,传参给share_token\n *\n * @param shareName\n * @return\n */\n public String getShareTokens(List shareName) {\n try {\n StringBuffer resToken = new StringBuffer();\n List tokens = apiService.selectToken(\"\");\n HashMap tokensHashMap = new HashMap<>();\n for (token tem : tokens) {\n if (tem.isSetPoolToken() && tem.isCheckSession()) {\n tokensHashMap.put(tem.getName(), tem.getShare_token());\n }\n }\n for (String temShareName : shareName) {\n try {\n String temShareToken = tokensHashMap.get(temShareName);\n String regex = \"fk-[0-9a-zA-Z_\\\\-]{43}\";\n if (temShareToken != null && Pattern.matches(regex, temShareToken)) {\n resToken.append(temShareToken + \"\\n\");\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n return resToken.toString();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n /**\n * 重新更新poolToken\n *\n * @return\n */\n public String refreshAllTokens() {\n log.info(\"开始自动更新PoolToken..........................\");\n List poolTokens = selectPoolToken(\"\");\n int count = 0;\n for (poolToken token : poolTokens) {\n String poolToken = token.getPoolToken();\n String shareToken = getShareTokens(token.getShareTokens());\n String resPoolToken = apiService.getPoolToken(poolToken, shareToken);\n if (resPoolToken != null && resPoolToken.equals(poolToken)) {\n token.setPoolToken(resPoolToken);\n if (requirePoolToken(token).contains(\"成功\")) {\n count++;\n }\n }\n }\n log.info(\"pool_token刷新成功:\" + count + \",失败:\" + (poolTokens.size() - count));\n return (\"
pool_token刷新成功:\" + count + \",失败:\" + (poolTokens.size() - count));\n }\n\n /**\n * 手动单个更新poolToken\n *\n * @param poolToken\n * @return\n */\n public String refreshSimplyToken(poolToken poolToken) {\n try {\n List poolTokens = selectPoolToken(\"\");\n for (poolToken token : poolTokens) {\n if (token.getPoolName().equals(poolToken.getPoolName())) {\n String poolTokenValue = token.getPoolToken();\n String shareToken = getShareTokens(token.getShareTokens());\n log.info(shareToken);\n String resPoolToken = apiService.getPoolToken(poolTokenValue, shareToken);\n if (resPoolToken != null && resPoolToken.equals(poolTokenValue)) {\n poolToken.setCheckPool(true);\n if (requirePoolToken(poolToken).contains(\"成功\")) {\n return \"刷新pool_token成功\";\n }\n }\n }\n }\n return \"没有找到该pool_token,刷新失败!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"刷新失败!\";\n }\n\n /**\n * 手动单个更改poolToken\n *\n * @param poolToken\n * @return\n */\n public String changePoolToken(poolToken poolToken) {\n try {\n String deletePoolToken = poolToken.getPoolToken();\n if (deletePoolToken != null && deletePoolToken.contains(\"pk\")) {\n String s = null;\n try {\n s = apiService.deletePoolToken(poolToken.getPoolToken());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n if (s == null) {\n return \"注销poolToken失败\";\n }\n }\n String res = null;\n try {\n String resPoolToken = apiService.getPoolToken(\"\", getShareTokens(poolToken.getShareTokens()));\n if (poolToken.isIntoOneApi()) {\n String[] strings = systemService.selectOneAPi();\n boolean temkeyId = deleteKeyId(poolToken, strings);\n if (!temkeyId) {\n return \"删除oneAPi里的poolToken失败!\";\n } else {\n try {\n poolToken.setPoolToken(resPoolToken);\n poolToken.setCheckPool(true);\n res = requirePoolToken(poolToken);\n boolean b = addKey(poolToken, strings);\n if (b && res.contains(\"成功\")) {\n return res;\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n }\n poolToken.setPoolToken(resPoolToken);\n // 恢复正常\n poolToken.setCheckPool(true);\n res = requirePoolToken(poolToken);\n return res;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 检查全部pool_token\n * 是否过期或者出现问题\n */\n public String verifyAllPoolToken() {\n try {\n String openAiUrl = getOpenaiUrl() + openAiChat;\n List poolTokens = selectPoolToken(\"\");\n int count = 0;\n for (poolToken poolToken : poolTokens) {\n String res = verifyPoolToken(poolToken, openAiUrl);\n if (res.contains(\"请确保\")) {\n return res;\n } else if (res != null && res.contains(\"正常\")) {\n count++;\n }\n }\n return \"poolToken验证成功:\" + count + \",失败:\" + (poolTokens.size() - count);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n @Override\n public String toRequirePoolToken(poolToken poolToken) {\n String[] strings = systemService.selectOneAPi();\n deleteKeyId(poolToken, strings);\n String resPoolToken;\n try {\n String shareTokens = getShareTokens(poolToken.getShareTokens());\n String temPoolToken = poolToken.getPoolToken();\n if (temPoolToken != null && temPoolToken.contains(\"pk\")) {\n resPoolToken = apiService.getPoolToken(temPoolToken, shareTokens);\n } else {\n resPoolToken = apiService.getPoolToken(\"\", shareTokens);\n }\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n try {\n if (resPoolToken == null) {\n return \"pool_token数据添加失败,请先按全部选择并生成,并确保url配对正确!\";\n }\n poolToken.setPoolToken(resPoolToken);\n if (poolToken.isIntoOneApi()) {\n boolean b = addKey(poolToken, strings);\n if (poolToken.getPriority() != 0) {\n boolean b1 = getPriority(poolToken, strings);\n if (b1) {\n log.info(\"修改优先级成功!\");\n }\n }\n if (b) {\n log.info(\"pool_token进one-Api成功!\");\n } else {\n return \"pool_token添加进one-api失败!\";\n }\n }\n String parent = selectFile();\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n ObjectMapper objectMapper = new ObjectMapper();\n ObjectNode rootNode;\n // 如果 JSON 文件不存在,创建一个新的 JSON 对象\n if (!jsonFile.exists()) {\n // 创建文件\n Files.createFile(jsonFilePath);\n System.out.println(\"pool.json创建完成: \" + jsonFilePath);\n rootNode = objectMapper.createObjectNode();\n } else {\n if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) {\n rootNode = objectMapper.readTree(jsonFile).deepCopy();\n } else {\n rootNode = objectMapper.createObjectNode();\n }\n }\n // 创建要添加的新数据\n ObjectNode newData = objectMapper.createObjectNode();\n newData.put(\"poolToken\", resPoolToken);\n List shareTokensList = poolToken.getShareTokens();\n ArrayNode arrayNode = objectMapper.createArrayNode();\n for (String value : shareTokensList) {\n arrayNode.add(value);\n }\n newData.set(\"shareTokens\", arrayNode);\n //0.5.0\n newData.put(\"checkPool\", true);\n newData.put(\"intoOneApi\", poolToken.isIntoOneApi());\n newData.put(\"pandoraNextGpt4\", poolToken.isPandoraNextGpt4());\n newData.put(\"oneApi_pandoraUrl\", poolToken.getOneApi_pandoraUrl());\n\n LocalDateTime now = LocalDateTime.now();\n newData.put(\"poolTime\", now.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")));\n // 将新数据添加到 JSON 树中\n rootNode.put(poolToken.getPoolName(), newData);\n // 将修改后的数据写回到文件\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode);\n log.info(\"数据成功添加到 JSON 文件中。\");\n return \"pool_token数据修改成功\";\n } catch (IOException e) {\n e.printStackTrace();\n return \"修改失败!\";\n }\n }\n\n /**\n * 检查单个pool_token\n * 是否过期或者出现问题\n */\n @Override\n public String verifySimplyPoolToken(poolToken poolToken) {\n try {\n String openAiUrl = getOpenaiUrl();\n String res = verifyPoolToken(poolToken, openAiUrl + openAiChat);\n if (res != null) {\n return res;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n /**\n * 检查pool_token\n * 是否过期或者出现问题\n */\n public String verifyPoolToken(poolToken poolToken, String url) {\n OkHttpClient client = new OkHttpClient();\n\n // 构造请求体,JSON格式,包含一个字符串参数prompt和一个整数参数max_tokens,如果有其他参数,延续即可。\n String json = \"{\" +\n \" \\\"model\\\": \\\"gpt-3.5-turbo\\\",\" +\n \" \\\"messages\\\": [{\\\"role\\\": \\\"user\\\", \\\"content\\\": \\\"Say this is a test!\\\"}],\" +\n \" \\\"temperature\\\": 0.7\" +\n \"}\";\n\n RequestBody body = RequestBody.create(json, MediaType.parse(\"application/json; charset=utf-8\"));\n\n Request request = new Request.Builder()\n .url(url)\n .post(body)\n .addHeader(\"Authorization\", \"Bearer \" + poolToken.getPoolToken())\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if(!response.isSuccessful() && response.code() == 404) {\n return \"请检查PandoraNext公网地址是否填写正确!\";\n }\n String result = response.body().string();\n JSONObject jsonResponse = new JSONObject(result);\n if (!jsonResponse.has(\"choices\")) {\n poolToken.setCheckPool(false);\n String s = requireCheckPoolToken(poolToken);\n if (s.contains(\"成功\")) {\n return \"pool_token过期,请重新刷新,\" + s;\n } else {\n log.info(\"已为你自动标记过期poolToken!\");\n return \"pool_token过期,请重新刷新!\";\n }\n }\n // 提取返回的数据\n JSONArray choicesArray = jsonResponse.getJSONArray(\"choices\");\n JSONObject firstChoiceObject = choicesArray.getJSONObject(0);\n JSONObject messageObject = firstChoiceObject.getJSONObject(\"message\");\n String content = messageObject.getString(\"content\");\n poolToken.setCheckPool(true);\n String s = requireCheckPoolToken(poolToken);\n return \"pool_token正常,请放心使用!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n public String getOpenaiUrl() {\n try {\n systemSetting systemSetting = systemService.selectSetting();\n String pandoraNextOutUrl = systemSetting.getPandoraNext_outUrl();\n String proxyApiPrefix = systemSetting.getProxy_api_prefix();\n if (pandoraNextOutUrl.charAt(pandoraNextOutUrl.length() - 1) != '/') {\n pandoraNextOutUrl += \"/\";\n }\n return pandoraNextOutUrl + proxyApiPrefix;\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * 添加Key值\n * 会通过Post方法访问One-Api接口/api/channel/,添加新keys\n *\n * @return \"true\"or\"false\"\n */\n public boolean addKey(poolToken addKeyPojo, String[] systemSetting) {\n if (!addKeyPojo.isIntoOneApi()) {\n return false;\n }\n String url = systemSetting[0].endsWith(\"/\") ? systemSetting[0] + oneAPiChannel\n : systemSetting[0] + \"/\" + oneAPiChannel;\n log.info(url);\n try {\n JSONObject jsonObject = new JSONObject();\n jsonObject.put(\"type\", 8);\n jsonObject.put(\"key\", addKeyPojo.getPoolToken());\n jsonObject.put(\"name\", addKeyPojo.getPoolName());\n jsonObject.put(\"base_url\", getOpenaiUrl());\n jsonObject.put(\"other\", \"\");\n if (addKeyPojo.isPandoraNextGpt4()) {\n jsonObject.put(\"models\", gpt4Models);\n } else {\n jsonObject.put(\"models\", gpt3Models);\n }\n String group = addKeyPojo.getGroupChecked();\n jsonObject.put(\"group\", group);\n jsonObject.put(\"model_mapping\", \"\");\n jsonObject.put(\"groups\", new JSONArray().put(group));\n // 将JSON对象转换为字符串\n String json = jsonObject.toString();\n\n OkHttpClient client = new OkHttpClient();\n RequestBody body = RequestBody.create(json, MediaType.parse(\"application/json; charset=utf-8\"));\n Request request = new Request.Builder()\n .url(url)\n .post(body)\n .addHeader(\"Authorization\", \"Bearer \" + systemSetting[1])\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"请求one-api失败,失败码: \" + response.code());\n return false;\n }\n String responseContent = response.body().string();\n JSONObject jsonResponse = new JSONObject(responseContent);\n boolean success = jsonResponse.getBoolean(\"success\");\n if (response.code() == 200 && success) {\n return true;\n } else {\n log.info(\"请求one-api失败,失败码: \" + response.code());\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n\n public boolean deleteKeyId(poolToken poolToken, String[] systemSetting) {\n String url = systemSetting[0].endsWith(\"/\") ? systemSetting[0] + oneApiSelect\n : systemSetting[0] + \"/\" + oneApiSelect;\n log.info(url);\n try {\n OkHttpClient client = new OkHttpClient();\n Request request = new Request.Builder()\n .url(url)\n .addHeader(\"Authorization\", \"Bearer \" + systemSetting[1])\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"浏览器状态为: \" + response.code());\n return false;\n }\n String responseContent = response.body().string();\n JSONObject jsonObject = new JSONObject(responseContent);\n JSONArray dataArray = jsonObject.getJSONArray(\"data\");\n int id = -1;\n for (int i = 0; i < dataArray.length(); i++) {\n JSONObject dataObject = dataArray.getJSONObject(i);\n String name = dataObject.getString(\"name\");\n if (name.equals(poolToken.getPoolName())) {\n id = dataObject.getInt(\"id\");\n break;\n }\n }\n if (response.code() == 200) {\n if (id > 0) {\n boolean res = deleteKey(systemSetting, id);\n return res;\n }\n log.info(\"没有找到相应的key名!\");\n return true;\n } else {\n log.info(\"浏览器状态为: \" + response.code());\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n\n public boolean getPriority(poolToken poolToken, String[] systemSetting) {\n String url = systemSetting[0].endsWith(\"/\") ? systemSetting[0] + oneApiSelect\n : systemSetting[0] + \"/\" + oneApiSelect;\n log.info(url);\n OkHttpClient client = new OkHttpClient();\n Request request = new Request.Builder()\n .url(url)\n .addHeader(\"Authorization\", \"Bearer \" + systemSetting[1])\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"没有找到相应的key名,浏览器状态为: \" + response.code());\n return false;\n }\n String responseContent = response.body().string();\n JSONObject jsonObject = new JSONObject(responseContent);\n JSONArray dataArray = jsonObject.getJSONArray(\"data\");\n for (int i = 0; i < dataArray.length(); i++) {\n JSONObject dataObject = dataArray.getJSONObject(i);\n String name = dataObject.getString(\"name\");\n if (name.equals(poolToken.getPoolName())) {\n int id = dataObject.getInt(\"id\");\n return priorityKey(systemSetting, id, poolToken.getPriority());\n }\n }\n log.info(\"没有找到相应的key名\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n public boolean deleteKey(String[] systemSetting, int keyId) {\n String url = systemSetting[0].endsWith(\"/\") ? systemSetting[0] + oneAPiChannel + keyId\n : systemSetting[0] + \"/\" + oneAPiChannel + keyId;\n log.info(\"请求one-api的网址为:\" + url);\n OkHttpClient client = new OkHttpClient();\n Request request = new Request.Builder()\n .url(url)\n .addHeader(\"Authorization\", \"Bearer \" + systemSetting[1])\n .delete()\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n log.info(\"未找到当前的key,浏览器状态为: \" + response.code());\n return false;\n }\n String responseContent = response.body().string();\n JSONObject jsonResponse = new JSONObject(responseContent);\n boolean success = jsonResponse.getBoolean(\"success\");\n if (success) {\n log.info(\"key删除成功!\");\n return true;\n }\n log.info(response.toString());\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n\n public boolean priorityKey(String[] systemSetting, int keyId, Integer priority) {\n String url = systemSetting[0].endsWith(\"/\") ? systemSetting[0] + oneAPiChannel\n : systemSetting[0] + \"/\" + oneAPiChannel;\n log.info(\"请求one-api的网址为:\" + url);\n OkHttpClient client = new OkHttpClient();\n RequestBody body = null;\n try {\n JSONObject jsonObject = new JSONObject();\n jsonObject.put(\"id\", keyId);\n jsonObject.put(\"priority\", priority);\n String json = jsonObject.toString();\n body = RequestBody.create(json, MediaType.parse(\"application/json; charset=utf-8\"));\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n Request request = new Request.Builder()\n .url(url)\n .addHeader(\"Authorization\", \"Bearer \" + systemSetting[1])\n .put(body)\n .build();\n try (Response response = client.newCall(request).execute()) {\n String responseContent = Objects.requireNonNull(response.body()).string();\n JSONObject jsonResponse = new JSONObject(responseContent);\n if (response.isSuccessful() && jsonResponse.getBoolean(\"success\")) {\n return true;\n } else {\n log.info(\"更改优先级失败,失败码: \" + response.code());\n }\n log.info(jsonResponse.toString());\n } catch (Exception e) {\n log.error(\"请求处理异常\", e);\n }\n return false;\n }\n\n}", "answers": [" systemSetting systemSetting = systemService.selectSetting();"], "length": 7194, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "80804cc1-1185-4030-b52d-20ba879f198c", "reasoning": "The tokenController method getSimplePoolToken starts with its signature and an opening brace. Following the pattern of earlier methods (e.g., getSharedToken, getAccessToken), the first operation inside the method is to retrieve the system settings via systemService. Therefore the next line should be the declaration and assignment of a systemSetting variable.", "reasoning_model_answer": "systemSetting systemSetting = systemService.selectSetting();", "assistant_with_reasoning": "\nThe tokenController method getSimplePoolToken starts with its signature and an opening brace. Following the pattern of earlier methods (e.g., getSharedToken, getAccessToken), the first operation inside the method is to retrieve the system settings via systemService. Therefore the next line should be the declaration and assignment of a systemSetting variable.\n\nsystemSetting systemSetting = systemService.selectSetting();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.658, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36772, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "systemSetting systemSetting = systemService.selectSetting();", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import mdteam.ait.AITMod;\nimport mdteam.ait.client.models.consoles.BorealisConsoleModel;\nimport mdteam.ait.client.models.consoles.ConsoleModel;\nimport mdteam.ait.client.registry.console.ClientConsoleVariantSchema;\nimport mdteam.ait.tardis.variant.console.AutumnVariant;\nimport net.minecraft.util.Identifier;", "context": "src/main/java/mdteam/ait/client/registry/console/impl/ClientAutumnVariant.java\npackage mdteam.ait.client.registry.console.impl;\n\n\npublic class ClientAutumnVariant extends ClientConsoleVariantSchema {\n public static final Identifier TEXTURE = new Identifier(AITMod.MOD_ID, (\"textures/blockentities/consoles/borealis_console_autumn.png\"));\n public static final Identifier EMISSION = new Identifier(AITMod.MOD_ID, (\"textures/blockentities/consoles/borealis_console_autumn_emission.png\"));\n public ClientAutumnVariant() {\n super(AutumnVariant.REFERENCE);\n }\n\n @Override\n public Identifier texture() {\n return TEXTURE;\n }\n\n @Override\n\nsrc/main/java/mdteam/ait/client/models/consoles/BorealisConsoleModel.java\npublic class BorealisConsoleModel extends ConsoleModel {\n public static final Identifier CONSOLE_TEXTURE = new Identifier(AITMod.MOD_ID, (\"textures/blockentities/consoles/borealis_console.png\"));\n public static final Identifier CONSOLE_TEXTURE_EMISSION = new Identifier(AITMod.MOD_ID, \"textures/blockentities/consoles/borealis_console_emission.png\");\n public ModelPart base_console;\n\n public BorealisConsoleModel(ModelPart root) {\n super(RenderLayer::getEntityCutoutNoCull);\n this.base_console = root.getChild(\"base_console\");\n }\n\n public static TexturedModelData getTexturedModelData() {\n ModelData modelData = new ModelData();\n ModelPartData modelPartData = modelData.getRoot();\n ModelPartData base_console = modelPartData.addChild(\"base_console\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 24.0F, 0.0F));\n\n ModelPartData panels = base_console.addChild(\"panels\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, -30.0F, 0.0F));\n\n ModelPartData bone25 = panels.addChild(\"bone25\", ModelPartBuilder.create().uv(0, 0).cuboid(-15.0F, 1.774F, -2.9235F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone38 = panels.addChild(\"bone38\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone44 = bone38.addChild(\"bone44\", ModelPartBuilder.create().uv(0, 0).cuboid(-15.0F, 1.774F, -2.9235F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone56 = bone38.addChild(\"bone56\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone152 = bone56.addChild(\"bone152\", ModelPartBuilder.create().uv(0, 0).cuboid(-15.0F, 1.774F, -2.9235F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone153 = bone56.addChild(\"bone153\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone154 = bone153.addChild(\"bone154\", ModelPartBuilder.create().uv(0, 0).cuboid(-15.0F, 1.774F, -2.9235F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone155 = bone153.addChild(\"bone155\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone156 = bone155.addChild(\"bone156\", ModelPartBuilder.create().uv(0, 0).cuboid(-15.0F, 1.774F, -2.9235F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone157 = bone155.addChild(\"bone157\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone158 = bone157.addChild(\"bone158\", ModelPartBuilder.create().uv(0, 0).cuboid(-15.0F, 1.774F, -2.9235F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData collar = base_console.addChild(\"collar\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F));\n\n ModelPartData bone86 = collar.addChild(\"bone86\", ModelPartBuilder.create().uv(96, 130).cuboid(-2.0F, -2.0F, -14.3F, 4.0F, 7.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -44.5F, 0.0F, 0.0F, -0.5236F, 0.0F));\n\n ModelPartData bone87 = bone86.addChild(\"bone87\", ModelPartBuilder.create().uv(96, 130).cuboid(-2.0F, -2.0F, -14.3F, 4.0F, 7.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone88 = bone87.addChild(\"bone88\", ModelPartBuilder.create().uv(96, 130).cuboid(-2.0F, -2.0F, -14.3F, 4.0F, 7.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone89 = bone88.addChild(\"bone89\", ModelPartBuilder.create().uv(96, 130).cuboid(-2.0F, -2.0F, -14.3F, 4.0F, 7.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone90 = bone89.addChild(\"bone90\", ModelPartBuilder.create().uv(96, 130).cuboid(-2.0F, -2.0F, -14.3F, 4.0F, 7.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone91 = bone90.addChild(\"bone91\", ModelPartBuilder.create().uv(96, 130).cuboid(-2.0F, -2.0F, -14.3F, 4.0F, 7.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone92 = collar.addChild(\"bone92\", ModelPartBuilder.create().uv(123, 27).cuboid(-5.0F, -2.0F, -12.3F, 10.0F, 6.0F, 3.0F, new Dilation(0.0F))\n .uv(128, 20).cuboid(-5.5F, -2.975F, -13.275F, 11.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -43.5F, 0.0F));\n\n ModelPartData bone93 = bone92.addChild(\"bone93\", ModelPartBuilder.create().uv(123, 27).cuboid(-5.0F, -2.0F, -12.3F, 10.0F, 6.0F, 3.0F, new Dilation(0.0F))\n .uv(128, 20).cuboid(-5.5F, -2.975F, -13.275F, 11.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone94 = bone93.addChild(\"bone94\", ModelPartBuilder.create().uv(123, 27).cuboid(-5.0F, -2.0F, -12.3F, 10.0F, 6.0F, 3.0F, new Dilation(0.0F))\n .uv(128, 20).cuboid(-5.5F, -2.975F, -13.275F, 11.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone95 = bone94.addChild(\"bone95\", ModelPartBuilder.create().uv(123, 27).cuboid(-5.0F, -2.0F, -12.3F, 10.0F, 6.0F, 3.0F, new Dilation(0.0F))\n .uv(128, 20).cuboid(-5.5F, -2.975F, -13.275F, 11.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone96 = bone95.addChild(\"bone96\", ModelPartBuilder.create().uv(123, 27).cuboid(-5.0F, -2.0F, -12.3F, 10.0F, 6.0F, 3.0F, new Dilation(0.0F))\n .uv(128, 20).cuboid(-5.5F, -2.975F, -13.275F, 11.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone97 = bone96.addChild(\"bone97\", ModelPartBuilder.create().uv(123, 27).cuboid(-5.0F, -2.0F, -12.3F, 10.0F, 6.0F, 3.0F, new Dilation(0.0F))\n .uv(128, 20).cuboid(-5.5F, -2.975F, -13.275F, 11.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone104 = collar.addChild(\"bone104\", ModelPartBuilder.create().uv(70, 92).cuboid(2.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(70, 92).cuboid(-4.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -45.5F, 0.0F));\n\n ModelPartData bone105 = bone104.addChild(\"bone105\", ModelPartBuilder.create().uv(70, 92).cuboid(2.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(70, 92).cuboid(-4.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone106 = bone105.addChild(\"bone106\", ModelPartBuilder.create().uv(70, 92).cuboid(2.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(70, 92).cuboid(-4.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone107 = bone106.addChild(\"bone107\", ModelPartBuilder.create().uv(70, 92).cuboid(2.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(70, 92).cuboid(-4.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone108 = bone107.addChild(\"bone108\", ModelPartBuilder.create().uv(70, 92).cuboid(2.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(70, 92).cuboid(-4.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone109 = bone108.addChild(\"bone109\", ModelPartBuilder.create().uv(70, 92).cuboid(2.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(70, 92).cuboid(-4.0F, 1.0F, -13.05F, 2.0F, 3.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone98 = collar.addChild(\"bone98\", ModelPartBuilder.create().uv(112, 119).cuboid(-6.0F, 2.0F, -13.3F, 12.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -43.5F, 0.0F));\n\n ModelPartData bone99 = bone98.addChild(\"bone99\", ModelPartBuilder.create().uv(112, 119).cuboid(-6.0F, 2.0F, -13.3F, 12.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone100 = bone99.addChild(\"bone100\", ModelPartBuilder.create().uv(112, 119).cuboid(-6.0F, 2.0F, -13.3F, 12.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone101 = bone100.addChild(\"bone101\", ModelPartBuilder.create().uv(112, 119).cuboid(-6.0F, 2.0F, -13.3F, 12.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone102 = bone101.addChild(\"bone102\", ModelPartBuilder.create().uv(112, 119).cuboid(-6.0F, 2.0F, -13.3F, 12.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone103 = bone102.addChild(\"bone103\", ModelPartBuilder.create().uv(112, 119).cuboid(-6.0F, 2.0F, -13.3F, 12.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData lower_dividers = base_console.addChild(\"lower_dividers\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, -28.0F, 0.0F));\n\n ModelPartData bone32 = lower_dividers.addChild(\"bone32\", ModelPartBuilder.create().uv(0, 75).cuboid(-17.0F, -0.5858F, -2.5858F, 34.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -27.8F, -0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone26 = lower_dividers.addChild(\"bone26\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone27 = bone26.addChild(\"bone27\", ModelPartBuilder.create().uv(0, 75).cuboid(-17.0F, -0.5858F, -2.5858F, 34.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -27.8F, -0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone28 = bone26.addChild(\"bone28\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone29 = bone28.addChild(\"bone29\", ModelPartBuilder.create().uv(0, 75).cuboid(-17.0F, -0.5858F, -2.5858F, 34.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -27.8F, -0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone30 = bone28.addChild(\"bone30\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone33 = bone30.addChild(\"bone33\", ModelPartBuilder.create().uv(0, 75).cuboid(-17.0F, -0.5858F, -2.5858F, 34.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -27.8F, -0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone34 = bone30.addChild(\"bone34\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone35 = bone34.addChild(\"bone35\", ModelPartBuilder.create().uv(0, 75).cuboid(-17.0F, -0.5858F, -2.5858F, 34.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -27.8F, -0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone36 = bone34.addChild(\"bone36\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone37 = bone36.addChild(\"bone37\", ModelPartBuilder.create().uv(0, 75).cuboid(-17.0F, -0.5858F, -2.5858F, 34.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -27.8F, -0.7854F, 0.0F, 0.0F));\n\n ModelPartData dividers2 = base_console.addChild(\"dividers2\", ModelPartBuilder.create().uv(67, 44).cuboid(-2.0F, -2.0F, -36.3F, 4.0F, 6.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -30.5F, 0.0F, 0.0F, -0.5236F, 0.0F));\n\n ModelPartData bone40 = dividers2.addChild(\"bone40\", ModelPartBuilder.create().uv(67, 44).cuboid(-2.0F, -2.0F, -36.3F, 4.0F, 6.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone39 = bone40.addChild(\"bone39\", ModelPartBuilder.create().uv(67, 44).cuboid(-2.0F, -2.0F, -36.3F, 4.0F, 6.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone41 = bone39.addChild(\"bone41\", ModelPartBuilder.create().uv(67, 44).cuboid(-2.0F, -2.0F, -36.3F, 4.0F, 6.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone42 = bone41.addChild(\"bone42\", ModelPartBuilder.create().uv(67, 44).cuboid(-2.0F, -2.0F, -36.3F, 4.0F, 6.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone43 = bone42.addChild(\"bone43\", ModelPartBuilder.create().uv(67, 44).cuboid(-2.0F, -2.0F, -36.3F, 4.0F, 6.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData dividers = base_console.addChild(\"dividers\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.5F, 0.0F, 0.0F, -0.5236F, 0.0F));\n\n ModelPartData bone50 = dividers.addChild(\"bone50\", ModelPartBuilder.create().uv(55, 75).cuboid(-2.0F, 0.0F, 0.0F, 4.0F, 4.0F, 22.0F, new Dilation(0.0F))\n .uv(81, 0).cuboid(-0.5F, -2.0F, -1.0F, 1.0F, 4.0F, 22.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -34.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone45 = dividers.addChild(\"bone45\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone46 = bone45.addChild(\"bone46\", ModelPartBuilder.create().uv(55, 75).cuboid(-2.0F, 0.0F, 0.0F, 4.0F, 4.0F, 22.0F, new Dilation(0.0F))\n .uv(81, 0).cuboid(-0.5F, -2.0F, -1.0F, 1.0F, 4.0F, 22.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -34.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone47 = bone45.addChild(\"bone47\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone48 = bone47.addChild(\"bone48\", ModelPartBuilder.create().uv(55, 75).cuboid(-2.0F, 0.0F, 0.0F, 4.0F, 4.0F, 22.0F, new Dilation(0.0F))\n .uv(81, 0).cuboid(-0.5F, -2.0F, -1.0F, 1.0F, 4.0F, 22.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -34.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone49 = bone47.addChild(\"bone49\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone51 = bone49.addChild(\"bone51\", ModelPartBuilder.create().uv(55, 75).cuboid(-2.0F, 0.0F, 0.0F, 4.0F, 4.0F, 22.0F, new Dilation(0.0F))\n .uv(81, 0).cuboid(-0.5F, -2.0F, -1.0F, 1.0F, 4.0F, 22.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -34.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone52 = bone49.addChild(\"bone52\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone53 = bone52.addChild(\"bone53\", ModelPartBuilder.create().uv(55, 75).cuboid(-2.0F, 0.0F, 0.0F, 4.0F, 4.0F, 22.0F, new Dilation(0.0F))\n .uv(81, 0).cuboid(-0.5F, -2.0F, -1.0F, 1.0F, 4.0F, 22.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -34.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone54 = bone52.addChild(\"bone54\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone55 = bone54.addChild(\"bone55\", ModelPartBuilder.create().uv(55, 75).cuboid(-2.0F, 0.0F, 0.0F, 4.0F, 4.0F, 22.0F, new Dilation(0.0F))\n .uv(81, 0).cuboid(-0.5F, -2.0F, -1.0F, 1.0F, 4.0F, 22.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -34.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone110 = base_console.addChild(\"bone110\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -44.5F, 0.0F, 0.0F, -0.5236F, 0.0F));\n\n ModelPartData leaf1 = bone110.addChild(\"leaf1\", ModelPartBuilder.create().uv(0, 84).cuboid(-1.0F, -7.0F, 0.0F, 2.0F, 7.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -12.3F, -1.0472F, 0.0F, 0.0F));\n\n ModelPartData bone111 = bone110.addChild(\"bone111\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData leaf2 = bone111.addChild(\"leaf2\", ModelPartBuilder.create().uv(0, 84).cuboid(-1.0F, -7.0F, 0.0F, 2.0F, 7.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -12.3F, -1.0472F, 0.0F, 0.0F));\n\n ModelPartData bone113 = bone111.addChild(\"bone113\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData leaf3 = bone113.addChild(\"leaf3\", ModelPartBuilder.create().uv(0, 84).cuboid(-1.0F, -7.0F, 0.0F, 2.0F, 7.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -12.3F, -1.0472F, 0.0F, 0.0F));\n\n ModelPartData bone115 = bone113.addChild(\"bone115\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData leaf4 = bone115.addChild(\"leaf4\", ModelPartBuilder.create().uv(0, 84).cuboid(-1.0F, -7.0F, 0.0F, 2.0F, 7.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -12.3F, -1.0472F, 0.0F, 0.0F));\n\n ModelPartData bone118 = bone115.addChild(\"bone118\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData leaf5 = bone118.addChild(\"leaf5\", ModelPartBuilder.create().uv(0, 84).cuboid(-1.0F, -7.0F, 0.0F, 2.0F, 7.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -12.3F, -1.0472F, 0.0F, 0.0F));\n\n ModelPartData bone120 = bone118.addChild(\"bone120\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData leaf6 = bone120.addChild(\"leaf6\", ModelPartBuilder.create().uv(0, 84).cuboid(-1.0F, -7.0F, 0.0F, 2.0F, 7.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -12.3F, -1.0472F, 0.0F, 0.0F));\n\n ModelPartData bone84 = base_console.addChild(\"bone84\", ModelPartBuilder.create().uv(106, 10).cuboid(-6.5F, -23.5F, -22.8F, 13.0F, 4.0F, 5.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -4.0F, 0.0F));\n\n ModelPartData bone85 = bone84.addChild(\"bone85\", ModelPartBuilder.create().uv(86, 75).cuboid(-5.5F, -3.0F, -4.5F, 11.0F, 7.0F, 11.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -22.5F, -20.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone148 = bone84.addChild(\"bone148\", ModelPartBuilder.create().uv(106, 10).cuboid(-6.5F, -23.5F, -22.8F, 13.0F, 4.0F, 5.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -2.0944F, 0.0F));\n\n ModelPartData bone149 = bone148.addChild(\"bone149\", ModelPartBuilder.create().uv(86, 75).cuboid(-5.5F, -3.0F, -4.5F, 11.0F, 7.0F, 11.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -22.5F, -20.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone166 = bone149.addChild(\"bone166\", ModelPartBuilder.create().uv(120, 71).cuboid(-4.5F, -5.0F, 0.0F, 9.0F, 5.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 3.0F, -4.5F, 0.6545F, 0.0F, 0.0F));\n\n ModelPartData bone150 = bone148.addChild(\"bone150\", ModelPartBuilder.create().uv(106, 10).cuboid(-6.5F, -23.5F, -22.8F, 13.0F, 4.0F, 5.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -2.0944F, 0.0F));\n\n ModelPartData bone151 = bone150.addChild(\"bone151\", ModelPartBuilder.create().uv(86, 75).cuboid(-5.5F, -3.0F, -4.5F, 11.0F, 7.0F, 11.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -22.5F, -20.3F, 0.4363F, 0.0F, 0.0F));\n\n ModelPartData bone62 = base_console.addChild(\"bone62\", ModelPartBuilder.create().uv(73, 126).cuboid(-2.5F, -18.5F, -17.8F, 5.0F, 5.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone81 = bone62.addChild(\"bone81\", ModelPartBuilder.create().uv(0, 44).cuboid(-17.0803F, -9.0F, -12.65F, 5.0F, 9.0F, 5.0F, new Dilation(0.0F))\n .uv(74, 116).cuboid(-18.0803F, -10.0F, -13.65F, 7.0F, 2.0F, 7.0F, new Dilation(0.0F)), ModelTransform.pivot(14.5803F, -13.5F, -10.15F));\n\n ModelPartData bone63 = bone62.addChild(\"bone63\", ModelPartBuilder.create().uv(73, 126).cuboid(-2.5F, -18.5F, -17.8F, 5.0F, 5.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -2.0944F, 0.0F));\n\n ModelPartData bone64 = bone63.addChild(\"bone64\", ModelPartBuilder.create().uv(0, 44).cuboid(-17.0803F, -9.0F, -12.65F, 5.0F, 9.0F, 5.0F, new Dilation(0.0F))\n .uv(74, 116).cuboid(-18.0803F, -10.0F, -13.65F, 7.0F, 2.0F, 7.0F, new Dilation(0.0F)), ModelTransform.pivot(14.5803F, -13.5F, -10.15F));\n\n ModelPartData bone82 = bone63.addChild(\"bone82\", ModelPartBuilder.create().uv(73, 126).cuboid(-2.5F, -18.5F, -17.8F, 5.0F, 5.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -2.0944F, 0.0F));\n\n ModelPartData bone83 = bone82.addChild(\"bone83\", ModelPartBuilder.create().uv(0, 44).cuboid(-17.0803F, -9.0F, -12.65F, 5.0F, 9.0F, 5.0F, new Dilation(0.0F))\n .uv(74, 116).cuboid(-18.0803F, -10.0F, -13.65F, 7.0F, 2.0F, 7.0F, new Dilation(0.0F)), ModelTransform.pivot(14.5803F, -13.5F, -10.15F));\n\n ModelPartData bone60 = base_console.addChild(\"bone60\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, -26.0F, 0.0F));\n\n ModelPartData bone61 = bone60.addChild(\"bone61\", ModelPartBuilder.create().uv(0, 22).cuboid(-15.0F, -1.226F, 0.0765F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -30.8F, -0.2182F, 0.0F, 0.0F));\n\n ModelPartData bone65 = bone60.addChild(\"bone65\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone66 = bone65.addChild(\"bone66\", ModelPartBuilder.create().uv(0, 22).cuboid(-15.0F, -1.226F, 0.0765F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -30.8F, -0.2182F, 0.0F, 0.0F));\n\n ModelPartData bone67 = bone65.addChild(\"bone67\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone68 = bone67.addChild(\"bone68\", ModelPartBuilder.create().uv(0, 22).cuboid(-15.0F, -1.226F, 0.0765F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -30.8F, -0.2182F, 0.0F, 0.0F));\n\n ModelPartData bone69 = bone67.addChild(\"bone69\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone70 = bone69.addChild(\"bone70\", ModelPartBuilder.create().uv(0, 22).cuboid(-15.0F, -1.226F, 0.0765F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -30.8F, -0.2182F, 0.0F, 0.0F));\n\n ModelPartData bone144 = bone69.addChild(\"bone144\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone145 = bone144.addChild(\"bone145\", ModelPartBuilder.create().uv(0, 22).cuboid(-15.0F, -1.226F, 0.0765F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -30.8F, -0.2182F, 0.0F, 0.0F));\n\n ModelPartData bone146 = bone144.addChild(\"bone146\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone147 = bone146.addChild(\"bone147\", ModelPartBuilder.create().uv(0, 22).cuboid(-15.0F, -1.226F, 0.0765F, 30.0F, 1.0F, 20.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -2.0F, -30.8F, -0.2182F, 0.0F, 0.0F));\n\n ModelPartData bone58 = base_console.addChild(\"bone58\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -28.5F, 0.0F, 0.0F, -0.5236F, 0.0F));\n\n ModelPartData bone59 = bone58.addChild(\"bone59\", ModelPartBuilder.create().uv(65, 44).cuboid(-2.0F, -6.0F, 0.0F, 4.0F, 6.0F, 24.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 2.0F, -34.3F, -0.3927F, 0.0F, 0.0F));\n\n ModelPartData bone71 = bone58.addChild(\"bone71\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone72 = bone71.addChild(\"bone72\", ModelPartBuilder.create().uv(65, 44).cuboid(-2.0F, -6.0F, 0.0F, 4.0F, 6.0F, 24.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 2.0F, -34.3F, -0.3927F, 0.0F, 0.0F));\n\n ModelPartData bone73 = bone71.addChild(\"bone73\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone74 = bone73.addChild(\"bone74\", ModelPartBuilder.create().uv(65, 44).cuboid(-2.0F, -6.0F, 0.0F, 4.0F, 6.0F, 24.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 2.0F, -34.3F, -0.3927F, 0.0F, 0.0F));\n\n ModelPartData bone75 = bone73.addChild(\"bone75\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone76 = bone75.addChild(\"bone76\", ModelPartBuilder.create().uv(65, 44).cuboid(-2.0F, -6.0F, 0.0F, 4.0F, 6.0F, 24.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 2.0F, -34.3F, -0.3927F, 0.0F, 0.0F));\n\n ModelPartData bone77 = bone75.addChild(\"bone77\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone78 = bone77.addChild(\"bone78\", ModelPartBuilder.create().uv(65, 44).cuboid(-2.0F, -6.0F, 0.0F, 4.0F, 6.0F, 24.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 2.0F, -34.3F, -0.3927F, 0.0F, 0.0F));\n\n ModelPartData bone79 = bone77.addChild(\"bone79\", ModelPartBuilder.create(), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone80 = bone79.addChild(\"bone80\", ModelPartBuilder.create().uv(65, 44).cuboid(-2.0F, -6.0F, 0.0F, 4.0F, 6.0F, 24.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 2.0F, -34.3F, -0.3927F, 0.0F, 0.0F));\n\n ModelPartData bone13 = base_console.addChild(\"bone13\", ModelPartBuilder.create().uv(23, 130).cuboid(-1.0F, -16.0F, -15.6832F, 2.0F, 16.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, 0.0F, 0.0F, -0.5236F, 0.0F));\n\n ModelPartData bone14 = bone13.addChild(\"bone14\", ModelPartBuilder.create().uv(23, 130).cuboid(-1.0F, -16.0F, -15.6832F, 2.0F, 16.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone15 = bone14.addChild(\"bone15\", ModelPartBuilder.create().uv(23, 130).cuboid(-1.0F, -16.0F, -15.6832F, 2.0F, 16.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone16 = bone15.addChild(\"bone16\", ModelPartBuilder.create().uv(23, 130).cuboid(-1.0F, -16.0F, -15.6832F, 2.0F, 16.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone17 = bone16.addChild(\"bone17\", ModelPartBuilder.create().uv(23, 130).cuboid(-1.0F, -16.0F, -15.6832F, 2.0F, 16.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone18 = bone17.addChild(\"bone18\", ModelPartBuilder.create().uv(23, 130).cuboid(-1.0F, -16.0F, -15.6832F, 2.0F, 16.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone19 = base_console.addChild(\"bone19\", ModelPartBuilder.create().uv(0, 110).cuboid(-6.0F, -20.0F, -11.8F, 12.0F, 20.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -4.0F, 0.0F));\n\n ModelPartData bone20 = bone19.addChild(\"bone20\", ModelPartBuilder.create().uv(0, 110).cuboid(-6.0F, -20.0F, -11.8F, 12.0F, 20.0F, 1.0F, new Dilation(0.0F))\n .uv(0, 22).cuboid(-3.0F, -11.0F, -13.8F, 6.0F, 9.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone21 = bone20.addChild(\"bone21\", ModelPartBuilder.create().uv(0, 110).cuboid(-6.0F, -20.0F, -11.8F, 12.0F, 20.0F, 1.0F, new Dilation(0.0F))\n .uv(128, 132).cuboid(-3.5F, -10.0F, -12.8F, 7.0F, 4.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone132 = bone21.addChild(\"bone132\", ModelPartBuilder.create().uv(137, 143).cuboid(-1.0F, -2.0F, 0.0F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F))\n .uv(82, 44).cuboid(2.5F, -3.0F, 0.0F, 1.0F, 3.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(-1.5F, -9.5F, -12.3F, 0.3491F, 0.0F, 0.0F));\n\n ModelPartData bone22 = bone21.addChild(\"bone22\", ModelPartBuilder.create().uv(0, 110).cuboid(-6.0F, -20.0F, -11.8F, 12.0F, 20.0F, 1.0F, new Dilation(0.0F))\n .uv(0, 34).cuboid(-3.0F, -6.0F, -14.8F, 6.0F, 2.0F, 3.0F, new Dilation(0.0F))\n .uv(81, 0).cuboid(-3.0F, -11.0F, -12.05F, 6.0F, 9.0F, 1.0F, new Dilation(0.0F))\n .uv(61, 130).cuboid(-1.0F, -14.0F, -14.3F, 2.0F, 14.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone23 = bone22.addChild(\"bone23\", ModelPartBuilder.create().uv(0, 110).cuboid(-6.0F, -20.0F, -11.8F, 12.0F, 20.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone24 = bone23.addChild(\"bone24\", ModelPartBuilder.create().uv(0, 110).cuboid(-6.0F, -20.0F, -11.8F, 12.0F, 20.0F, 1.0F, new Dilation(0.0F))\n .uv(0, 0).cuboid(-3.0F, -11.0F, -13.8F, 6.0F, 9.0F, 2.0F, new Dilation(0.0F))\n .uv(16, 44).cuboid(-2.0F, -9.0F, -14.8F, 1.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(98, 16).cuboid(-0.5F, -4.75F, -14.8F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone7 = base_console.addChild(\"bone7\", ModelPartBuilder.create().uv(83, 138).cuboid(-1.0F, -4.0F, -17.6832F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -0.5236F, 0.0F));\n\n ModelPartData bone8 = bone7.addChild(\"bone8\", ModelPartBuilder.create().uv(83, 138).cuboid(-1.0F, -4.0F, -17.6832F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone9 = bone8.addChild(\"bone9\", ModelPartBuilder.create().uv(83, 138).cuboid(-1.0F, -4.0F, -17.6832F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone10 = bone9.addChild(\"bone10\", ModelPartBuilder.create().uv(83, 138).cuboid(-1.0F, -4.0F, -17.6832F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone11 = bone10.addChild(\"bone11\", ModelPartBuilder.create().uv(83, 138).cuboid(-1.0F, -4.0F, -17.6832F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone12 = bone11.addChild(\"bone12\", ModelPartBuilder.create().uv(83, 138).cuboid(-1.0F, -4.0F, -17.6832F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone = base_console.addChild(\"bone\", ModelPartBuilder.create().uv(47, 102).cuboid(-8.0F, -4.0F, -15.8F, 16.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 0.0F, 0.0F));\n\n ModelPartData bone2 = bone.addChild(\"bone2\", ModelPartBuilder.create().uv(47, 102).cuboid(-8.0F, -4.0F, -15.8F, 16.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone3 = bone2.addChild(\"bone3\", ModelPartBuilder.create().uv(47, 102).cuboid(-8.0F, -4.0F, -15.8F, 16.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone4 = bone3.addChild(\"bone4\", ModelPartBuilder.create().uv(47, 102).cuboid(-8.0F, -4.0F, -15.8F, 16.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone5 = bone4.addChild(\"bone5\", ModelPartBuilder.create().uv(47, 102).cuboid(-8.0F, -4.0F, -15.8F, 16.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone6 = bone5.addChild(\"bone6\", ModelPartBuilder.create().uv(47, 102).cuboid(-8.0F, -4.0F, -15.8F, 16.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone208 = base_console.addChild(\"bone208\", ModelPartBuilder.create().uv(81, 27).cuboid(-7.0F, -1.0F, -11.8F, 14.0F, 1.0F, 13.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 0.0F, 0.0F));\n\n ModelPartData bone209 = bone208.addChild(\"bone209\", ModelPartBuilder.create().uv(81, 27).cuboid(-7.0F, -1.0F, -11.8F, 14.0F, 1.0F, 13.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone210 = bone209.addChild(\"bone210\", ModelPartBuilder.create().uv(81, 27).cuboid(-7.0F, -1.0F, -11.8F, 14.0F, 1.0F, 13.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone211 = bone210.addChild(\"bone211\", ModelPartBuilder.create().uv(81, 27).cuboid(-7.0F, -1.0F, -11.8F, 14.0F, 1.0F, 13.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone212 = bone211.addChild(\"bone212\", ModelPartBuilder.create().uv(81, 27).cuboid(-7.0F, -1.0F, -11.8F, 14.0F, 1.0F, 13.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone213 = bone212.addChild(\"bone213\", ModelPartBuilder.create().uv(81, 27).cuboid(-7.0F, -1.0F, -11.8F, 14.0F, 1.0F, 13.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData rotor = base_console.addChild(\"rotor\", ModelPartBuilder.create().uv(0, 44).cuboid(-11.0F, -42.0F, -11.0F, 22.0F, 1.0F, 22.0F, new Dilation(0.0F))\n .uv(52, 111).cuboid(-3.5F, -53.5F, -3.5F, 7.0F, 2.0F, 7.0F, new Dilation(0.0F))\n .uv(27, 110).cuboid(-3.0F, -55.0F, -3.0F, 6.0F, 13.0F, 6.0F, new Dilation(0.0F))\n .uv(135, 48).cuboid(-2.0F, -56.0F, -2.0F, 4.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(52, 111).cuboid(-3.5F, -47.5F, -3.5F, 7.0F, 2.0F, 7.0F, new Dilation(0.0F))\n .uv(52, 111).cuboid(-3.5F, -50.5F, -3.5F, 7.0F, 2.0F, 7.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 0.0F, 0.0F));\n\n ModelPartData bone138 = rotor.addChild(\"bone138\", ModelPartBuilder.create().uv(81, 27).cuboid(-1.5F, -7.475F, -8.775F, 3.0F, 9.0F, 3.0F, new Dilation(0.0F))\n .uv(97, 0).cuboid(-0.5F, -8.975F, -7.775F, 1.0F, 11.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -43.5F, 0.0F));\n\n ModelPartData bone139 = bone138.addChild(\"bone139\", ModelPartBuilder.create().uv(81, 27).cuboid(-1.5F, -7.475F, -8.775F, 3.0F, 9.0F, 3.0F, new Dilation(0.0F))\n .uv(97, 0).cuboid(-0.5F, -8.975F, -7.775F, 1.0F, 11.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone140 = bone139.addChild(\"bone140\", ModelPartBuilder.create().uv(81, 27).cuboid(-1.5F, -7.475F, -8.775F, 3.0F, 9.0F, 3.0F, new Dilation(0.0F))\n .uv(97, 0).cuboid(-0.5F, -8.975F, -7.775F, 1.0F, 11.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone141 = bone140.addChild(\"bone141\", ModelPartBuilder.create().uv(81, 27).cuboid(-1.5F, -7.475F, -8.775F, 3.0F, 9.0F, 3.0F, new Dilation(0.0F))\n .uv(97, 0).cuboid(-0.5F, -8.975F, -7.775F, 1.0F, 11.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone142 = bone141.addChild(\"bone142\", ModelPartBuilder.create().uv(81, 27).cuboid(-1.5F, -7.475F, -8.775F, 3.0F, 9.0F, 3.0F, new Dilation(0.0F))\n .uv(97, 0).cuboid(-0.5F, -8.975F, -7.775F, 1.0F, 11.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone143 = bone142.addChild(\"bone143\", ModelPartBuilder.create().uv(81, 27).cuboid(-1.5F, -7.475F, -8.775F, 3.0F, 9.0F, 3.0F, new Dilation(0.0F))\n .uv(97, 0).cuboid(-0.5F, -8.975F, -7.775F, 1.0F, 11.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData glow = base_console.addChild(\"glow\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, 0.0F, 0.0F));\n\n ModelPartData NORTH2 = glow.addChild(\"NORTH2\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, -30.0F, 0.0F));\n\n ModelPartData bone31 = NORTH2.addChild(\"bone31\", ModelPartBuilder.create().uv(145, 54).cuboid(-9.5F, 0.524F, -0.4235F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(145, 54).cuboid(-6.75F, 0.524F, -0.4235F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(145, 54).cuboid(7.5F, 0.524F, -0.4235F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(145, 54).cuboid(4.75F, 0.524F, -0.4235F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(0, 140).cuboid(1.0F, 1.024F, 0.5765F, 1.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(0, 140).cuboid(-2.0F, 1.024F, 0.5765F, 1.0F, 1.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone178 = bone31.addChild(\"bone178\", ModelPartBuilder.create(), ModelTransform.of(-9.0F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone179 = bone31.addChild(\"bone179\", ModelPartBuilder.create(), ModelTransform.of(-6.25F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone180 = bone31.addChild(\"bone180\", ModelPartBuilder.create(), ModelTransform.of(5.25F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone181 = bone31.addChild(\"bone181\", ModelPartBuilder.create(), ModelTransform.of(8.0F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone182 = bone31.addChild(\"bone182\", ModelPartBuilder.create().uv(37, 98).cuboid(0.0F, -0.75F, -2.5F, 1.0F, 1.0F, 5.0F, new Dilation(0.0F)), ModelTransform.of(-7.75F, 1.274F, 6.0765F, 0.0F, 0.0F, 0.6109F));\n\n ModelPartData bone183 = bone31.addChild(\"bone183\", ModelPartBuilder.create().uv(37, 98).mirrored().cuboid(-1.0F, -0.75F, -2.5F, 1.0F, 1.0F, 5.0F, new Dilation(0.0F)).mirrored(false), ModelTransform.of(7.75F, 1.274F, 6.0765F, 0.0F, 0.0F, -0.6109F));\n\n ModelPartData bone184 = bone31.addChild(\"bone184\", ModelPartBuilder.create().uv(79, 138).cuboid(0.0F, -0.75F, -2.5F, 1.0F, 1.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(-8.75F, 1.274F, 6.0765F, 0.0F, 0.0F, 0.6109F));\n\n ModelPartData bone185 = bone31.addChild(\"bone185\", ModelPartBuilder.create().uv(79, 138).mirrored().cuboid(-1.0F, -0.75F, -2.5F, 1.0F, 1.0F, 2.0F, new Dilation(0.0F)).mirrored(false), ModelTransform.of(8.75F, 1.274F, 6.0765F, 0.0F, 0.0F, -0.6109F));\n\n ModelPartData NORTH_WEST2 = glow.addChild(\"NORTH_WEST2\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData northwestcontrolpanel2 = NORTH_WEST2.addChild(\"northwestcontrolpanel2\", ModelPartBuilder.create().uv(144, 136).cuboid(8.5F, -0.226F, 0.0765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData wheatleyeye = northwestcontrolpanel2.addChild(\"wheatleyeye\", ModelPartBuilder.create().uv(52, 121).cuboid(-1.0F, -1.0F, -4.25F, 2.0F, 2.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 1.274F, 6.0765F, -0.9163F, 0.0F, 0.0F));\n\n ModelPartData bone189 = northwestcontrolpanel2.addChild(\"bone189\", ModelPartBuilder.create().uv(94, 119).cuboid(-4.0F, 0.0F, -5.0F, 4.0F, 1.0F, 9.0F, new Dilation(0.0F)), ModelTransform.of(-4.0F, 1.024F, 6.0765F, 0.0F, 0.0F, 0.3927F));\n\n ModelPartData bone190 = northwestcontrolpanel2.addChild(\"bone190\", ModelPartBuilder.create().uv(94, 119).mirrored().cuboid(0.0F, 0.0F, -5.0F, 4.0F, 1.0F, 9.0F, new Dilation(0.0F)).mirrored(false), ModelTransform.of(4.0F, 1.024F, 6.0765F, 0.0F, 0.0F, -0.3927F));\n\n ModelPartData SOUTH_WEST2 = glow.addChild(\"SOUTH_WEST2\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, -2.0944F, 0.0F));\n\n ModelPartData bone188 = SOUTH_WEST2.addChild(\"bone188\", ModelPartBuilder.create().uv(136, 37).cuboid(-10.0F, 1.274F, 3.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(86, 81).cuboid(-1.0F, 1.024F, 1.5765F, 2.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(98, 42).cuboid(1.0F, 1.024F, 9.0765F, 1.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(9, 132).cuboid(-1.5F, 0.024F, 9.0765F, 3.0F, 2.0F, 3.0F, new Dilation(0.0F))\n .uv(98, 42).cuboid(-2.0F, 1.024F, 9.0765F, 1.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(16, 59).cuboid(4.0F, 0.774F, 4.0765F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(16, 59).cuboid(-5.0F, 0.774F, 4.0765F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(144, 61).cuboid(-9.5F, 1.024F, 3.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(144, 61).cuboid(-7.25F, 1.024F, 7.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(136, 37).cuboid(-7.75F, 1.274F, 7.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(144, 61).mirrored().cuboid(5.25F, 1.024F, 7.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F)).mirrored(false)\n .uv(136, 37).mirrored().cuboid(4.75F, 1.274F, 7.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F)).mirrored(false)\n .uv(144, 61).mirrored().cuboid(7.5F, 1.024F, 3.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F)).mirrored(false)\n .uv(136, 37).mirrored().cuboid(7.0F, 1.274F, 3.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F)).mirrored(false), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData SOUTH2 = glow.addChild(\"SOUTH2\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, 3.1416F, 0.0F));\n\n ModelPartData bone191 = SOUTH2.addChild(\"bone191\", ModelPartBuilder.create().uv(98, 61).cuboid(-6.5F, 1.524F, 10.0765F, 13.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(32, 130).cuboid(-5.0F, 0.274F, 10.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(32, 130).cuboid(-1.0F, 0.274F, 10.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(32, 130).cuboid(3.0F, 0.274F, 10.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(0, 140).cuboid(-2.0F, 1.024F, 3.5765F, 1.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(0, 140).cuboid(1.0F, 1.024F, 3.5765F, 1.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(46, 111).cuboid(-9.0F, 1.024F, 0.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone192 = bone191.addChild(\"bone192\", ModelPartBuilder.create(), ModelTransform.of(-7.5F, 1.274F, 1.5765F, 0.0F, -0.7854F, 0.0F));\n\n ModelPartData SOUTH_EAST2 = glow.addChild(\"SOUTH_EAST2\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, 2.0944F, 0.0F));\n\n ModelPartData bone193 = SOUTH_EAST2.addChild(\"bone193\", ModelPartBuilder.create().uv(123, 37).cuboid(-6.0F, 1.274F, 7.5765F, 6.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(101, 94).cuboid(2.0F, 0.524F, 7.5765F, 2.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(45, 98).cuboid(3.0F, 0.024F, 10.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(98, 47).cuboid(-5.0F, 0.524F, 10.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(86, 94).cuboid(-4.5F, 0.274F, 11.0765F, 6.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(131, 86).cuboid(5.0F, 1.024F, -0.4235F, 1.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(131, 86).cuboid(8.0F, 1.024F, -0.4235F, 1.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(11, 138).cuboid(0.5F, 1.024F, 0.5765F, 1.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(131, 86).cuboid(-6.0F, 1.024F, -0.4235F, 1.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(131, 86).cuboid(-9.0F, 1.024F, -0.4235F, 1.0F, 1.0F, 6.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone194 = bone193.addChild(\"bone194\", ModelPartBuilder.create(), ModelTransform.of(3.5F, 0.024F, 11.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone195 = bone193.addChild(\"bone195\", ModelPartBuilder.create(), ModelTransform.of(2.5F, 0.524F, 7.8265F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone196 = bone193.addChild(\"bone196\", ModelPartBuilder.create(), ModelTransform.of(4.0F, 1.024F, 8.8265F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone197 = bone193.addChild(\"bone197\", ModelPartBuilder.create(), ModelTransform.of(-0.75F, 1.774F, 2.5765F, 0.0F, 0.0F, -0.7854F));\n\n ModelPartData NORTH_EAST2 = glow.addChild(\"NORTH_EAST2\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, 1.0472F, 0.0F));\n\n ModelPartData bone198 = NORTH_EAST2.addChild(\"bone198\", ModelPartBuilder.create().uv(0, 98).cuboid(8.5F, 0.774F, 1.0765F, 1.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(86, 75).cuboid(6.5F, 0.774F, 0.0765F, 1.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(96, 116).cuboid(3.5F, 0.524F, 11.5765F, 1.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(106, 0).cuboid(-5.5F, 0.524F, 1.0765F, 11.0F, 1.0F, 8.0F, new Dilation(0.0F))\n .uv(45, 98).cuboid(-1.0F, 0.024F, 11.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone199 = bone198.addChild(\"bone199\", ModelPartBuilder.create(), ModelTransform.of(-8.5F, 0.774F, 3.0765F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone200 = bone198.addChild(\"bone200\", ModelPartBuilder.create().uv(12, 12).cuboid(2.0F, -1.0F, -1.0F, 1.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(-3.5F, 1.524F, 10.8265F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone201 = bone198.addChild(\"bone201\", ModelPartBuilder.create(), ModelTransform.of(3.5F, 0.024F, 12.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone202 = glow.addChild(\"bone202\", ModelPartBuilder.create().uv(41, 68).cuboid(-5.0F, 1.0F, -12.55F, 10.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, -44.5F, 0.0F));\n\n ModelPartData bone203 = bone202.addChild(\"bone203\", ModelPartBuilder.create().uv(41, 68).cuboid(-5.0F, 1.0F, -12.55F, 10.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone204 = bone203.addChild(\"bone204\", ModelPartBuilder.create().uv(41, 68).cuboid(-5.0F, 1.0F, -12.55F, 10.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone205 = bone204.addChild(\"bone205\", ModelPartBuilder.create().uv(41, 68).cuboid(-5.0F, 1.0F, -12.55F, 10.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone206 = bone205.addChild(\"bone206\", ModelPartBuilder.create().uv(41, 68).cuboid(-5.0F, 1.0F, -12.55F, 10.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData bone207 = bone206.addChild(\"bone207\", ModelPartBuilder.create().uv(41, 68).cuboid(-5.0F, 1.0F, -12.55F, 10.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 0.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData NORTH = base_console.addChild(\"NORTH\", ModelPartBuilder.create(), ModelTransform.pivot(0.0F, -30.0F, 0.0F));\n\n ModelPartData northcontrolpanel = NORTH.addChild(\"northcontrolpanel\", ModelPartBuilder.create().uv(130, 108).cuboid(4.0F, 1.274F, -0.9235F, 6.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(130, 108).cuboid(-10.0F, 1.274F, -0.9235F, 6.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(41, 92).cuboid(-6.0F, 1.274F, 3.0765F, 12.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(103, 111).cuboid(-5.0F, 0.774F, 7.0765F, 10.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(81, 16).cuboid(-3.5F, 0.274F, 10.5765F, 7.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(45, 138).cuboid(-3.0F, 0.774F, 8.5765F, 6.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(145, 141).cuboid(-0.5F, 0.524F, 8.0765F, 1.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(41, 84).cuboid(-5.0F, 1.274F, 7.0765F, 10.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(81, 11).cuboid(-3.0F, 1.274F, 0.0765F, 6.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(117, 143).cuboid(-9.0F, 1.274F, 3.0765F, 2.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(8, 144).cuboid(-8.0F, 1.274F, 6.0765F, 1.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(117, 143).mirrored().cuboid(7.0F, 1.274F, 3.0765F, 2.0F, 1.0F, 3.0F, new Dilation(0.0F)).mirrored(false)\n .uv(8, 144).mirrored().cuboid(7.0F, 1.274F, 6.0765F, 1.0F, 1.0F, 3.0F, new Dilation(0.0F)).mirrored(false), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData door_control = northcontrolpanel.addChild(\"door_control\", ModelPartBuilder.create().uv(96, 142).cuboid(-2.5F, -4.476F, -28.7235F, 5.0F, 2.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 4.0F, 29.8F));\n\n ModelPartData bone137 = northcontrolpanel.addChild(\"bone137\", ModelPartBuilder.create().uv(67, 44).cuboid(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(-9.0F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone159 = northcontrolpanel.addChild(\"bone159\", ModelPartBuilder.create().uv(67, 44).cuboid(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(-6.25F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone160 = northcontrolpanel.addChild(\"bone160\", ModelPartBuilder.create().uv(67, 44).cuboid(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(5.25F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone161 = northcontrolpanel.addChild(\"bone161\", ModelPartBuilder.create().uv(67, 44).cuboid(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(8.0F, 0.524F, 0.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone162 = northcontrolpanel.addChild(\"bone162\", ModelPartBuilder.create(), ModelTransform.of(-7.75F, 1.274F, 6.0765F, 0.0F, 0.0F, 0.6109F));\n\n ModelPartData bone163 = northcontrolpanel.addChild(\"bone163\", ModelPartBuilder.create(), ModelTransform.of(7.75F, 1.274F, 6.0765F, 0.0F, 0.0F, -0.6109F));\n\n ModelPartData bone164 = northcontrolpanel.addChild(\"bone164\", ModelPartBuilder.create(), ModelTransform.of(-8.75F, 1.274F, 6.0765F, 0.0F, 0.0F, 0.6109F));\n\n ModelPartData bone165 = northcontrolpanel.addChild(\"bone165\", ModelPartBuilder.create(), ModelTransform.of(8.75F, 1.274F, 6.0765F, 0.0F, 0.0F, -0.6109F));\n\n ModelPartData NORTH_WEST = base_console.addChild(\"NORTH_WEST\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, -1.0472F, 0.0F));\n\n ModelPartData northwestcontrolpanel = NORTH_WEST.addChild(\"northwestcontrolpanel\", ModelPartBuilder.create().uv(0, 84).cuboid(-7.0F, 1.024F, 0.0765F, 14.0F, 1.0F, 12.0F, new Dilation(0.0F))\n .uv(0, 12).cuboid(8.0F, 0.524F, -0.9235F, 3.0F, 2.0F, 5.0F, new Dilation(0.0F))\n .uv(76, 102).cuboid(3.0F, 1.024F, 0.0765F, 4.0F, 1.0F, 12.0F, new Dilation(0.0F))\n .uv(133, 101).cuboid(-2.5F, -0.976F, 8.5765F, 5.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData monitor = northwestcontrolpanel.addChild(\"monitors\", ModelPartBuilder.create().uv(100, 94).cuboid(-4.0F, -4.0F, -4.0F, 8.0F, 8.0F, 8.0F, new Dilation(0.0F))\n .uv(98, 42).cuboid(-4.5F, -4.5F, -4.5F, 9.0F, 9.0F, 9.0F, new Dilation(0.0F))\n .uv(70, 138).cuboid(4.0F, -2.0F, -2.0F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F))\n .uv(36, 138).cuboid(-6.0F, -2.0F, -2.0F, 2.0F, 4.0F, 4.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 1.274F, 6.0765F, -0.9163F, 0.0F, 0.0F));\n\n ModelPartData bone131 = northwestcontrolpanel.addChild(\"bone131\", ModelPartBuilder.create().uv(68, 84).cuboid(-1.0F, -1.0F, -1.0F, 2.0F, 3.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(9.5F, 1.274F, 4.0765F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone129 = northwestcontrolpanel.addChild(\"bone129\", ModelPartBuilder.create(), ModelTransform.of(-4.0F, 1.024F, 6.0765F, 0.0F, 0.0F, 0.3927F));\n\n ModelPartData bone130 = northwestcontrolpanel.addChild(\"bone130\", ModelPartBuilder.create(), ModelTransform.of(4.0F, 1.024F, 6.0765F, 0.0F, 0.0F, -0.3927F));\n\n ModelPartData SOUTH_WEST = base_console.addChild(\"SOUTH_WEST\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, -2.0944F, 0.0F));\n\n ModelPartData bone133 = SOUTH_WEST.addChild(\"bone133\", ModelPartBuilder.create().uv(0, 68).cuboid(-9.0F, 1.524F, -0.9235F, 18.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(126, 42).cuboid(-5.0F, 1.274F, 1.0765F, 10.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(145, 129).cuboid(-4.0F, 0.274F, 1.5765F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(137, 5).cuboid(-3.0F, 1.524F, 6.0765F, 6.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(116, 125).cuboid(-4.5F, 1.024F, 8.0765F, 9.0F, 1.0F, 5.0F, new Dilation(0.0F))\n .uv(125, 94).cuboid(-4.5F, 1.524F, 8.0765F, 9.0F, 1.0F, 5.0F, new Dilation(0.0F))\n .uv(134, 138).cuboid(-1.5F, -0.976F, 9.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(106, 143).cuboid(-7.75F, 1.524F, 4.0765F, 2.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(106, 143).mirrored().cuboid(5.75F, 1.524F, 4.0765F, 2.0F, 1.0F, 3.0F, new Dilation(0.0F)).mirrored(false)\n .uv(0, 44).cuboid(-6.75F, -0.976F, 8.0765F, 1.0F, 3.0F, 1.0F, new Dilation(0.0F))\n .uv(0, 44).mirrored().cuboid(5.75F, -0.976F, 8.0765F, 1.0F, 3.0F, 1.0F, new Dilation(0.0F)).mirrored(false), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone134 = bone133.addChild(\"bone134\", ModelPartBuilder.create().uv(111, 132).cuboid(-2.5F, -0.5F, -2.0F, 5.0F, 2.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, 1.524F, 5.0765F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone135 = bone133.addChild(\"bone135\", ModelPartBuilder.create().uv(145, 129).cuboid(-1.0F, 0.0F, -1.0F, 2.0F, 1.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(3.0F, 0.774F, 2.5765F, 0.0F, -0.829F, 0.0F));\n\n ModelPartData SOUTH = base_console.addChild(\"SOUTH\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, 3.1416F, 0.0F));\n\n ModelPartData southcontrolpanel = SOUTH.addChild(\"southcontrolpanel\", ModelPartBuilder.create().uv(121, 138).cuboid(-1.5F, 1.024F, 10.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(108, 138).cuboid(-5.5F, 1.024F, 10.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(108, 138).mirrored().cuboid(2.5F, 1.024F, 10.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F)).mirrored(false)\n .uv(41, 87).mirrored().cuboid(1.5F, 1.024F, 11.0765F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)).mirrored(false)\n .uv(41, 87).cuboid(-2.5F, 1.024F, 11.0765F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(81, 11).cuboid(-3.0F, 1.274F, 3.0765F, 6.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(0, 59).cuboid(5.0F, 1.274F, -0.9235F, 5.0F, 1.0F, 5.0F, new Dilation(0.0F))\n .uv(137, 0).cuboid(6.0F, 0.774F, 0.0765F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(0, 59).cuboid(-10.0F, 1.274F, -0.9235F, 5.0F, 1.0F, 5.0F, new Dilation(0.0F))\n .uv(41, 84).cuboid(-8.0F, 0.274F, 1.0765F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(67, 62).cuboid(-4.0F, 1.524F, 0.0765F, 8.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(41, 92).cuboid(-6.0F, 1.274F, 6.0765F, 12.0F, 1.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData XYZmod = southcontrolpanel.addChild(\"XYZmod\", ModelPartBuilder.create().uv(96, 142).cuboid(-2.5F, -4.476F, -28.7235F, 5.0F, 2.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 4.0F, 32.8F));\n\n ModelPartData randomiser = southcontrolpanel.addChild(\"randomiser\", ModelPartBuilder.create().uv(138, 10).cuboid(-1.5F, -0.5F, -1.5F, 3.0F, 1.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(-7.5F, 1.274F, 1.5765F, 0.0F, -0.7854F, 0.0F));\n\n ModelPartData land_type = southcontrolpanel.addChild(\"land_type\", ModelPartBuilder.create().uv(143, 69).cuboid(-2.0F, -3.226F, -29.7235F, 3.0F, 2.0F, 2.0F, new Dilation(0.0F))\n .uv(0, 12).cuboid(-1.0F, -3.726F, -29.7235F, 1.0F, 3.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(8.0F, 2.5F, 30.8F));\n\n ModelPartData SOUTH_EAST = base_console.addChild(\"SOUTH_EAST\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, 2.0944F, 0.0F));\n\n ModelPartData southeastcontrolpanel = SOUTH_EAST.addChild(\"southeastcontrolpanel\", ModelPartBuilder.create().uv(120, 81).cuboid(-5.5F, 1.024F, 10.0765F, 11.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(140, 125).cuboid(1.0F, 1.024F, 7.0765F, 4.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(45, 71).cuboid(-6.0F, 1.524F, 7.0765F, 6.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(52, 121).cuboid(4.0F, 1.274F, -0.9235F, 6.0F, 1.0F, 7.0F, new Dilation(0.0F))\n .uv(135, 54).cuboid(0.0F, 1.274F, 0.0765F, 2.0F, 1.0F, 5.0F, new Dilation(0.0F))\n .uv(0, 59).cuboid(0.5F, 0.024F, 2.5765F, 1.0F, 2.0F, 1.0F, new Dilation(0.0F))\n .uv(67, 47).cuboid(-1.5F, 0.774F, 7.5765F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F))\n .uv(140, 86).cuboid(-2.0F, 1.274F, 0.5765F, 1.0F, 1.0F, 4.0F, new Dilation(0.0F))\n .uv(0, 132).cuboid(-3.5F, 1.274F, -0.4235F, 1.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(0, 132).cuboid(2.5F, 1.274F, -0.4235F, 1.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(52, 121).cuboid(-10.0F, 1.274F, -0.9235F, 6.0F, 1.0F, 7.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData handbrake = southeastcontrolpanel.addChild(\"handbrake\", ModelPartBuilder.create().uv(136, 113).cuboid(-2.5F, -4.0F, -0.5F, 5.0F, 4.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(-7.0F, 1.524F, 2.5765F, -1.309F, 0.0F, 0.0F));\n\n ModelPartData throttle = southeastcontrolpanel.addChild(\"throttle\", ModelPartBuilder.create().uv(96, 142).cuboid(4.5F, -4.476F, -32.7235F, 5.0F, 2.0F, 1.0F, new Dilation(0.0F)), ModelTransform.pivot(0.0F, 4.0F, 32.8F));\n\n ModelPartData bone173 = southeastcontrolpanel.addChild(\"bone173\", ModelPartBuilder.create().uv(128, 143).cuboid(-1.0F, -0.5F, -1.0F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(-0.75F, 1.774F, 2.5765F, 0.0F, 0.0F, -0.7854F));\n\n ModelPartData bone171 = southeastcontrolpanel.addChild(\"bone171\", ModelPartBuilder.create().uv(67, 44).cuboid(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(3.5F, 0.024F, 11.0765F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone172 = southeastcontrolpanel.addChild(\"bone172\", ModelPartBuilder.create().uv(67, 44).cuboid(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(2.5F, 0.524F, 7.8265F, 0.6109F, 0.0F, 0.0F));\n\n ModelPartData bone170 = southeastcontrolpanel.addChild(\"bone170\", ModelPartBuilder.create().uv(0, 103).cuboid(-2.0F, -0.5F, -1.0F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(4.0F, 1.024F, 8.8265F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData NORTH_EAST = base_console.addChild(\"NORTH_EAST\", ModelPartBuilder.create(), ModelTransform.of(0.0F, -30.0F, 0.0F, 0.0F, 1.0472F, 0.0F));\n\n ModelPartData bone174 = NORTH_EAST.addChild(\"bone174\", ModelPartBuilder.create().uv(0, 98).cuboid(-6.5F, 1.024F, 0.0765F, 13.0F, 1.0F, 10.0F, new Dilation(0.0F))\n .uv(36, 130).cuboid(-10.5F, 1.024F, -0.9235F, 6.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(49, 141).cuboid(-9.5F, 0.274F, 0.0765F, 2.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(125, 61).cuboid(4.5F, 1.024F, -0.9235F, 6.0F, 1.0F, 6.0F, new Dilation(0.0F))\n .uv(67, 57).cuboid(-5.5F, 0.774F, 11.0765F, 7.0F, 1.0F, 3.0F, new Dilation(0.0F))\n .uv(143, 119).cuboid(-5.0F, 0.274F, 11.5765F, 3.0F, 1.0F, 2.0F, new Dilation(0.0F))\n .uv(143, 15).cuboid(3.0F, 0.774F, 11.0765F, 2.0F, 1.0F, 3.0F, new Dilation(0.0F)), ModelTransform.of(0.0F, -4.0F, -27.8F, 0.48F, 0.0F, 0.0F));\n\n ModelPartData bone175 = bone174.addChild(\"bone175\", ModelPartBuilder.create().uv(0, 103).cuboid(-1.0F, -0.5F, -1.0F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(-8.5F, 0.774F, 3.0765F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone176 = bone174.addChild(\"bone176\", ModelPartBuilder.create().uv(0, 103).cuboid(-1.0F, -1.0F, -1.0F, 2.0F, 2.0F, 2.0F, new Dilation(0.0F)), ModelTransform.of(-3.5F, 1.524F, 10.8265F, 0.7854F, 0.0F, 0.0F));\n\n ModelPartData bone177 = bone174.addChild(\"bone177\", ModelPartBuilder.create().uv(67, 44).cuboid(-4.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, new Dilation(0.0F)), ModelTransform.of(3.5F, 0.024F, 12.0765F, 0.6109F, 0.0F, 0.0F));\n return TexturedModelData.of(modelData, 256, 256);\n }\n\n @Override\n public void render(MatrixStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha) {\n this.base_console.render(matrices, vertices, light, overlay, 1, 1, 1, 1);\n }\n\n @Override\n public void renderWithAnimations(ConsoleBlockEntity console, ModelPart root, MatrixStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float pAlpha) {\n if (console.getTardis() == null) return;\n matrices.push();\n // fixme id do it but i genuinely dont want to bc i cba\n\n ModelPart southEastControls = this.base_console.getChild(\"SOUTH_EAST\").getChild(\"southeastcontrolpanel\");\n ModelPart northControls = this.base_console.getChild(\"NORTH\").getChild(\"northcontrolpanel\");\n ModelPart southControls = this.base_console.getChild(\"SOUTH\").getChild(\"southcontrolpanel\");\n\n boolean isInFlight = console.getTardis().getTravel().getState() == TardisTravel.State.DEMAT || console.getTardis().getTravel().getState() == TardisTravel.State.FLIGHT;\n boolean isHandbrakeActive = PropertiesHandler.getBool(console.getTardis().getHandlers().getProperties(), PropertiesHandler.HANDBRAKE);\n boolean leftDoor = console.getTardis().getDoor().getDoorState() == DoorHandler.DoorStateEnum.FIRST;\n boolean rightDoor = console.getTardis().getDoor().getDoorState() == DoorHandler.DoorStateEnum.SECOND;\n boolean locked = console.getTardis().getDoor().locked();\n boolean isUpOrDown = PropertiesHandler.getBool(console.getTardis().getHandlers().getProperties(), PropertiesHandler.FIND_GROUND);\n\n int increment = console.getTardis().getTravel().getPosManager().increment;\n float throttleZ = southEastControls.getChild(\"throttle\").pivotZ;\n float doorZ = northControls.getChild(\"door_control\").pivotZ;\n float doorY = northControls.getChild(\"door_control\").pivotY;\n float incrementModZ = southControls.getChild(\"XYZmod\").pivotZ;\n float landTypeY = southControls.getChild(\"land_type\").pivotY;\n Vector3f handbrakeRotation = new Vector3f(isHandbrakeActive ? 0 : -1.309F * -2, 0, 0);\n southEastControls.getChild(\"throttle\").pivotZ = isInFlight ? throttleZ + 3f : throttleZ;\n southEastControls.getChild(\"handbrake\").rotate(handbrakeRotation);\n northControls.getChild(\"door_control\").pivotZ = leftDoor ? doorZ + 1 : rightDoor ? doorZ + 2 : doorZ;\n northControls.getChild(\"door_control\").pivotY = locked ? doorY + 1 : doorY;\n southControls.getChild(\"XYZmod\").pivotZ = increment == 10 ? incrementModZ + 1 : increment == 100 ? incrementModZ + 2 : increment == 1000 ? incrementModZ + 3 : incrementModZ;\n southControls.getChild(\"land_type\").pivotY = isUpOrDown ? landTypeY : landTypeY + 1;\n matrices.pop();\n\n matrices.push();\n\n matrices.translate(0.5f, -0.75f, -0.5f);\n matrices.scale(0.5f, 0.5f, 0.5f);\n\n super.renderWithAnimations(console, root, matrices, vertices, light, overlay, red, green, blue, pAlpha);\n\n matrices.pop();\n }\n\n @Override\n public ModelPart getPart() {\n return this.base_console;\n }\n\n @Override\n public Animation getAnimationForState(TardisTravel.State state) {\n return switch (state) {\n case LANDED -> BorealisAnimations.CONSOLE_IDLE_WHEATLEY;\n case DEMAT -> BorealisAnimations.CONSOLE_ROTOR_DEMATERIALIZE;\n case FLIGHT, CRASH -> BorealisAnimations.CONSOLE_ROTOR_INFLIGHT;\n case MAT -> BorealisAnimations.CONSOLE_ROTOR_MATERIALIZE;\n };\n }\n}\n\nsrc/main/java/mdteam/ait/client/models/consoles/ConsoleModel.java\n@SuppressWarnings(\"rawtypes\")\npublic abstract class ConsoleModel extends SinglePartEntityModel {\n public static int MAX_TICK_COUNT = 2 * 20;\n\n public ConsoleModel() {\n this(RenderLayer::getEntityCutoutNoCull);\n }\n\n public ConsoleModel(Function function) {\n super(function);\n }\n\n // Thanks craig for help w animation code\n public void animateTile(ConsoleBlockEntity console) {\n this.getPart().traverse().forEach(ModelPart::resetTransform);\n if (console.getTardis() == null)\n return;\n // System.out.println(getAnimationForState(console.getTardis().getTravel().getState()));\n\n TardisTravel.State state = console.getTardis().getTravel().getState();\n\n if (!console.getTardis().hasPower()) return;\n\n this.updateAnimation(console.ANIM_FLIGHT, getAnimationForState(state), console.animationTimer);\n /*if(console.getControlEntityFromName(\"direction\") != null && console.getControlEntityFromName(\"direction\").getControl() != null) {\n this.updateAnimation(console.getControlEntityFromName(\"direction\")\n .getControl().getAnimationState(HartnellAnimations.animationFromDirection(console.getTardis().getTravel())),\n console.getControlEntityFromName(\"direction\").getControl().getAnimation(HartnellAnimations.animationFromDirection(console.getTardis().getTravel())), console.animationTimer);\n }*/\n }\n\n public void renderWithAnimations(ConsoleBlockEntity console, ModelPart root, MatrixStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float pAlpha) {\n if (console.getTardis() == null) return;\n root.render(matrices, vertices, light, overlay, red, green, blue, pAlpha);\n }\n\n @Override\n public void setAngles(Entity entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) {\n }\n\n public abstract Animation getAnimationForState(TardisTravel.State state);\n}\n\nsrc/main/java/mdteam/ait/client/registry/console/ClientConsoleVariantSchema.java\n@Environment(EnvType.CLIENT)\npublic abstract class ClientConsoleVariantSchema {\n private final Identifier parent;\n private final Identifier id;\n\n protected ClientConsoleVariantSchema(Identifier parent, Identifier id) {\n this.parent = parent;\n this.id = id;\n }\n protected ClientConsoleVariantSchema(Identifier parent) {\n this.id = parent;\n this.parent = parent;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() == null) return false;\n\n ClientConsoleVariantSchema that = (ClientConsoleVariantSchema) o;\n\n return id.equals(that.id);\n }\n\n public ConsoleVariantSchema parent() { return ConsoleVariantRegistry.REGISTRY.get(this.parent); }\n public Identifier id() { return id; }\n public abstract Identifier texture();\n public abstract Identifier emission();\n @Environment(EnvType.CLIENT)\n public abstract ConsoleModel model();\n\n public static Object serializer() {\n return new Serializer();\n }\n\n private static class Serializer implements JsonSerializer, JsonDeserializer {\n\n @Override\n public ClientConsoleVariantSchema deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {\n Identifier id;\n\n try {\n id = new Identifier(json.getAsJsonPrimitive().getAsString());\n } catch (InvalidIdentifierException e) {\n id = BorealisVariant.REFERENCE;\n }\n\n return ClientConsoleVariantRegistry.REGISTRY.get(id);\n }\n\n @Override\n public JsonElement serialize(ClientConsoleVariantSchema src, Type typeOfSrc, JsonSerializationContext context) {\n return new JsonPrimitive(src.id().toString());\n }\n }\n}\n\nsrc/main/java/mdteam/ait/tardis/variant/console/AutumnVariant.java\npublic class AutumnVariant extends ConsoleVariantSchema {\n public static final Identifier REFERENCE = new Identifier(AITMod.MOD_ID, \"console/autumn\");\n public AutumnVariant() {\n super(BorealisConsole.REFERENCE, REFERENCE);\n }\n}", "answers": [" public Identifier emission() {"], "length": 5712, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "2850c88d-32c5-4583-9b5b-9a18ed0b0572", "reasoning": "In ClientAutumnVariant we have overridden texture() and now need to override the next abstract method emission() from the superclass. After the @Override annotation the next line should start the method definition returning the EMISSION identifier.", "reasoning_model_answer": "public Identifier emission() {", "assistant_with_reasoning": "\nIn ClientAutumnVariant we have overridden texture() and now need to override the next abstract method emission() from the superclass. After the @Override annotation the next line should start the method definition returning the EMISSION identifier.\n\npublic Identifier emission() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.849, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36334, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public Identifier emission() {", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport net.pl3x.map.core.Pl3xMap;\nimport net.pl3x.map.core.configuration.Config;\nimport net.pl3x.map.core.configuration.Lang;\nimport net.pl3x.map.core.configuration.PlayersLayerConfig;\nimport net.pl3x.map.core.configuration.WorldConfig;\nimport net.pl3x.map.core.image.io.IO;\nimport net.pl3x.map.core.markers.Point;\nimport net.pl3x.map.core.scheduler.Task;\nimport net.pl3x.map.core.util.FileUtil;\nimport net.pl3x.map.core.world.World;\nimport org.jetbrains.annotations.NotNull;", "context": "core/src/main/java/net/pl3x/map/core/renderer/task/UpdateSettingsData.java\n/*\n * MIT License\n *\n * Copyright (c) 2020-2023 William Blake Galbreath\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage net.pl3x.map.core.renderer.task;\n\n\npublic class UpdateSettingsData extends Task {\n private final Gson gson = new GsonBuilder()\n //.setPrettyPrinting()\n .disableHtmlEscaping()\n .serializeNulls()\n .setLenient()\n .create();\n\n public UpdateSettingsData() {\n super(1, true);\n }\n\n @Override\n public void run() {\n try {\n parseSettings();\n } catch (Throwable t) {\n t.printStackTrace();\n }\n }\n\n private @NotNull List<@NotNull Object> parsePlayers() {\n if (!PlayersLayerConfig.ENABLED) {\n return Collections.emptyList();\n }\n List players = new ArrayList<>();\n Pl3xMap.api().getPlayerRegistry().forEach(player -> {\n // do not expose hidden players in the json\n if (player.isHidden() || player.isNPC()) {\n return;\n }\n if (PlayersLayerConfig.HIDE_SPECTATORS && player.isSpectator()) {\n return;\n }\n if (PlayersLayerConfig.HIDE_INVISIBLE && player.isInvisible()) {\n return;\n }\n\n Map playerEntry = new LinkedHashMap<>();\n\n playerEntry.put(\"name\", player.getDecoratedName());\n playerEntry.put(\"uuid\", player.getUUID().toString());\n playerEntry.put(\"displayName\", player.getDecoratedName());\n playerEntry.put(\"world\", player.getWorld().getName());\n playerEntry.put(\"position\", player.getPosition());\n\n players.add(playerEntry);\n });\n return players;\n }\n\n private @NotNull List<@NotNull Map<@NotNull String, @NotNull Object>> parseWorlds() {\n List> worldSettings = new ArrayList<>();\n Pl3xMap.api().getWorldRegistry().entrySet().forEach(entry -> {\n World world = entry.getValue();\n if (!world.isEnabled()) {\n return;\n }\n\n WorldConfig config = world.getConfig();\n\n Map spawn = new LinkedHashMap<>();\n Point point = world.getSpawn();\n spawn.put(\"x\", point.x());\n spawn.put(\"z\", point.z());\n\n Map zoom = new LinkedHashMap<>();\n zoom.put(\"default\", config.ZOOM_DEFAULT);\n zoom.put(\"maxOut\", config.ZOOM_MAX_OUT);\n zoom.put(\"maxIn\", config.ZOOM_MAX_IN);\n\n Map ui = new LinkedHashMap<>();\n ui.put(\"link\", config.UI_LINK);\n ui.put(\"coords\", config.UI_COORDS);\n ui.put(\"blockinfo\", config.UI_BLOCKINFO);\n ui.put(\"attribution\", config.UI_ATTRIBUTION);\n\n Map settings = new LinkedHashMap<>();\n settings.put(\"name\", world.getName().replace(\":\", \"-\"));\n settings.put(\"tileUpdateInterval\", 10);\n settings.put(\"spawn\", spawn);\n settings.put(\"zoom\", zoom);\n settings.put(\"ui\", ui);\n\n FileUtil.writeJson(this.gson.toJson(settings), world.getTilesDirectory().resolve(\"settings.json\"));\n\n List renderers = new ArrayList<>();\n world.getRenderers().forEach((rendererKey, builder) -> {\n String icon = world.getConfig().RENDER_RENDERERS.get(rendererKey);\n renderers.add(Map.of(\"label\", rendererKey, \"value\", builder.getName(), \"icon\", icon));\n });\n\n Map worldsList = new LinkedHashMap<>();\n\ncore/src/main/java/net/pl3x/map/core/util/FileUtil.java\npublic class FileUtil {\n public static @NotNull Path getTilesDir() {\n return getWebDir().resolve(\"tiles\");\n }\n\n public static @NotNull Path getWebDir() {\n return Config.WEB_DIR.startsWith(\"/\") ? Path.of(Config.WEB_DIR) : Pl3xMap.api().getMainDir().resolve(Config.WEB_DIR);\n }\n\n public static void extractFile(@NotNull Class clazz, @NotNull String filename, @NotNull Path outDir, boolean replace) {\n try (InputStream in = clazz.getResourceAsStream(\"/\" + filename)) {\n if (in == null) {\n throw new RuntimeException(\"Could not read file from jar! (\" + filename + \")\");\n }\n Path path = outDir.resolve(filename);\n if (!Files.exists(path) || replace) {\n Files.createDirectories(path.getParent());\n Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void extractDir(@NotNull String sourceDir, @NotNull Path outDir, boolean replace) {\n try (JarFile jarFile = new JarFile(Pl3xMap.api().getJarPath().toFile())) {\n Logger.debug(\"Extracting \" + sourceDir + \" directory from jar...\");\n String path = sourceDir.substring(1);\n Enumeration entries = jarFile.entries();\n while (entries.hasMoreElements()) {\n JarEntry entry = entries.nextElement();\n String name = entry.getName();\n if (!name.startsWith(path)) {\n continue;\n }\n Path file = outDir.resolve(name.substring(path.length()));\n boolean exists = Files.exists(file);\n if (!replace && exists) {\n Logger.debug(\" exists \" + name);\n continue;\n }\n if (entry.isDirectory()) {\n if (!exists) {\n try {\n Files.createDirectories(file);\n Logger.debug(\" creating \" + name);\n } catch (IOException e) {\n Logger.debug(\" failed \" + name);\n }\n } else {\n Logger.debug(\" exists \" + name);\n }\n continue;\n }\n try (\n InputStream in = new BufferedInputStream(jarFile.getInputStream(entry));\n OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile()))\n ) {\n byte[] buffer = new byte[4096];\n int readCount;\n while ((readCount = in.read(buffer)) > 0) {\n out.write(buffer, 0, readCount);\n }\n out.flush();\n Logger.debug(\" writing \" + name);\n } catch (IOException e) {\n Logger.debug(\" failed \" + name);\n Logger.warn(\"Failed to extract file (\" + name + \") from jar!\");\n e.printStackTrace();\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void writeJson(@NotNull String str, @NotNull Path file) {\n Path tmp = tmp(file);\n try (\n OutputStream fileOut = Files.newOutputStream(mkDirs(tmp));\n Writer writer = new OutputStreamWriter(fileOut)\n ) {\n writer.write(str);\n writer.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n try {\n atomicMove(tmp, file);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void saveGzip(@NotNull String json, @NotNull Path file) throws IOException {\n Path tmp = tmp(file);\n try (\n OutputStream fileOut = Files.newOutputStream(mkDirs(tmp));\n GZIPOutputStream gzipOut = new GZIPOutputStream(fileOut);\n Writer writer = new OutputStreamWriter(gzipOut)\n ) {\n writer.write(json);\n writer.flush();\n }\n atomicMove(tmp, file);\n }\n\n public static void saveGzip(byte[] bytes, @NotNull Path file) throws IOException {\n Path tmp = tmp(file);\n try (\n OutputStream fileOut = Files.newOutputStream(mkDirs(tmp));\n GZIPOutputStream gzipOut = new GZIPOutputStream(fileOut)\n ) {\n gzipOut.write(bytes);\n gzipOut.flush();\n }\n atomicMove(tmp, file);\n }\n\n public static void readGzip(@NotNull Path file, @NotNull ByteBuffer buffer) throws IOException {\n try (\n InputStream fileIn = Files.newInputStream(file);\n GZIPInputStream gzipIn = new GZIPInputStream(fileIn)\n ) {\n // try reading all bytes and closing stream _before_ putting into buffer\n byte[] bytes = gzipIn.readAllBytes();\n gzipIn.close();\n buffer.put(bytes);\n }\n }\n\n public static String readGzip(@NotNull Path file) throws IOException {\n try (\n InputStream fileIn = Files.newInputStream(file);\n GZIPInputStream gzipIn = new GZIPInputStream(fileIn);\n Reader reader = new InputStreamReader(gzipIn, StandardCharsets.UTF_8);\n Writer writer = new StringWriter()\n ) {\n char[] buffer = new char[4096];\n for (int length; (length = reader.read(buffer)) > 0; ) {\n writer.write(buffer, 0, length);\n }\n return writer.toString();\n }\n }\n\n public static Path tmp(Path file) {\n return file.resolveSibling(\".\" + file.getFileName().toString() + \".tmp\");\n }\n\n public static void atomicMove(Path source, Path target) throws IOException {\n try {\n atomicMove(source, target, 0);\n } catch (AccessDeniedException | NoSuchFileException ignore) {\n }\n }\n\n private static void atomicMove(Path source, Path target, int attempt) throws IOException {\n try {\n com.google.common.io.Files.move(source.toFile(), target.toFile());\n Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);\n } catch (AtomicMoveNotSupportedException e) {\n Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);\n } catch (AccessDeniedException e) {\n if (attempt < 5) {\n try {\n Thread.sleep(20);\n } catch (InterruptedException ignore) {\n }\n atomicMove(source, target, ++attempt);\n } else if (source.getFileName().toString().endsWith(\".tmp\")) {\n try {\n Files.delete(source);\n } catch (Throwable ignore) {\n }\n }\n }\n }\n\n public static @NotNull Path mkDirs(@NotNull Path file) throws IOException {\n if (!Files.exists(file)) {\n Files.createDirectories(file.getParent());\n Files.createFile(file);\n }\n return file;\n }\n\n public static void createDirs(@NotNull Path dirPath) {\n if (!Files.exists(dirPath)) {\n try {\n Files.createDirectories(dirPath);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public static void deleteDirectory(@NotNull Path dir) throws IOException {\n try (Stream walk = Files.walk(dir)) {\n walk.sorted(Comparator.reverseOrder())\n .map(Path::toFile)\n .forEach(File::delete);\n }\n }\n\n public static @NotNull Collection<@NotNull Point> regionPathsToPoints(@NotNull World world, @Nullable Collection<@NotNull Path> paths, boolean ignoreTimestamp) {\n if (paths == null || paths.isEmpty()) {\n return Collections.emptyList();\n }\n List regions = new ArrayList<>();\n for (Path file : paths) {\n if (file.toFile().length() <= 0) {\n Logger.debug(\"Skipping zero length region file: \" + file.getFileName());\n continue;\n }\n try {\n String[] split = file.getFileName().toString().split(\"\\\\.\");\n int rX = Integer.parseInt(split[1]);\n int rZ = Integer.parseInt(split[2]);\n if (!world.visibleRegion(rX, rZ)) {\n Logger.debug(\"Skipping region outside of visible areas: \" + file.getFileName());\n continue;\n }\n if (ignoreTimestamp) {\n regions.add(Point.of(rX, rZ));\n continue;\n }\n long storedModifiedTime = world.getRegionModifiedState().get(Mathf.asLong(rX, rZ));\n long actualModifiedTime = Files.getLastModifiedTime(file).toMillis();\n if (actualModifiedTime > storedModifiedTime) {\n Logger.debug(\"Found modified region file: \" + file.getFileName());\n regions.add(Point.of(rX, rZ));\n } else {\n //Logger.debug(\"Skipping unmodified region file: \" + file.getFileName() + \" \" + actualModifiedTime + \" <= \" + storedModifiedTime);\n }\n } catch (NumberFormatException ignore) {\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n return regions;\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/Pl3xMap.java\npublic abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes;\n private final HttpdServer httpdServer;\n private final RegionProcessor regionProcessor;\n private final RegionDoubleChecker regionDoubleChecker;\n private final Scheduler scheduler;\n\n private final BlockRegistry blockRegistry;\n private final EventRegistry eventRegistry;\n private final HeightmapRegistry heightmapRegistry;\n private final IconRegistry iconRegistry;\n private final PlayerRegistry playerRegistry;\n private final RendererRegistry rendererRegistry;\n private final WorldRegistry worldRegistry;\n\n private ExecutorService renderExecutor;\n\n private String commit;\n private Metrics metrics;\n private boolean enabled;\n\n public Pl3xMap(boolean isBukkit) {\n this.isBukkit = isBukkit;\n\n /*try {\n // Due to these bugs(?) in spi\n // * relocated libraries cant find their services (xnio fails)\n // * imageio fails to find twelvemonkeys spis at all\n // I am forced to load them all myself instead of relying on the META-INF\n SpiFix.forceRegisterSpis();\n } catch (Throwable ignore) {\n }*/\n\n try {\n Field api = Provider.class.getDeclaredField(\"api\");\n api.setAccessible(true);\n api.set(null, this);\n } catch (NoSuchFieldException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n\n Manifest manifest;\n try (JarFile jarFile = new JarFile(getJarPath().toFile())) {\n JarEntry entry = jarFile.getJarEntry(\"META-INF/MANIFEST.MF\");\n try (InputStream in = new BufferedInputStream(jarFile.getInputStream(entry))) {\n manifest = new Manifest(in);\n }\n } catch (Exception e) {\n manifest = new Manifest();\n e.printStackTrace();\n }\n this.manifestAttributes = manifest.getMainAttributes();\n\n // setup internal server\n this.httpdServer = new HttpdServer();\n\n // setup tasks\n this.regionProcessor = new RegionProcessor();\n this.regionDoubleChecker = new RegionDoubleChecker();\n this.scheduler = new Scheduler();\n\n // setup registries\n this.blockRegistry = new BlockRegistry();\n this.eventRegistry = new EventRegistry();\n this.heightmapRegistry = new HeightmapRegistry();\n this.iconRegistry = new IconRegistry();\n this.playerRegistry = new PlayerRegistry();\n this.rendererRegistry = new RendererRegistry();\n this.worldRegistry = new WorldRegistry();\n }\n\n public boolean isEnabled() {\n return this.enabled;\n }\n\n public @NotNull HttpdServer getHttpdServer() {\n return this.httpdServer;\n }\n\n public @NotNull RegionProcessor getRegionProcessor() {\n return this.regionProcessor;\n }\n\n public @NotNull RegionDoubleChecker getRegionDoubleChecker() {\n return this.regionDoubleChecker;\n }\n\n public @NotNull BlockRegistry getBlockRegistry() {\n return this.blockRegistry;\n }\n\n public @NotNull EventRegistry getEventRegistry() {\n return this.eventRegistry;\n }\n\n public @NotNull HeightmapRegistry getHeightmapRegistry() {\n return this.heightmapRegistry;\n }\n\n public @NotNull IconRegistry getIconRegistry() {\n return this.iconRegistry;\n }\n\n public @NotNull PlayerRegistry getPlayerRegistry() {\n return this.playerRegistry;\n }\n\n public @NotNull RendererRegistry getRendererRegistry() {\n return this.rendererRegistry;\n }\n\n public @NotNull WorldRegistry getWorldRegistry() {\n return this.worldRegistry;\n }\n\n public @NotNull ExecutorService getRenderExecutor() {\n return this.renderExecutor;\n }\n\n public @NotNull Scheduler getScheduler() {\n return this.scheduler;\n }\n\n public void enable() {\n // load up configs\n Logger.debug(\"Loading configs\");\n Config.reload();\n Lang.reload();\n ColorsConfig.reload();\n PlayersLayerConfig.reload();\n SpawnLayerConfig.reload();\n WorldBorderLayerConfig.reload();\n\n // initialize block registry\n getBlockRegistry().init();\n\n // initialize icons\n getIconRegistry().init();\n\n // load blocks _after_ we loaded colors\n Logger.debug(\"Registering blocks\");\n Blocks.registerDefaults();\n loadBlocks();\n\n // create the executor service\n Logger.debug(\"Creating services\");\n this.renderExecutor = ThreadFactory.createService(\"Pl3xMap-Renderer\", Config.RENDER_THREADS);\n\n // register built in tile image types\n Logger.debug(\"Registering tile image types\");\n IO.register();\n\n // register built-in heightmaps\n Logger.debug(\"Registering heightmaps\");\n getHeightmapRegistry().register();\n\n // register built-in renderers\n Logger.debug(\"Registering renderers\");\n getRendererRegistry().register();\n\n this.enabled = true;\n\n new Pl3xMapEnabledEvent().callEvent();\n\n // load up already loaded worlds\n Logger.debug(\"Registering worlds\");\n loadWorlds();\n\n // load up players already connected to the server\n Logger.debug(\"Registering players\");\n loadPlayers();\n\n // start integrated server\n Logger.debug(\"Starting internal server\");\n getHttpdServer().startServer();\n\n // start tasks\n Logger.debug(\"Starting region processor\");\n getRegionProcessor().start(10000L);\n getRegionDoubleChecker().start(250000L);\n\n Logger.debug(\"Starting update settings data task\");\n getScheduler().addTask(new UpdateSettingsData());\n\n Logger.info(\"Platform: \" + getPlatform());\n Logger.info(\"Version: \" + getVersion());\n\n try {\n this.metrics = new Metrics(this);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n Pl3xMap.api().getRegionProcessor().setPaused(false);\n }\n\n public void disable() {\n Pl3xMap.api().getRegionProcessor().setPaused(true);\n\n if (this.metrics != null) {\n this.metrics.shutdown();\n this.metrics = null;\n }\n\n // stop tasks\n Logger.debug(\"Stopping tasks\");\n getScheduler().cancelAll();\n getRegionDoubleChecker().stop();\n getRegionProcessor().stop();\n if (this.renderExecutor != null) {\n this.renderExecutor.shutdownNow();\n }\n\n // stop integrated server\n Logger.debug(\"Stopping internal server\");\n getHttpdServer().stopServer();\n\n this.enabled = false;\n\n new Pl3xMapDisabledEvent().callEvent();\n\n // unload all players\n Logger.debug(\"Unregistering players\");\n getPlayerRegistry().unregister();\n\n // unload all map worlds\n Logger.debug(\"Unregistering worlds\");\n getWorldRegistry().unregister();\n\n // unregister renderers\n Logger.debug(\"Unregistering renderers\");\n getRendererRegistry().unregister();\n\n // unregister icons\n Logger.debug(\"Unregistering icons\");\n getIconRegistry().unregister();\n\n // unregister heightmaps\n Logger.debug(\"Unregistering heightmaps\");\n getHeightmapRegistry().unregister();\n\n // unregister tile image types\n Logger.debug(\"Unregistering tile image types\");\n IO.unregister();\n\n // unregister blocks\n Logger.debug(\"Unregistering blocks\");\n getBlockRegistry().unregister();\n\n System.gc();\n }\n\n public boolean isBukkit() {\n return this.isBukkit;\n }\n\n public abstract @NotNull String getPlatform();\n\n public abstract @NotNull String getVersion();\n\n public @NotNull String getVersionCommit() {\n if (this.commit == null) {\n this.commit = this.manifestAttributes.getValue(\"Git-Commit\");\n if (this.commit == null) {\n this.commit = \"unknown\";\n }\n }\n return this.commit;\n }\n\n public abstract int getMaxPlayers();\n\n public abstract boolean getOnlineMode();\n\n public abstract String getServerVersion();\n\n public abstract @NotNull AudienceProvider adventure();\n\n public abstract @NotNull Path getMainDir();\n\n public abstract @NotNull Path getJarPath();\n\n public abstract int getColorForPower(byte power);\n\n public abstract @Nullable Block getFlower(@NotNull World world, @NotNull Biome biome, int blockX, int blockY, int blockZ);\n\n protected abstract void loadBlocks();\n\n protected abstract void loadWorlds();\n\n protected abstract void loadPlayers();\n\n public abstract @NotNull World cloneWorld(@NotNull World world);\n\n protected static final class Provider {\n static Pl3xMap api;\n\n static @NotNull Pl3xMap api() {\n return Provider.api;\n }\n }\n\n public static final class ThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory {\n private final String name;\n private final int threads;\n\n private final AtomicInteger id = new AtomicInteger();\n\n public ThreadFactory(@NotNull String name, int threads) {\n this.name = name;\n this.threads = threads;\n }\n\n public static @NotNull ExecutorService createService(@NotNull String name) {\n return createService(new ThreadFactory(name, 1));\n }\n\n public static @NotNull ExecutorService createService(@NotNull String name, int threads) {\n int max = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);\n int parallelism = Mathf.clamp(1, max, threads < 1 ? max : threads);\n return createService(new ThreadFactory(name, parallelism));\n }\n\n private static @NotNull ExecutorService createService(@NotNull ThreadFactory factory) {\n return new ForkJoinPool(factory.threads, factory, null, false);\n }\n\n @Override\n public @NotNull ForkJoinWorkerThread newThread(@NotNull ForkJoinPool pool) {\n ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);\n // use current classloader, this fixes ClassLoading issues with forge\n thread.setContextClassLoader(Pl3xMap.class.getClassLoader());\n thread.setName(this.threads > 1 ? String.format(\"%s-%d\", this.name, this.id.getAndIncrement()) : this.name);\n return thread;\n }\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/scheduler/Task.java\npublic abstract class Task implements Runnable {\n final int delay;\n final boolean repeat;\n\n boolean cancelled = false;\n int tick;\n\n /**\n * Creates a new schedulable task.\n *\n * @param delay Delay (in seconds) before task starts\n */\n public Task(int delay) {\n this(delay, false);\n }\n\n /**\n * Creates a new schedulable task.\n *\n * @param delay Delay (in seconds) before task starts\n * @param repeat Whether this task should repeat\n */\n public Task(int delay, boolean repeat) {\n this.delay = delay;\n this.repeat = repeat;\n }\n\n /**\n * Mark task as cancelled.\n */\n public void cancel() {\n this.cancelled = true;\n }\n\n /**\n * Check if task is marked as cancelled.\n *\n * @return True if cancelled\n */\n public boolean cancelled() {\n return this.cancelled;\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/configuration/Lang.java\n@SuppressWarnings(\"CanBeFinal\")\npublic final class Lang extends AbstractConfig {\n @Key(\"prefix.command\")\n public static String PREFIX_COMMAND = \"[Pl3xMap] \";\n @Key(\"command.base\")\n public static String COMMAND_BASE = \"View the map at ''>'\";\n\n @Key(\"command.event.click-for-help\")\n public static String CLICK_FOR_HELP = \"Click for help\";\n @Key(\"command.event.click-to-confirm\")\n public static String CLICK_TO_CONFIRM = \"Click to confirm\";\n\n @Key(\"httpd.started.success\")\n public static String HTTPD_STARTED = \"Internal webserver running on :\";\n @Key(\"httpd.started.error\")\n public static String HTTPD_START_ERROR = \"Internal webserver could not start\";\n @Key(\"httpd.stopped.success\")\n public static String HTTPD_STOPPED = \"Internal webserver stopped\";\n @Key(\"httpd.stopped.error\")\n public static String HTTPD_STOP_ERROR = \"An error occurred with the internal webserver\";\n @Key(\"httpd.disabled\")\n public static String HTTPD_DISABLED = \"Internal webserver is disabled\";\n\n @Key(\"progress.eta.unknown\")\n public static String PROGRESS_ETA_UNKNOWN = \"Unknown\";\n\n @Key(\"command.argument.optional-player\")\n public static String COMMAND_ARGUMENT_OPTIONAL_PLAYER_DESCRIPTION = \"Defaults to the executing player if unspecified (console must specify a player)\";\n @Key(\"command.argument.optional-center\")\n public static String COMMAND_ARGUMENT_OPTIONAL_CENTER_DESCRIPTION = \"Defaults to (0, 0) if unspecified\";\n @Key(\"command.argument.optional-zoom\")\n public static String COMMAND_ARGUMENT_OPTIONAL_ZOOM_DESCRIPTION = \"Map zoom level\";\n @Key(\"command.argument.required-renderer\")\n public static String COMMAND_ARGUMENT_REQUIRED_RENDERER_DESCRIPTION = \"Renderer is required\";\n @Key(\"command.argument.required-world\")\n public static String COMMAND_ARGUMENT_REQUIRED_WORLD_DESCRIPTION = \"World is required\";\n\n @Key(\"command.confirm.description\")\n public static String COMMAND_CONFIRM_DESCRIPTION = \"Confirm a pending command\";\n @Key(\"command.confirm.not-rendering\")\n public static String COMMAND_CONFIRM_CONFIRMATION_REQUIRED_MESSAGE = \"Confirmation required. Confirm using /map confirm\";\n @Key(\"command.confirm.success\")\n public static String COMMAND_CONFIRM_NO_PENDING_MESSAGE = \"You don't have any pending confirmations\";\n\n @Key(\"command.fullrender.description\")\n public static String COMMAND_FULLRENDER_DESCRIPTION = \"Fully render a world\";\n @Key(\"command.fullrender.starting\")\n public static String COMMAND_FULLRENDER_STARTING = \"Full render starting. Check /map status for more info\";\n\n @Key(\"command.help.description\")\n public static String COMMAND_HELP_DESCRIPTION = \"Get help for Pl3xmap commands\";\n @Key(\"command.help.argument.query\")\n public static String COMMAND_HELP_ARGUMENT_QUERY_DESCRIPTION = \"Help Query\";\n\n @Key(\"command.hide.description\")\n public static String COMMAND_HIDE_DESCRIPTION = \"Hide a player from the map\";\n @Key(\"command.hide.already-hidden\")\n public static String COMMAND_HIDE_ALREADY_HIDDEN = \" is already hidden from the map\";\n @Key(\"command.hide.success\")\n public static String COMMAND_HIDE_SUCCESS = \" is now hidden from the map\";\n\n @Key(\"command.pause.description\")\n public static String COMMAND_PAUSE_DESCRIPTION = \"Toggle the pause state of renderers\";\n @Key(\"command.pause.paused\")\n public static String COMMAND_PAUSE_PAUSED = \"Renderers are now paused\";\n @Key(\"command.pause.unpaused\")\n public static String COMMAND_PAUSE_UNPAUSED = \"Renderers are now unpaused\";\n\n @Key(\"command.radiusrender.description\")\n public static String COMMAND_RADIUSRENDER_DESCRIPTION = \"Render a section of a world\";\n @Key(\"command.radiusrender.starting\")\n public static String COMMAND_RADIUSRENDER_STARTING = \"Radius render starting. Check /map status for more info\";\n\n @Key(\"command.reload.description\")\n public static String COMMAND_RELOAD_DESCRIPTION = \"Reloads the plugin\";\n @Key(\"command.reload.success\")\n public static String COMMAND_RELOAD_SUCCESS = \"Pl3xMap v reloaded\";\n\n @Key(\"command.resetmap.description\")\n public static String COMMAND_RESETMAP_DESCRIPTION = \"Cancel active render of a world\";\n @Key(\"command.resetmap.begin\")\n public static String COMMAND_RESETMAP_BEGIN = \"Map reset for has begun\";\n @Key(\"command.resetmap.success\")\n public static String COMMAND_RESETMAP_SUCCESS = \"Successfully reset map for \";\n @Key(\"command.resetmap.failed\")\n public static String COMMAND_RESETMAP_FAILED = \"Could not reset map for \";\n\n @Key(\"command.show.description\")\n public static String COMMAND_SHOW_DESCRIPTION = \"Show a player on the map\";\n @Key(\"command.show.not-hidden\")\n public static String COMMAND_SHOW_NOT_HIDDEN = \" is not hidden from the map\";\n @Key(\"command.show.success\")\n public static String COMMAND_SHOW_SUCCESS = \" is no longer hidden from the map\";\n\n @Key(\"command.status.description\")\n public static String COMMAND_STATUS_DESCRIPTION = \"View the render status\";\n\n @Key(\"command.stitch.description\")\n public static String COMMAND_STITCH_DESCRIPTION = \"Stitches tiles into one image\";\n @Key(\"command.stitch.missing-directory\")\n public static String COMMAND_STITCH_MISSING_DIRECTORY = \"Unable to find tiles directory.\";\n @Key(\"command.stitch.error-reading-directory\")\n public static String COMMAND_STITCH_ERROR_READING_DIRECTORY = \"There was a problem reading the tiles directory.\";\n @Key(\"command.stitch.empty-directory\")\n public static String COMMAND_STITCH_EMPTY_DIRECTORY = \"There are no tiles to stitch.\";\n @Key(\"command.stitch.starting\")\n public static String COMMAND_STITCH_STARTING = \"Started stitching tiles..\\n(min: , max: , size: ,)\";\n @Key(\"command.stitch.finished\")\n public static String COMMAND_STITCH_FINISHED = \"Finished stitching tiles!\\nYou can find it at /tiles//stitched/\";\n\n @Key(\"command.version.description\")\n public static String COMMAND_VERSION_DESCRIPTION = \"Get version information\";\n @Key(\"command.version.please-wait\")\n public static String COMMAND_VERSION_PLEASE_WAIT = \"Checking version, please wait...\";\n @Key(\"command.version.still-checking\")\n public static String COMMAND_VERSION_STILL_CHECKING = \"Still checking...\";\n @Key(\"command.version.error.not-array\")\n public static String COMMAND_VERSION_ERROR_NOT_ARRAY = \"Error: response not an array\";\n @Key(\"command.version.error.corrupt-json\")\n public static String COMMAND_VERSION_ERROR_CORRUPT_JSON = \"Error: response is corrupt json\";\n @Key(\"command.version.error.unknown-version\")\n public static String COMMAND_VERSION_ERROR_UNKNOWN_VERSION = \"Error: response has unknown version\";\n @Key(\"command.version.error.unable-to-determine\")\n public static String COMMAND_VERSION_ERROR_UNABLE_TO_DETERMINE = \"Error: Unable to determine latest build\";\n @Key(\"command.version.success\")\n public static String COMMAND_VERSION_SUCCESS = \"Pl3xMap v3 () git-\";\n @Key(\"command.version.snapshot\")\n public static String COMMAND_VERSION_SNAPSHOT = \"You are running a snapshot\";\n @Key(\"command.version.latest-build-is\")\n public static String COMMAND_VERSION_LATEST_BUILD_IS = \"Latest build is \";\n @Key(\"command.version.running-latest-build\")\n public static String COMMAND_VERSION_RUNNING_LATEST_BUILD = \"You are running the latest build.\";\n @Key(\"command.version.builds-behind\")\n public static String COMMAND_VERSION_BUILDS_BEHIND = \"You are builds behind.\";\n @Key(\"command.version.download\")\n public static String COMMAND_VERSION_DOWNLOAD = \"Download new build at: \";\n @Key(\"command.version.time-traveler\")\n public static String COMMAND_VERSION_TIME_TRAVELER = \"Are you a time traveler?\";\n\n @Key(\"error.must-specify-player\")\n public static String ERROR_MUST_SPECIFY_PLAYER = \"You must specify the player\";\n @Key(\"error.no-such-player\")\n public static String ERROR_NO_SUCH_PLAYER = \"No such player \";\n @Key(\"error.must-specify-renderer\")\n public static String ERROR_MUST_SPECIFY_RENDERER = \"You must specify the renderer\";\n @Key(\"error.no-such-renderer\")\n public static String ERROR_NO_SUCH_RENDERER = \"No such renderer \";\n @Key(\"error.must-specify-world\")\n public static String ERROR_MUST_SPECIFY_WORLD = \"You must specify the world\";\n @Key(\"error.no-such-world\")\n public static String ERROR_NO_SUCH_WORLD = \"No such world \";\n @Key(\"error.world-disabled\")\n public static String ERROR_WORLD_DISABLED = \"Pl3xMap is disabled for world \";\n @Key(\"error.not-valid-zoom-level\")\n public static String ERROR_NOT_VALID_ZOOM_LEVEL = \"Not a valid zoom level\";\n @Key(\"error.point-invalid-format\")\n public static String ERROR_POINT_INVALID_FORMAT = \"'' is not a valid location. Required format is ' '\";\n\n @Key(\"ui.layer.players\")\n public static String UI_LAYER_PLAYERS = \"Players\";\n @Key(\"ui.layer.spawn\")\n public static String UI_LAYER_SPAWN = \"Spawn\";\n @Key(\"ui.layer.worldborder\")\n public static String UI_LAYER_WORLDBORDER = \"World Border\";\n\n @Key(\"ui.title\")\n public static String UI_TITLE = \"Pl3xMap\";\n @Key(\"ui.block-and-biome-lang-file\")\n public static String UI_BLOCK_AND_BIOME_LANG_FILE = \"en_us.json\";\n @Key(\"ui.blockinfo.label\")\n public static String UI_BLOCKINFO_LABEL = \"BlockInfo\";\n @Key(\"ui.blockinfo.value\")\n public static String UI_BLOCKINFO_VALUE = \"
\";\n @Key(\"ui.coords.label\")\n public static String UI_COORDS_LABEL = \"Coordinates\";\n @Key(\"ui.coords.value\")\n public static String UI_COORDS_VALUE = \", , \";\n @Key(\"ui.link.label\")\n public static String UI_LINK_LABEL = \"Sharable Link\";\n @Key(\"ui.link.value\")\n public static String UI_LINK_VALUE = \"\";\n @Key(\"ui.markers.label\")\n public static String UI_MARKERS_LABEL = \"Markers\";\n @Key(\"ui.markers.value\")\n public static String UI_MARKERS_VALUE = \"No markers have been configured\";\n @Key(\"ui.players.label\")\n public static String UI_PLAYERS_LABEL = \"Players (/)\";\n @Key(\"ui.players.value\")\n public static String UI_PLAYERS_VALUE = \"No players are currently online\";\n @Key(\"ui.worlds.label\")\n public static String UI_WORLDS_LABEL = \"Worlds\";\n @Key(\"ui.worlds.value\")\n public static String UI_WORLDS_VALUE = \"No worlds have been configured\";\n @Key(\"ui.layers.label\")\n public static String UI_LAYERS_LABEL = \"Layers\";\n @Key(\"ui.layers.value\")\n public static String UI_LAYERS_VALUE = \"No layers have been configured\";\n\n private static final Lang CONFIG = new Lang();\n\n public static void reload() {\n Path localeDir = Pl3xMap.api().getMainDir().resolve(\"locale\");\n\n // extract locale dir from jar\n FileUtil.extractDir(\"/locale/\", localeDir, false);\n\n CONFIG.reload(localeDir.resolve(Config.LANGUAGE_FILE), Lang.class);\n }\n\n public static @NotNull Component parse(@NotNull String msg, @NotNull TagResolver.@NotNull Single... placeholders) {\n return MiniMessage.miniMessage().deserialize(msg, placeholders);\n }\n\n public static @NotNull String strip(@NotNull String msg) {\n return MiniMessage.miniMessage().stripTags(msg);\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/configuration/WorldConfig.java\n@SuppressWarnings(\"CanBeFinal\")\npublic final class WorldConfig extends AbstractConfig {\n @Key(\"enabled\")\n @Comment(\"\"\"\n Enables this world to be rendered on the map.\"\"\")\n public boolean ENABLED = true;\n\n @Key(\"render.renderers\")\n @Comment(\"\"\"\n Renderers to use. Each renderer will render a different\n type of map. The built-in renderers include:\n vintage_story, basic, biomes, flowermap, inhabited, night, and vanilla\"\"\")\n public Map<@NotNull String, @NotNull String> RENDER_RENDERERS = new LinkedHashMap<>() {{\n put(\"vintage_story\", \"overworld_basic\");\n }};\n\n @Key(\"render.biome-blend\")\n @Comment(\"\"\"\n Enables blending of biome grass/foliage/water colors similar to\n the client's biome blending option.\n Values are clamped to 0-7\"\"\")\n public int RENDER_BIOME_BLEND = 3;\n\n @Key(\"render.skylight\")\n @Comment(\"\"\"\n World skylight value. This is used for the day/night cycle\n map (not yet implemented) .Values are clamped to 0-15\n with 0 being darkest and 15 being full bright.\"\"\")\n public int RENDER_SKYLIGHT = 15;\n\n @Key(\"render.translucent-fluids\")\n @Comment(\"\"\"\n Enable translucent fluids.\n This will make the fluids look fancier and translucent,\n so you can see the blocks below in shallow fluids.\"\"\")\n public boolean RENDER_TRANSLUCENT_FLUIDS = true;\n\n @Key(\"render.translucent-glass\")\n @Comment(\"\"\"\n Enable translucent glass.\n This will make the glass look fancier and translucent,\n so you can see the blocks below.\"\"\")\n public boolean RENDER_TRANSLUCENT_GLASS = true;\n\n @Key(\"render.heightmap-type\")\n @Comment(\"\"\"\n Type of heightmap to render.\n NONE has no heightmap drawn.\n EVEN_ODD makes every other Y layer darker, like Dynmap.\n HIGH_CONTRAST same as MODERN, but darker.\n LOW_CONTRAST same as MODERN, but lighter.\n MODERN is a clearer, more detailed view.\n OLD_SCHOOL is the old type from v1.\n VANILLA matches the in-game vanilla maps.\n EVEN_ODD_HIGH_CONTRAST mix of EVEN_ODD and HIGH_CONTRAST.\n EVEN_ODD_LOW_CONTRAST mix of EVEN_ODD and LOW_CONTRAST.\n EVEN_ODD_MODERN mix of EVEN_ODD and MODERN.\n EVEN_ODD_OLD_SCHOOL mix of EVEN_ODD and OLD_SCHOOL.\n EVEN_ODD_VANILLA mix of EVEN_ODD and VANILLA.\"\"\")\n public String RENDER_HEIGHTMAP_TYPE = \"MODERN\";\n\n @Key(\"ui.display-name\")\n @Comment(\"\"\"\n The display name of the world in the world list.\n Use to use the official world name.\"\"\")\n public String DISPLAY_NAME = \"\";\n\n @Key(\"ui.order\")\n @Comment(\"\"\"\n The order of the world in the world list\"\"\")\n public int ORDER = 0;\n\n @Key(\"ui.attribution\")\n @Comment(\"\"\"\n Shows the footer attributes\"\"\")\n public boolean UI_ATTRIBUTION = true;\n\n @Key(\"ui.blockinfo\")\n @Comment(\"\"\"\n The display position for the blockinfo box\"\"\")\n public String UI_BLOCKINFO = \"bottomleft\";\n\n @Key(\"ui.coords\")\n @Comment(\"\"\"\n The display position for the coordinates box\"\"\")\n public String UI_COORDS = \"bottomcenter\";\n\n @Key(\"ui.link\")\n @Comment(\"\"\"\n The display position for the link box\"\"\")\n public String UI_LINK = \"bottomright\";\n\n @Key(\"zoom.default\")\n @Comment(\"\"\"\n The default zoom when loading the map in browser.\n Normal sized tiles (1 pixel = 1 block) are\n always at zoom level 0.\"\"\")\n public int ZOOM_DEFAULT = 0;\n @Key(\"zoom.max-out\")\n @Comment(\"\"\"\n The maximum zoom out you can do on the map.\n Each additional level requires a new set of tiles\n to be rendered, so don't go too wild here.\"\"\")\n public int ZOOM_MAX_OUT = 3;\n @Key(\"zoom.max-in\")\n @Comment(\"\"\"\n Extra zoom in layers will stretch the original\n tile images so you can zoom in further without\n the extra cost of rendering more tiles.\"\"\")\n public int ZOOM_MAX_IN = 2;\n\n @Key(\"render.visible-areas\")\n @Comment(\"\"\"\n Visible areas of the world.\"\"\")\n public List VISIBLE_AREAS = new ArrayList<>(); // defaults added in ctor\n\n private final World world;\n\n public WorldConfig(@NotNull World world) {\n this.world = world;\n\n // we need an instance of the world to get the border\n VISIBLE_AREAS.add(new Border(world));\n\n reload();\n }\n\n public void reload() {\n reload(Pl3xMap.api().getMainDir().resolve(\"config.yml\"), WorldConfig.class);\n\n RENDER_BIOME_BLEND = Mathf.clamp(0, 7, RENDER_BIOME_BLEND);\n RENDER_SKYLIGHT = Mathf.clamp(0, 15, RENDER_SKYLIGHT);\n }\n\n @Override\n protected @NotNull Object getClassObject() {\n return this;\n }\n\n @Override\n protected @Nullable Object getValue(@NotNull String path, @Nullable Object def) {\n if (getConfig().get(\"world-settings.default.\" + path) == null) {\n set(\"world-settings.default.\" + path, def);\n }\n return get(\"world-settings.\" + this.world.getName() + \".\" + path,\n get(\"world-settings.default.\" + path, def));\n }\n\n @Override\n protected void setComment(@NotNull String path, @Nullable String comment) {\n getConfig().setComment(\"world-settings.default.\" + path, comment);\n }\n\n @Override\n protected @Nullable Object get(@NotNull String path) {\n if (!path.contains(\"render.visible-areas\")) {\n return super.get(path);\n }\n Object value = getConfig().get(path);\n if (!(value instanceof List)) {\n return value;\n }\n @SuppressWarnings(\"unchecked\")\n List> list = (List>) value;\n List areas = new ArrayList<>();\n for (Map map : list) {\n areas.add(Area.deserialize(this.world, map));\n }\n return areas;\n }\n\n @Override\n protected void set(@NotNull String path, @Nullable Object value) {\n if (value != null && path.contains(\"render.visible-areas\")) {\n @SuppressWarnings(\"unchecked\")\n List list = (List) value;\n value = list.stream().map(Area::serialize).toList();\n }\n getConfig().set(path, value);\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/configuration/Config.java\n@SuppressWarnings(\"CanBeFinal\")\npublic final class Config extends AbstractConfig {\n @Key(\"settings.debug-mode\")\n @Comment(\"\"\"\n Extra logger/console output. (can be spammy)\"\"\")\n public static boolean DEBUG_MODE = false;\n\n @Key(\"settings.language-file\")\n @Comment(\"\"\"\n The language file to use from the locale folder.\"\"\")\n public static String LANGUAGE_FILE = \"lang-en.yml\";\n\n @Key(\"settings.web-address\")\n @Comment(\"\"\"\n Set the web address players use to connect to your map. This\n is only used for the client mod to know where to connect.\"\"\")\n public static String WEB_ADDRESS = \"http://localhost:8080\";\n\n @Key(\"settings.web-directory.path\")\n @Comment(\"\"\"\n The directory that houses the website and world tiles.\n This is a relative path from Pl3xMap's plugin directory,\n unless it starts with / in which case it will be treated\n as an absolute path.\"\"\")\n public static String WEB_DIR = \"web/\";\n @Key(\"settings.web-directory.read-only\")\n @Comment(\"\"\"\n Set to true if you don't want Pl3xMap to overwrite\n the website files on startup. (Good for servers that\n customize these files)\n Note: Be sure this is false when upgrading.\"\"\")\n public static boolean WEB_DIR_READONLY = false;\n @Key(\"settings.web-directory.tile-format\")\n @Comment(\"\"\"\n The image format for tile images.\n Built in types: bmp, gif, jpg, jpeg, png\"\"\")\n public static String WEB_TILE_FORMAT = \"png\";\n @Key(\"settings.web-directory.tile-quality\")\n @Comment(\"\"\"\n The quality for image tiles (0.0 - 1.0)\n 0.0 is low quality, high compression, small file size\n 1.0 is high quality, no compression, large file size\n Note: Not all image formats honor this setting.\"\"\")\n public static double WEB_TILE_QUALITY = 0.0D;\n\n @Key(\"settings.map.zoom.snap\")\n @Comment(\"\"\"\n Forces the map's zoom level to always be a multiple of this.\n By default, the zoom level snaps to the nearest integer; lower\n values (e.g. 0.5 or 0.1) allow for greater granularity. A\n value of 0 means the zoom level will not be snapped.\"\"\")\n public static double MAP_ZOOM_SNAP = 0.25D;\n @Key(\"settings.map.zoom.delta\")\n @Comment(\"\"\"\n Controls how much the map's zoom level will change after a zoom in,\n zoom out, pressing + or - on the keyboard, or using the zoom controls.\n Values smaller than 1 (e.g. 0.5) allow for greater granularity.\"\"\")\n public static double MAP_ZOOM_DELTA = 0.25D;\n @Key(\"settings.map.zoom.wheel\")\n @Comment(\"\"\"\n How many scroll pixels (as reported by L.DomEvent.getWheelDelta) mean\n a change of one full zoom level. Smaller values will make wheel-zooming\n faster (and vice versa).\"\"\")\n public static int MAP_ZOOM_WHEEL = 120;\n\n @Key(\"settings.internal-webserver.enabled\")\n @Comment(\"\"\"\n Enable the built-in web server.\n Disable this if you want to use a standalone web server\n such as apache or nginx.\"\"\")\n public static boolean HTTPD_ENABLED = true;\n @Key(\"settings.internal-webserver.bind\")\n @Comment(\"\"\"\n The interface the built-in web server should bind to.\n This is NOT always the same as your public facing IP.\n If you don't understand what this is,\n leave it set to 0.0.0.0\"\"\")\n public static String HTTPD_BIND = \"0.0.0.0\";\n @Key(\"settings.internal-webserver.port\")\n @Comment(\"\"\"\n The port the built-in web server listens to.\n Make sure the port is allocated if using Pterodactyl.\"\"\")\n public static int HTTPD_PORT = 8080;\n @Key(\"settings.internal-webserver.follow-symlinks\")\n @Comment(\"\"\"\n Allows the built-in web server to follow symlinks.\n It is generally advised against enabling this,\n for security reasons. But you do you, boo boo.\"\"\")\n public static boolean HTTPD_FOLLOW_SYMLINKS = false;\n\n @Key(\"settings.performance.render-threads\")\n @Comment(\"\"\"\n The number of process-threads to use for loading and scanning chunks.\n Value of -1 will use 50% of the available cpu-threads. (recommended)\"\"\")\n public static int RENDER_THREADS = -1;\n\n @Key(\"settings.performance.gc.when-finished\")\n @Comment(\"\"\"\n Runs the JVM GC after a render job stops to free up memory immediately.\"\"\")\n public static boolean GC_WHEN_FINISHED = true;\n\n @Key(\"settings.performance.gc.when-running\")\n @Comment(\"\"\"\n Runs the JVM GC aggressively while a render is running\n CAUTION: this _will_ slow down your renders!\"\"\")\n public static boolean GC_WHEN_RUNNING = false;\n\n private static final Config CONFIG = new Config();\n\n public static void reload() {\n Path mainDir = Pl3xMap.api().getMainDir();\n\n // extract default config from jar\n FileUtil.extractFile(Config.class, \"config.yml\", mainDir, false);\n\n CONFIG.reload(mainDir.resolve(\"config.yml\"), Config.class);\n\n if (!Pl3xMap.api().isBukkit()) {\n tryRenamePath(\"world-settings.world\", \"world-settings.minecraft:overworld\");\n tryRenamePath(\"world-settings.world_nether\", \"world-settings.minecraft:the_nether\");\n tryRenamePath(\"world-settings.world_the_end\", \"world-settings.minecraft:the_end\");\n }\n }\n\n private static void tryRenamePath(String oldPath, String newPath) {\n YamlFile config = CONFIG.getConfig();\n Object oldValue = config.get(oldPath);\n if (oldValue == null) {\n return; // old default doesn't exist; do nothing\n }\n if (config.get(newPath) != null) {\n return; // new default already set; do nothing\n }\n config.set(newPath, oldValue);\n config.set(oldPath, null);\n CONFIG.save();\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/image/io/IO.java\npublic abstract class IO {\n private static final Registry<@NotNull Type> TYPES = new Registry<>();\n\n public static void register() {\n IO.register(\"bmp\", new Bmp());\n IO.register(\"gif\", new Gif());\n IO.register(\"jpg\", new Jpg());\n IO.register(\"jpeg\", get(\"jpg\"));\n IO.register(\"png\", new Png());\n }\n\n public static void register(@NotNull String name, @NotNull Type type) {\n if (TYPES.has(name)) {\n throw new IllegalStateException(String.format(\"IO type %s already registered\", name));\n }\n TYPES.register(name, type);\n }\n\n public static void unregister() {\n TYPES.unregister();\n }\n\n public static void unregister(@NotNull String name) {\n TYPES.unregister(name);\n }\n\n public static @NotNull Type get(@NotNull String format) {\n Type type = TYPES.get(format.toLowerCase(Locale.ROOT));\n if (type == null) {\n throw new IllegalStateException(\"Unknown or unsupported image format\");\n }\n return type;\n }\n\n public abstract static class Type extends Keyed {\n public Type(@NotNull String key) {\n super(key);\n }\n\n public @NotNull BufferedImage createBuffer() {\n return new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);\n }\n\n public int color(int argb) {\n return argb;\n }\n\n public @Nullable BufferedImage read(@NotNull Path path) {\n BufferedImage buffer = null;\n ImageReader reader = null;\n try (ImageInputStream in = ImageIO.createImageInputStream(Files.newInputStream(path))) {\n reader = ImageIO.getImageReadersBySuffix(getKey()).next();\n reader.setInput(in, false, true);\n buffer = reader.read(0);\n in.flush();\n } catch (IOException e) {\n Logger.warn(\"Could not read tile image: \" + path);\n e.printStackTrace();\n } finally {\n if (reader != null) {\n reader.dispose();\n }\n }\n return buffer;\n }\n\n public void write(@NotNull Path path, @NotNull BufferedImage buffer) {\n Path tmp = FileUtil.tmp(path);\n ImageWriter writer = null;\n try (ImageOutputStream out = ImageIO.createImageOutputStream(tmp.toFile())) {\n writer = ImageIO.getImageWritersBySuffix(getKey()).next();\n ImageWriteParam param = writer.getDefaultWriteParam();\n if (param.canWriteCompressed()) {\n param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n if (param.getCompressionType() == null) {\n param.setCompressionType(param.getCompressionTypes()[0]);\n }\n param.setCompressionQuality((float) Config.WEB_TILE_QUALITY);\n }\n writer.setOutput(out);\n writer.write(null, new IIOImage(buffer, null, null), param);\n out.flush();\n } catch (IOException e) {\n Logger.warn(\"Could not write tile image: \" + tmp);\n e.printStackTrace();\n } finally {\n if (writer != null) {\n writer.dispose();\n }\n }\n try {\n FileUtil.atomicMove(tmp, path);\n } catch (IOException e) {\n Logger.warn(\"Could not write tile image: \" + path);\n e.printStackTrace();\n }\n }\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/configuration/PlayersLayerConfig.java\n@SuppressWarnings(\"CanBeFinal\")\npublic final class PlayersLayerConfig extends AbstractConfig {\n @Key(\"settings.enabled\")\n @Comment(\"\"\"\n Show online players on the map and sidebar.\"\"\")\n public static boolean ENABLED = true;\n\n @Key(\"settings.hide.invisible\")\n @Comment(\"\"\"\n Should invisible players be hidden from the map.\"\"\")\n public static boolean HIDE_INVISIBLE = true;\n\n @Key(\"settings.hide.spectators\")\n @Comment(\"\"\"\n Should spectators be hidden from the map.\"\"\")\n public static boolean HIDE_SPECTATORS = true;\n\n @Key(\"settings.layer.update-interval\")\n @Comment(\"\"\"\n How often (in seconds) to update the marker.\n Setting to 0 is the same as setting it to 1.\"\"\")\n public static int UPDATE_INTERVAL = 0;\n @Key(\"settings.layer.show-controls\")\n @Comment(\"\"\"\n Whether the players layer control shows up in the layers list or not.\"\"\")\n public static boolean SHOW_CONTROLS = true;\n @Key(\"settings.layer.default-hidden\")\n @Comment(\"\"\"\n Whether the players layer should be hidden (toggled off) by default.\"\"\")\n public static boolean DEFAULT_HIDDEN = false;\n @Key(\"settings.layer.priority\")\n @Comment(\"\"\"\n Priority order players layer shows up in the layers list.\n (lower values = higher in the list)\"\"\")\n public static int PRIORITY = 20;\n @Key(\"settings.layer.z-index\")\n @Comment(\"\"\"\n Z-Index order players layer shows up in the map.\n (higher values are drawn on top of lower values)\"\"\")\n public static int Z_INDEX = 999;\n\n @Key(\"settings.icon\")\n @Comment(\"\"\"\n The player icon.\n Icon must be in the web/images/icon/ directory.\"\"\")\n public static String ICON = \"players\";\n\n @Key(\"settings.tooltip\")\n @Comment(\"\"\"\n Tooltip for player markers.\n Variables: uuid, name, decoratedName, health, armor\"\"\")\n public static String TOOLTIP = \"\"\"\n
    \n
  • <name>
  • \n
  • \n \n Health <health>\n Armor <armor>\n
  • \n
\"\"\";\n\n @Key(\"settings.pane\")\n @Comment(\"\"\"\n The custom pane layer for the player tracker.\n This is used to make custom css styled tooltips.\n (see css setting below)\"\"\")\n public static String PANE = \"nameplates\";\n\n @Key(\"settings.css\")\n @Comment(\"\"\"\n Custom css for players marker layer.\n Class names use the pane name set above.\"\"\")\n public static String CSS = \"\"\"\n div.leaflet-nameplates-pane div img.head {\n image-rendering: pixelated;\n image-rendering: -moz-crisp-edges;\n -ms-interpolation-mode: nearest-neighbor;\n }\n div.leaflet-nameplates-pane div {\n margin: 0;\n padding: 0;\n color: #ffffff;\n font-weight: 700;\n line-height: 1rem;\n background: rgba(0, 0, 0, 0.5);\n border-color: rgba(0, 0, 0, 0.75);\n }\n div.leaflet-nameplates-pane div ul {\n padding: 3px;\n }\n div.leaflet-nameplates-pane div:before {\n border-color: transparent;\n }\n div.leaflet-nameplates-pane div img.head {\n vertical-align: middle;\n width: 32px;\n height: 32px;\n border-radius: 5px;\n border: 1px solid black;\n }\n div.leaflet-nameplates-pane div img.health {\n margin-top: 3px;\n }\n div.leaflet-nameplates-pane div img.armor,\n div.leaflet-nameplates-pane div img.health {\n display: block;\n width: 81px;\n height: 9px;\n background-position: 0 0;\n }\n div.leaflet-nameplates-pane div img.armor {\n background: url('images/armor.png') no-repeat;\n }\n div.leaflet-nameplates-pane div img.health {\n background: url('images/health.png') no-repeat;\n }\n div.leaflet-nameplates-pane div,\n div.leaflet-marker-pane img {\n transition: all 0.25s;\n }\"\"\";\n\n private static final PlayersLayerConfig CONFIG = new PlayersLayerConfig();\n\n public static void reload() {\n CONFIG.reload(Pl3xMap.api().getMainDir().resolve(\"layers/players.yml\"), PlayersLayerConfig.class);\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/world/World.java\npublic abstract class World extends Keyed {\n public static final PathMatcher JSON_MATCHER = FileSystems.getDefault().getPathMatcher(\"glob:**/*.json\");\n public static final PathMatcher MCA_MATCHER = FileSystems.getDefault().getPathMatcher(\"glob:**/r.*.*.mca\");\n public static final PathMatcher PNG_MATCHER = FileSystems.getDefault().getPathMatcher(\"glob:**/*_*.png\");\n\n private final Path customMarkersDirectory;\n private final Path markersDirectory;\n private final Path regionDirectory;\n private final Path tilesDirectory;\n private final WorldConfig worldConfig;\n\n private final long seed;\n private final Point spawn;\n private final Type type;\n\n private final BiomeManager biomeManager;\n private final BiomeRegistry biomeRegistry;\n private final Registry<@NotNull Layer> layerRegistry;\n\n private final LoadingCache<@NotNull Long, @NotNull Region> regionCache;\n private final RegionModifiedState regionModifiedState;\n //private final RegionFileWatcher regionFileWatcher;\n private final UpdateMarkerData markerTask;\n private final Map<@NotNull String, Renderer.@NotNull Builder> renderers = new LinkedHashMap<>();\n\n public World(@NotNull String name, long seed, @NotNull Point spawn, @NotNull Type type, @NotNull Path regionDirectory) {\n super(name);\n\n this.seed = seed;\n this.spawn = spawn;\n this.type = type;\n\n String safeNameForDirectories = name.replace(\":\", \"-\");\n\n this.regionDirectory = regionDirectory;\n this.tilesDirectory = FileUtil.getTilesDir().resolve(safeNameForDirectories);\n this.customMarkersDirectory = Pl3xMap.api().getMainDir().resolve(\"markers\").resolve(safeNameForDirectories);\n this.markersDirectory = getTilesDirectory().resolve(\"markers\");\n\n FileUtil.createDirs(this.regionDirectory);\n FileUtil.createDirs(this.tilesDirectory);\n FileUtil.createDirs(this.customMarkersDirectory);\n FileUtil.createDirs(this.markersDirectory);\n\n this.worldConfig = new WorldConfig(this);\n\n this.biomeManager = new BiomeManager(hashSeed(getSeed()));\n this.biomeRegistry = new BiomeRegistry();\n this.layerRegistry = new Registry<>();\n\n this.regionCache = Caffeine.newBuilder()\n .expireAfterWrite(1, TimeUnit.MINUTES)\n .maximumSize(100)\n .build(this::loadRegion);\n\n this.regionModifiedState = new RegionModifiedState(this);\n //this.regionFileWatcher = new RegionFileWatcher(this);\n this.markerTask = new UpdateMarkerData(this);\n }\n\n protected void init() {\n if (!isEnabled()) {\n return;\n }\n\n getBiomeRegistry().init(this);\n\n //this.regionFileWatcher.start();\n\n getConfig().RENDER_RENDERERS.forEach((id, icon) -> {\n Renderer.Builder renderer = Pl3xMap.api().getRendererRegistry().get(id);\n if (renderer == null) {\n return;\n }\n Path path = FileUtil.getWebDir().resolve(\"images/icon/\" + icon + \".png\");\n try {\n IconImage image = new IconImage(icon, ImageIO.read(path.toFile()), \"png\");\n Pl3xMap.api().getIconRegistry().register(image);\n } catch (IOException e) {\n Logger.severe(\"Cannot load world renderer icon \" + path, e);\n }\n this.renderers.put(renderer.getKey(), renderer);\n });\n\n if (WorldBorderLayerConfig.ENABLED) {\n Logger.debug(\"Registering world border layer\");\n getLayerRegistry().register(WorldBorderLayer.KEY, new WorldBorderLayer(this));\n }\n\n if (SpawnLayerConfig.ENABLED) {\n Logger.debug(\"Registering spawn layer\");\n getLayerRegistry().register(SpawnLayer.KEY, new SpawnLayer(this));\n }\n\n if (PlayersLayerConfig.ENABLED) {\n Logger.debug(\"Registering player tracker layer\");\n getLayerRegistry().register(PlayersLayer.KEY, new PlayersLayer(this));\n }\n\n Logger.debug(\"Checking all region files\");\n Pl3xMap.api().getRegionProcessor().addRegions(this, listRegions(false));\n\n Logger.debug(\"Starting marker task\");\n Pl3xMap.api().getScheduler().addTask(1, true, this.markerTask);\n\n // load up custom markers\n Logger.debug(\"Loading custom markers for \" + getName());\n for (Path file : getCustomMarkerFiles()) {\n CustomLayer.load(this, file);\n }\n }\n\n public void cleanup() {\n this.regionCache.invalidateAll();\n getRegionModifiedState().save();\n }\n\n public @NotNull Path getCustomMarkersDirectory() {\n return this.customMarkersDirectory;\n }\n\n public @NotNull Path getMarkersDirectory() {\n return this.markersDirectory;\n }\n\n public @NotNull Path getRegionDirectory() {\n return this.regionDirectory;\n }\n\n public @NotNull Path getTilesDirectory() {\n return this.tilesDirectory;\n }\n\n public @NotNull WorldConfig getConfig() {\n return this.worldConfig;\n }\n\n public @NotNull RegionModifiedState getRegionModifiedState() {\n return this.regionModifiedState;\n }\n\n //public @NotNull RegionFileWatcher getRegionFileWatcher() {\n // return this.regionFileWatcher;\n //}\n\n public @NotNull UpdateMarkerData getMarkerTask() {\n return this.markerTask;\n }\n\n public @NotNull Map<@NotNull String, Renderer.@NotNull Builder> getRenderers() {\n return Collections.unmodifiableMap(this.renderers);\n }\n\n /**\n * Get whether this world is enabled.\n *\n * @return true if enabled\n */\n public boolean isEnabled() {\n return getConfig().ENABLED;\n }\n\n public @NotNull String getName() {\n return getKey();\n }\n\n public long getSeed() {\n return this.seed;\n }\n\n public @NotNull Point getSpawn() {\n return this.spawn;\n }\n\n public int getSkylight() {\n return getConfig().RENDER_SKYLIGHT;\n }\n\n /**\n * Get the world's type.\n *\n * @return world type\n */\n public @NotNull Type getType() {\n return this.type;\n }\n\n public @NotNull BiomeManager getBiomeManager() {\n return this.biomeManager;\n }\n\n public @NotNull BiomeRegistry getBiomeRegistry() {\n return this.biomeRegistry;\n }\n\n public @NotNull Registry getLayerRegistry() {\n return this.layerRegistry;\n }\n\n public abstract @NotNull T getLevel();\n\n public abstract long hashSeed(long seed);\n\n public abstract boolean hasCeiling();\n\n public abstract int getMinBuildHeight();\n\n public abstract int getMaxBuildHeight();\n\n public abstract int getLogicalHeight();\n\n public abstract double getBorderMinX();\n\n public abstract double getBorderMinZ();\n\n public abstract double getBorderMaxX();\n\n public abstract double getBorderMaxZ();\n\n public abstract @NotNull Collection<@NotNull Player> getPlayers();\n\n public boolean visibleBlock(int blockX, int blockZ) {\n for (Area area : getConfig().VISIBLE_AREAS) {\n if (area.containsBlock(blockX, blockZ)) {\n return true;\n }\n }\n return getConfig().VISIBLE_AREAS.isEmpty();\n }\n\n public boolean visibleChunk(int chunkX, int chunkZ) {\n for (Area area : getConfig().VISIBLE_AREAS) {\n if (area.containsChunk(chunkX, chunkZ)) {\n return true;\n }\n }\n return getConfig().VISIBLE_AREAS.isEmpty();\n }\n\n public boolean visibleRegion(int regionX, int regionZ) {\n for (Area area : getConfig().VISIBLE_AREAS) {\n if (area.containsRegion(regionX, regionZ)) {\n return true;\n }\n }\n return getConfig().VISIBLE_AREAS.isEmpty();\n }\n\n public @NotNull Chunk getChunk(@Nullable Region region, int chunkX, int chunkZ) {\n return getRegion(region, chunkX >> 5, chunkZ >> 5).getChunk(chunkX, chunkZ);\n }\n\n public @NotNull Region getRegion(@Nullable Region region, int regionX, int regionZ) {\n if (region != null && region.getX() == regionX && region.getZ() == regionZ) {\n return region;\n }\n return getRegion(Mathf.asLong(regionX, regionZ));\n }\n\n private @NotNull Region getRegion(long pos) {\n return this.regionCache.get(pos);\n }\n\n public void unloadRegion(int regionX, int regionZ) {\n unloadRegion(Mathf.asLong(regionX, regionZ));\n }\n\n private void unloadRegion(long pos) {\n this.regionCache.invalidate(pos);\n }\n\n public @NotNull Collection<@NotNull Path> getRegionFiles() {\n if (!Files.exists(getRegionDirectory())) {\n return Collections.emptySet();\n }\n try (Stream stream = Files.list(getRegionDirectory())) {\n return stream.filter(MCA_MATCHER::matches).toList();\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to list region files in directory '\" + getRegionDirectory().toAbsolutePath() + \"'\", e);\n }\n }\n\n public @NotNull Collection<@NotNull Path> getCustomMarkerFiles() {\n if (!Files.exists(getCustomMarkersDirectory())) {\n return Collections.emptySet();\n }\n try (Stream stream = Files.list(getCustomMarkersDirectory())) {\n return stream.filter(JSON_MATCHER::matches).toList();\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to list custom marker files in directory '\" + getCustomMarkersDirectory().toAbsolutePath() + \"'\", e);\n }\n }\n\n public @NotNull Collection<@NotNull Point> listRegions(boolean ignoreTimestamp) {\n return FileUtil.regionPathsToPoints(this, getRegionFiles(), ignoreTimestamp);\n }\n\n private @NotNull Region loadRegion(long pos) {\n int x = Mathf.longToX(pos);\n int z = Mathf.longToZ(pos);\n return new Region(this, x, z, getMCAFile(x, z));\n }\n\n private @NotNull Path getMCAFile(int regionX, int regionZ) {\n return getRegionDirectory().resolve(\"r.\" + regionX + \".\" + regionZ + \".mca\");\n }\n\n @Override\n public boolean equals(@Nullable Object o) {\n if (this == o) {\n return true;\n }\n if (o == null) {\n return false;\n }\n if (this.getClass() != o.getClass()) {\n return false;\n }\n World other = (World) o;\n return getLevel() == other.getLevel();\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getName());\n }\n\n @Override\n public abstract @NotNull String toString();\n\n /**\n * Represents a world's type.\n */\n public enum Type {\n OVERWORLD,\n NETHER,\n THE_END,\n CUSTOM;\n\n private final String name;\n\n Type() {\n this.name = name().toLowerCase(Locale.ROOT);\n }\n\n /**\n * Get the world type from a server level.\n *\n * @param dimension dimension name\n * @return world type\n */\n public static @NotNull Type get(@NotNull String dimension) {\n return switch (dimension) {\n case \"minecraft:overworld\" -> OVERWORLD;\n case \"minecraft:the_nether\" -> NETHER;\n case \"minecraft:the_end\" -> THE_END;\n default -> CUSTOM;\n };\n }\n\n @Override\n public @NotNull String toString() {\n return this.name;\n }\n }\n}", "answers": [" worldsList.put(\"name\", world.getName().replace(\":\", \"-\"));"], "length": 6250, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "62d0df99-e84f-4aa8-a15e-83fe0d9671b8", "reasoning": "In the parseWorlds method, after building each world's individual settings and the list of renderer entries, the code creates a new map called worldsList. The next logical step is to populate this map with the world's identifier and its renderers before adding it to the overall worldSettings list. The first entry to add is the world name (with colons replaced by hyphens) matching the naming used elsewhere. Hence the next line should put the name into worldsList.", "reasoning_model_answer": "worldsList.put(\"name\", world.getName().replace(\":\", \"-\"));", "assistant_with_reasoning": "\nIn the parseWorlds method, after building each world's individual settings and the list of renderer entries, the code creates a new map called worldsList. The next logical step is to populate this map with the world's identifier and its renderers before adding it to the overall worldSettings list. The first entry to add is the world name (with colons replaced by hyphens) matching the naming used elsewhere. Hence the next line should put the name into worldsList.\n\nworldsList.put(\"name\", world.getName().replace(\":\", \"-\"));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.637, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36731, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "worldsList.put(\"name\", world.getName().replace(\":\", \"-\"));", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.Serializable;\nimport java.util.Iterator;\nimport edu.uky.cs.nil.sabre.Utilities;\nimport edu.uky.cs.nil.sabre.logic.Comparison;\nimport edu.uky.cs.nil.sabre.logic.Value;\nimport edu.uky.cs.nil.sabre.util.ArrayIterator;\nimport edu.uky.cs.nil.sabre.util.Countable;", "context": "src/edu/uky/cs/nil/sabre/hg/CostSet.java\npackage edu.uky.cs.nil.sabre.hg;\n\n\n\n/**\n * A cost set is a collection of {@link Value values} where each is associated\n * with a numeric cost.\n * \n * @author Stephen G. Ware\n */\npublic interface CostSet extends Iterable, Serializable, Countable {\n\t\n\t/**\n\t * An individual {@link Value value}/cost pair in a {@link CostSet cost\n\t * set}. Cost set entries are {@link Comparable#compareTo(Object) naturally\n\t * ordered} by their costs.\n\t * \n\t * @author Stephen G. Ware\n\t */\n\tpublic static class Entry implements Comparable {\n\n\t\t/** The value in the cost set */\n\t\tpublic final Value value;\n\t\t\n\t\t/** The cost of the value in the cost set */\n\t\tpublic final double cost;\n\t\t\n\t\t/**\n\t\t * Constructs a new cost set entry.\n\t\t * \n\t\t * @param value a value from the cost set\n\t\t * @param cost the cost of the value\n\t\t */\n\t\tprotected Entry(Value value, double cost) {\n\t\t\tthis.value = value;\n\t\t\tthis.cost = cost;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object other) {\n\t\t\tif(getClass().equals(other.getClass())) {\n\t\t\t\tEntry otherCost = (Entry) other;\n\t\t\t\treturn Utilities.equals(value, otherCost.value) && cost == otherCost.cost;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn Utilities.hashCode(getClass(), value, cost);\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn Utilities.DEFAULT_PRINTER.toString(this);\n\t\t}\n\n\t\t@Override\n\t\tpublic int compareTo(Entry other) {\n\t\t\tdouble comparison = cost - other.cost;\n\t\t\tif(comparison == 0)\n\t\t\t\treturn 0;\n\t\t\telse if(comparison < 0)\n\t\t\t\treturn -1;\n\t\t\telse\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic default Iterator iterator() {\n\t\tEntry[] entries = new Entry[size()];\n\t\tfor(int i=0; i(entries);\n\t}\n\t\n\t/**\n\t * Returns the {@link Value value} at a given index in the set. The cost of\n\t * value can be accessed via {@link #getCost(int)}.\n\t * \n\t * @param index the index of the desired value\n\t * @return the value at that index\n\t */\n\tpublic Value getValue(int index);\n\t\n\t/**\n\t * Returns the cost of the value at a given index in the set. The value\n\t * itself can be accessed via {@link #getValue(int)}.\n\t * \n\t * @param index the index of the value whose cost is desired\n\t * @return the cost of the value at that index\n\t */\n\tpublic double getCost(int index);\n\n\t/**\n\t * Returns the cost associated with the given value, which is an estimate\n\t * of the number of {@link edu.uky.cs.nil.sabre.Action actions} that need\n\t * to be taken from the state a heuristic graph was {@link\n\t * HeuristicGraph#initialize(edu.uky.cs.nil.sabre.State) initialized to}\n\t * before the {@link edu.uky.cs.nil.sabre.logic.Expression logical\n\t * expression} this set represents can have the given value. A cost of 0\n\t * means the logical expression has this value from the start. A cost of\n\t * {@link Double#POSITIVE_INFINITY positive infinity} means the expression\n\t * cannot have this value.\n\t * \n\t * @param value a value the logical expression this set represents might\n\t * have\n\t * @return an estimate of the number of actions that would need to be\n\t * taken before this set can contain that value\n\t */\n\tpublic default double getCost(Value value) {\n\t\treturn getCost(Comparison.EQUAL_TO, value);\n\t}\n\t\n\t/**\n\t * Returns the cost of some value in this set satisfying the given {@link\n\t * Comparison.Operator comparison operator} when it is on the left and a\n\t * given value is on the right. For example, if this method is called with\n\t * the {@link Comparison#GREATER_THAN greater than operator} and the value\n\t * 0, it means \"what is the cost of this set having a value above 0?\"\n\t * \n\t * @param operator the comparison operator to satisfy\n\t * @param value the value on the right hand side of the comparison\n\t * @return the cost of some value in this set that satisfies the comparison\n\t * when it is on the left hand side of the comparison\n\t */\n\nsrc/edu/uky/cs/nil/sabre/util/ArrayIterator.java\npublic class ArrayIterator implements Iterator {\n\n\tprivate final Object[] array;\n\tprivate final int last;\n\tprivate int index;\n\t\n\t/**\n\t * Constructs a new array iterator that will iterate over a subset of\n\t * elements in an array.\n\t * \n\t * @param array the array to iterate over\n\t * @param first index of the first element to return while iterating\n\t * @param last index of the last element to return while iterating\n\t */\n\tpublic ArrayIterator(T[] array, int first, int last) {\n\t\tthis.array = array;\n\t\tthis.index = Math.max(first, 0);\n\t\tthis.last = Math.min(last, array.length - 1);\n\t}\n\t\n\t/**\n\t * Constructs a new array iterator that will iterate over all elements in\n\t * an array.\n\t * \n\t * @param array the array to iterator over\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic ArrayIterator(T...array) {\n\t\tthis(array, 0, array.length - 1);\n\t}\n\t\n\t@Override\n\tpublic boolean hasNext() {\n\t\treturn index <= last;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"unchecked\")\n\tpublic T next() {\n\t\tif(!hasNext())\n\t\t\tthrow Exceptions.iteratorOutOfElements();\n\t\treturn (T) array[index++];\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/util/Countable.java\npublic interface Countable {\n\n\t/**\n\t * Returns the number of elements in this collection\n\t * \n\t * @return the number of elements in this collection\n\t */\n\tpublic int size();\n}\n\nsrc/edu/uky/cs/nil/sabre/logic/Comparison.java\npublic class Comparison implements Proposition {\n\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * An operator is a singleton object that represents one of the possible\n\t * binary relationship between the left and right expressions of a {@link\n\t * Comparison comparison}.\n\t * \n\t * @author Stephen G. Ware\n\t */\n\tpublic static abstract class Operator implements Comparable, Serializable, Unique {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = Comparison.serialVersionUID;\n\t\t\n\t\tprivate Operator() {}\n\t\t\n\t\t@Override\n\t\tpublic int compareTo(Operator other) {\n\t\t\treturn hashCode() - other.hashCode();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Tests whether the relationship represented by this operator holds\n\t\t * between two {@link Value values} which appear on the left and right\n\t\t * of a {@link Comparison comparison}.\n\t\t * \n\t\t * @param left the value on the left of the comparison\n\t\t * @param right the value on the right of the comparison\n\t\t * @return true if the relationship holds, false otherwise\n\t\t */\n\t\tpublic abstract boolean test(Value left, Value right);\n\t\t\n\t\t/**\n\t\t * Returns the operator this operator would become when {@link\n\t\t * Comparison#flip() flipping} a comparison in which it appears.\n\t\t * \n\t\t * @return the flipped operator\n\t\t */\n\t\tpublic abstract Operator flip();\n\t\t\n\t\t/**\n\t\t * Returns the operator this operator would become when {@link\n\t\t * Comparison#negate() negating} a comparison in which it appears.\n\t\t * \n\t\t * @return the negated operator\n\t\t */\n\t\tpublic abstract Operator negate();\n\t\t\n\t\t/**\n\t\t * If a {@link Comparison comparison} using this operator with the\n\t\t * given left and right expressions can be simplified, this method\n\t\t * returns the simplified expression; otherwise it returns null. The\n\t\t * most common case in which a comparison can be simplified is when\n\t\t * its left and right expressions are both {@link Value values}, in\n\t\t * which case this method returns {@link True true} if {@link\n\t\t * #test(Value, Value) this operator's test method} returns true, and\n\t\t * {@link False false} if this operator's test method returns false.\n\t\t * \n\t\t * @param left the left expression of a comparison\n\t\t * @param right the right expression of a comparison\n\t\t * @return a simplified expression or null if the comparison cannot be\n\t\t * simplified\n\t\t */\n\t\tpublic Expression simplify(Expression left, Expression right) {\n\t\t\tif(left instanceof Value && right instanceof Value) {\n\t\t\t\tif(test((Value) left, (Value) right))\n\t\t\t\t\treturn True.TRUE;\n\t\t\t\telse\n\t\t\t\t\treturn False.FALSE;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn null;\n\t\t}\n\t\t\n\t\t/**\n\t\t * If a {@link Precondition} (that is, an {@link Atom atomic} {@link\n\t\t * Comparison comparison}) using this operator can be {@link\n\t\t * Atom#combine(Atom) combined} with a second precondition, this method\n\t\t * returns the resulting precondition, or null if they cannot be\n\t\t * combined. This method assumes the {@link Comparison#left left sides}\n\t\t * of both preconditions are the same. If the operators of the two\n\t\t * preconditions are different, this method should be called twice,\n\t\t * once for the first precondition's operator and once for the second\n\t\t * precondition's operator, and only one of those methods needs to\n\t\t * return the combined precondition if it exists.\n\t\t * \n\t\t * @param self the first precondition\n\t\t * @param other the second precondition with matching left side\n\t\t * @return a combined precondition which represents both, if one\n\t\t * exists, or null if one does not exist\n\t\t */\n\t\tprotected Precondition combine(Precondition self, Precondition other) {\n\t\t\tif(self.equals(other))\n\t\t\t\treturn self;\n\t\t\telse\n\t\t\t\treturn null;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Tests whether a {@link Precondition} (that is, an {@link Atom\n\t\t * atomic} {@link Comparison comparison}) using this operator {@link\n\t\t * Atom#negates(Atom) negates} a second precondition. This method\n\t\t * assumes the {@link Comparison#left left sides} of both preconditions\n\t\t * are the same. If the operators of the two preconditions are\n\t\t * different, this method should be called twice, once for the first\n\t\t * precondition's operator and once for the second precondition's\n\t\t * operator, and only one of those methods needs to return true if the\n\t\t * preconditions negate one another.\n\t\t * \n\t\t * @param self the first precondition\n\t\t * @param other the second precondition with matching left side\n\t\t * @return true if the preconditions negate one another, false\n\t\t * otherwise\n\t\t */\n\t\tprotected boolean negates(Precondition self, Precondition other) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t/**\n\t * Represents a {@link Comparison} where the left and right are the same.\n\t */\n\tpublic static final Operator EQUAL_TO = new Operator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.EQUAL_TO_KEYWORD;\n\t\t}\n\n\t\t/**\n\t\t * Returns true if and only if the left and right values are the same.\n\t\t * \n\t\t * @param left the value on the left of the comparison\n\t\t * @param right the value on the right of the comparison\n\t\t * @return true if the values are the same, false otherwise\n\t\t */\n\t\t@Override\n\t\tpublic boolean test(Value left, Value right) {\n\t\t\treturn left.equals(right);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator flip() {\n\t\t\treturn EQUAL_TO;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#NOT_EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#NOT_EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator negate() {\n\t\t\treturn NOT_EQUAL_TO;\n\t\t}\n\t\t\n\t\t/**\n\t\t * If the left and right expressions are {@link Object#equals(Object)\n\t\t * equal to} each other, this method returns {@link True true}. If the\n\t\t * left and right expressions are different {@link Value values}, this\n\t\t * method returns {@link False false}. Otherwise, this method returns\n\t\t * null.\n\t\t * \n\t\t * @param left the left expression of an equal to comparison\n\t\t * @param right the right expression of an equal to comparison\n\t\t * @return true if the left and right must be the same, false if they\n\t\t * cannot be the same, or null if the comparison cannot be simplified\n\t\t */\n\t\t@Override\n\t\tpublic Expression simplify(Expression left, Expression right) {\n\t\t\tif(left.equals(right))\n\t\t\t\treturn True.TRUE;\n\t\t\telse\n\t\t\t\treturn super.simplify(left, right);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Precondition combine(Precondition self, Precondition other) {\n\t\t\tif(other.operator.equals(NOT_EQUAL_TO) && self.right instanceof Value && other.right instanceof Value && !self.right.equals(other.right))\n\t\t\t\treturn self;\n\t\t\telse if(other.operator.equals(GREATER_THAN_OR_EQUAL_TO) && self.right.equals(other.right))\n\t\t\t\treturn self;\n\t\t\telse if(other.operator.equals(LESS_THAN_OR_EQUAL_TO) && self.right.equals(other.right))\n\t\t\t\treturn self;\n\t\t\telse\n\t\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected boolean negates(Precondition self, Precondition other) {\n\t\t\tif(other.operator.equals(EQUAL_TO))\n\t\t\t\treturn self.right instanceof Value && other.right instanceof Value && !self.right.equals(other.right);\n\t\t\telse if(other.operator.equals(NOT_EQUAL_TO))\n\t\t\t\treturn self.right.equals(other.right);\n\t\t\telse\n\t\t\t\treturn super.negates(self, other);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn EQUAL_TO;\n\t\t}\n\t};\n\t\n\t/**\n\t * Represents a {@link Comparison} where the left and right are not the\n\t * same.\n\t */\n\tpublic static final Operator NOT_EQUAL_TO = new Operator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.NOT_EQUAL_TO_KEYWORD;\n\t\t}\n\n\t\t/**\n\t\t * Returns true if and only if the left and right values are different.\n\t\t * \n\t\t * @param left the value on the left of the comparison\n\t\t * @param right the value on the right of the comparison\n\t\t * @return true if the values are different, false otherwise\n\t\t */\n\t\t@Override\n\t\tpublic boolean test(Value left, Value right) {\n\t\t\treturn !left.equals(right);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#NOT_EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#NOT_EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator flip() {\n\t\t\treturn NOT_EQUAL_TO;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator negate() {\n\t\t\treturn EQUAL_TO;\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Precondition combine(Precondition self, Precondition other) {\n\t\t\tif(other.operator.equals(GREATER_THAN_OR_EQUAL_TO) && self.right.equals(other.right))\n\t\t\t\treturn new Precondition(GREATER_THAN, self.left, self.right);\n\t\t\telse if(other.operator.equals(LESS_THAN_OR_EQUAL_TO) && self.right.equals(other.right))\n\t\t\t\treturn new Precondition(LESS_THAN, self.left, self.right);\n\t\t\telse\n\t\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected boolean negates(Precondition self, Precondition other) {\n\t\t\tif(other.operator.equals(EQUAL_TO))\n\t\t\t\treturn self.right.equals(other.right);\n\t\t\telse\n\t\t\t\treturn super.negates(self, other);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn NOT_EQUAL_TO;\n\t\t}\n\t};\n\t\n\t/**\n\t * An numeric operator is an {@link Operator operator} which compares\n\t * expressions of type {@code number}.\n\t * \n\t * @author Stephen G. Ware\n\t */\n\tpublic static abstract class NumericOperator extends Operator {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = Comparison.serialVersionUID;\n\t\t\n\t\tprivate NumericOperator() {}\n\t\t\n\t\t@Override\n\t\tpublic boolean test(Value left, Value right) {\n\t\t\tif(left instanceof Number && right instanceof Number)\n\t\t\t\treturn test((Number) left, (Number) right);\n\t\t\telse\n\t\t\t\treturn false;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Tests whether the relationship represented by this numeric operator\n\t\t * holds between two {@link Number numbers} which appear on the left\n\t\t * and right of a {@link Comparison comparison}.\n\t\t * \n\t\t * @param left the number on the left of the comparison\n\t\t * @param right the number on the right of the comparison\n\t\t * @return true if the relationship holds, false otherwise\n\t\t */\n\t\tpublic abstract boolean test(Number left, Number right);\n\t\t\n\t\t@Override\n\t\tpublic Expression simplify(Expression left, Expression right) {\n\t\t\tif(left.equals(Unknown.UNKNOWN) || right.equals(Unknown.UNKNOWN))\n\t\t\t\treturn new Comparison(EQUAL_TO, left, right).simplify();\n\t\t\telse\n\t\t\t\treturn super.simplify(left, right);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Precondition combine(Precondition self, Precondition other) {\n\t\t\tif(self.right instanceof Number && other.right instanceof Number)\n\t\t\t\treturn combine(self, other, (Number) self.right, (Number) other.right);\n\t\t\telse\n\t\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t/**\n\t\t * This convenience method behaves exactly like {@link\n\t\t * Operator#simplify(Expression, Expression)} and makes the same\n\t\t * assumptions, except that it only handles cases where the right sides\n\t\t * of both preconditions are {@link Number numbers}.\n\t\t * \n\t\t * @param self the first precondition\n\t\t * @param other the second precondition with matching left side\n\t\t * @param sr the right side of the first precondition\n\t\t * @param or the right side of the second precondition\n\t\t * @return a combined precondition which represents both, if one\n\t\t * exists, or null if one does not exist\n\t\t */\n\t\tprotected Precondition combine(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected boolean negates(Precondition self, Precondition other) {\n\t\t\tif(self.right instanceof Number && other.right instanceof Number)\n\t\t\t\treturn negates(self, other, (Number) self.right, (Number) other.right);\n\t\t\telse\n\t\t\t\treturn super.negates(self, other);\n\t\t}\n\t\t\n\t\t/**\n\t\t * This convenience method behaves exactly like {@link\n\t\t * Operator#negates(Precondition, Precondition)} and makes the same\n\t\t * assumptions, except that it only handles cases where the right sides\n\t\t * of both preconditions are {@link Number numbers}.\n\t\t * \n\t\t * @param self the first precondition\n\t\t * @param other the second precondition with matching left side\n\t\t * @param sr the right side of the first precondition\n\t\t * @param or the right side of the second precondition\n\t\t * @return true if the preconditions negate one another, false\n\t\t * otherwise\n\t\t */\n\t\tprotected boolean negates(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\treturn super.negates(self, other);\n\t\t}\n\t}\n\t\n\t/**\n\t * Represents a {@link Comparison} where the left is greater than the\n\t * right.\n\t */\n\tpublic static final Operator GREATER_THAN = new NumericOperator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 2;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.GREATER_THAN_KEYWORD;\n\t\t}\n\n\t\t/**\n\t\t * Returns true if and only if the left {@link Number number} {@link\n\t\t * Number#isGreaterThan(Number) is greater than} the right.\n\t\t * \n\t\t * @param left the number on the left of the comparison\n\t\t * @param right the number on the right of the comparison\n\t\t * @return true if the left is greater than the right\n\t\t */\n\t\t@Override\n\t\tpublic boolean test(Number left, Number right) {\n\t\t\treturn left.isGreaterThan(right);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#LESS_THAN}.\n\t\t * \n\t\t * @returns {@link Comparison#LESS_THAN}\n\t\t */\n\t\t@Override\n\t\tpublic Operator flip() {\n\t\t\treturn LESS_THAN;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#LESS_THAN_OR_EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#LESS_THAN_OR_EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator negate() {\n\t\t\treturn LESS_THAN_OR_EQUAL_TO;\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Precondition combine(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) && sr.isLessThan(or))\n\t\t\t\treturn other;\n\t\t\telse if(other.operator.equals(GREATER_THAN) || other.operator.equals(GREATER_THAN_OR_EQUAL_TO)) {\n\t\t\t\tif(sr.isLessThan(or))\n\t\t\t\t\treturn other;\n\t\t\t\telse\n\t\t\t\t\treturn self;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected boolean negates(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) || other.operator.equals(LESS_THAN) || other.operator.equals(LESS_THAN_OR_EQUAL_TO))\n\t\t\t\treturn sr.isGreaterThanOrEqualTo(or);\n\t\t\telse\n\t\t\t\treturn super.negates(self, other, sr, or);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn GREATER_THAN;\n\t\t}\n\t};\n\t\n\t/**\n\t * Represents a {@link Comparison} where the left is greater than or equal\n\t * to the right.\n\t */\n\tpublic static final Operator GREATER_THAN_OR_EQUAL_TO = new NumericOperator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 3;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.GREATER_THAN_OR_EQUAL_TO_KEYWORD;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean test(Value left, Value right) {\n\t\t\treturn EQUAL_TO.test(left, right) || GREATER_THAN.test(left, right);\n\t\t}\n\n\t\t/**\n\t\t * Returns true if and only if the left {@link Number number} {@link\n\t\t * Number#isGreaterThanOrEqualTo(Number) is greater than or equal to}\n\t\t * the right.\n\t\t * \n\t\t * @param left the number on the left of the comparison\n\t\t * @param right the number on the right of the comparison\n\t\t * @return true if the left is greater than or equal to the right\n\t\t */\n\t\t@Override\n\t\tpublic boolean test(Number left, Number right) {\n\t\t\treturn left.isGreaterThanOrEqualTo(right);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#LESS_THAN_OR_EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#LESS_THAN_OR_EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator flip() {\n\t\t\treturn LESS_THAN_OR_EQUAL_TO;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#LESS_THAN}.\n\t\t * \n\t\t * @returns {@link Comparison#LESS_THAN}\n\t\t */\n\t\t@Override\n\t\tpublic Operator negate() {\n\t\t\treturn LESS_THAN;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Expression simplify(Expression left, Expression right) {\n\t\t\tif(!left.isNumber() || !right.isNumber())\n\t\t\t\treturn new Comparison(Comparison.EQUAL_TO, left, right);\n\t\t\telse\n\t\t\t\treturn super.simplify(left, right);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Precondition combine(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) && sr.isLessThanOrEqualTo(or))\n\t\t\t\treturn other;\n\t\t\telse if(other.operator.equals(GREATER_THAN) || other.operator.equals(GREATER_THAN_OR_EQUAL_TO)) {\n\t\t\t\tif(sr.isLessThanOrEqualTo(or))\n\t\t\t\t\treturn other;\n\t\t\t\telse\n\t\t\t\t\treturn self;\n\t\t\t}\n\t\t\telse if(other.operator.equals(LESS_THAN_OR_EQUAL_TO) && sr.equals(or))\n\t\t\t\treturn new Precondition(EQUAL_TO, self.left, sr);\t\t\t\t\n\t\t\telse\n\t\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected boolean negates(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) || other.operator.equals(LESS_THAN_OR_EQUAL_TO))\n\t\t\t\treturn sr.isGreaterThan(or);\n\t\t\telse if(other.operator.equals(LESS_THAN))\n\t\t\t\treturn sr.isGreaterThanOrEqualTo(or);\n\t\t\telse\n\t\t\t\treturn super.negates(self, other, sr, or);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn GREATER_THAN_OR_EQUAL_TO;\n\t\t}\n\t};\n\t\n\t/**\n\t * Represents a {@link Comparison} where the left is less than the right.\n\t */\n\tpublic static final Operator LESS_THAN = new NumericOperator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 4;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.LESS_THAN_KEYWORD;\n\t\t}\n\n\t\t/**\n\t\t * Returns true if and only if the left {@link Number number} {@link\n\t\t * Number#isLessThan(Number) is less than} the right.\n\t\t * \n\t\t * @param left the number on the left of the comparison\n\t\t * @param right the number on the right of the comparison\n\t\t * @return true if the left is less than the right\n\t\t */\n\t\t@Override\n\t\tpublic boolean test(Number left, Number right) {\n\t\t\treturn left.isLessThan(right);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#GREATER_THAN}.\n\t\t * \n\t\t * @returns {@link Comparison#GREATER_THAN}\n\t\t */\n\t\t@Override\n\t\tpublic Operator flip() {\n\t\t\treturn GREATER_THAN;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#GREATER_THAN_OR_EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#GREATER_THAN_OR_EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator negate() {\n\t\t\treturn GREATER_THAN_OR_EQUAL_TO;\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Precondition combine(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) && sr.isGreaterThan(or))\n\t\t\t\treturn other;\n\t\t\telse if(other.operator.equals(LESS_THAN) || other.operator.equals(LESS_THAN_OR_EQUAL_TO)) {\n\t\t\t\tif(sr.isGreaterThan(or))\n\t\t\t\t\treturn other;\n\t\t\t\telse\n\t\t\t\t\treturn self;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected boolean negates(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) || other.operator.equals(GREATER_THAN) || other.operator.equals(GREATER_THAN_OR_EQUAL_TO))\n\t\t\t\treturn sr.isLessThanOrEqualTo(or);\n\t\t\telse\n\t\t\t\treturn super.negates(self, other, sr, or);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn LESS_THAN;\n\t\t}\n\t};\n\t\n\t/**\n\t * Represents a {@link Comparison} where the left is less than or equal to\n\t * the right.\n\t */\n\tpublic static final Operator LESS_THAN_OR_EQUAL_TO = new NumericOperator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 5;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.LESS_THAN_OR_EQUAL_TO_KEYWORD;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean test(Value left, Value right) {\n\t\t\treturn EQUAL_TO.test(left, right) || LESS_THAN.test(left, right);\n\t\t}\n\n\t\t/**\n\t\t * Returns true if and only if the left {@link Number number} {@link\n\t\t * Number#isLessThanOrEqualTo(Number) is less than or equal to} the\n\t\t * right.\n\t\t * \n\t\t * @param left the number on the left of the comparison\n\t\t * @param right the number on the right of the comparison\n\t\t * @return true if the left is less than or equal to the right\n\t\t */\n\t\t@Override\n\t\tpublic boolean test(Number left, Number right) {\n\t\t\treturn left.isLessThanOrEqualTo(right);\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#GREATER_THAN_OR_EQUAL_TO}.\n\t\t * \n\t\t * @returns {@link Comparison#GREATER_THAN_OR_EQUAL_TO}\n\t\t */\n\t\t@Override\n\t\tpublic Operator flip() {\n\t\t\treturn GREATER_THAN_OR_EQUAL_TO;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns {@link Comparison#GREATER_THAN}.\n\t\t * \n\t\t * @returns {@link Comparison#GREATER_THAN}\n\t\t */\n\t\t@Override\n\t\tpublic Operator negate() {\n\t\t\treturn GREATER_THAN;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic Expression simplify(Expression left, Expression right) {\n\t\t\tif(!left.isNumber() || !right.isNumber())\n\t\t\t\treturn new Comparison(Comparison.EQUAL_TO, left, right);\n\t\t\telse\n\t\t\t\treturn super.simplify(left, right);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Precondition combine(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) && sr.isGreaterThanOrEqualTo(or))\n\t\t\t\treturn other;\n\t\t\telse if(other.operator.equals(LESS_THAN) || other.operator.equals(LESS_THAN_OR_EQUAL_TO)) {\n\t\t\t\tif(sr.isGreaterThanOrEqualTo(or))\n\t\t\t\t\treturn other;\n\t\t\t\telse\n\t\t\t\t\treturn self;\n\t\t\t}\n\t\t\telse if(other.operator.equals(GREATER_THAN_OR_EQUAL_TO) && sr.equals(or))\n\t\t\t\treturn new Precondition(EQUAL_TO, self.left, sr);\t\t\t\t\n\t\t\telse\n\t\t\t\treturn super.combine(self, other);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected boolean negates(Precondition self, Precondition other, Number sr, Number or) {\n\t\t\tif(other.operator.equals(EQUAL_TO) || other.operator.equals(GREATER_THAN_OR_EQUAL_TO))\n\t\t\t\treturn sr.isLessThan(or);\n\t\t\telse if(other.operator.equals(GREATER_THAN))\n\t\t\t\treturn sr.isLessThanOrEqualTo(or);\n\t\t\telse\n\t\t\t\treturn super.negates(self, other, sr, or);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn LESS_THAN_OR_EQUAL_TO;\n\t\t}\n\t};\n\n\t/** The relationship between the left and right sides */\n\tpublic final Operator operator;\n\t\n\t/** The left side expression */\n\tpublic final Expression left;\n\t\n\t/** The right side expression */\n\tpublic final Expression right;\n\t\n\t/**\n\t * Constructs a new comparison with a given {@link Operator relationship},\n\t * left side, and right side.\n\t * \n\t * @param operator the relationship between the sides\n\t * @param left the left side\n\t * @param right the right side\n\t */\n\tpublic Comparison(Operator operator, Expression left, Expression right) {\n\t\tthis.operator = operator;\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif(getClass().equals(other.getClass())) {\n\t\t\tComparison otherComparison = (Comparison) other;\n\t\t\treturn operator.equals(otherComparison.operator) && left.equals(otherComparison.left) && right.equals(otherComparison.right);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Utilities.hashCode(getClass(), operator, left, right);\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + left + \" \" + operator + \" \" + right + \")\";\n\t}\n\t\n\t@Override\n\tpublic int compareTo(Logical other) {\n\t\tif(getClass().equals(other.getClass())) {\n\t\t\tComparison otherComparison = (Comparison) other;\n\t\t\treturn Utilities.compare(left, otherComparison.left, operator, otherComparison.operator, right, otherComparison.right);\n\t\t}\n\t\telse\n\t\t\treturn Proposition.super.compareTo(other);\n\t}\n\n\t@Override\n\tpublic boolean isGround() {\n\t\treturn left.isGround() && right.isGround();\n\t}\n\n\t@Override\n\tpublic Comparison apply(Function function) {\n\t\tExpression left = (Expression) function.apply(this.left);\n\t\tExpression right = (Expression) function.apply(this.right);\n\t\tif(left != this.left || right != this.right)\n\t\t\treturn new Comparison(operator, left, right);\n\t\telse\n\t\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Expression simplify() {\n\t\tComparison simplified = (Comparison) Proposition.super.simplify();\n\t\tExpression further = operator.simplify(simplified.left, simplified.right);\n\t\tif(further == null)\n\t\t\treturn simplified;\n\t\telse\n\t\t\treturn further;\n\t}\n\t\n\t/**\n\t * Returns {@link True true} if the relationship represented by this\n\t * comparison's {@link #operator operator} holds between the left and right\n\t * sides, or {@link False false} otherwise.\n\t * \n\t * @param state the state in which this comparison will be evaluated\n\t * @return the Boolean value of this expression\n\t */\n\t@Override\n\tpublic Value evaluate(State state) {\n\t\tif(operator.test(left.evaluate(state), right.evaluate(state)))\n\t\t\treturn True.TRUE;\n\t\telse\n\t\t\treturn False.FALSE;\n\t}\n\t\n\t@Override\n\tpublic Comparison prepend(Parameter character) {\n\t\treturn (Comparison) Proposition.super.prepend(character);\n\t}\n\t\n\t/**\n\t * Returns a new comparison with the same left and right sides, but with a\n\t * {@link Operator#negate() negated operator}.\n\t * \n\t * @return a comparison with the opposite value of this comparison\n\t */\n\t@Override\n\tpublic Comparison negate() {\n\t\treturn new Comparison(operator.negate(), left, right);\n\t}\n\t\n\t@Override\n\tpublic Disjunction> toPrecondition() {\n\t\t// Case 1: Two values. Simplify.\n\t\tif(left instanceof Value && right instanceof Value)\n\t\t\treturn simplify().toPrecondition();\n\t\t// Case 2: Numeric. Make constraints on all variables and fluents explicit.\n\t\telse if(left.isNumber() && left.isValued() && right.isNumber() && right.isValued()) {\n\t\t\tArrayList constraints = new ArrayList<>();\n\t\t\tfor(Fluent fluent : collect(Fluent.class))\n\t\t\t\tconstraints.add(isolate(fluent));\n\t\t\treturn new Conjunction<>(constraints).toPrecondition();\n\t\t}\n\t\t// Case 3: Valid left side and valid right side.\n\t\telse if((left instanceof Variable || left instanceof Fluent) && !left.isNumber() && right.isValued()) {\n\t\t\tif(operator.equals(NOT_EQUAL_TO) && right.isBoolean())\n\t\t\t\treturn new Comparison(operator.negate(), left, right.negate()).toPrecondition();\n\t\t\telse\n\t\t\t\treturn new Precondition(operator, left, right).toPrecondition();\n\t\t}\n\t\telse if((right instanceof Variable || right instanceof Fluent) && !right.isNumber() && left.isValued())\n\t\t\treturn flip().toPrecondition();\n\t\t// Case 4: Need to factor out something that is not valued.\n\t\telse if(!right.isValued()) {\n\t\t\tConditional>> valued = right.toValued();\n\t\t\tExpression[] branches = new Expression[valued.branches.size()];\n\t\t\tfor(int i=0; i(valued.conditions, new ImmutableArray<>(branches)).toPrecondition();\n\t\t}\n\t\t// Case 5: Flip\n\t\telse\n\t\t\treturn flip().toPrecondition();\n\t}\n\t\n\t@Override\n\tpublic Clause toEffect() {\n\t\tif(left instanceof Fluent && operator.equals(EQUAL_TO))\n\t\t\treturn new Assignment((Fluent) left, right).toEffect();\n\t\telse if(left instanceof Fluent && left.isBoolean() && operator.equals(NOT_EQUAL_TO))\n\t\t\treturn new Assignment((Fluent) left, right.negate()).toEffect();\n\t\telse\n\t\t\treturn Proposition.super.toEffect();\n\t}\n\t\n\t/**\n\t * Attempts to isolate a given {@link Fluent fluent} which might appear\n\t * anywhere in this comparison on the left side of this comparison. If the\n\t * fluent is numeric, {@link\n\t * Arithmetic#isolate(Fluent, Operator, Expression) some arithmetic may\n\t * need to be done to isolate the fluent}, but the comparison returned\n\t * should be logically equivalent to this comparison.\n\t * \n\t * @param query the query which should be isolated on the left side\n\t * @return an equivalent comparison with the query on the left side\n\t * @throws FormatException if the query cannot be isolated\n\t */\n\tExpression isolate(Fluent query) {\n\t\tif(left.equals(query))\n\t\t\treturn new Precondition(operator, query, right.simplify());\n\t\telse if(right.equals(query))\n\t\t\treturn flip().isolate(query);\n\t\telse if(left.occurs(query) && left instanceof Arithmetic)\n\t\t\treturn ((Arithmetic) left).isolate(query, operator, right);\n\t\telse if(right.occurs(query) && right instanceof Arithmetic)\n\t\t\treturn flip().isolate(query);\n\t\telse\n\t\t\tthrow Exceptions.cannotIsolate(query, this);\n\t}\n\t\n\t/**\n\t * Returns a new comparison where the left is now on the right, the right\n\t * is now on the left, and the operator has been {@link Operator#flip()\n\t * flipped}.\n\t * \n\t * @return an equivalent comparison, but with its sides flipped\n\t */\n\tpublic Comparison flip() {\n\t\treturn new Comparison(operator.flip(), right, left);\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/Utilities.java\npublic class Utilities {\n\t\n\t/**\n\t * A default {@link edu.uky.cs.nil.sabre.io.Printer printer} generally used\n\t * for converting objects to strings\n\t */\n\tpublic static final DefaultPrinter DEFAULT_PRINTER = new DefaultPrinter();\n\t\n\t/**\n\t * Checks whether two objects are {@link Object#equals(Object) equal to}\n\t * one another without causing a {@link NullPointerException} if one or\n\t * both of them is null.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return true if they are equal or both null, false otherwise\n\t */\n\tpublic static final boolean equals(Object o1, Object o2) {\n\t\tif(o1 == null)\n\t\t\treturn o2 == null;\n\t\telse if(o2 == null)\n\t\t\treturn false;\n\t\telse\n\t\t\treturn o1.equals(o2);\n\t}\n\t\n\t/**\n\t * Returns an object's {@link Object#hashCode() hash code} or 0 if the\n\t * object is null.\n\t * \n\t * @param object the object or null\n\t * @return the object's hash code or 0 if the object was null\n\t */\n\tpublic static final int hashCode(Object object) {\n\t\tif(object == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn object.hashCode();\n\t}\n\t\n\t/**\n\t * Combines two {@link #hashCode(Object) hash code} values.\n\t * \n\t * @param hc1 the first hash code\n\t * @param hc2 the second hash code\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc1, int hc2) {\n\t\treturn hc1 * 31 + hc2;\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of an object.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1) {\n\t\treturn hashCode(hc, hashCode(o1));\n\t}\n\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of two objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2) {\n\t\treturn hashCode(hashCode(o1), hashCode(o2));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of two objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2) {\n\t\treturn hashCode(hashCode(hc, o1), hashCode(o2));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of three\n\t * objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3) {\n\t\treturn hashCode(hashCode(o1, o2), hashCode(o3));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of three objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3) {\n\t\treturn hashCode(hashCode(hc, o1, o2), hashCode(o3));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of four objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4) {\n\t\treturn hashCode(hashCode(o1, o2, o3), hashCode(o4));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of four objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3, Object o4) {\n\t\treturn hashCode(hashCode(hc, o1, o2, o3), hashCode(o4));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of five objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4, Object o5) {\n\t\treturn hashCode(hashCode(o1, o2, o3, o4), hashCode(o5));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of five objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3, Object o4, Object o5) {\n\t\treturn hashCode(hashCode(hc, o1, o2, o3, o4), hashCode(o5));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of six objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @param o6 the sixth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4, Object o5, Object o6) {\n\t\treturn hashCode(hashCode(o1, o2, o3, o4, o5), hashCode(o6));\n\t}\n\t\n\t/**\n\t * Rounds a {@code double} up to the nearest whole number.\n\t * \n\t * @param value the value to round up\n\t * @return the nearest whole number that is greater than or equal to the\n\t * value\n\t */\n\tpublic static final double roundUp(double value) {\n\t\treturn new BigDecimal(value).setScale(0, RoundingMode.UP).doubleValue();\n\t}\n\t\n\t/**\n\t * Compares a pair of {@link Comparable comparable} objects.\n\t * \n\t * @param the type of the objects\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return a negative integer, zero, or a positive integer as the first\n\t * object is less than, equal to, or greater than the second object\n\t */\n\tpublic static final > int compare(C1 o1, C1 o2) {\n\t\treturn o1.compareTo(o2);\n\t}\n\t\n\t/**\n\t * Compares two pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is\n\t * not 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4) {\n\t\tint comparison = compare(o1, o2);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o3, o4);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares three pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is not\n\t * 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param the type of the third pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @param o5 the first object in the third pair\n\t * @param o6 the second object in the third pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable, C3 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4, C3 o5, C3 o6) {\n\t\tint comparison = compare(o1, o2, o3, o4);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o5, o6);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares four pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is\n\t * not 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param the type of the third pair of objects\n\t * @param the type of the fourth pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @param o5 the first object in the third pair\n\t * @param o6 the second object in the third pair\n\t * @param o7 the first object in the fourth pair\n\t * @param o8 the second object in the fourth pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable, C3 extends Comparable, C4 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4, C3 o5, C3 o6, C4 o7, C4 o8) {\n\t\tint comparison = compare(o1, o2, o3, o4, o5, o6);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o7, o8);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares two {@link ImmutableArray arrays} of {@link Logical logical}\n\t * objects. The first elements of both arrays are compared. If the result\n\t * is not 0, it is returned, otherwise the second elements of both arrays\n\t * are compared, and so on.\n\t * \n\t * @param array1 the first array\n\t * @param array2 the second array\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * elements are less than, equal to, or greater than the later elements\n\t */\n\tpublic static final int compare(ImmutableArray array1, ImmutableArray array2) {\n\t\tint comparison = 0;\n\t\tint size = Math.min(array1.size(), array2.size());\n\t\tfor(int i=0; i array2.size())\n\t\t\t\treturn 1;\n\t\t\telse if(array2.size() > array1.size())\n\t\t\t\treturn -1;\n\t\t}\n\t\treturn comparison;\n\t}\n\n\t/**\n\t * Iterates through all elements of an {@link Iterable iterable} and places\n\t * them into an array of a given type.\n\t * \n\t * @param the component type of the array\n\t * @param iterable the iterable\n\t * @param type the class of the component type of the array\n\t * @return an array containing all the elements in the iterable\n\t */\n\tpublic static final T[] toArray(Iterable iterable, Class type) {\n\t\treturn toArray(iterable.iterator(), 0, type);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tprivate static final T[] toArray(Iterator iterator, int index, Class type) {\n\t\tif(iterator.hasNext()) {\n\t\t\tT element = iterator.next();\n\t\t\tT[] array = toArray(iterator, index + 1, type);\n\t\t\tarray[index] = element;\n\t\t\treturn array;\n\t\t}\n\t\telse\n\t\t\treturn (T[]) Array.newInstance(type, index);\n\t}\n\t\n\t/**\n\t * Iterates through all elements of an {@link Iterable iterable} and places\n\t * into a {@link ImmutableSet set} only those items which are of a given\n\t * type.\n\t * \n\t * @param the type of elements to collect\n\t * @param type the class object of the type\n\t * @param iterable the iterable to iterate through\n\t * @return a set of elements from the iterable of the given type\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static final ImmutableSet collect(Class type, Iterable iterable) {\n\t\tLinkedHashSet set = new LinkedHashSet<>();\n\t\tfor(Object element : iterable)\n\t\t\tif(type.isAssignableFrom(element.getClass()))\n\t\t\t\tset.add((T) element);\n\t\treturn new ImmutableSet<>(set);\n\t}\n\t\n\t/**\n\t * Wrap a string in parentheses, unless it is already so wrapped.\n\t * \n\t * @param string the second\n\t * @return the string, wrapped in parentheses\n\t */\n\tpublic static final String wrap(String string) {\n\t\tif(string.startsWith(\"(\") && string.endsWith(\")\"))\n\t\t\treturn string;\n\t\telse\n\t\t\treturn \"(\" + string + \")\";\n\t}\n\t\n\t/**\n\t * Converts a number of milliseconds into a short string representation\n\t * that gives the numbers of days, hours, minutes, seconds, and\n\t * milliseconds. For example, {@code \"2d1h3m45s20ms\"} represents two days,\n\t * 1 hour, 3 minutes, fourty-five seconds, and twenty milliseconds.\n\t * \n\t * @param ms the number of milliseconds\n\t * @return a string representation of that amount of time\n\t */\n\tpublic static final String time(long ms) {\n\t\tlong days = TimeUnit.MILLISECONDS.toDays(ms);\n\t\tms -= TimeUnit.DAYS.toMillis(days);\n\t\tlong hours = TimeUnit.MILLISECONDS.toHours(ms);\n\t\tms -= TimeUnit.HOURS.toMillis(hours);\n\t\tlong minutes = TimeUnit.MILLISECONDS.toMinutes(ms);\n\t\tms -= TimeUnit.MINUTES.toMillis(minutes);\n\t\tlong seconds = TimeUnit.MILLISECONDS.toSeconds(ms);\n\t\tms -= TimeUnit.SECONDS.toMillis(seconds);\n\t\tString string = \"\";\n\t\tif(days > 0)\n\t\t\tstring += days + \"d\";\n\t\tif(hours > 0)\n\t\t\tstring += hours + \"h\";\n\t\tif(minutes > 0)\n\t\t\tstring += minutes + \"m\";\n\t\tif(seconds > 0)\n\t\t\tstring += seconds + \"s\";\n\t\tif(ms > 0)\n\t\t\tstring += ms + \"ms\";\n\t\tif(string.isEmpty())\n\t\t\treturn \"0ms\";\n\t\treturn string;\n\t}\n}", "answers": ["\tpublic double getCost(Comparison.Operator operator, Value value);"], "length": 6388, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "f80385ce-7b70-496c-9479-21d3f9b78379", "reasoning": "The comment just before the placeholder describes a method that returns the cost of a value satisfying a given comparison operator. In the CostSet interface, after this comment the next line should be the method declaration matching the description. Therefore the appropriate next line is the method signature for getCost with an operator and a value.", "reasoning_model_answer": "public double getCost(Comparison.Operator operator, Value value);", "assistant_with_reasoning": "\nThe comment just before the placeholder describes a method that returns the cost of a value satisfying a given comparison operator. In the CostSet interface, after this comment the next line should be the method declaration matching the description. Therefore the appropriate next line is the method signature for getCost with an operator and a value.\n\npublic double getCost(Comparison.Operator operator, Value value);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.072, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36300, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public double getCost(Comparison.Operator operator, Value value);", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.lang.reflect.Method;\nimport java.util.Iterator;\nimport enviromine.client.gui.hud.items.*;\nimport org.apache.logging.log4j.Level;\nimport cpw.mods.fml.client.registry.ClientRegistry;\nimport cpw.mods.fml.client.registry.RenderingRegistry;\nimport cpw.mods.fml.common.FMLCommonHandler;\nimport cpw.mods.fml.common.Loader;\nimport cpw.mods.fml.common.event.FMLInitializationEvent;\nimport cpw.mods.fml.common.event.FMLPostInitializationEvent;\nimport cpw.mods.fml.common.event.FMLPreInitializationEvent;\nimport cpw.mods.fml.relauncher.Side;\nimport cpw.mods.fml.relauncher.SideOnly;\nimport enviromine.EntityPhysicsBlock;\nimport enviromine.blocks.tiles.TileEntityDavyLamp;\nimport enviromine.blocks.tiles.TileEntityElevator;\nimport enviromine.blocks.tiles.TileEntityEsky;\nimport enviromine.blocks.tiles.TileEntityFreezer;\nimport enviromine.client.gui.Gui_EventManager;\nimport enviromine.client.gui.hud.HUDRegistry;\nimport enviromine.client.gui.menu.EM_Gui_Menu;\nimport enviromine.client.renderer.RenderPlayerEM;\nimport enviromine.client.renderer.itemInventory.ArmoredCamelPackRenderer;\nimport enviromine.client.renderer.tileentity.RenderGasHandler;\nimport enviromine.client.renderer.tileentity.RenderSpecialHandler;\nimport enviromine.client.renderer.tileentity.TileEntityDavyLampRenderer;\nimport enviromine.client.renderer.tileentity.TileEntityElevatorRenderer;\nimport enviromine.client.renderer.tileentity.TileEntityEskyRenderer;\nimport enviromine.client.renderer.tileentity.TileEntityFreezerRenderer;\nimport enviromine.core.EM_ConfigHandler.EnumLogVerbosity;\nimport enviromine.core.EM_Settings;\nimport enviromine.core.EnviroMine;\nimport enviromine.handlers.ObjectHandler;\nimport enviromine.handlers.keybinds.EnviroKeybinds;\nimport net.minecraft.client.Minecraft;\nimport net.minecraft.client.gui.GuiMainMenu;\nimport net.minecraft.client.renderer.entity.RenderFallingBlock;\nimport net.minecraft.entity.player.EntityPlayer;\nimport net.minecraft.item.Item;\nimport net.minecraft.item.ItemArmor;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.util.StatCollector;\nimport net.minecraftforge.client.IItemRenderer;\nimport net.minecraftforge.client.IItemRenderer.ItemRenderType;\nimport net.minecraftforge.client.MinecraftForgeClient;\nimport net.minecraftforge.common.MinecraftForge;", "context": "src/main/java/enviromine/core/proxies/EM_ClientProxy.java\npackage enviromine.core.proxies;\n\n\n\n\n\npublic class EM_ClientProxy extends EM_CommonProxy\n{\n\n\n\t@Override\n\tpublic boolean isClient()\n\t{\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isOpenToLAN()\n\t{\n\t\tif (Minecraft.getMinecraft().isIntegratedServerRunning())\n\t\t{\n\t\t\treturn Minecraft.getMinecraft().getIntegratedServer().getPublic();\n\t\t} else\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void registerTickHandlers()\n\t{\n\t\tsuper.registerTickHandlers();\n\t}\n\n\t@Override\n\tpublic void registerEventHandlers()\n\t{\n\t\tsuper.registerEventHandlers();\n\t\t//MinecraftForge.EVENT_BUS.register(new EM_GuiEnviroMeters(Minecraft.getMinecraft(), Minecraft.getMinecraft().getResourceManager()));\n\t\tMinecraftForge.EVENT_BUS.register(new ObjectHandler());\n\t\tMinecraftForge.EVENT_BUS.register(new Gui_EventManager());\n\t\tFMLCommonHandler.instance().bus().register(new EnviroKeybinds());\n\t}\n\n\t@Override\n\tpublic void preInit(FMLPreInitializationEvent event)\n\t{\n\t\tsuper.preInit(event);\n\t}\n\n\t@Override\n\tpublic void init(FMLInitializationEvent event)\n\t{\n\t\tsuper.init(event);\n\t\tEnviroKeybinds.Init();\n\n\t\tinitRenderers();\n\t\tregisterHudItems();\n\n\t}\n\n\t@SideOnly(Side.CLIENT)\n\tpublic static void initRenderers()\n\t{\n\t\tObjectHandler.renderGasID = RenderingRegistry.getNextAvailableRenderId();\n\t\tObjectHandler.renderSpecialID = RenderingRegistry.getNextAvailableRenderId();\n\t\tRenderingRegistry.registerBlockHandler(ObjectHandler.renderGasID, new RenderGasHandler());\n\t\tRenderingRegistry.registerBlockHandler(ObjectHandler.renderSpecialID, new RenderSpecialHandler());\n\n\t\tRenderingRegistry.registerEntityRenderingHandler(EntityPhysicsBlock.class, new RenderFallingBlock());\n\n\t\tarmoredCamelRenderers();\n\n\t\tClientRegistry.bindTileEntitySpecialRenderer(TileEntityElevator.class, new TileEntityElevatorRenderer());\n\n\nsrc/main/java/enviromine/client/renderer/tileentity/RenderSpecialHandler.java\n@SideOnly(Side.CLIENT)\npublic class RenderSpecialHandler implements ISimpleBlockRenderingHandler\n{\n\tstatic HashMap blockToTile = new HashMap();\n\t\n\t@Override\n\tpublic void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer)\n\t{\n\t\tif(blockToTile.containsKey(block))\n\t\t{\n GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);\n GL11.glTranslatef(-0.5F, -0.5F, -0.5F);\n if(!blockToTile.get(block).hasWorldObj())\n {\n \tblockToTile.get(block).setWorldObj(renderer.minecraftRB.theWorld);\n }\n \n if(blockToTile.get(block).blockType == null)\n {\n \tblockToTile.get(block).blockType = block;\n }\n blockToTile.get(block).blockMetadata = metadata;\n\t\t\tTileEntityRendererDispatcher.instance.renderTileEntityAt(blockToTile.get(block), 0.0D, 0.0D, 0.0D, 0.0F);\n GL11.glEnable(GL12.GL_RESCALE_NORMAL);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)\n\t{\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean shouldRender3DInInventory(int modelId)\n\t{\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic int getRenderId()\n\t{\n\t\treturn ObjectHandler.renderSpecialID;\n\t}\n\t\n\t{\n\t\tblockToTile.put(ObjectHandler.esky, new TileEntityEsky());\n\t\tblockToTile.put(ObjectHandler.freezer, new TileEntityFreezer());\n\t\tblockToTile.put(ObjectHandler.elevator, new TileEntityElevator());\n\t}\n}\n\nsrc/main/java/enviromine/client/gui/menu/EM_Gui_Menu.java\n@SideOnly(Side.CLIENT)\npublic class EM_Gui_Menu extends GuiScreen implements GuiYesNoCallback\n{\n\t\n\tprivate GuiScreen parentGuiScreen = null;\n\t\n\tpublic EM_Gui_Menu()\n\t{\n\t\t\n\t}\n\t\n\tpublic EM_Gui_Menu(GuiScreen par1GuiScreen)\n\t{\n\t\tthis.parentGuiScreen = par1GuiScreen;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic void initGui()\n\t{\n\t\tGuiButtonExt changeProfile = new GuiButtonExt(205, this.width / 2 - 90, this.height / 6 + 86, 180, 20, I18n.format(\"editor.enviromine.changeprofile\"));\n//\t\tGuiButtonExt serverSettings = new GuiButtonExt(103, this.width / 2 - 90, this.height / 6 + 122 - 6, 180, 20, \"(Coming Soon)\"+ StatCollector.translateToLocal(\"options.enviromine.configSettings\"));\n\t\tGuiButtonExt customEditor = new GuiButtonExt(104, this.width / 2 - 90, this.height / 6 + 108, 180, 20, StatCollector.translateToLocal(\"options.enviromine.customEditor\"));\n\t\t\n\t\t\n//\t\tserverSettings.enabled = false;\n\t\tcustomEditor.enabled = Minecraft.getMinecraft().isIntegratedServerRunning();\n\t\tchangeProfile.enabled = Minecraft.getMinecraft().isIntegratedServerRunning();\n\t\t\n//\t\tserverSettings.visible = true;\n\t\t\n\t\t// There will be no new posts.\n\t\t//String newPost = UpdateNotification.isNewPost() ? \" \" + StatCollector.translateToLocal(\"news.enviromine.newpost\") : \"\";\n\t\n \tthis.buttonList.add(changeProfile);\n/* \tif(!EM_Settings.voxelMenuExists) this.buttonList.add(new EM_Button(105, this.width / 2 - 90, this.height / 6 + 4, 180, 20, StatCollector.translateToLocal(\"options.enviromine.newsPage\"), newPost));\n \telse this.buttonList.add(new GuiButtonExt(105, this.width / 2 - 90, this.height / 6 + 4, 180, 20, StatCollector.translateToLocal(\"options.enviromine.newsPage\")+\" \" +newPost));*/\n \t//this.buttonList.add(new GuiButtonExt(105, this.width / 2 - 90, this.height / 6 + 4, 180, 20, StatCollector.translateToLocal(\"options.enviromine.newsPage\")));\n \t\n\t\tthis.buttonList.add(new GuiButtonExt(102, this.width / 2 - 90, this.height / 6 + 12, 180, 20, StatCollector.translateToLocal(\"options.enviromine.guiSounds\")));\n \tthis.buttonList.add(new GuiButtonExt(101, this.width / 2 - 90, this.height / 6 + 34, 180, 20, StatCollector.translateToLocal(\"options.enviromine.guiOptions\")));\n//\t\tthis.buttonList.add(serverSettings);\n\t\tthis.buttonList.add(customEditor);\n\t\tthis.buttonList.add(new GuiButtonExt(200, this.width / 2 - 100, this.height / 6 + 160, StatCollector.translateToLocal(\"gui.done\")));\n\t\t\n//\t\tthis.buttonList.add(new GuiButtonExt(300, 30 , this.height -55 , 75, 20, StatCollector.translateToLocal(\"options.enviromine.supportUs\")));\n//\t\tthis.buttonList.add(new GuiButtonExt(301, 30, this.height -30 , 75,20, StatCollector.translateToLocal(\"options.enviromine.website\")));\n\t\t\n\t\t\n\t}\n\t\n\t@Override\n\tpublic boolean doesGuiPauseGame()\n\t{\n\t\treturn true;\n\t}\n\t\n//\tprivate String ourwebsite = \"https://enviromine.wordpress.com/\";\n//\tprivate String supportPage = \"https://enviromine.wordpress.com/support-us/\";\n\t\n\t\n\t/* Send player to URL from this menu\n\t * (non-Javadoc)\n\t * @see net.minecraft.client.gui.GuiScreen#confirmClicked(boolean, int)\n\t */\n\t@Override\n\tpublic void confirmClicked(boolean p_73878_1_, int p_73878_2_) \n\t{\n//\t\tString url = \"\";\n//\t\tboolean go = false;\n//\t\t\n//\t\tif(p_73878_1_) // if true\n//\t\t{\n//\t\t\tif(p_73878_2_ == 1)\n//\t\t\t{\n//\t\t\t\turl = ourwebsite;\n//\t\t\t\tgo = true;\n//\t\t\t}\n//\t\t\t\n//\t\t\tif(p_73878_2_ == 2)\n//\t\t\t{\n//\t\t\t\turl = supportPage;\n//\t\t\t\tgo = true;\n//\t\t\t}\t\t\n//\t\t\t\n//\t\t\tif(Desktop.isDesktopSupported() && go)\n//\t\t\t{\n//\t\t\t\ttry \n//\t\t\t\t{\n//\t\t\t\t\tDesktop.getDesktop().browse(new URI(url));\n//\t\t\t\t}catch (Exception e) {\n//\t\t\t\t\tEnviroMine.logger.log(Level.WARN, \"(EM_Gui_Menu) Failed to open Default Browser to: \" + url);\n//\t\t\t\t}\n//\t\t\t}\n//\n//\t\t}\n\t\t\n\t\t\n\t\tthis.mc.displayGuiScreen(this);\n\t}\n\t\n\t/**\n\t * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e).\n\t */\n\t@Override\n\tprotected void actionPerformed(GuiButton par1GuiButton)\n\t{\n\t \t\n\t\tif(par1GuiButton.id == 205) \n\t\t{\n\t\t\tthis.mc.displayGuiScreen(new ProfileMenu(this));\t\n\t\t}\n\t\telse if (par1GuiButton.id == 100)\n\t\t{\n\t\t\tthis.mc.displayGuiScreen(new EM_Gui_General(this));\t\n\t\t}\n\t\telse if (par1GuiButton.id == 101)\n\t\t{\n\t\t\tthis.mc.displayGuiScreen(new EM_Gui_GuiSettings(this));\t\n\t\t}\n\t\telse if (par1GuiButton.id == 102)\n\t\t{\n\t\t\tthis.mc.displayGuiScreen(new EM_Gui_SoundSettings(this));\t\n\t\t}\n\t\telse if (par1GuiButton.id == 103)\n\t\t{\n\t\t\treturn; // Server settings. Coming soon...\n\t\t}\n\t\telse if (par1GuiButton.id == 104)\n\t\t{\n\t\t\tthis.mc.displayGuiScreen(new EM_ConfigMenu(this)); // In game editor\n\t\t}\n//\t\telse if (par1GuiButton.id == 105)\n//\t\t{\n//\t\t\tthis.mc.displayGuiScreen(new NewsPage(this, 150));\n//\t\t}\n//\t\telse if(par1GuiButton.id == 301)\n//\t\t{\n//\t\t\tthis.mc.displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal(\"options.enviromine.website\"), StatCollector.translateToLocal(\"options.enviromine.website.YesNo\"), 1));\n//\t\t}\n//\t\telse if(par1GuiButton.id == 300)\n//\t\t{\n//\t\t\tthis.mc.displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal(\"options.enviromine.supportUs\"), StatCollector.translateToLocal(\"options.enviromine.website.YesNo\"), 2));\n//\t\t}\n\t\telse if (par1GuiButton.id == 200)\n\t\t{\n\t\t\tthis.mc.displayGuiScreen(parentGuiScreen);\n\t\t}\n\n\t}\n\t\n\t@Override\n\tpublic void drawScreen(int par1, int par2, float par3)\n\t{\n\t\tthis.drawDefaultBackground();\n\t\t\n//\t\tif(!EnviroMine.proxy.isClient() && MinecraftServer.getServer().getConfigurationManager().func_152607_e(mc.thePlayer.getGameProfile()) || EnviroMine.proxy.isClient() )\n//\t\t{\n//\t\t\tthis.drawString(this.fontRendererObj, StatCollector.translateToLocal(\"options.enviromine.adminOptions.title\") + \" \", this.width / 2 -30, this.height / 6 + 84, 16777215);\n//\t\t}\n\t\tthis.drawCenteredString(this.fontRendererObj, StatCollector.translateToLocal(\"options.enviromine.guiMainmenu.title\"), this.width / 2, 30, 16777215);\n this.drawCenteredString(this.fontRendererObj, I18n.format(\"editor.enviromine.currentProfile\") +\": \"+ ChatFormatting.AQUA+EM_ConfigHandler.getProfileName()+ChatFormatting.RESET, this.width / 2, this.height / 6 + 74, 16777215);\n\t\tsuper.drawScreen(par1, par2, par3);\n\t}\n}\n\nsrc/main/java/enviromine/client/renderer/tileentity/TileEntityEskyRenderer.java\n@SideOnly(Side.CLIENT)\npublic class TileEntityEskyRenderer extends TileEntitySpecialRenderer\n{\n private static final ResourceLocation field_147520_b = new ResourceLocation(\"enviromine\", \"textures/models/blocks/esky_model.png\");\n private ModelChest field_147521_c = new ModelChest();\n\n public void renderTileEntityAt(TileEntityEsky p_147500_1_, double p_147500_2_, double p_147500_4_, double p_147500_6_, float p_147500_8_)\n {\n int i = 0;\n\n if (p_147500_1_.hasWorldObj())\n {\n i = p_147500_1_.getBlockMetadata();\n }\n\n this.bindTexture(field_147520_b);\n GL11.glPushMatrix();\n GL11.glEnable(GL12.GL_RESCALE_NORMAL);\n GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);\n GL11.glTranslatef((float)p_147500_2_, (float)p_147500_4_ + 1.0F, (float)p_147500_6_ + 1.0F);\n GL11.glScalef(1.0F, -1.0F, -1.0F);\n GL11.glTranslatef(0.5F, 0.5F, 0.5F);\n short short1 = 0;\n\n if (i == 2)\n {\n short1 = 180;\n }\n\n if (i == 3)\n {\n short1 = 0;\n }\n\n if (i == 4)\n {\n short1 = 90;\n }\n\n if (i == 5)\n {\n short1 = -90;\n }\n\n GL11.glRotatef((float)short1, 0.0F, 1.0F, 0.0F);\n GL11.glTranslatef(-0.5F, -0.5F, -0.5F);\n float f1 = p_147500_1_.field_145975_i + (p_147500_1_.field_145972_a - p_147500_1_.field_145975_i) * p_147500_8_;\n f1 = 1.0F - f1;\n f1 = 1.0F - f1 * f1 * f1;\n this.field_147521_c.chestLid.rotateAngleX = -(f1 * (float)Math.PI / 2.0F);\n this.field_147521_c.renderAll();\n GL11.glDisable(GL12.GL_RESCALE_NORMAL);\n GL11.glPopMatrix();\n GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);\n }\n\n @Override\n public void renderTileEntityAt(TileEntity p_147500_1_, double p_147500_2_, double p_147500_4_, double p_147500_6_, float p_147500_8_)\n {\n this.renderTileEntityAt((TileEntityEsky)p_147500_1_, p_147500_2_, p_147500_4_, p_147500_6_, p_147500_8_);\n }\n}\n\nsrc/main/java/enviromine/core/EM_Settings.java\npublic class EM_Settings\n{\n\tpublic static final UUID FROST1_UUID = UUID.fromString(\"B0C5F86A-78F3-417C-8B5A-527B90A1E919\");\n\tpublic static final UUID FROST2_UUID = UUID.fromString(\"5C4111A7-A66C-40FB-9FAD-1C6ADAEE7E27\");\n\tpublic static final UUID FROST3_UUID = UUID.fromString(\"721E793E-2203-4F6F-883F-6F44D7DDCCE1\");\n\tpublic static final UUID HEAT1_UUID = UUID.fromString(\"CA6E2CFA-4C53-4CD2-AAD3-3D6177A4F126\");\n\tpublic static final UUID DEHY1_UUID = UUID.fromString(\"38909A39-E1A1-4E93-9016-B2CCBE83D13D\");\n\n\tpublic static File worldDir = null;\n\n\t//Mod Data\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String MOD_ID = \"enviromine\";\n\tpublic static final String MOD_NAME = \"EnviroMine\";\n\tpublic static final String MOD_NAME_COLORIZED = EnumChatFormatting.AQUA + MOD_NAME + EnumChatFormatting.RESET;\n\tpublic static final String Channel = \"EM_CH\";\n\tpublic static final String Proxy = \"enviromine.core.proxies\";\n\tpublic static final String URL = \"https://modrinth.com/mod/enviromine-for-galaxy-odyssey\";\n\tpublic static final String VERSION_CHECKER_URL = \"https://gitgud.io/AstroTibs/enviromine-for-galaxy-odyssey/-/raw/1.7.10/CURRENT_VERSION\";\n\tpublic static final String GUI_FACTORY = MOD_ID+\".client.gui.menu.config.EnviroMineGuiFactory\";\n\n\tpublic static boolean versionChecker;\n\n\tpublic static int loggerVerbosity;\n\n public static boolean DeathFromHeartAttack;\n\n public static int HeartAttackTimeToDie;\n public static int HbmGasMaskBreakMultiplier;\n\n public static int EnviromineGasMaskBreakMultiplier;\n public static int HbmGasMaskBreakChanceNumber;\n\n public static boolean hardcoregases = false;\n\n\tpublic static boolean enablePhysics = false;\n\tpublic static boolean enableLandslide = true;\n\tpublic static boolean waterCollapse = true; // Added out of necessity/annoyance -- AstroTibs\n\n\tpublic static float blockTempDropoffPower = 0.75F;\n\tpublic static int scanRadius = 6;\n\tpublic static float auraRadius = 0.5F;\n\n\t@ShouldOverride\n\tpublic static boolean enableAirQ = true;\n\t@ShouldOverride\n\tpublic static boolean enableHydrate = true;\n\t@ShouldOverride\n\tpublic static boolean enableSanity = true;\n\t@ShouldOverride\n\tpublic static boolean enableBodyTemp = true;\n\n\tpublic static boolean trackNonPlayer = false;\n\n\tpublic static boolean spreadIce = false;\n\n\tpublic static boolean useFarenheit = false;\n\tpublic static String heatBarPos;\n\tpublic static String waterBarPos;\n\tpublic static String sanityBarPos;\n\tpublic static String oxygenBarPos;\n\n\tpublic static int dirtBottleID = 5001;\n\tpublic static int saltBottleID = 5002;\n\tpublic static int coldBottleID = 5003;\n\tpublic static int camelPackID = 5004;\n\n\tpublic static final String GAS_MASK_FILL_TAG_KEY = \"gasMaskFill\";\n\tpublic static final String GAS_MASK_MAX_TAG_KEY = \"gasMaskMax\";\n\tpublic static final String CAMEL_PACK_FILL_TAG_KEY = \"camelPackFill\";\n\tpublic static final String CAMEL_PACK_MAX_TAG_KEY = \"camelPackMax\";\n\tpublic static final String IS_CAMEL_PACK_TAG_KEY = \"isCamelPack\";\n\tpublic static int gasMaskMax = 1000;\n\tpublic static int filterRestore = 500;\n\tpublic static int camelPackMax = 100;\n\tpublic static float gasMaskUpdateRestoreFraction = 1F;\n\n\t/*\n\tpublic static int gasMaskID = 5005;\n\tpublic static int airFilterID = 5006;\n\tpublic static int hardHatID = 5007;\n\tpublic static int rottenFoodID = 5008;\n\n\tpublic static int blockElevatorTopID = 501;\n\tpublic static int blockElevatorBottomID = 502;\n\tpublic static int gasBlockID = 503;\n\tpublic static int fireGasBlockID = 504;\n\t*/\n\n\tpublic static int hypothermiaPotionID = 27;\n\tpublic static int heatstrokePotionID = 28;\n\tpublic static int frostBitePotionID = 29;\n\tpublic static int dehydratePotionID = 30;\n\tpublic static int insanityPotionID = 31;\n\n\tpublic static boolean enableHypothermiaGlobal = true;\n\tpublic static boolean enableHeatstrokeGlobal = true;\n\tpublic static boolean enableFrostbiteGlobal = true;\n\tpublic static boolean frostbitePermanent = true;\n\n\t//Gases\n\tpublic static boolean renderGases = false;\n\tpublic static int gasTickRate = 32; //GasFires are 4x faster than this\n\tpublic static int gasPassLimit = -1;\n\tpublic static boolean gasWaterLike = true;\n\tpublic static boolean slowGases = true; // Normal gases use random ticks to move\n\tpublic static boolean noGases = false;\n\n\t//World Gen\n\tpublic static boolean shaftGen = true;\n\tpublic static boolean gasGen = true;\n\tpublic static boolean oldMineGen = true;\n\n\t//Properties\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.ArmorPropsEncoder\")\n\t@ShouldOverride({String.class, ArmorProperties.class})\n\tpublic static HashMap armorProperties = new HashMap();\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.BlocksPropsEncoder\")\n\t@ShouldOverride({String.class, BlockProperties.class})\n\tpublic static HashMap blockProperties = new HashMap();\n\t@ShouldOverride({Integer.class, EntityProperties.class})\n\tpublic static HashMap livingProperties = new HashMap();\n\t@ShouldOverride({String.class, ItemProperties.class})\n\tpublic static HashMap itemProperties = new HashMap();\n\t@ShouldOverride({Integer.class, BiomeProperties.class})\n\tpublic static HashMap biomeProperties = new HashMap();\n\t@ShouldOverride({Integer.class, DimensionProperties.class})\n\tpublic static HashMap dimensionProperties = new HashMap();\n\n\tpublic static HashMap stabilityTypes = new HashMap();\n\n\t@ShouldOverride({String.class, RotProperties.class})\n\tpublic static HashMap rotProperties = new HashMap();\n\n\tpublic static boolean streamsDrink = true;\n\tpublic static boolean witcheryVampireImmunities = true;\n\tpublic static boolean witcheryWerewolfImmunities = true;\n\tpublic static boolean matterOverdriveAndroidImmunities = true;\n\n\tpublic static int updateCap = 128;\n\tpublic static boolean stoneCracks = true;\n\tpublic static String defaultStability = \"loose\";\n\n\tpublic static double sanityMult = 1.0D;\n\tpublic static double hydrationMult = 1.0D;\n\tpublic static double tempMult = 1.0D;\n\tpublic static double airMult = 1.0D;\n\n\t//public static boolean updateCheck = true;\n\t//public static boolean useDefaultConfig = true;\n\tpublic static boolean genConfigs = false;\n\tpublic static boolean genDefaults = false;\n\n\tpublic static int physInterval = 6;\n\tpublic static int worldDelay = 1000;\n\tpublic static int chunkDelay = 1000;\n\tpublic static int entityFailsafe = 1;\n\tpublic static boolean villageAssist = true;\n\n\tpublic static boolean minimalHud;\n\tpublic static boolean limitCauldron;\n\tpublic static boolean allowTinting = true;\n\tpublic static boolean torchesBurn = true;\n\tpublic static boolean torchesGoOut = true;\n\tpublic static boolean genFlammableCoal = true; // In case you don't want burny-coal\n\tpublic static boolean randomizeInsanityPitch = true;\n\tpublic static boolean catchFireAtHighTemps = true;\n\n\tpublic static int caveDimID = -3;\n\tpublic static int caveBiomeID = 23;\n\tpublic static boolean disableCaves = false;\n\tpublic static int limitElevatorY = 10;\n\tpublic static boolean caveOreEvent = true;\n\tpublic static boolean caveLava = false;\n\tpublic static int caveRavineRarity = 30;\n\tpublic static int caveTunnelRarity = 7;\n\tpublic static int caveDungeons = 8;\n\tpublic static int caveLiquidY = 32;\n\tpublic static boolean caveFlood = true;\n\tpublic static boolean caveRespawn = false;\n\tpublic static boolean enforceWeights = false;\n\tpublic static ArrayList caveGenProperties = new ArrayList();\n\tpublic static HashMap caveSpawnProperties = new HashMap();\n\n\tpublic static boolean foodSpoiling = true;\n\tpublic static int foodRotTime = 7;\n\n\t/** Whether or not this overridden with server settings */\n\tpublic static boolean isOverridden = false;\n\tpublic static boolean enableConfigOverride = false;\n\tpublic static boolean profileOverride = false;\n\tpublic static String profileSelected = \"default\";\n\n\tpublic static boolean enableQuakes = true;\n\tpublic static boolean quakePhysics = true;\n\tpublic static int quakeRarity = 100;\n\n\tpublic static boolean finiteWater = false;\n\tpublic static float thingChance = 0.000001F;\n\tpublic static boolean noNausea = false;\n\tpublic static boolean keepStatus = false;\n\tpublic static boolean renderGear = true;\n\tpublic static String[] cauldronHeatingBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\tpublic static String[] notWaterBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\n\tpublic static boolean voxelMenuExists = false;\n\n\t/**\n\t * Tells the server that this field should be sent to the client to overwrite
\n\t * Usage:
\n\t * @ShouldOverride - for ints/booleans/floats/Strings
\n\t * @ShouldOverride(Class[] value) - for ArrayList or HashMap types\n\t * */\n\t@Target(ElementType.FIELD)\n\t@Retention(RetentionPolicy.RUNTIME)\n\tpublic @interface ShouldOverride\n\t{\n\t\tClass[] value() default {};\n\t}\n}\n\nsrc/main/java/enviromine/blocks/tiles/TileEntityElevator.java\npublic class TileEntityElevator extends TileEntity\n{\n}\n\nsrc/main/java/enviromine/client/renderer/RenderPlayerEM.java\n@SideOnly(Side.CLIENT)\npublic class RenderPlayerEM extends RenderPlayer {\n\n\tpublic RenderPlayerEM() \n\t{\n\t\tsuper();\n\t\t\n\t\tthis.mainModel = new ModelPlayerEM(0.0F);\n\t\tthis.modelBipedMain = (ModelPlayerEM) this.mainModel;\n\t\tthis.modelArmorChestplate = new ModelPlayerEM(1.0F);\n\t\tthis.modelArmor = new ModelPlayerEM(0.5F);\n\t\n\t}\n\n\t@Override\n\tprotected void renderModel(EntityLivingBase par1EntityLivingBase, float par2, float par3, float par4, float par5, float par6, float par7) \n\t{\n\t\tsuper.renderModel(par1EntityLivingBase, par2, par3, par4, par5, par6, par7);\n\n\t}\n\n\t/*\n\t@Override\n\tprotected void rotateCorpse(AbstractClientPlayer par1AbstractClientPlayer,\tfloat par2, float par3, float par4) \n\t{\n\t\tif (par1AbstractClientPlayer.isEntityAlive() && par1AbstractClientPlayer.isPlayerSleeping()) \n\t\t{\n\t\t\tRotatePlayerEvent event = new RotatePlayerEvent(par1AbstractClientPlayer);\n\t\t\tMinecraftForge.EVENT_BUS.post(event);\n\t\t\tif (event.shouldRotate == null || event.shouldRotate) \n\t\t\t{\n\t\t\t\tGL11.glRotatef(\tpar1AbstractClientPlayer.getBedOrientationInDegrees(),\t0.0F, 1.0F, 0.0F);\n\t\t\t}\n\t\t} else \n\t\t{\n\t\t\tsuper.rotateCorpse(par1AbstractClientPlayer, par2, par3, par4);\n\t\t}\n\t}\n\n\tpublic static class RotatePlayerEvent extends PlayerEvent \n\t{\n\t\tpublic Boolean shouldRotate = null;\n\n\t\tpublic RotatePlayerEvent(AbstractClientPlayer player) \n\t\t{\n\t\t\tsuper(player);\n\t\t}\n\t}\n*/\n}\n\nsrc/main/java/enviromine/client/renderer/tileentity/TileEntityElevatorRenderer.java\npublic class TileEntityElevatorRenderer extends TileEntitySpecialRenderer\n{\n\tIModelCustom modelTop;\n\tIModelCustom modelBottom;\n\tResourceLocation mainTexture;\n\tResourceLocation recallTexture;\n\t\n\tpublic TileEntityElevatorRenderer()\n\t{\n\t\tmodelTop = AdvancedModelLoader.loadModel(new ResourceLocation(\"enviromine\", \"models/topblockelevator.obj\"));\n\t\tmodelBottom = AdvancedModelLoader.loadModel(new ResourceLocation(\"enviromine\", \"models/bottomblockelevator.obj\"));\n\t\tmainTexture = new ResourceLocation(\"enviromine\", \"textures/models/blocks/elevator_model.png\");\n\t\trecallTexture = new ResourceLocation(\"enviromine\", \"textures/models/blocks/recall_model.png\");\n\t}\n\t\n\t@Override\n\tpublic void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f)\n\t{\n\t\tGL11.glPushMatrix();\n GL11.glTranslated(x, y, z);\n if(tileentity.getBlockMetadata() >= 2)\n {\n \tMinecraft.getMinecraft().renderEngine.bindTexture(recallTexture);\n } else\n {\n \tMinecraft.getMinecraft().renderEngine.bindTexture(mainTexture);\n }\n if(tileentity.getBlockMetadata()%2 == 0)\n {\n \tmodelTop.renderAll();\n } else\n {\n \tmodelBottom.renderAll();\n }\n GL11.glPopMatrix();\n\t}\n}\n\nsrc/main/java/enviromine/blocks/tiles/TileEntityDavyLamp.java\npublic class TileEntityDavyLamp extends TileEntity\n{\n\tpublic TileEntityDavyLamp()\n\t{\n\t}\n}\n\nsrc/main/java/enviromine/client/renderer/tileentity/TileEntityDavyLampRenderer.java\npublic class TileEntityDavyLampRenderer extends TileEntitySpecialRenderer\n{\n\tIModelCustom model;\n\tResourceLocation texOff;\n\tResourceLocation[] texLit;\n\tResourceLocation[] texGas;\n\t\n\tpublic TileEntityDavyLampRenderer()\n\t{\n\t\tmodel = AdvancedModelLoader.loadModel(new ResourceLocation(\"enviromine\", \"models/davy_lamp.obj\"));\n\t\ttexOff = new ResourceLocation(\"enviromine\", \"textures/models/blocks/davy_lamp_model_off.png\");\n\t\ttexLit = new ResourceLocation[]{new ResourceLocation(\"enviromine\", \"textures/models/blocks/davy_lamp_model_lit_0.png\"), new ResourceLocation(\"enviromine\", \"textures/models/blocks/davy_lamp_model_lit_1.png\")};\n\t\ttexGas = new ResourceLocation[]{new ResourceLocation(\"enviromine\", \"textures/models/blocks/davy_lamp_model_gas_0.png\"), new ResourceLocation(\"enviromine\", \"textures/models/blocks/davy_lamp_model_gas_1.png\")};\n\t}\n\t\n\t@Override\n\tpublic void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f)\n\t{\n\t\tint pass = (int)(tileEntity.getWorldObj().getTotalWorldTime()/2%2);\n\t\tGL11.glPushMatrix();\n GL11.glTranslated(x, y, z);\n if(tileEntity.getBlockMetadata() == 1)\n {\n \tMinecraft.getMinecraft().renderEngine.bindTexture(texLit[pass]);\n } else if(tileEntity.getBlockMetadata() == 2)\n {\n \tMinecraft.getMinecraft().renderEngine.bindTexture(texGas[pass]);\n } else\n {\n \tMinecraft.getMinecraft().renderEngine.bindTexture(texOff);\n }\n model.renderAll();\n GL11.glPopMatrix();\n\t}\n}\n\nsrc/main/java/enviromine/client/gui/Gui_EventManager.java\n@SideOnly(Side.CLIENT)\npublic class Gui_EventManager\n{\n\n\tint width, height;\n\n\t//Render HUD\n\t//Render Player\n\n\t// Button Functions\n\tGuiButton enviromine;\n\n\t// Captures the initiation of vanilla menus to render new buttons\n\t@SuppressWarnings(\"unchecked\")\n\t@SubscribeEvent\n\tpublic void renderevent(InitGuiEvent.Post event)\n\t{\n\t\twidth = event.gui.width;\n\t\theight = event.gui.height;\n\n\t\tif(event.gui instanceof GuiIngameMenu && !EM_Settings.voxelMenuExists)\n\t\t{\n\t\t\t// There will be no new posts.\n\t\t\t//String newPost = UpdateNotification.isNewPost() ? \" \" + StatCollector.translateToLocal(\"news.enviromine.newpost\") : \"\";\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tbyte b0 = -16;\n\t\t\t\tenviromine = new GuiButton(1348, width / 2 - 100, height / 4 + 24 + b0, StatCollector.translateToLocal(\"options.enviromine.menu.title\"));\n\t\t\t\t//enviromine = new EM_Button(1348, width / 2 - 100, height / 4 + 24 + b0, StatCollector.translateToLocal(\"options.enviromine.menu.title\") , newPost);\n\t\t\t\tevent.buttonList.set(1, new GuiButton(4, width / 2 - 100, height / 4 + 0 + b0, I18n.format(\"menu.returnToGame\", new Object[0])));\n\t\t\t\tevent.buttonList.add(enviromine);\n\t\t\t} catch(Exception e)\n\t\t\t{\n\t\t\t\t//enviromine = new GuiButton(1348, width - 175, height - 30, 160, 20, StatCollector.translateToLocal(\"options.enviromine.menu.title\") + newPost);\n\t\t\t\tenviromine = new GuiButton(1348, width - 175, height - 30, 160, 20, StatCollector.translateToLocal(\"options.enviromine.menu.title\"));\n\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, \"Error shifting Minecrafts Menu to add in new button: \" + e);\n\t\t\t\tevent.buttonList.add(enviromine);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Used to capture when an Enviromine button is hit in a vanilla menu\n\t@SubscribeEvent\n\tpublic void action(ActionPerformedEvent.Post event)\n\t{\n\t\tif(event.gui instanceof GuiIngameMenu)\n\t\t{\n\t\t\tif(event.button.id == enviromine.id)\n\t\t\t{\n\t\t\t\tMinecraft.getMinecraft().displayGuiScreen(new EM_Gui_Menu(event.gui));\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic static int scaleTranslateX, scaleTranslateY;\n\n\tprivate Minecraft mc = Minecraft.getMinecraft();\n\n\tpublic static final ResourceLocation guiResource = new ResourceLocation(\"enviromine\", \"textures/gui/status_Gui.png\");\n\tpublic static final ResourceLocation blurOverlayResource = new ResourceLocation(\"enviromine\", \"textures/misc/blur.png\");\n\n\tpublic static EnviroDataTracker tracker = null;\n\n\t/**\n\t * All Enviromine Gui and Hud Items will render here\n\t * @param event\n\t */\n\t@SubscribeEvent\n\t@SideOnly(Side.CLIENT)\n\tpublic void onGuiRender(RenderGameOverlayEvent.Post event)\n\t{\n\t\tif(event.type != ElementType.HELMET || event.isCancelable())\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tmc.thePlayer.yOffset = 1.62F;\n\t\tif(ClientQuake.GetQuakeShake(mc.theWorld, mc.thePlayer) > 0)\n\t\t{\n\t\t\tif(mc.thePlayer == null || mc.thePlayer.isPlayerSleeping() || !mc.thePlayer.onGround || (mc.currentScreen != null && mc.currentScreen.doesGuiPauseGame()))\n\t\t\t{\n\t\t\t} else\n\t\t\t{\n\t\t\t\tfloat shakeMult = ClientQuake.GetQuakeShake(mc.theWorld, mc.thePlayer);\n\n\t\t\t\tdouble shakeSpeed = 2D * shakeMult;\n\t\t\t\tfloat offsetY = 0.2F * shakeMult;\n\n\t\t\t\tdouble shake = (int)(mc.theWorld.getTotalWorldTime() % 24000L) * shakeSpeed;\n\n\t\t\t\tmc.thePlayer.yOffset -= (Math.sin(shake) * (offsetY / 2F)) + (offsetY / 2F);\n\t\t\t\tmc.thePlayer.cameraPitch = (float)(Math.sin(shake) * offsetY / 4F);\n\t\t\t\tmc.thePlayer.cameraYaw = (float)(Math.sin(shake) * offsetY / 4F);\n\t\t\t}\n\t\t}\n\n\t\tHUDRegistry.checkForResize();\n\n\t\tif(tracker == null)\n\t\t{\n\t\t\tif(!(EM_Settings.enableAirQ == false && EM_Settings.enableBodyTemp == false && EM_Settings.enableHydrate == false && EM_Settings.enableSanity == false))\n\t\t\t{\n\t\t\t\t//Minecraft.getMinecraft().fontRenderer.drawStringWithShadow(\"NO ENVIRONMENT DATA\", xPos, (height - yPos) - 8, 16777215);\n\t\t\t\ttracker = EM_StatusManager.lookupTrackerFromUsername(this.mc.thePlayer.getCommandSenderName());\n\t\t\t}\n\t\t} else if(tracker.isDisabled || !EM_StatusManager.trackerList.containsValue(tracker))\n\t\t{\n\t\t\ttracker = null;\n\t\t} else\n\t\t{\n\n\t\t\tHudItem.blinkTick++;\n\n\n\t\t\t// Render GasMask Overlays\n\t\t\tif(UI_Settings.overlay)\n\t\t\t{\n\t\t\t\tGasMaskHud.renderGasMask(mc);\n\t\t\t}\n\n\t\t\t// Render Hud Items\n\t\t\tGL11.glPushMatrix();\n\t\t\tGL11.glDisable(GL11.GL_LIGHTING);\n\t GL11.glColor4f(1F, 1F, 1F, 1F);\n\n\t\t\tfor(HudItem huditem : HUDRegistry.getActiveHudItemList())\n\t\t\t{\n\n\t\t\t\tif(mc.playerController.isInCreativeMode() && !huditem.isRenderedInCreative())\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(mc.thePlayer.ridingEntity instanceof EntityLivingBase)\n\t\t\t\t{\n\t\t\t\t\tif(huditem.shouldDrawOnMount())\n\t\t\t\t\t{\n\t\t\t\t\t\tif(UI_Settings.overlay)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRenderAssist.bindTexture(huditem.getResource(\"TintOverlay\"));\n\t\t\t\t\t\t\thuditem.renderScreenOverlay(HUDRegistry.screenWidth, HUDRegistry.screenHeight);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tRenderAssist.bindTexture(huditem.getResource(\"\"));\n\n\t\t\t\t\t\t//float transx = (float)(huditem.posX - (huditem.posX * UI_Settings.guiScale));\n\t\t\t\t\t\t//float transy = (float)(huditem.posY - (huditem.posY * UI_Settings.guiScale));\n\n\t\t\t\t\t\t//GL11.glTranslated(transx, transy, 0);\n\n\t\t\t\t\t\t//GL11.glScalef((float)UI_Settings.guiScale, (float)UI_Settings.guiScale, (float)UI_Settings.guiScale);\n\n\t\t\t\t\t\thuditem.fixBounds();\n\t\t\t\t\t\thuditem.render();\n\n\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif(huditem.shouldDrawAsPlayer())\n\t\t\t\t\t{\n\t\t\t\t\t\tif(UI_Settings.overlay)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRenderAssist.bindTexture(huditem.getResource(\"TintOverlay\"));\n\t\t\t\t\t\t\thuditem.renderScreenOverlay(HUDRegistry.screenWidth, HUDRegistry.screenHeight);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tRenderAssist.bindTexture(huditem.getResource(\"\"));\n\n\t\t\t\t\t\t//float transx = (float)(huditem.posX - (huditem.posX * UI_Settings.guiScale));\n\t\t\t\t\t\t//float transy = (float)(huditem.posY - (huditem.posY * UI_Settings.guiScale));\n\n\t\t\t\t\t\t//GL11.glTranslated(transx, transy, 0);\n\n\t\t\t\t\t\t//GL11.glScalef((float)UI_Settings.guiScale, (float)UI_Settings.guiScale, (float)UI_Settings.guiScale);\n\n\t\t\t\t\t\thuditem.fixBounds();\n\t\t\t\t\t\thuditem.render();\n\n\t\t\t\t\t\t//GL11.glTranslated(0, 0, 0);\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tDebug_Info.ShowDebugText(event, mc);\n\t\t\tGL11.glPopMatrix();\n\t\t}\n\n\t}\n\n\t//TODO Was used for Debugging Gui\n\t/*@SubscribeEvent\n\tpublic void onGuiOpen(GuiOpenEvent event)\n\t{\n\t\tif(event == null) return;\n\t\tif(event.gui == null) return;\n\t\tSystem.out.println(event.gui.getClass().getSimpleName().toString());\n\t\tif(event.gui instanceof GuiConfig)\n\t\t{\n\t\t\tGuiConfig guiConfig = (GuiConfig) event.gui;\n\n\t\t\tSystem.out.println(\"configID:\"+guiConfig.configID +\" modID:\"+ guiConfig.modID);\n\n\t\t\tIterator elements = guiConfig.configElements.iterator();\n\n\t\t\twhile(elements.hasNext())\n\t\t\t{\n\t\t\t\tIConfigElement element = elements.next();\n\n\n\t\t\t\tSystem.out.println(\"element name:\"+ element.getName() +\" Type:\"+ element.getType() + \" QNamed:\"+element.getQualifiedName());\n\n\t\t\t}\n\n\t\t}\n\t}*/\n\n}\n\nsrc/main/java/enviromine/client/renderer/tileentity/RenderGasHandler.java\n@SideOnly(Side.CLIENT)\npublic class RenderGasHandler implements ISimpleBlockRenderingHandler\n{\n\tprivate IIcon icon;\n\tprivate Tessellator tessellator;\n\tprivate int verts;\n\n\t@Override\n\tpublic void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer)\n\t{\n\t\tTessellator tessellator = Tessellator.instance;\n\n\t\tfloat red = 1.0F;\n\t\tfloat green = 1.0F;\n\t\tfloat blue = 1.0F;\n\n\t\tif(renderer.useInventoryTint)\n\t\t{\n\t\t\tint var6 = block.getRenderColor(metadata);\n\n\t\t\tred = (float)(var6 >> 16 & 255) / 255.0F;\n\t\t\tgreen = (float)(var6 >> 8 & 255) / 255.0F;\n\t\t\tblue = (float)(var6 & 255) / 255.0F;\n\t\t}\n\n\t\trenderer.setRenderBoundsFromBlock(block);\n\t\tGL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);\n\t\tGL11.glTranslatef(-0.5F, -0.5F, -0.5F);\n\t\tGL11.glColor4f(red, green, blue, 1.0F);\n\n\t\ttessellator.startDrawingQuads();\n\t\ttessellator.setNormal(0.0F, -1.0F, 0.0F);\n\t\trenderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 0, metadata));\n\t\ttessellator.draw();\n\n\t\ttessellator.startDrawingQuads();\n\t\ttessellator.setNormal(0.0F, 1.0F, 0.0F);\n\t\trenderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata));\n\t\ttessellator.draw();\n\n\t\ttessellator.startDrawingQuads();\n\t\ttessellator.setNormal(0.0F, 0.0F, -1.0F);\n\t\trenderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 2, metadata));\n\t\ttessellator.draw();\n\t\ttessellator.startDrawingQuads();\n\t\ttessellator.setNormal(0.0F, 0.0F, 1.0F);\n\t\trenderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 3, metadata));\n\t\ttessellator.draw();\n\t\ttessellator.startDrawingQuads();\n\t\ttessellator.setNormal(-1.0F, 0.0F, 0.0F);\n\t\trenderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 4, metadata));\n\t\ttessellator.draw();\n\t\ttessellator.startDrawingQuads();\n\t\ttessellator.setNormal(1.0F, 0.0F, 0.0F);\n\t\trenderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 5, metadata));\n\t\ttessellator.draw();\n\n\t\tGL11.glTranslatef(0.5F, 0.5F, 0.5F);\n\t}\n\n\t@Override\n\tpublic boolean renderWorldBlock(IBlockAccess blockAccess, int i, int j, int k, Block oBlock, int modelId, RenderBlocks renderer)\n\t{\n if (!hardcoregases) {\n BlockGas block = (BlockGas) oBlock;\n\n Block sideBlock;\n float sideAlpha;\n\n if (!(blockAccess.getBlock(i, j, k) instanceof BlockGas)) {\n if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel())\n EnviroMine.logger.log(Level.ERROR, \"Trying to render gas without block at position!\");\n return false;\n } else if (blockAccess.getTileEntity(i, j, k) == null) {\n if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel())\n EnviroMine.logger.log(Level.ERROR, \"Trying to render gas without tile at position!\");\n return false;\n }\n\n icon = renderer.hasOverrideBlockTexture() ? renderer.overrideBlockTexture : renderer.getBlockIcon(block);\n int brightness = block.getMixedBrightnessForBlock(blockAccess, i, j, k);\n int color = block.colorMultiplier(blockAccess, i, j, k);\n\n float red = (float) ((color >> 16) & 0xFF) / 255.0F;\n float green = (float) ((color >> 8) & 0xFF) / 255.0F;\n float blue = (float) (color & 0xFF) / 255.0F;\n float alpha = block.getOpacity(blockAccess, i, j, k);\n\n if (alpha <= 0.1F) {\n return false;\n }\n\n double minX = 0D;\n double maxX = 1.0D;\n\n double minY = block.getMinY(blockAccess, i, j, k);\n double maxY = block.getMaxY(blockAccess, i, j, k);\n\n double minZ = 0D;\n double maxZ = 1.0D;\n\n double sideMinY;\n double sideMaxY;\n\n verts = 0;\n tessellator = Tessellator.instance;\n\n tessellator.setBrightness(brightness);\n tessellator.addTranslation((float) i, (float) j, (float) k);\n\n tessellator.setColorRGBA_F(red * 0.9F, green * 0.9F, blue * 0.9F, alpha * 0.9F);\n if (block.shouldSideBeRendered(blockAccess, i, j, k, 2)) {\n sideBlock = blockAccess.getBlock(i, j, k - 1);\n sideAlpha = sideBlock instanceof BlockGas ? ((BlockGas) sideBlock).getOpacity(blockAccess, i, j, k - 1) : 0F;\n\n if (sideAlpha > 0.1F) {\n sideMinY = ((BlockGas) sideBlock).getMinY(blockAccess, i, j, k - 1);\n sideMaxY = ((BlockGas) sideBlock).getMaxY(blockAccess, i, j, k - 1);\n\n if ((minY <= sideMinY & minY <= sideMaxY & maxY <= sideMinY & maxY <= sideMinY) | (minY >= sideMinY & minY >= sideMaxY & maxY >= sideMinY & maxY >= sideMinY)) {\n vertexAutoMap(minX, minY, minZ, maxX, minY);\n vertexAutoMap(minX, maxY, minZ, maxX, maxY);\n vertexAutoMap(maxX, maxY, minZ, minX, maxY);\n vertexAutoMap(maxX, minY, minZ, minX, minY);\n } else {\n if (minY < sideMinY) {\n vertexAutoMap(minX, minY, minZ, maxX, minY);\n vertexAutoMap(minX, sideMinY, minZ, maxX, sideMinY);\n vertexAutoMap(maxX, sideMinY, minZ, minX, sideMinY);\n vertexAutoMap(maxX, minY, minZ, minX, minY);\n }\n\n if (maxY > sideMaxY) {\n vertexAutoMap(minX, sideMaxY, minZ, maxX, sideMaxY);\n vertexAutoMap(minX, maxY, minZ, maxX, maxY);\n vertexAutoMap(maxX, maxY, minZ, minX, maxY);\n vertexAutoMap(maxX, sideMaxY, minZ, minX, sideMaxY);\n }\n }\n } else {\n vertexAutoMap(minX, minY, minZ, maxX, minY);\n vertexAutoMap(minX, maxY, minZ, maxX, maxY);\n vertexAutoMap(maxX, maxY, minZ, minX, maxY);\n vertexAutoMap(maxX, minY, minZ, minX, minY);\n }\n\n }\n\n if (block.shouldSideBeRendered(blockAccess, i, j, k, 3)) {\n sideBlock = blockAccess.getBlock(i, j, k + 1);\n sideAlpha = sideBlock instanceof BlockGas ? ((BlockGas) sideBlock).getOpacity(blockAccess, i, j, k + 1) : 0F;\n\n if (sideAlpha > 0.1F) {\n sideMinY = ((BlockGas) sideBlock).getMinY(blockAccess, i, j, k + 1);\n sideMaxY = ((BlockGas) sideBlock).getMaxY(blockAccess, i, j, k + 1);\n\n if ((minY <= sideMinY & minY <= sideMaxY & maxY <= sideMinY & maxY <= sideMinY) | (minY >= sideMinY & minY >= sideMaxY & maxY >= sideMinY & maxY >= sideMinY)) {\n vertexAutoMap(maxX, minY, maxZ, maxX, minY);\n vertexAutoMap(maxX, maxY, maxZ, maxX, maxY);\n vertexAutoMap(minX, maxY, maxZ, minX, maxY);\n vertexAutoMap(minX, minY, maxZ, minX, minY);\n } else {\n if (minY < sideMinY) {\n vertexAutoMap(maxX, minY, maxZ, maxX, minY);\n vertexAutoMap(maxX, sideMinY, maxZ, maxX, sideMinY);\n vertexAutoMap(minX, sideMinY, maxZ, minX, sideMinY);\n vertexAutoMap(minX, minY, maxZ, minX, minY);\n }\n\n if (maxY > sideMaxY) {\n vertexAutoMap(maxX, sideMaxY, maxZ, maxX, sideMaxY);\n vertexAutoMap(maxX, maxY, maxZ, maxX, maxY);\n vertexAutoMap(minX, maxY, maxZ, minX, maxY);\n vertexAutoMap(minX, sideMaxY, maxZ, minX, sideMaxY);\n }\n }\n } else {\n vertexAutoMap(maxX, minY, maxZ, maxX, minY);\n vertexAutoMap(maxX, maxY, maxZ, maxX, maxY);\n vertexAutoMap(minX, maxY, maxZ, minX, maxY);\n vertexAutoMap(minX, minY, maxZ, minX, minY);\n }\n }\n\n if (block.shouldSideBeRendered(blockAccess, i, j, k, 4)) {\n sideBlock = blockAccess.getBlock(i - 1, j, k);\n sideAlpha = sideBlock instanceof BlockGas ? ((BlockGas) sideBlock).getOpacity(blockAccess, i - 1, j, k) : 0F;\n\n if (sideAlpha > 0.1F) {\n sideMinY = ((BlockGas) sideBlock).getMinY(blockAccess, i - 1, j, k);\n sideMaxY = ((BlockGas) sideBlock).getMaxY(blockAccess, i - 1, j, k);\n\n if ((minY <= sideMinY & minY <= sideMaxY & maxY <= sideMinY & maxY <= sideMinY) | (minY >= sideMinY & minY >= sideMaxY & maxY >= sideMinY & maxY >= sideMinY)) {\n vertexAutoMap(minX, minY, maxZ, minZ, maxY);\n vertexAutoMap(minX, maxY, maxZ, minZ, minY);\n vertexAutoMap(minX, maxY, minZ, maxZ, minY);\n vertexAutoMap(minX, minY, minZ, maxZ, maxY);\n } else {\n if (minY < sideMinY) {\n vertexAutoMap(minX, minY, maxZ, minZ, sideMinY);\n vertexAutoMap(minX, sideMinY, maxZ, minZ, minY);\n vertexAutoMap(minX, sideMinY, minZ, maxZ, minY);\n vertexAutoMap(minX, minY, minZ, maxZ, sideMinY);\n }\n\n if (maxY > sideMaxY) {\n vertexAutoMap(minX, sideMaxY, maxZ, minZ, maxY);\n vertexAutoMap(minX, maxY, maxZ, minZ, sideMaxY);\n vertexAutoMap(minX, maxY, minZ, maxZ, sideMaxY);\n vertexAutoMap(minX, sideMaxY, minZ, maxZ, maxY);\n }\n }\n } else {\n vertexAutoMap(minX, minY, maxZ, minZ, maxY);\n vertexAutoMap(minX, maxY, maxZ, minZ, minY);\n vertexAutoMap(minX, maxY, minZ, maxZ, minY);\n vertexAutoMap(minX, minY, minZ, maxZ, maxY);\n }\n }\n\n if (block.shouldSideBeRendered(blockAccess, i, j, k, 5)) {\n sideBlock = blockAccess.getBlock(i + 1, j, k);\n sideAlpha = sideBlock instanceof BlockGas ? ((BlockGas) sideBlock).getOpacity(blockAccess, i + 1, j, k) : 0F;\n\n if (sideAlpha > 0.1F) {\n sideMinY = ((BlockGas) sideBlock).getMinY(blockAccess, i + 1, j, k);\n sideMaxY = ((BlockGas) sideBlock).getMaxY(blockAccess, i + 1, j, k);\n\n if ((minY <= sideMinY & minY <= sideMaxY & maxY <= sideMinY & maxY <= sideMinY) | (minY >= sideMinY & minY >= sideMaxY & maxY >= sideMinY & maxY >= sideMinY)) {\n vertexAutoMap(maxX, minY, minZ, minZ, maxY);\n vertexAutoMap(maxX, maxY, minZ, minZ, minY);\n vertexAutoMap(maxX, maxY, maxZ, maxZ, minY);\n vertexAutoMap(maxX, minY, maxZ, maxZ, maxY);\n } else {\n if (minY < sideMinY) {\n vertexAutoMap(maxX, minY, minZ, minZ, sideMinY);\n vertexAutoMap(maxX, sideMinY, minZ, minZ, minY);\n vertexAutoMap(maxX, sideMinY, maxZ, maxZ, minY);\n vertexAutoMap(maxX, minY, maxZ, maxZ, sideMinY);\n }\n\n if (maxY > sideMaxY) {\n vertexAutoMap(maxX, sideMaxY, minZ, minZ, maxY);\n vertexAutoMap(maxX, maxY, minZ, minZ, sideMaxY);\n vertexAutoMap(maxX, maxY, maxZ, maxZ, sideMaxY);\n vertexAutoMap(maxX, sideMaxY, maxZ, maxZ, maxY);\n }\n }\n } else {\n vertexAutoMap(maxX, minY, minZ, minZ, maxY);\n vertexAutoMap(maxX, maxY, minZ, minZ, minY);\n vertexAutoMap(maxX, maxY, maxZ, maxZ, minY);\n vertexAutoMap(maxX, minY, maxZ, maxZ, maxY);\n }\n }\n\n tessellator.setColorRGBA_F(red * 0.8F, green * 0.8F, blue * 0.8F, alpha * 0.9F);\n if (block.shouldSideBeRendered(blockAccess, i, j, k, 0)) {\n vertexAutoMap(maxX, minY, minZ, maxX, maxZ);\n vertexAutoMap(maxX, minY, maxZ, maxX, minZ);\n vertexAutoMap(minX, minY, maxZ, minX, minZ);\n vertexAutoMap(minX, minY, minZ, minX, maxZ);\n }\n\n tessellator.setColorRGBA_F(red, green, blue, alpha * 0.9F);\n if (block.shouldSideBeRendered(blockAccess, i, j, k, 1)) {\n vertexAutoMap(maxX, maxY, maxZ, maxX, maxZ);\n vertexAutoMap(maxX, maxY, minZ, maxX, minZ);\n vertexAutoMap(minX, maxY, minZ, minX, minZ);\n vertexAutoMap(minX, maxY, maxZ, minX, maxZ);\n }\n\n tessellator.addTranslation((float) -i, (float) -j, (float) -k);\n }\n if (verts <= 0) {\n return false;\n } else {\n return true;\n }\n\t}\n\n\tprivate void vertexAutoMap(double x, double y, double z, double u, double v)\n\t{\n\t\ttessellator.addVertexWithUV(x, y, z, icon.getInterpolatedU(u * 16.0D), icon.getInterpolatedV(v * 16.0D));\n\t\tverts += 1;\n\t}\n\n\t@Override\n\tpublic boolean shouldRender3DInInventory(int i)\n\t{\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic int getRenderId()\n\t{\n\t\treturn ObjectHandler.renderGasID;\n\t}\n\n}\n\nsrc/main/java/enviromine/blocks/tiles/TileEntityEsky.java\npublic class TileEntityEsky extends TileEntity implements IInventory\n{\n\tint tick = 0;\n\tint interval = 30;\n\tItemStack[] items = new ItemStack[27];\n\tlong lastCheck = -1;\n\t\n public float field_145972_a;\n public float field_145975_i;\n public int numPlayersUsing;\n private int field_145974_k;\n\t\n\tpublic TileEntityEsky()\n\t{\n\t}\n\t\n\t/**\n\t * Automatically adjust the use-by date on food items stored within the chest so they rot at half speed\n\t */\n\t@Override\n\tpublic void updateEntity()\n\t{\n\t\tsuper.updateEntity();\n\t\t\n\t\t// Chest Code\n\t\t\n if (++this.field_145974_k % 20 * 4 == 0)\n {\n this.worldObj.addBlockEvent(this.xCoord, this.yCoord, this.zCoord, Blocks.ender_chest, 1, this.numPlayersUsing);\n }\n\n this.field_145975_i = this.field_145972_a;\n float f = 0.1F;\n double d1;\n\n if (this.numPlayersUsing > 0 && this.field_145972_a == 0.0F)\n {\n double d0 = (double)this.xCoord + 0.5D;\n d1 = (double)this.zCoord + 0.5D;\n //this.worldObj.playSoundEffect(d0, (double)this.yCoord + 0.5D, d1, \"random.chestopen\", 0.5F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F);\n this.worldObj.playSoundEffect(d0, (double)this.yCoord + 0.5D, d1, \"enviromine:eskyopen\", 0.5F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F);\n }\n\n if (this.numPlayersUsing == 0 && this.field_145972_a > 0.0F || this.numPlayersUsing > 0 && this.field_145972_a < 1.0F)\n {\n float f2 = this.field_145972_a;\n\n if (this.numPlayersUsing > 0)\n {\n this.field_145972_a += f;\n }\n else\n {\n this.field_145972_a -= f;\n }\n\n if (this.field_145972_a > 1.0F)\n {\n this.field_145972_a = 1.0F;\n }\n\n float f1 = 0.5F;\n\n if (this.field_145972_a < f1 && f2 >= f1)\n {\n d1 = (double)this.xCoord + 0.5D;\n double d2 = (double)this.zCoord + 0.5D;\n //this.worldObj.playSoundEffect(d1, (double)this.yCoord + 0.5D, d2, \"random.chestclosed\", 0.5F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F);\n this.worldObj.playSoundEffect(d1, (double)this.yCoord + 0.5D, d2, \"enviromine:eskyclose\", 0.5F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F);\n }\n\n if (this.field_145972_a < 0.0F)\n {\n this.field_145972_a = 0.0F;\n }\n }\n \n // Esky Code\n\t\t\n\t\tif(this.getWorldObj() == null)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(lastCheck <= -1)\n\t\t{\n\t\t\tlastCheck = worldObj.getTotalWorldTime();\n\t\t}\n\t\t\n\t\tif(tick >= interval && !this.worldObj.isRemote)\n\t\t{\n\t\t\ttick = 0;\n\t\t\t\n\t\t\tlong time = worldObj.getTotalWorldTime() - lastCheck;\n\t\t\tlastCheck = worldObj.getTotalWorldTime();\n\t\t\t\n\t\t\tfor(int i = 0; i < this.getSizeInventory(); i++)\n\t\t\t{\n\t\t\t\tItemStack stack = this.getStackInSlot(i);\n\t\t\t\t\n\t\t\t\tif(stack == null)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tRotProperties rotProps = null;\n\t\t\t\tlong rotTime = (long)(EM_Settings.foodRotTime * 24000L);\n\t\t\t\t\n\t\t\t\tif(EM_Settings.rotProperties.containsKey(\"\" + Item.itemRegistry.getNameForObject(stack.getItem())))\n\t\t\t\t{\n\t\t\t\t\trotProps = EM_Settings.rotProperties.get(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()));\n\t\t\t\t\trotTime = (long)(rotProps.days * 24000L);\n\t\t\t\t} else if(EM_Settings.rotProperties.containsKey(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()) + \",\" + stack.getItemDamage()))\n\t\t\t\t{\n\t\t\t\t\trotProps = EM_Settings.rotProperties.get(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()) + \",\" + stack.getItemDamage());\n\t\t\t\t\trotTime = (long)(rotProps.days * 24000L);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(!EM_Settings.foodSpoiling || (rotProps == null && !(stack.getItem() instanceof ItemFood)) || rotTime < 0)\n\t\t\t\t{\n\t\t\t\t\tif(stack.getTagCompound() != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(stack.getTagCompound().hasKey(\"EM_ROT_DATE\"))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstack.getTagCompound().removeTag(\"EM_ROT_DATE\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(stack.getTagCompound().hasKey(\"EM_ROT_TIME\"))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstack.getTagCompound().removeTag(\"EM_ROT_TIME\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tif(stack.getTagCompound() == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tstack.setTagCompound(new NBTTagCompound());\n\t\t\t\t\t}\n\t\t\t\t\tNBTTagCompound tags = stack.getTagCompound();\n\t\t\t\t\t\n\t\t\t\t\tif(tags.hasKey(\"EM_ROT_DATE\"))\n\t\t\t\t\t{\n\t\t\t\t\t\ttags.setLong(\"EM_ROT_DATE\", tags.getLong(\"EM_ROT_DATE\") + time/2);\n\t\t\t\t\t\ttags.setLong(\"EM_ROT_TIME\", tags.getLong(\"EM_ROT_TIME\") + time/2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tthis.markDirty();\n\t\t} else\n\t\t{\n\t\t\ttick++;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int getSizeInventory()\n\t{\n\t\treturn 27;\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlot(int slot)\n\t{\n\t\treturn items[slot];\n\t}\n\n\t@Override\n\tpublic ItemStack decrStackSize(int p_70298_1_, int p_70298_2_)\n\t{\n if (this.items[p_70298_1_] != null)\n {\n ItemStack itemstack;\n\n if (this.items[p_70298_1_].stackSize <= p_70298_2_)\n {\n itemstack = this.items[p_70298_1_];\n this.items[p_70298_1_] = null;\n this.markDirty();\n return itemstack;\n }\n else\n {\n itemstack = this.items[p_70298_1_].splitStack(p_70298_2_);\n\n if (this.items[p_70298_1_].stackSize == 0)\n {\n this.items[p_70298_1_] = null;\n }\n\n this.markDirty();\n return itemstack;\n }\n }\n else\n {\n return null;\n }\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlotOnClosing(int p_70304_1_)\n\t{\n if (this.items[p_70304_1_] != null)\n {\n ItemStack itemstack = this.items[p_70304_1_];\n this.items[p_70304_1_] = null;\n return itemstack;\n }\n else\n {\n return null;\n }\n\t}\n\n\t@Override\n\tpublic void setInventorySlotContents(int slot, ItemStack stack)\n\t{\n this.items[slot] = stack;\n\n if (stack != null && stack.stackSize > this.getInventoryStackLimit())\n {\n stack.stackSize = this.getInventoryStackLimit();\n }\n\n this.markDirty();\n\t}\n\n\t@Override\n\tpublic String getInventoryName()\n\t{\n return \"container.enviromine.esky\";\n\t}\n\n\t@Override\n\tpublic boolean hasCustomInventoryName()\n\t{\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getInventoryStackLimit()\n\t{\n\t\treturn 64;\n\t}\n\n\t@Override\n\tpublic void markDirty()\n\t{\n\t}\n\n\t@Override\n\tpublic boolean isUseableByPlayer(EntityPlayer player)\n\t{\n return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : player.getDistanceSq((double)this.xCoord + 0.5D, (double)this.yCoord + 0.5D, (double)this.zCoord + 0.5D) <= 64.0D;\n\t}\n\n /**\n * Called when a client event is received with the event number and argument, see World.sendClientEvent\n */\n\t@Override\n public boolean receiveClientEvent(int p_145842_1_, int p_145842_2_)\n {\n if (p_145842_1_ == 1)\n {\n this.numPlayersUsing = p_145842_2_;\n return true;\n }\n else\n {\n return super.receiveClientEvent(p_145842_1_, p_145842_2_);\n }\n }\n\n\t@Override\n\tpublic void openInventory()\n\t{\n if (this.numPlayersUsing < 0)\n {\n this.numPlayersUsing = 0;\n }\n\n ++this.numPlayersUsing;\n this.worldObj.addBlockEvent(this.xCoord, this.yCoord, this.zCoord, this.getBlockType(), 1, this.numPlayersUsing);\n this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType());\n this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord - 1, this.zCoord, this.getBlockType());\n\t}\n\n\t@Override\n\tpublic void closeInventory()\n\t{\n if (this.getBlockType() instanceof BlockEsky)\n {\n --this.numPlayersUsing;\n this.worldObj.addBlockEvent(this.xCoord, this.yCoord, this.zCoord, this.getBlockType(), 1, this.numPlayersUsing);\n this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord, this.zCoord, this.getBlockType());\n this.worldObj.notifyBlocksOfNeighborChange(this.xCoord, this.yCoord - 1, this.zCoord, this.getBlockType());\n }\n\t}\n\n\t@Override\n\tpublic boolean isItemValidForSlot(int slot, ItemStack stack)\n\t{\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic void readFromNBT(NBTTagCompound tags)\n\t{\n super.readFromNBT(tags);\n \n if(tags.hasKey(\"RotCheck\"))\n {\n \tthis.lastCheck = tags.getLong(\"RotCheck\");\n } else\n {\n \tthis.lastCheck = -1;\n }\n \n NBTTagList nbttaglist = tags.getTagList(\"Items\", 10);\n this.items = new ItemStack[this.getSizeInventory()];\n\n for (int i = 0; i < nbttaglist.tagCount(); ++i)\n {\n NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);\n int j = nbttagcompound1.getByte(\"Slot\") & 255;\n\n if (j >= 0 && j < this.items.length)\n {\n this.items[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);\n }\n }\n\t}\n\t\n\t@Override\n\tpublic void writeToNBT(NBTTagCompound tags)\n\t{\n\t\tsuper.writeToNBT(tags);\n NBTTagList nbttaglist = new NBTTagList();\n\n for (int i = 0; i < this.items.length; ++i)\n {\n if (this.items[i] != null)\n {\n NBTTagCompound nbttagcompound1 = new NBTTagCompound();\n nbttagcompound1.setByte(\"Slot\", (byte)i);\n this.items[i].writeToNBT(nbttagcompound1);\n nbttaglist.appendTag(nbttagcompound1);\n }\n }\n\n tags.setTag(\"Items\", nbttaglist);\n tags.setLong(\"RotCheck\", this.lastCheck);\n\t}\n\t\n}\n\nsrc/main/java/enviromine/EntityPhysicsBlock.java\npublic class EntityPhysicsBlock extends EntityFallingBlock implements IEntityAdditionalSpawnData\n{\n\t\n\tpublic boolean isAnvil2 = true;\n\tpublic boolean isBreakingAnvil2;\n\tpublic int fallHurtMax2;\n\tpublic float fallHurtAmount2;\n\tpublic boolean isLandSlide = false;\n\tpublic boolean earthquake = false;\n\t\n\tpublic int fallTime = 0;\n\t\n\tpublic Block block;\n\tpublic int meta;\n\t\n\tpublic EntityPhysicsBlock(World world)\n\t{\n\t\tsuper(world);\n\t\tthis.isAnvil2 = true;\n\t\tthis.fallHurtMax2 = 40;\n\t\tthis.fallHurtAmount2 = 2.0F;\n\t\t\n\t\tif(EM_Settings.entityFailsafe > 0 && !world.isRemote)\n\t\t{\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tList entityList = this.worldObj.getEntitiesWithinAABB(EntityPhysicsBlock.class, this.boundingBox.expand(8F, 8F, 8F));\n\t\t\t\n\t\t\tif(entityList.size() >= 1024)\n\t\t\t{\n\t\t\t\tif(EM_Settings.entityFailsafe == 1)\n\t\t\t\t{\n\t\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel())\n\t\t\t\t\t{\n\t\t\t\t\t\tEnviroMine.logger.log(Level.WARN, \"Entity fail safe activated! Canceling new entities!\");\n\t\t\t\t\t\tEnviroMine.logger.log(Level.WARN, \"Location: \" + this.posX + \",\" + this.posY + \",\" + this.posZ);\n\t\t\t\t\t\tEnviroMine.logger.log(Level.WARN, \"No.: \" + entityList.size());\n\t\t\t\t\t}\n\t\t\t\t\tEM_PhysManager.physSchedule.clear();\n\t\t\t\t\tthis.setDead();\n\t\t\t\t\treturn;\n\t\t\t\t} else if(EM_Settings.entityFailsafe >= 2)\n\t\t\t\t{\n\t\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel())\n\t\t\t\t\t{\n\t\t\t\t\t\tEnviroMine.logger.log(Level.ERROR, \"Entity fail safe activated! Deleting excess entities!\");\n\t\t\t\t\t\tEnviroMine.logger.log(Level.ERROR, \"Location: \" + this.posX + \",\" + this.posY + \",\" + this.posZ);\n\t\t\t\t\t\tEnviroMine.logger.log(Level.ERROR, \"No.: \" + entityList.size());\n\t\t\t\t\t}\n\t\t\t\t\tIterator iterator = entityList.iterator();\n\t\t\t\t\t\n\t\t\t\t\twhile(iterator.hasNext())\n\t\t\t\t\t{\n\t\t\t\t\t\tEntityPhysicsBlock oldPhysBlock = iterator.next();\n\t\t\t\t\t\tif(!oldPhysBlock.isDead)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toldPhysBlock.setDead();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\n\t\t\t\t\tEM_PhysManager.physSchedule.clear();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic EntityPhysicsBlock(World world, double x, double y, double z, Block block, int meta, boolean update)\n\t{\n\t\tsuper(world, x, y, z, flowerID(block), meta);\n\t\tthis.isAnvil2 = true;\n\t\tthis.fallHurtMax2 = 40;\n\t\tthis.fallHurtAmount2 = 2.0F;\n\t\tthis.block = block;\n\t\tthis.meta = meta;\n\t\t\n\t\tif(EM_Settings.entityFailsafe > 0 && !world.isRemote)\n\t\t{\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tList entityList = this.worldObj.getEntitiesWithinAABB(EntityPhysicsBlock.class, this.boundingBox.expand(8F, 8F, 8F));\n\t\t\t\n\t\t\tif(entityList.size() >= 512)\n\t\t\t{\n\t\t\t\tif(EM_Settings.entityFailsafe == 1)\n\t\t\t\t{\n\t\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel())\n\t\t\t\t\t{\n\t\t\t\t\t\tEnviroMine.logger.log(Level.WARN, \"Entity fail safe activated: Level 1\");\n\t\t\t\t\t\tEnviroMine.logger.log(Level.WARN, \"Location: \" + this.posX + \",\" + this.posY + \",\" + this.posZ);\n\t\t\t\t\t\tEnviroMine.logger.log(Level.WARN, \"No.: \" + entityList.size());\n\t\t\t\t\t}\n\t\t\t\t\tEM_PhysManager.physSchedule.clear();\n\t\t\t\t\tthis.setDead();\n\t\t\t\t\treturn;\n\t\t\t\t} else if(EM_Settings.entityFailsafe >= 2)\n\t\t\t\t{\n\t\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel())\n\t\t\t\t\t{\n\t\t\t\t\t\tEnviroMine.logger.log(Level.ERROR, \"Entity fail safe activated: Level 2\");\n\t\t\t\t\t\tEnviroMine.logger.log(Level.ERROR, \"Location: \" + this.posX + \",\" + this.posY + \",\" + this.posZ);\n\t\t\t\t\t\tEnviroMine.logger.log(Level.ERROR, \"No.: \" + entityList.size());\n\t\t\t\t\t}\n\t\t\t\t\tIterator iterator = entityList.iterator();\n\t\t\t\t\t\n\t\t\t\t\twhile(iterator.hasNext())\n\t\t\t\t\t{\n\t\t\t\t\t\tEntityPhysicsBlock oldPhysBlock = iterator.next();\n\t\t\t\t\t\tif(!oldPhysBlock.isDead)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toldPhysBlock.setDead();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\n\t\t\t\t\tEM_PhysManager.physSchedule.clear();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tEM_PhysManager.usedSlidePositions.add(\"\" + MathHelper.floor_double(this.posX) + \",\" + MathHelper.floor_double(this.posZ));\n\t\t\n\t\tif(update)\n\t\t{\n\t\t\tEM_PhysManager.schedulePhysUpdate(world, (int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z), false, earthquake? \"Quake\" : \"Collapse\");\n\t\t}\n\t}\n\t\n\tpublic static Block flowerID(Block block)\n\t{\n\t\tif(block instanceof BlockFlower)\n\t\t{\n\t\t\treturn Blocks.air;\n\t\t} else\n\t\t{\n\t\t\treturn block;\n\t\t}\n\t}\n\t\n\t@Override\n\t/**\n\t * Returns true if other Entities should be prevented from moving through this Entity.\n\t */\n\tpublic boolean canBeCollidedWith()\n\t{\n\t\treturn false;\n\t}\n\t\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic void onUpdate()\n\t{\n\t\tif(this.block == null || this.block == Blocks.air)\n\t\t{\n\t\t\tthis.setDead();\n\t\t} else\n\t\t{\n\t\t\tthis.prevPosX = this.posX;\n\t\t\tthis.prevPosY = this.posY;\n\t\t\tthis.prevPosZ = this.posZ;\n\t\t\t++this.fallTime;\n\t\t\tthis.motionY -= 0.03999999910593033D;\n\t\t\tthis.moveEntity(this.motionX, this.motionY, this.motionZ);\n\t\t\tthis.motionX *= 0.9800000190734863D;\n\t\t\tthis.motionY *= 0.9800000190734863D;\n\t\t\tthis.motionZ *= 0.9800000190734863D;\n\t\t\t\n\t\t\tif(!this.worldObj.isRemote)\n\t\t\t{\n\t\t\t\tint i = MathHelper.floor_double(this.posX);\n\t\t\t\tint j = MathHelper.floor_double(this.posY);\n\t\t\t\tint k = MathHelper.floor_double(this.posZ);\n\t\t\t\t\n\t\t\t\tif(this.fallTime == 1)\n\t\t\t\t{\n\t\t\t\t\tif(this.worldObj.getBlock(i, j, k) != this.block && !isLandSlide)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\t\tList before = ((List)this.worldObj.getEntitiesWithinAABB(EntityItem.class, this.boundingBox.expand(1, 1, 1)));\n\t\t\t\t\tthis.worldObj.setBlockToAir(i, j, k);\n\t\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\t\tList after = ((List)this.worldObj.getEntitiesWithinAABB(EntityItem.class, this.boundingBox.expand(1, 1, 1)));\n\t\t\t\t\t\n\t\t\t\t\tfor (Entity e : before) {\n\t\t\t\t\t\tafter.remove(e);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfor (Entity e : after) {\n\t\t\t\t\t\te.setDead();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t AxisAlignedBB axisalignedbb = block.getCollisionBoundingBoxFromPool(this.worldObj, i, j - 1, k);\n\t\t\t if(axisalignedbb != null)\n\t\t\t {\n\t\t\t \tList fallingBlocks = this.worldObj.getEntitiesWithinAABB(EntityPhysicsBlock.class, axisalignedbb);\n\t\t\t \t\n\t\t\t \tfallingBlocks.remove(this);\n\t\t\t \t\n\t\t\t\t if(fallingBlocks.size() >= 1 && isLandSlide)\n\t\t\t\t {\n\t\t\t\t \tthis.motionY = 0;\n\t\t\t\t \tthis.setPosition(i + 0.5D, j + 0.5D, k + 0.5D);\n\t\t\t\t }\n\t\t\t }\n\t\t\t\t} catch(NullPointerException e)\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(earthquake)\n\t\t\t\t{\n\t\t\t\t\tfor(int jj = j; j >= MathHelper.ceiling_double_int(motionY); j --)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(jj <= 5)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else if(this.worldObj.getBlock(i, jj, k).getMaterial() == Material.lava)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else if(this.worldObj.getBlock(i, jj, k).getMaterial() == Material.water)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else if(this.worldObj.getBlock(i, jj, k) == Blocks.obsidian || this.worldObj.getBlock(i, jj, k) == Blocks.cobblestone)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(this.worldObj.getBlock(i, jj - 1, k).getMaterial() == Material.lava)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(this.onGround)\n\t\t\t\t{\n\t\t\t\t\tthis.motionX *= 0.699999988079071D;\n\t\t\t\t\tthis.motionZ *= 0.699999988079071D;\n\t\t\t\t\tthis.motionY *= -0.5D;\n\t\t\t\t\t\n\t\t\t\t\tif(this.worldObj.getBlock(i, j, k) != Blocks.piston_extension)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.setDead();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(!this.worldObj.canPlaceEntityOnSide(Blocks.anvil, i, j, k, true, 1, (Entity)null, (ItemStack)null) && !EM_PhysManager.blockNotSolid(this.worldObj, i, j, k, false))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tj += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif((this.block == Blocks.snow_layer && this.worldObj.getBlock(i, j, k) == Blocks.snow_layer && this.worldObj.getBlockMetadata(i, j, k) < 15) || (!this.isBreakingAnvil2 && this.worldObj.canPlaceEntityOnSide(Blocks.anvil, i, j, k, true, 1, (Entity)null, (ItemStack)null) && !BlockFalling.func_149831_e(this.worldObj, i, j - 1, k) && this.worldObj.setBlock(i, j, k, this.block, this.meta, 3)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(this.block == Blocks.snow_layer && this.worldObj.getBlock(i, j, k) == Blocks.snow_layer && this.worldObj.getBlockMetadata(i, j, k) < 15)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(this.worldObj.getBlockMetadata(i, j, k) >= 14)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tthis.worldObj.setBlock(i, j, k, Blocks.snow);\n\t\t\t\t\t\t\t\t} else\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tthis.worldObj.setBlockMetadataWithNotify(i, j, k, this.worldObj.getBlockMetadata(i, j, k) + 1, 3);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if(meta != this.worldObj.getBlockMetadata(i, j, k))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tthis.worldObj.setBlockMetadataWithNotify(i, j, k, meta, 2);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tEM_PhysManager.schedulePhysUpdate(this.worldObj, i, j, k, true, earthquake? \"Quake\" : \"Collapse\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t/*if(block instanceof BlockFalling)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t((BlockFalling)block).func_149828_a(this.worldObj, i, j, k, this.meta);\n\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tBlock bSurface = null;\n\t\t\t\t\t\t\tif(this.worldObj.getBlock(i, j - 1, k) != Blocks.air && this.worldObj.getBlock(i, j - 1, k).getMaterial() != Material.air)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbSurface = this.worldObj.getBlock(i, j -1 , k);\n\t\t\t\t\t\t\t\tthis.worldObj.playSoundEffect((double)((float)i + 0.5F), (double)((float)j + 0.5F), (double)((float)k + 0.5F), bSurface.stepSound.func_150496_b(), (bSurface.stepSound.getVolume() + 1.0F) / 2.0F, bSurface.stepSound.getPitch() * 0.5F);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(bSurface == null || bSurface != this.block)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tthis.worldObj.playSoundEffect((double)((float)i + 0.5F), (double)((float)j + 0.5F), (double)((float)k + 0.5F), this.block.stepSound.func_150496_b(), (this.block.stepSound.getVolume() + 1.0F) / 2.0F, this.block.stepSound.getPitch() * 0.5F);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(this.field_145810_d != null && block instanceof ITileEntityProvider)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tTileEntity tileentity = this.worldObj.getTileEntity(i, j, k);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(tileentity != null)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tNBTTagCompound nbttagcompound = new NBTTagCompound();\n\t\t\t\t\t\t\t\t\ttileentity.writeToNBT(nbttagcompound);\n\t\t\t\t\t\t\t\t\tIterator iterator = this.field_145810_d.func_150296_c().iterator();\n\n while (iterator.hasNext())\n {\n String s = (String)iterator.next();\n NBTBase nbtbase = this.field_145810_d.getTag(s);\n\n if (!s.equals(\"x\") && !s.equals(\"y\") && !s.equals(\"z\"))\n {\n nbttagcompound.setTag(s, nbtbase.copy());\n }\n }\n\n tileentity.readFromNBT(nbttagcompound);\n tileentity.markDirty();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if(this.field_145813_c && !this.isBreakingAnvil2 && !earthquake)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis.entityDropItem(new ItemStack(this.block, 1, this.block.damageDropped(this.meta)), 0.0F);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if(this.fallTime > 100 && !this.worldObj.isRemote && (j < 1 || j > 256) || this.fallTime > 600)\n\t\t\t\t{\n\t\t\t\t\tif(this.field_145813_c && !earthquake)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.entityDropItem(new ItemStack(this.block, 1, this.block.damageDropped(this.meta)), 0.0F);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis.setDead();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@SuppressWarnings({\"unchecked\", \"rawtypes\"})\n\t@Override\n\tprotected void fall(float par1)\n\t{\n\t\tif(this.isAnvil2)\n\t\t{\n\t\t\tint i = MathHelper.ceiling_float_int(par1 - 1.0F);\n\t\t\t\n\t\t\tif(isLandSlide)\n\t\t\t{\n\t\t\t\ti = 2;\n\t\t\t}\n\t\t\t\n\t\t\tif(i > 0)\n\t\t\t{\n\t\t\t\tArrayList arraylist = new ArrayList(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox));\n\t\t\t\t\n\t\t\t\tDamageSource damagesource;\n\t\t\t\t\n\t\t\t\tif(isLandSlide)\n\t\t\t\t{\n\t\t\t\t\tif(this.block.getMaterial() == Material.snow)\n\t\t\t\t\t{\n\t\t\t\t\t\tdamagesource = EnviroDamageSource.avalanche;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tdamagesource = EnviroDamageSource.landslide;\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tdamagesource = this.block == Blocks.anvil ? DamageSource.anvil : DamageSource.fallingBlock;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tIterator iterator = arraylist.iterator();\n\t\t\t\t\n\t\t\t\twhile(iterator.hasNext())\n\t\t\t\t{\n\t\t\t\t\tEntity entity = (Entity)iterator.next();\n\t\t\t\t\tentity.attackEntityFrom(damagesource, (float)Math.min(MathHelper.floor_float((float)i * this.fallHurtAmount2), this.fallHurtMax2));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(this.block == Blocks.anvil && (double)this.rand.nextFloat() < 0.05000000074505806D + (double)i * 0.05D)\n\t\t\t\t{\n\t\t\t\t\tint j = this.meta >> 2;\n\t\t\t\t\tint k = this.meta & 3;\n\t\t\t\t\t++j;\n\t\t\t\t\t\n\t\t\t\t\tif(j > 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.isBreakingAnvil2 = true;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.meta = k | j << 2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n /**\n * (abstract) Protected helper method to write subclass entity data to NBT.\n */\n\t@Override\n protected void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)\n {\n \tsuper.writeEntityToNBT(par1NBTTagCompound);\n \tpar1NBTTagCompound.setByte(\"Tile\", (byte)Block.getIdFromBlock(this.block));\n \tpar1NBTTagCompound.setInteger(\"TileID\", Block.getIdFromBlock(this.block));\n \tpar1NBTTagCompound.setByte(\"Data\", (byte)this.meta);\n par1NBTTagCompound.setBoolean(\"HurtEntities2\", this.isAnvil2);\n par1NBTTagCompound.setFloat(\"FallHurtAmount2\", this.fallHurtAmount2);\n par1NBTTagCompound.setInteger(\"FallHurtMax2\", this.fallHurtMax2);\n par1NBTTagCompound.setBoolean(\"Landslide\", this.isLandSlide);\n }\n\n /**\n * (abstract) Protected helper method to read subclass entity data from NBT.\n */\n @Override\n protected void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)\n {\n \tsuper.readEntityFromNBT(par1NBTTagCompound);\n\n if (par1NBTTagCompound.hasKey(\"TileID\", 99))\n {\n this.block = Block.getBlockById(par1NBTTagCompound.getInteger(\"TileID\"));\n }\n else\n {\n this.block = Block.getBlockById(par1NBTTagCompound.getByte(\"Tile\") & 255);\n }\n \n this.meta = par1NBTTagCompound.getByte(\"Data\") & 255;\n \n if (par1NBTTagCompound.hasKey(\"HurtEntities2\"))\n {\n this.isAnvil2 = par1NBTTagCompound.getBoolean(\"HurtEntities2\");\n this.fallHurtAmount2 = par1NBTTagCompound.getFloat(\"FallHurtAmount2\");\n this.fallHurtMax2 = par1NBTTagCompound.getInteger(\"FallHurtMax2\");\n }\n else if (this.block == Blocks.anvil)\n {\n this.isAnvil2 = true;\n }\n this.isLandSlide = par1NBTTagCompound.getBoolean(\"Landslide\");\n }\n\n\t@Override\n\tpublic void writeSpawnData(ByteBuf buffer)\n\t{\n\t\tNBTTagCompound tags = new NBTTagCompound();\n\t\tthis.writeEntityToNBT(tags);\n\t\t\n\t\tByteBufUtils.writeTag(buffer, tags);\n\t}\n\n\t@Override\n\tpublic void readSpawnData(ByteBuf additionalData)\n\t{\n\t\tNBTTagCompound tags = ByteBufUtils.readTag(additionalData);\n\t\tthis.readEntityFromNBT(tags);\n\t}\n}", "answers": ["\t\tClientRegistry.bindTileEntitySpecialRenderer(TileEntityDavyLamp.class, new TileEntityDavyLampRenderer());"], "length": 6255, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "850432db-a935-499e-9bcd-d991b20ec5aa", "reasoning": "The EM_ClientProxy.initRenderers() method registers renderers for various tile entities. After binding the TileEntityElevator renderer, the next logical registration is for the TileEntityEsky renderer, using the same ClientRegistry.bindTileEntitySpecialRenderer pattern.", "reasoning_model_answer": "ClientRegistry.bindTileEntitySpecialRenderer(TileEntityEsky.class, new TileEntityEskyRenderer());", "assistant_with_reasoning": "\nThe EM_ClientProxy.initRenderers() method registers renderers for various tile entities. After binding the TileEntityElevator renderer, the next logical registration is for the TileEntityEsky renderer, using the same ClientRegistry.bindTileEntitySpecialRenderer pattern.\n\nClientRegistry.bindTileEntitySpecialRenderer(TileEntityEsky.class, new TileEntityEskyRenderer());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.567, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 38310, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "ClientRegistry.bindTileEntitySpecialRenderer(TileEntityEsky.class, new TileEntityEskyRenderer());", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport com.siam.package_order.mapper.OrderRefundMapper;\nimport com.siam.package_order.mapper.OrderMapper;\nimport com.siam.package_order.service.OrderRefundService;\nimport com.siam.package_order.entity.OrderRefund;\nimport com.siam.package_order.model.example.OrderRefundExample;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.math.BigDecimal;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;", "context": "siam-order/order-provider/src/main/java/com/siam/package_order/service_impl/OrderRefundServiceImpl.java\npackage com.siam.package_order.service_impl;\n\n\n\n@Service\npublic class OrderRefundServiceImpl implements OrderRefundService {\n @Autowired\n private OrderRefundMapper orderRefundMapper;\n @Autowired\n private OrderMapper orderMapper;\n\n public int countByExample(OrderRefundExample example){\n return orderRefundMapper.countByExample(example);\n }\n\n public void deleteByPrimaryKey(Integer id){\n orderRefundMapper.deleteByPrimaryKey(id);\n }\n\n public void insertSelective(OrderRefund record){\n orderRefundMapper.insertSelective(record);\n }\n\n\nsiam-order/order-provider/src/main/java/com/siam/package_order/mapper/OrderMapper.java\npublic interface OrderMapper extends BaseMapper {\n int countByExample(OrderExample example);\n\n int deleteByExample(OrderExample example);\n\n int deleteByPrimaryKey(Integer id);\n\n int insertSelective(Order record);\n\n List selectByExample(OrderExample example);\n\n Order selectByPrimaryKey(Integer id);\n\n int updateByExampleSelective(@Param(\"record\") Order record, @Param(\"example\") OrderExample example);\n\n int updateByExample(@Param(\"record\") Order record, @Param(\"example\") OrderExample example);\n\n int updateByPrimaryKeySelective(Order record);\n\n int updateByPrimaryKey(Order record);\n\n @ResultMap(\"BaseResultMap\")\n @Select(\"\")\n Page getListByPageWithAsc(@Param(\"page\") Page page, @Param(\"orderDto\") OrderParam param);\n\n @ResultMap(\"CustomResultMap\")\n @Select(\"\")\n Page> getListByPageWithDesc(@Param(\"page\") Page page, @Param(\"order\") OrderParam param);\n\n @ResultMap(\"BaseResultMap\")\n @Select(\"select o.* from tb_order o where o.order_no = #{orderNo}\")\n Order selectByOrderNo(@Param(\"orderNo\") String orderNo);\n\n //查询超时未支付订单\n @ResultMap(\"BaseResultMap\")\n @Select(\"select o.* from tb_order o where o.status = 1 and payment_deadline < now()\")\n List selectOverdueOrder();\n\n @Update(\"\")\n int batchUpdateIsPrintedTrue(@Param(\"idList\") List idList);\n\n @Select(\"select max(queue_no) from tb_order where to_days(create_time) = to_days(now())\")\n Integer findMaxQueueNo();\n\n @ResultMap(\"BaseResultMap\")\n @Select(\"\")\n Page getListByTodayOrderWithAsc(@Param(\"page\") Page page, @Param(\"orderDto\") OrderParam param);\n\n @Update(\"update tb_order set order_completion_time=#{updateTime}, update_time=#{updateTime}, status=#{status} where payment_success_time < #{overdueTime} and status in(2, 3, 4, 5)\")\n int updateFinish(@Param(\"overdueTime\") Date overdueTime,@Param(\"updateTime\") Date updateTime,@Param(\"status\") Integer status);\n\n @ResultMap(\"CustomResultMap\")\n @Select(\"\")\n Map countOrder(@Param(\"order\") OrderParam param);\n\n @ResultMap(\"BaseResultMap\")\n @Select(\"select o.* from tb_order o where o.change_to_delivery_out_trade_no = #{changeToDeliveryOutTradeNo}\")\n Order selectByChangeToDeliveryOutTradeNo(@Param(\"changeToDeliveryOutTradeNo\") String changeToDeliveryOutTradeNo);\n\n @Select(\"select count(*) as latelyMonthlySales from tb_order as o \"+\n \"where shop_id = #{shopId} and o.status = 6 and (o.create_time between #{startTime} and #{endTime})\")\n Integer selectLatelyMonthlySalesByShopId(@Param(\"startTime\") Date startTime, @Param(\"endTime\") Date endTime, @Param(\"shopId\") Integer shopId);\n\n @Select(\"\")\n BigDecimal selectSumMerchantIncome(@Param(\"order\") OrderParam param);\n\n @Select(\"\")\n BigDecimal selectSumActualPrice(@Param(\"order\") OrderParam param);\n\n @Select(\"\")\n Integer selectCountCompleted(@Param(\"order\") OrderParam param);\n\n @Select(\"\")\n Integer selectCountPaid(@Param(\"order\") OrderParam param);\n\n @Select(\"SELECT if(o.status in (2, 4) and TIMESTAMPDIFF(MINUTE, o.payment_success_time, now()) < 1, true, false) FROM tb_order as o WHERE o.id = #{order.id}\")\n boolean getIsAllowCancelNoReason(@Param(\"order\") OrderParam param);\n\n @Select(\"SELECT if(o.status not in (1, 7, 8, 9, 10, 11) and TIMESTAMPDIFF(HOUR, o.payment_success_time, now()) < 24, true, false) FROM tb_order as o WHERE o.id = #{order.id}\")\n boolean getIsAllowApplyRefund(@Param(\"order\") OrderParam param);\n\n @ResultMap(\"CustomResultMap\")\n @Select(\"\")\n Page getAfterSalesListByPageWithAsc(@Param(\"page\") Page page, @Param(\"orderDto\") OrderParam param);\n\n @ResultMap(\"BaseResultMap\")\n @Select(\"SELECT o.* FROM tb_order o where o.status in (6, 9) and TIMESTAMPDIFF(HOUR, o.payment_success_time, now()) > 24 and o.is_pay_to_merchant = 0\")\n List selectByNeedPayOrderFrozenBalanceOfMerchant();\n\n @Select(\"SELECT o.shop_id FROM tb_order o WHERE o.status IN (2, 4) AND TIMESTAMPDIFF(MINUTE, o.payment_success_time, NOW()) > 10 GROUP BY o.shop_id\")\n List selectShopIdByOvertimeOrder();\n\n @Select(\"\")\n List> selectStatisticOrder(@Param(\"shopId\") Integer shopId);\n\n @Select(\"\")\n String selectStartDateOrder(@Param(\"shopId\") Integer shopId);\n\n //查询支付人数\n @Select(\"\")\n int selectCountPayers(@Param(\"order\") OrderParam param);\n\n //查询下单人数\n @Select(\"\")\n int selectCountOrderPeoples(@Param(\"order\") OrderParam param);\n\n @Select(\"\")\n Map selectSumField(@Param(\"order\") OrderParam param);\n\n @Select(\"\")\n Integer selectCountUnCompleted(@Param(\"order\") OrderParam param);\n\n @Select(\"\")\n Integer selectCountWaitHandle(@Param(\"order\") OrderParam param);\n\n}\n\nsiam-order/order-provider/src/main/java/com/siam/package_order/service/OrderRefundService.java\npublic interface OrderRefundService {\n int countByExample(OrderRefundExample example);\n\n void deleteByPrimaryKey(Integer id);\n\n void insertSelective(OrderRefund record);\n\n List selectByExample(OrderRefundExample example);\n\n OrderRefund selectByPrimaryKey(Integer id);\n\n void updateByExampleSelective(OrderRefund record, OrderRefundExample example);\n\n void updateByPrimaryKeySelective(OrderRefund record);\n\n Page getListByPage(int pageNo, int pageSize, OrderRefund orderRefund);\n\n OrderRefund selectByOrderId(Integer orderId);\n\n Map selectSumField(OrderRefund orderRefund);\n\n BigDecimal selectSumRefundAmount(OrderRefund orderRefund, Date startTime, Date endTime);\n\n BigDecimal selectSumRefundAmountByPlatformCoin(OrderRefund orderRefund, Date startTime, Date endTime);\n}\n\nsiam-order/order-api/src/main/java/com/siam/package_order/entity/OrderRefund.java\n@Data\n@TableName(\"tb_order_refund\")\npublic class OrderRefund {\n\n Date startTime;\n Date endTime;\n\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n private Integer orderId;\n\n private Integer type;\n\n private Integer refundWay;\n\n private Integer refundReason;\n\n private String refundReasonDescription;\n\n private String evidenceImages;\n\n private BigDecimal refundAmount;\n\n private Integer refundAccount;\n\n private Integer status;\n\n private Integer goodsTotalQuantity;\n\n private BigDecimal goodsTotalPrice;\n\n private BigDecimal packingCharges;\n\n private Boolean isRefundDeliveryFee;\n\n private BigDecimal deliveryFee;\n\n private Boolean isUsedCoupons;\n\n private Boolean isUsedFullReductionRule;\n\n private Date createTime;\n\n private Date updateTime;\n\n //页码\n private Integer pageNo = 1;\n\n //页面大小\n private Integer pageSize = 20;\n\n public Integer getPageNo() {\n return pageNo;\n }\n\n public void setPageNo(Integer pageNo) {\n this.pageNo = pageNo;\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Integer getOrderId() {\n return orderId;\n }\n\n public void setOrderId(Integer orderId) {\n this.orderId = orderId;\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Integer getRefundWay() {\n return refundWay;\n }\n\n public void setRefundWay(Integer refundWay) {\n this.refundWay = refundWay;\n }\n\n public Integer getRefundReason() {\n return refundReason;\n }\n\n public void setRefundReason(Integer refundReason) {\n this.refundReason = refundReason;\n }\n\n public String getRefundReasonDescription() {\n return refundReasonDescription;\n }\n\n public void setRefundReasonDescription(String refundReasonDescription) {\n this.refundReasonDescription = refundReasonDescription == null ? null : refundReasonDescription.trim();\n }\n\n public String getEvidenceImages() {\n return evidenceImages;\n }\n\n public void setEvidenceImages(String evidenceImages) {\n this.evidenceImages = evidenceImages == null ? null : evidenceImages.trim();\n }\n\n public BigDecimal getRefundAmount() {\n return refundAmount;\n }\n\n public void setRefundAmount(BigDecimal refundAmount) {\n this.refundAmount = refundAmount;\n }\n\n public Integer getRefundAccount() {\n return refundAccount;\n }\n\n public void setRefundAccount(Integer refundAccount) {\n this.refundAccount = refundAccount;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Integer getGoodsTotalQuantity() {\n return goodsTotalQuantity;\n }\n\n public void setGoodsTotalQuantity(Integer goodsTotalQuantity) {\n this.goodsTotalQuantity = goodsTotalQuantity;\n }\n\n public BigDecimal getGoodsTotalPrice() {\n return goodsTotalPrice;\n }\n\n public void setGoodsTotalPrice(BigDecimal goodsTotalPrice) {\n this.goodsTotalPrice = goodsTotalPrice;\n }\n\n public BigDecimal getPackingCharges() {\n return packingCharges;\n }\n\n public void setPackingCharges(BigDecimal packingCharges) {\n this.packingCharges = packingCharges;\n }\n\n public Boolean getIsRefundDeliveryFee() {\n return isRefundDeliveryFee;\n }\n\n public void setIsRefundDeliveryFee(Boolean isRefundDeliveryFee) {\n this.isRefundDeliveryFee = isRefundDeliveryFee;\n }\n\n public BigDecimal getDeliveryFee() {\n return deliveryFee;\n }\n\n public void setDeliveryFee(BigDecimal deliveryFee) {\n this.deliveryFee = deliveryFee;\n }\n\n public Boolean getIsUsedCoupons() {\n return isUsedCoupons;\n }\n\n public void setIsUsedCoupons(Boolean isUsedCoupons) {\n this.isUsedCoupons = isUsedCoupons;\n }\n\n public Boolean getIsUsedFullReductionRule() {\n return isUsedFullReductionRule;\n }\n\n public void setIsUsedFullReductionRule(Boolean isUsedFullReductionRule) {\n this.isUsedFullReductionRule = isUsedFullReductionRule;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n}", "answers": [" public List selectByExample(OrderRefundExample example){"], "length": 3517, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "caec92c3-cd55-4990-8f7d-ffe0d8e6aaea", "reasoning": "The OrderRefundServiceImpl class is implementing the OrderRefundService interface. After the insertSelective method, the next method defined in the interface is selectByExample, which returns a List of OrderRefund objects. Therefore, the next line of code should be the method signature for selectByExample.", "reasoning_model_answer": "public List selectByExample(OrderRefundExample example) {", "assistant_with_reasoning": "\nThe OrderRefundServiceImpl class is implementing the OrderRefundService interface. After the insertSelective method, the next method defined in the interface is selectByExample, which returns a List of OrderRefund objects. Therefore, the next line of code should be the method signature for selectByExample.\n\npublic List selectByExample(OrderRefundExample example) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.987, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36578, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public List selectByExample(OrderRefundExample example) {", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.IOException;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.StringTokenizer;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpSession;\nimport javax.validation.Valid;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.PageRequest;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.validation.BindingResult;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.SessionAttribute;\nimport org.springframework.web.multipart.MultipartFile;\nimport com.github.pagehelper.util.StringUtil;\nimport cn.gson.oasys.common.formValid.BindingResultVOUtil;\nimport cn.gson.oasys.common.formValid.MapToList;\nimport cn.gson.oasys.common.formValid.ResultEnum;\nimport cn.gson.oasys.common.formValid.ResultVO;\nimport cn.gson.oasys.model.dao.maildao.InMailDao;\nimport cn.gson.oasys.model.dao.maildao.MailnumberDao;\nimport cn.gson.oasys.model.dao.maildao.MailreciverDao;\nimport cn.gson.oasys.model.dao.notedao.AttachmentDao;\nimport cn.gson.oasys.model.dao.roledao.RoleDao;\nimport cn.gson.oasys.model.dao.system.StatusDao;\nimport cn.gson.oasys.model.dao.system.TypeDao;\nimport cn.gson.oasys.model.dao.user.DeptDao;\nimport cn.gson.oasys.model.dao.user.PositionDao;\nimport cn.gson.oasys.model.dao.user.UserDao;\nimport cn.gson.oasys.model.entity.mail.Inmaillist;\nimport cn.gson.oasys.model.entity.mail.Mailnumber;\nimport cn.gson.oasys.model.entity.mail.Mailreciver;\nimport cn.gson.oasys.model.entity.mail.Pagemail;\nimport cn.gson.oasys.model.entity.note.Attachment;\nimport cn.gson.oasys.model.entity.role.Role;\nimport cn.gson.oasys.model.entity.system.SystemStatusList;\nimport cn.gson.oasys.model.entity.system.SystemTypeList;\nimport cn.gson.oasys.model.entity.user.Dept;\nimport cn.gson.oasys.model.entity.user.Position;\nimport cn.gson.oasys.model.entity.user.User;\nimport cn.gson.oasys.services.mail.MailServices;\nimport cn.gson.oasys.services.process.ProcessService;", "context": "src/main/java/cn/gson/oasys/controller/mail/MailController.java\npackage cn.gson.oasys.controller.mail;\n\n\n\n\n\n\n\n@Controller\n@RequestMapping(\"/\")\npublic class MailController {\n\t\n\t\n\t@Autowired\n\tprivate MailnumberDao mndao;\n\t\n\t@Autowired\n\tprivate StatusDao sdao;\n\t@Autowired\n\tprivate TypeDao tydao;\n\t@Autowired\n\tprivate UserDao udao;\n\t@Autowired\n\tprivate DeptDao ddao;\n\t@Autowired\n\tprivate RoleDao rdao;\n\t@Autowired\n\tprivate PositionDao pdao;\n\t@Autowired\n\tprivate InMailDao imdao;\n\t@Autowired\n\nsrc/main/java/cn/gson/oasys/common/formValid/ResultEnum.java\npublic enum ResultEnum {\n ERROR(2, \"验证失败\"),\n SUCCESS(200, \"成功\"),\n NONETYPE(1, \"找不到参数\"),;\n\n private Integer code;\n private String message;\n\n\n ResultEnum(Integer code, String message) {\n this.code = code;\n this.message = message;\n }\n\n public Integer getCode() {\n return code;\n }\n\n public String getMessage() {\n return message;\n }\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/system/SystemTypeList.java\n@Entity\n@Table(name=\"aoa_type_list\")\npublic class SystemTypeList {\n\t\n\t@Id\n\t@Column(name=\"type_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long typeId;\t\t\t//类型id\n\t\n\t@Column(name=\"type_name\")\n\t@NotEmpty(message=\"类型名称不能为空\")\n\tprivate String typeName;\t\t//类型名字\n\t\n\t@Column(name=\"sort_value\")\n\tprivate Integer typeSortValue;\t//排序值\n\t\n\t@Column(name=\"type_model\")\n\tprivate String typeModel;\t\t//所属模块\n\t\n\t@Column(name=\"type_color\")\n\tprivate String typeColor;\t\t//类型颜色\n\n\tpublic Long getTypeId() {\n\t\treturn typeId;\n\t}\n\n\tpublic void setTypeId(Long typeId) {\n\t\tthis.typeId = typeId;\n\t}\n\n\tpublic String getTypeName() {\n\t\treturn typeName;\n\t}\n\n\tpublic void setTypeName(String typeName) {\n\t\tthis.typeName = typeName;\n\t}\n\n\tpublic Integer getTypeSortValue() {\n\t\treturn typeSortValue;\n\t}\n\n\tpublic void setTypeSortValue(Integer typeSortValue) {\n\t\tthis.typeSortValue = typeSortValue;\n\t}\n\n\tpublic String getTypeModel() {\n\t\treturn typeModel;\n\t}\n\n\tpublic void setTypeModel(String typeModel) {\n\t\tthis.typeModel = typeModel;\n\t}\n\n\tpublic String getTypeColor() {\n\t\treturn typeColor;\n\t}\n\n\tpublic void setTypeColor(String typeColor) {\n\t\tthis.typeColor = typeColor;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SystemTypeList [typeId=\" + typeId + \", typeName=\" + typeName + \", typeSortValue=\" + typeSortValue\n\t\t\t\t+ \", typeModel=\" + typeModel + \", typeColor=\" + typeColor + \"]\";\n\t}\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/user/UserDao.java\npublic interface UserDao extends JpaRepository{\n \n\tList findByUserId(Long id);\n\t\n\tList findByFatherId(Long parentid);\n\n\t@Query(\"select u from User u \")\n\tList findAll();\n\n\t@Query(\"select u from User u \")\n\tPage findAllPage(Pageable pa);\n\t\n\tPage findByFatherId(Long parentid,Pageable pa);\n\t\n\t//名字模糊查找\n\t@Query(\"select u from User u where (u.userName like %?1% or u.realName like %?1%) and u.fatherId=?2 \")\n\tPage findbyFatherId(String name,Long parentid,Pageable pa);\n\n\t//名字模糊查找\n\t@Query(\"select u from User u where (u.userName like %?1% or u.realName like %?1%)\")\n\tPage findAllUserByName(String name,Pageable pa);\n\t\n\t@Query(\"select u from User u where u.userName=:name\")\n\tUser findid(@Param(\"name\")String name);\n\t\n\t@Query(\"select tu.pkId from Taskuser tu where tu.taskId.taskId=:taskid and tu.userId.userId=:userid\")\n\tLong findpkId(@Param(\"taskid\")Long taskid,@Param(\"userid\")Long userid);\n\t\n\t//根据名字找用户\n\tUser findByUserName(String title);\n\t\n\t//根据用户名模糊查找\n\t@Query(\"from User u where u.userName like %:name% or u.realName like %:name%\")\n\tPage findbyUserNameLike(@Param(\"name\")String name,Pageable pa);\n\t//根据真实姓名模糊查找\n\tPage findByrealNameLike(String title,Pageable pa);\n\t\n\t//根据姓名首拼模糊查找,并分页\n\tPage findByPinyinLike(String pinyin,Pageable pa);\n\t\n\t//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页\n\t@Query(\"from User u where (u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1) and u.pinyin like ?2\")\n\tPage findSelectUsers(String baseKey,String pinyinm,Pageable pa);\n\t\n\t//根据姓名首拼+查找关键字查找(部门、姓名、电话号码),并分页\n\t@Query(\"from User u where u.userName like ?1 or u.dept.deptName like ?1 or u.userTel like ?1 or u.position.name like ?1 or u.pinyin like ?2\")\n\tPage findUsers(String baseKey,String baseKey2,Pageable pa);\n\t/**\n\t * 用户管理查询可用用户\n\t * @param isLock\n\t * @param pa\n\t * @return\n\t */\n\tPage findByIsLock(Integer isLock,Pageable pa);\n\t\n\t\n\t@Query(\"from User u where u.dept.deptName like %?1% or u.userName like %?1% or u.realName like %?1% or u.userTel like %?1% or u.role.roleName like %?1%\")\n\tPage findnamelike(String name,Pageable pa);\n\t\n\tList findByDept(Dept dept);\n\t@Query(\"select u from User u where u.role.roleId=?1\")\n\tList findrole(Long lid); \n\t\n\t/*通过(用户名或者电话号码)+密码查找用户*/\n\t@Query(\"from User u where (u.userName = ?1 or u.userTel = ?1) and u.password =?2\")\n\tUser findOneUser(String userName,String password);\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/maildao/MailreciverDao.java\npublic interface MailreciverDao extends PagingAndSortingRepository{\n\n\t//未读邮件查询\n\tList findByReadAndDelAndReciverId(Boolean read,Boolean del,User reciverid);\n\t\n\t@Query(\"select mr.mailId.mailId from Mailreciver mr where mr.reciverId=?1\")\n\tList findByReciverId(User user);\n\t\n\t@Query(\"from Mailreciver mr where mr.reciverId=?1 and mr.mailId.mailId=?2\")\n\tMailreciver findbyReciverIdAndmailId(User user,Long id);\n\t\n\t\n\t\n\t//收件箱查询\n\t@Query(\"select new cn.gson.oasys.model.entity.mail.Pagemail(list.mailId,list.mailType,list.mailStatusid,list.mailTitle,list.inReceiver,list.mailFileid.attachmentId,list.mailCreateTime,mr.star,mr.read) \"\n\t\t\t+ \"from Mailreciver as mr ,Inmaillist as list where list.mailId=mr.mailId.mailId and mr.reciverId=?1 and mr.del=?2 order by list.mailCreateTime DESC\")\n\tPage findmail(User user,Boolean bo,Pageable pa);\n\t\n\t//邮件主题或者接收人的模糊查询\n\t@Query(\"select new cn.gson.oasys.model.entity.mail.Pagemail(list.mailId,list.mailType,list.mailStatusid,list.mailTitle,list.inReceiver,list.mailFileid.attachmentId,list.mailCreateTime,mr.star,mr.read) \"\n\t\t\t+ \"from Mailreciver as mr ,Inmaillist as list where list.mailId=mr.mailId.mailId and mr.reciverId=?1 and mr.del=?2 and (list.mailTitle like %?3% or list.inReceiver like %?3%) order by list.mailCreateTime DESC\")\n\tPage findmails(User user,Boolean bo,String title,Pageable pa);\n\t\n\t//根据状态查询接收邮件\n\t@Query(\"select new cn.gson.oasys.model.entity.mail.Pagemail(list.mailId,list.mailType,list.mailStatusid,list.mailTitle,list.inReceiver,list.mailFileid.attachmentId,list.mailCreateTime,mr.star,mr.read) \"\n\t\t\t+ \"from Mailreciver as mr ,Inmaillist as list where list.mailId=mr.mailId.mailId and mr.reciverId=?1 and list.mailStatusid=?2 and mr.del=?3 order by list.mailCreateTime DESC\")\n\tPage findmailbystatus(User tu,Long statusId,Boolean bo,Pageable pa);\n\t\n\t//根据状态查询接收邮件\n\t@Query(\"select new cn.gson.oasys.model.entity.mail.Pagemail(list.mailId,list.mailType,list.mailStatusid,list.mailTitle,list.inReceiver,list.mailFileid.attachmentId,list.mailCreateTime,mr.star,mr.read) \"\n\t\t\t+ \"from Mailreciver as mr ,Inmaillist as list where list.mailId=mr.mailId.mailId and mr.reciverId=?1 and list.mailType=?2 and mr.del=?3 order by list.mailCreateTime DESC\")\n\tPage findmailbytype(User tu,Long typeid,Boolean bo,Pageable pa);\n\n\tList findByDelAndReciverId(Boolean b,User u);\n\t\n\t@Query(\"select mr.del from Mailreciver as mr where mr.mailId.mailId=?1 \")\n\tList findbyMailId(Long id);\n\t\n\tList findByMailId(Long id);\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/roledao/RoleDao.java\npublic interface RoleDao extends JpaRepository{\n\n\t@Query(\"select ro from Role as ro where ro.roleName like %?1%\")\n\tPage findbyrolename(String val, Pageable pa);\n\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/maildao/MailnumberDao.java\npublic interface MailnumberDao extends PagingAndSortingRepository{\n\t//根据状态和user来找account\n\tPage findByMailUserId(User user,Pageable page);\n\n\t//根据用户和type排序account\n\tPage findByMailUserIdOrderByMailType(User user,Pageable page);\n\n\t//根据用户和status排序account\n\tPage findByMailUserIdOrderByStatus(User user,Pageable page);\n\n\t//根据用户和创建时间排序account\n\tPage findByMailUserIdOrderByMailCreateTimeDesc(User user,Pageable page);\n\n\t//根据用户和发件别名模糊查找account\n\t@Query(\"select mn from Mailnumber mn where mn.mailUserName like %:val% and mn.mailUserId=:tu \")\n\tPage findByMailUserNameLikeAndMailUserId(@Param(\"val\")String val,@Param(\"tu\") User tu,Pageable page);\n\t\n\tList findByStatusAndMailUserId(Long status,User u);\n\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/mail/Pagemail.java\npublic class Pagemail {\n\n\tprivate Long mailId;//邮件id\n\t\n\tprivate Long mailType;//邮件类型(通知,公告,邮件)\n\t\n\tprivate Long mailStatusid;//邮件状态(一般,紧急,重要)\n\t\n\tprivate String mailTitle;//邮件主题\n\t\n\tprivate String inReceiver;//接收人(可以是多个)\n\t\n\tprivate Long mailFileid;//邮件附件id\n\t\n\tprivate Date mailCreateTime;//邮件创建时间\n\t\n\tprivate Boolean star=false;//是否星标\n\t\n\tprivate Boolean read=false;//是否已读\n\t\n\tpublic Pagemail(){}\n\n\tpublic Pagemail(Long mailId, Long mailType, Long mailStatusid, String mailTitle,String inReceiver,\n\t\t\tLong mailFileid, Date mailCreateTime, Boolean star, Boolean read) {\n\t\tsuper();\n\t\tthis.mailId = mailId;\n\t\tthis.mailType = mailType;\n\t\tthis.mailStatusid = mailStatusid;\n\t\tthis.mailTitle = mailTitle;\n\t\tthis.inReceiver = inReceiver;\n\t\tthis.mailFileid = mailFileid;\n\t\tthis.mailCreateTime = mailCreateTime;\n\t\tthis.star = star;\n\t\tthis.read = read;\n\t}\n\n\tpublic Long getMailId() {\n\t\treturn mailId;\n\t}\n\n\tpublic void setMailId(Long mailId) {\n\t\tthis.mailId = mailId;\n\t}\n\n\tpublic Long getMailType() {\n\t\treturn mailType;\n\t}\n\n\tpublic void setMailType(Long mailType) {\n\t\tthis.mailType = mailType;\n\t}\n\n\tpublic Long getMailStatusid() {\n\t\treturn mailStatusid;\n\t}\n\n\tpublic void setMailStatusid(Long mailStatusid) {\n\t\tthis.mailStatusid = mailStatusid;\n\t}\n\n\tpublic String getMailTitle() {\n\t\treturn mailTitle;\n\t}\n\n\tpublic void setMailTitle(String mailTitle) {\n\t\tthis.mailTitle = mailTitle;\n\t}\n\n\t\n\n\tpublic String getInReceiver() {\n\t\treturn inReceiver;\n\t}\n\n\tpublic void setInReceiver(String inReceiver) {\n\t\tthis.inReceiver = inReceiver;\n\t}\n\n\tpublic Long getMailFileid() {\n\t\treturn mailFileid;\n\t}\n\n\tpublic void setMailFileid(Long mailFileid) {\n\t\tthis.mailFileid = mailFileid;\n\t}\n\n\tpublic Date getMailCreateTime() {\n\t\treturn mailCreateTime;\n\t}\n\n\tpublic void setMailCreateTime(Date mailCreateTime) {\n\t\tthis.mailCreateTime = mailCreateTime;\n\t}\n\n\n\n\tpublic Boolean getStar() {\n\t\treturn star;\n\t}\n\n\tpublic void setStar(Boolean star) {\n\t\tthis.star = star;\n\t}\n\n\t\n\tpublic Boolean getRead() {\n\t\treturn read;\n\t}\n\n\tpublic void setRead(Boolean read) {\n\t\tthis.read = read;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pagemail [mailId=\" + mailId + \", mailType=\" + mailType + \", mailStatusid=\" + mailStatusid\n\t\t\t\t+ \", mailTitle=\" + mailTitle + \", inReceiver=\" + inReceiver + \", mailFileid=\" + mailFileid\n\t\t\t\t+ \", mailCreateTime=\" + mailCreateTime + \", star=\" + star + \", read=\" + read + \"]\";\n\t}\n\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/common/formValid/ResultVO.java\npublic class ResultVO {\n /**\n * 错误码\n */\n private Integer code;\n /**\n * 提示信息\n */\n private String msg;\n /**\n * 返回的具体内容\n */\n\n T Data;\n\n public ResultVO() {\n }\n\n public ResultVO(Integer code, String msg, T data) {\n this.code = code;\n this.msg = msg;\n Data = data;\n }\n\n public ResultVO(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n public ResultVO success(T data) {\n this.code = ResultEnum.SUCCESS.getCode();\n this.msg = ResultEnum.SUCCESS.getMessage();\n this.Data = data;\n return new ResultVO(code, msg, data);\n }\n\n public Integer getCode() {\n return code;\n }\n\n public void setCode(Integer code) {\n this.code = code;\n }\n\n public String getMsg() {\n return msg;\n }\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n\n public T getData() {\n return Data;\n }\n\n public void setData(T data) {\n Data = data;\n }\n\n\n public ResultVO error(Integer code, String message, T data) {\n this.code = ResultEnum.ERROR.getCode();\n this.msg = msg;\n this.Data = data;\n return new ResultVO(code, msg, data);\n }\n}\n\nsrc/main/java/cn/gson/oasys/services/mail/MailServices.java\n@Service\n@Transactional\npublic class MailServices {\n\t@Autowired\n\tprivate StatusDao sdao;\n\t@Autowired\n\tprivate TypeDao tydao;\n\t@Autowired\n\tprivate MailnumberDao mdao;\n\t@Autowired\n\tprivate MailreciverDao mrdao;\n\t\n\t@Autowired\n\tprivate InMailDao imdao;\n\n\t@Value(\"${file.root.path}\")\n\tprivate String rootpath;\n\n\t//@PostConstruct\n\tpublic void UserpanelController(){\n\t\ttry {\n\t\t\trootpath= ResourceUtils.getURL(\"classpath:\").getPath().replace(\"/target/classes/\",\"/static/attachment\");\n\t\t\t//System.out.println(rootpath);\n\n\t\t}catch (IOException e){\n\t\t\tSystem.out.println(\"获取项目路径异常\");\n\t\t}\n\t}\n\t/**\n\t * 收件箱\n\t */\n\tpublic Page recive(int page,int size,User tu,String val,String title){\n\t\tPage pagelist=null;\n\t\tPageable pa=new PageRequest(page, size);\n\t\tList orders = new ArrayList<>();\n\t\tSystemStatusList status=sdao.findByStatusModelAndStatusName(\"aoa_in_mail_list\", val);\n\t\tSystemTypeList type=tydao.findByTypeModelAndTypeName(\"aoa_in_mail_list\", val);\n\t\tif((\"收件箱\").equals(title)){\n\t\t\tif(StringUtil.isEmpty(val)){\n\t\t\t\torders.add(new Order(Direction.ASC, \"read\"));\n\t\t\t\tSort sort = new Sort(orders);\n\t\t\t\tpa=new PageRequest(page, size,sort);\n\t\t\t\tpagelist=mrdao.findmail(tu,false,pa);\n\t\t\t}else if(!Objects.isNull(status)){\n\t\t\t\tpagelist=mrdao.findmailbystatus(tu,status.getStatusId(),false,pa);\n\t\t\t}else if(!Objects.isNull(type)){\n\t\t\t\tpagelist=mrdao.findmailbytype(tu,type.getTypeId(),false,pa);\n\t\t\t}else{\n\t\t\t\tpagelist=mrdao.findmails(tu,false, val, pa);\n\t\t\t}\n\t\t}else{\n\t\t\tif(StringUtil.isEmpty(val)){\n\t\t\t\torders.add(new Order(Direction.ASC, \"read\"));\n\t\t\t\tSort sort = new Sort(orders);\n\t\t\t\tpa=new PageRequest(page, size,sort);\n\t\t\t\tpagelist=mrdao.findmail(tu,true,pa);\n\t\t\t}else if(!Objects.isNull(status)){\n\t\t\t\tpagelist=mrdao.findmailbystatus(tu,status.getStatusId(),true,pa);\n\t\t\t}else if(!Objects.isNull(type)){\n\t\t\t\tpagelist=mrdao.findmailbytype(tu,type.getTypeId(),false,pa);\n\t\t\t}else{\n\t\t\t\tpagelist=mrdao.findmails(tu, true,val, pa);\n\t\t\t}\n\t\t}\n\t\treturn pagelist;\n\t}\n\t\n\t\n\t/**\n\t * 封装json\n\t */\n\tpublic List> mail(Page mail){\n\t\tList maillist=mail.getContent();\n\t\tList> list = new ArrayList<>();\n\t\tfor (int i = 0; i < maillist.size(); i++) {\n\t\t\tMap result=new HashMap<>();\n\t\t\tString typename=tydao.findname(maillist.get(i).getMailType());\n\t\t\tSystemStatusList status=sdao.findOne(maillist.get(i).getMailStatusid());\n\t\t\tresult.put(\"typename\", typename);\n\t\t\tresult.put(\"statusname\", status.getStatusName());\n\t\t\tresult.put(\"statuscolor\", status.getStatusColor());\n\t\t\tresult.put(\"star\", maillist.get(i).getStar());\n\t\t\tresult.put(\"read\", maillist.get(i).getRead());\n\t\t\tresult.put(\"time\", maillist.get(i).getMailCreateTime());\n\t\t\tresult.put(\"reciver\", maillist.get(i).getInReceiver());\n\t\t\tresult.put(\"title\", maillist.get(i).getMailTitle());\n\t\t\tresult.put(\"mailid\", maillist.get(i).getMailId());\n\t\t\tresult.put(\"fileid\", maillist.get(i).getMailFileid());\n\t\t\tlist.add(result);\n\t\t\t\n\t\t}\n\t\treturn list;\n\t}\n\t\n\t/**\n\t * 发件箱\n\t */\n\tpublic Page inmail(int page,int size,User tu,String val,String title){\n\t\tPage pagemail=null;\n\t\tPageable pa=new PageRequest(page, size);\n\t\tList orders = new ArrayList<>();\n\t\tSystemStatusList status=sdao.findByStatusModelAndStatusName(\"aoa_in_mail_list\", val);\n\t\tSystemTypeList type=tydao.findByTypeModelAndTypeName(\"aoa_in_mail_list\", val);\n\t\tif((\"发件箱\").equals(title)){\n\t\tif(StringUtil.isEmpty(val)){\n\t\t\torders.add(new Order(Direction.DESC, \"mailStatusid\"));\n\t\t\tSort sort = new Sort(orders);\n\t\t\tpa=new PageRequest(page, size,sort);\n\t\t\tpagemail=imdao.findByPushAndMailUseridAndDelOrderByMailCreateTimeDesc(true,tu,false,pa);\n\t\t}else if(!Objects.isNull(status)){\n\t\t\tpagemail=imdao.findByMailUseridAndMailStatusidAndPushAndDelOrderByMailCreateTimeDesc(tu, status.getStatusId(),true,false, pa);\n\t\t}else if(!Objects.isNull(type)){\n\t\t\tpagemail=imdao.findByMailUseridAndMailTypeAndPushAndDelOrderByMailCreateTimeDesc(tu, type.getTypeId(),true,false, pa);\n\t\t}else{\n\t\t\tpagemail=imdao.findbymailUseridAndPushAndDel(tu,true,false,val,pa);\n\t\t}\n\t\t}else{\n\t\t\t//草稿箱\n\t\t\tif(StringUtil.isEmpty(val)){\n\t\t\t\torders.add(new Order(Direction.DESC, \"mailStatusid\"));\n\t\t\t\tSort sort = new Sort(orders);\n\t\t\t\tpa=new PageRequest(page, size,sort);\n\t\t\t\tpagemail=imdao.findByPushAndMailUseridAndDelOrderByMailCreateTimeDesc(false,tu,false,pa);\n\t\t\t}else if(!Objects.isNull(status)){\n\t\t\t\tpagemail=imdao.findByMailUseridAndMailStatusidAndPushAndDelOrderByMailCreateTimeDesc(tu, status.getStatusId(),false,false, pa);\n\t\t\t}else if(!Objects.isNull(type)){\n\t\t\t\tpagemail=imdao.findByMailUseridAndMailTypeAndPushAndDelOrderByMailCreateTimeDesc(tu, type.getTypeId(),true,false, pa);\n\t\t\t}else{\n\t\t\t\tpagemail=imdao.findbymailUseridAndPushAndDel(tu,false,false,val,pa);\n\t\t\t}\n\t\t}\n\t\treturn pagemail;\n\t\t\n\t}\n\t/**\n\t * 发件箱封装\n\t */\n\tpublic List> maillist(Page mail){\n\t\tList maillist=mail.getContent();\n\t\tList> list = new ArrayList<>();\n\t\tfor (int i = 0; i < maillist.size(); i++) {\n\t\t\tMap result=new HashMap<>();\n\t\t\tString typename=tydao.findname(maillist.get(i).getMailType());\n\t\t\tSystemStatusList status=sdao.findOne(maillist.get(i).getMailStatusid());\n\t\t\tresult.put(\"typename\", typename);\n\t\t\tresult.put(\"statusname\", status.getStatusName());\n\t\t\tresult.put(\"statuscolor\", status.getStatusColor());\n\t\t\tresult.put(\"star\", maillist.get(i).getStar());\n\t\t\tresult.put(\"read\", true);\n\t\t\tresult.put(\"time\", maillist.get(i).getMailCreateTime());\n\t\t\tresult.put(\"reciver\", maillist.get(i).getInReceiver());\n\t\t\tresult.put(\"title\", maillist.get(i).getMailTitle());\n\t\t\tresult.put(\"mailid\", maillist.get(i).getMailId());\n\t\t\tresult.put(\"fileid\", maillist.get(i).getMailFileid());\n\t\t\tlist.add(result);\n\t\t\t\n\t\t}\n\t\treturn list;\n\t}\n\t\n\t/**\n\t * 账号\n\t * @param page\n\t * @param size\n\t * @param tu\n\t * @param val\n\t * @return\n\t */\n\tpublic Page index(int page,int size,User tu,String val,Model model){\n\t\tPage account=null;\n\t\tList orders = new ArrayList<>();\n\t\tPageable pa=new PageRequest(page, size);\n\t\tif(StringUtil.isEmpty(val)){\n\t\t\torders.addAll(Arrays.asList(new Order(Direction.ASC, \"status\"), new Order(Direction.DESC, \"mailCreateTime\")));\n\t\t\tSort sort = new Sort(orders);\n\t\t\tpa=new PageRequest(page, size, sort);\n\t\t\taccount=mdao.findByMailUserId(tu,pa);\n\t\t}else if ((\"类型\").equals(val)) {\n\t\t\taccount=mdao.findByMailUserIdOrderByMailType(tu,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}else if((\"状态\").equals(val)){\n\t\t\taccount=mdao.findByMailUserIdOrderByStatus(tu,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}else if((\"创建时间\").equals(val)){\n\t\t\taccount=mdao.findByMailUserIdOrderByMailCreateTimeDesc(tu,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}else{\n\t\t\t//名字的模糊查询\n\t\t\taccount = mdao.findByMailUserNameLikeAndMailUserId(val,tu,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}\n\t\treturn account;\n\t}\n\t\n\tpublic List> up(Page num){\n\t\tList account=num.getContent();\n\t\tList> list = new ArrayList<>();\n\t\tfor (int i = 0; i < account.size(); i++) {\n\t\t\tMap result=new HashMap<>();\n\t\t\tSystemStatusList status=sdao.findOne(account.get(i).getStatus());\n\t\t\tresult.put(\"accountid\", account.get(i).getMailNumberId());\n\t\t\tresult.put(\"typename\", tydao.findname(account.get(i).getMailType()));\n\t\t\tresult.put(\"statusname\", status.getStatusName());\n\t\t\tresult.put(\"statuscolor\", status.getStatusColor());\n\t\t\tresult.put(\"accountname\", account.get(i).getMailUserName());\n\t\t\tresult.put(\"creattime\", account.get(i).getMailCreateTime());\n\t\t\tlist.add(result);\n\t\t}\n\t\treturn list;\n\t}\n\t\n\t/**\n\t * 上传附件\n\t * @throws IOException \n\t * @throws IllegalStateException \n\t */\n\tpublic Attachment upload(MultipartFile file,User mu) throws IllegalStateException, IOException{\n\t\tSimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyy/MM\");\n\t\tFile root = new File(rootpath,simpleDateFormat.format(new Date()));\n\t\tFile savepath = new File(root,mu.getUserName());\n\t\t\n\t\tif (!savepath.exists()) {\n\t\t\tsavepath.mkdirs();\n\t\t}\n\t\tString fileName=file.getOriginalFilename();\n\t\tif(!StringUtil.isEmpty(fileName)){\n\t\t\tString suffix=FilenameUtils.getExtension(fileName);\n\t\t\tString newFileName = UUID.randomUUID().toString().toLowerCase()+\".\"+suffix;\n\t\t\tFile targetFile = new File(savepath,newFileName);\n\t\t\tfile.transferTo(targetFile);\n\t\t\t\n\t\t\tAttachment attachment=new Attachment();\n\t\t\tattachment.setAttachmentName(file.getOriginalFilename());\n\t\t\tattachment.setAttachmentPath(targetFile.getAbsolutePath().replace(\"\\\\\", \"/\").replace(rootpath, \"\"));\n\t\t\tattachment.setAttachmentShuffix(suffix);\n\t\t\tattachment.setAttachmentSize(file.getSize());\n\t\t\tattachment.setAttachmentType(file.getContentType());\n\t\t\tattachment.setUploadTime(new Date());\n\t\t\tattachment.setUserId(mu.getUserId()+\"\");\n\t\t\t\n\t\t\treturn attachment;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * 删除账号\n\t */\n\tpublic void dele(Long id){\n\t\tmdao.delete(id);\n\t}\n\t\n\t/**\n\t * 校验中文\n\t * @param str\n\t * @return\n\t */\n\tpublic boolean isContainChinese(String str) {\n\t\t \n Pattern p = Pattern.compile(\"[\\u4e00-\\u9fa5]\");\n Matcher m = p.matcher(str);\n if (m.find()) {\n return true;\n }\n return false;\n }\n\t\n\t/**\n\t * 发外部邮件\n\t * @return \n\t */\n\t\tpublic void pushmail(String account,String password,String reciver,\n\t\t\t\tString name,String title,String content,String affix,String filename){\n\t\t\tString file=null;\n\t\t\tif(!StringUtil.isEmpty(affix)){\n\t\t\t\tFile root = new File(rootpath,affix);\n\t\t\t\tfile=root.getAbsolutePath();\n\t\t\t}\t\n\t\t\t// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)\n\t\t\tString myEmailAccount = account;\n\t\t String myEmailPassword = password;\n\t\t \n\t\t // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com\n\t\t //qq smtp.qq.com\n\t\t String myEmailSMTPHost = \"smtp.qq.com\";\n\t\t \n\t\t // 收件人邮箱(替换为自己知道的有效邮箱)\n\t\t // String receiveMailAccount = \"1533047354@qq.com\";\n\t\t \n\t\t // 1. 创建参数配置, 用于连接邮件服务器的参数配置\n\t Properties props = new Properties(); // 参数配置\n\t props.setProperty(\"mail.transport.protocol\", \"smtp\"); // 使用的协议(JavaMail规范要求)\n\t props.setProperty(\"mail.smtp.host\", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址\n\t props.setProperty(\"mail.smtp.auth\", \"true\"); // 需要请求认证\n\t \t\n\t // 开启 SSL 安全连接。\n\t // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,\n\t // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,\n\t // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)\n\t final String smtpPort = \"465\";\n\t props.setProperty(\"mail.smtp.port\", smtpPort);\n\t props.setProperty(\"mail.smtp.socketFactory.class\", \"javax.net.ssl.SSLSocketFactory\");\n\t props.setProperty(\"mail.smtp.socketFactory.fallback\", \"false\");\n\t props.setProperty(\"mail.smtp.socketFactory.port\", smtpPort);\n\t \n\t \t\n\t // 2. 根据配置创建会话对象, 用于和邮件服务器交互\n\t Session session = Session.getDefaultInstance(props);\n\t session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log\n\t \n\t // 3. 创建一封邮件\n\t MimeMessage message;\n\t\t\ttry {\n\t\t\t\tmessage = createMimeMessage(session, myEmailAccount, reciver,name ,title, content,file,filename);\n\t\t\t\t\n\t\t\t\t // 4. 根据 Session 获取邮件传输对象\n\t\t Transport transport = session.getTransport();\n\t\t \n\t\t // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错\n\t\t transport.connect(myEmailAccount, myEmailPassword);\n\n\t\t // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人\n\t\t transport.sendMessage(message, message.getAllRecipients());\n\t\t\t\t\n\t\t // 7. 关闭连接\n\t\t transport.close();\n\t\t\t\t\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t \n\t \n\t\t\t\n\t\t}\n\t public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,\n\t\t\t String name,String title,String content,String affix,String filename) throws Exception {\n\t // 1. 创建一封邮件\n\t MimeMessage message = new MimeMessage(session);\n\n\t // 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称)\n\t message.setFrom(new InternetAddress(sendMail, name, \"UTF-8\"));\n\n\t // 3. To: 收件人(可以增加多个收件人、抄送、密送)\n\t message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, \"XX用户\", \"UTF-8\"));\n\n\t // 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题)\n\t message.setSubject(title, \"UTF-8\");\n\n\t if(!StringUtil.isEmpty(affix)){\n\t\n\t\t\t// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件\n\t\t\tMultipart multipart = new MimeMultipart();\n\t\t\t// 设置邮件的文本内容\n\t\t\tBodyPart contentPart = new MimeBodyPart();\n\t\t\tcontentPart.setContent(content, \"text/html;charset=UTF-8\");\n\t\t\tmultipart.addBodyPart(contentPart);\n\t\t\t// 添加附件\n\t\t\tBodyPart messageBodyPart = new MimeBodyPart();\n\t\t\tDataSource source = new FileDataSource(affix);//附件路径\n\t\t\t// 添加附件的内容\n\t\t\tmessageBodyPart.setDataHandler(new DataHandler(source));\n\t\t\t// 添加附件的标题\n\t\t\t// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码\n\t\t\tsun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();\n\t\t\tmessageBodyPart.setFileName(\"=?GBK?B?\"+ enc.encode(filename.getBytes()) + \"?=\");\n\t\t\tmultipart.addBodyPart(messageBodyPart);\n\t\t\t\n\t\t\t// 将multipart对象放到message中\n\t\t\tmessage.setContent(multipart,\"text/html;charset=UTF-8\");\n\t\t}else{\n\t\t\t // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)\n\t message.setContent(content, \"text/html;charset=UTF-8\");\n\t\t}\n\t // 6. 设置发件时间\n\t message.setSentDate(new Date());\n\n\t // 7. 保存设置\n\t message.saveChanges();\n\t \n\t \n\n\t return message;\n\t }\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/user/DeptDao.java\npublic interface DeptDao extends PagingAndSortingRepository{\n\n\tList findByDeptId(Long id);\n\t\n\t\n\t@Query(\"select de.deptName from Dept de where de.deptId=:id\")\n\tString findname(@Param(\"id\")Long id);\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/mail/Mailnumber.java\n@Entity\n@Table(name=\"aoa_mailnumber\")\n//邮箱账号表\npublic class Mailnumber {\n\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\t@Column(name=\"mail_number_id\")\n\tprivate Long mailNumberId; //邮箱的主键id\n\t\n\t@Column(name=\"mail_type\")\n\tprivate Long mailType;//邮件账号类型\n\t\n\t@Column(name=\"status\")\n\tprivate Long status;//邮件状态(是否可用)\n\t\n\t@ManyToOne\n\t@JoinColumn(name=\"mail_num_user_id\")\n\tprivate User mailUserId;//用户id\n\t\n\t@Column(name=\"mail_user_name\",nullable=false)\n\t@NotEmpty(message=\"发件昵称不能为空\")\n\tprivate String mailUserName;//用户别名\n\t\n\t@Column(name=\"mail_create_time\")\n\tprivate Date mailCreateTime;//账号创建时间\n\t\n\t@Column(name=\"mail_account\",nullable=false)\n\t@NotEmpty(message=\"邮件账号不能为空\")\n\t@Pattern(regexp=\"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\\\.[a-zA-Z0-9_-]{2,3}){1,2})$\",message=\"请填写正确邮箱号\")\n\tprivate String mailAccount;//邮件账号\n\t\n\t@Column(name=\"password\",nullable=false)\n\t@NotEmpty(message=\"授权码不能为空\")\n\tprivate String password;//账号授权码\n\t\n\t@Column(name=\"mail_des\")\n\tprivate String mailDes;//账号信息备注\n\t\n\tpublic Mailnumber(){}\n\t\n\n\tpublic Long getMailNumberId() {\n\t\treturn mailNumberId;\n\t}\n\n\tpublic void setMailNumberId(Long mailNumberId) {\n\t\tthis.mailNumberId = mailNumberId;\n\t}\n\n\tpublic Long getMailType() {\n\t\treturn mailType;\n\t}\n\n\tpublic void setMailType(Long mailType) {\n\t\tthis.mailType = mailType;\n\t}\n\n\tpublic Long getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic void setStatus(Long status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic User getMailUserId() {\n\t\treturn mailUserId;\n\t}\n\n\tpublic void setMailUserId(User mailUserId) {\n\t\tthis.mailUserId = mailUserId;\n\t}\n\n\tpublic String getMailUserName() {\n\t\treturn mailUserName;\n\t}\n\n\tpublic void setMailUserName(String mailUserName) {\n\t\tthis.mailUserName = mailUserName;\n\t}\n\n\tpublic Date getMailCreateTime() {\n\t\treturn mailCreateTime;\n\t}\n\n\tpublic void setMailCreateTime(Date mailCreateTime) {\n\t\tthis.mailCreateTime = mailCreateTime;\n\t}\n\n\tpublic String getMailAccount() {\n\t\treturn mailAccount;\n\t}\n\n\tpublic void setMailAccount(String mailAccount) {\n\t\tthis.mailAccount = mailAccount;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic String getMailDes() {\n\t\treturn mailDes;\n\t}\n\n\tpublic void setMailDes(String mailDes) {\n\t\tthis.mailDes = mailDes;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Mailnumber [mailNumberId=\" + mailNumberId + \", mailType=\" + mailType + \", status=\" + status\n\t\t\t\t+ \", mailUserName=\" + mailUserName + \", mailCreateTime=\" + mailCreateTime\n\t\t\t\t+ \", mailAccount=\" + mailAccount + \", password=\" + password + \", mailDes=\" + mailDes + \"]\";\n\t}\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/user/Dept.java\n@Entity\n@Table(name = \"aoa_dept\")\npublic class Dept {\n\t@Id\n\t@Column(name = \"dept_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long deptId;\t//部门id\n\t\n\t@Column(name = \"dept_name\")\n\t@NotEmpty(message=\"部门名称不为空\")\n\tprivate String deptName;\t//部门名字 非空 唯一\n\t\n\t@Column(name = \"dept_tel\")\n\tprivate String deptTel;\t\t//部门电话 \n\t\n\t@Column(name = \"dept_fax\")\n\tprivate String deptFax;\t\t//部门传真\n\t\n\tprivate String email;\t\t//部门email\n\t\n\t@Column(name = \"dept_addr\")\n\tprivate String deptAddr;\t//部门地址\n\t\n\tprivate Long deptmanager;\n\t\n//\t@Column(name = \"start_time\")\n//\tprivate Date startTime;\t\t//部门上班时间\n\t\n//\t@Column(name = \"end_time\")\n//\tprivate Date endTime;\t\t//部门下班时间\n\n\tpublic Dept() {\n\n\t}\n\n\tpublic Long getDeptId() {\n\t\treturn deptId;\n\t}\n\n\tpublic void setDeptId(Long deptId) {\n\t\tthis.deptId = deptId;\n\t}\n\n\tpublic String getDeptName() {\n\t\treturn deptName;\n\t}\n\n\tpublic void setDeptName(String deptName) {\n\t\tthis.deptName = deptName;\n\t}\n\n\tpublic String getDeptTel() {\n\t\treturn deptTel;\n\t}\n\n\tpublic void setDeptTel(String deptTel) {\n\t\tthis.deptTel = deptTel;\n\t}\n\n\tpublic String getDeptFax() {\n\t\treturn deptFax;\n\t}\n\n\tpublic void setDeptFax(String deptFax) {\n\t\tthis.deptFax = deptFax;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getDeptAddr() {\n\t\treturn deptAddr;\n\t}\n\n\tpublic void setDeptAddr(String deptAddr) {\n\t\tthis.deptAddr = deptAddr;\n\t}\n\n\tpublic Long getDeptmanager() {\n\t\treturn deptmanager;\n\t}\n\n\tpublic void setDeptmanager(Long deptmanager) {\n\t\tthis.deptmanager = deptmanager;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Dept [deptId=\" + deptId + \", deptName=\" + deptName + \", deptTel=\" + deptTel + \", deptFax=\" + deptFax\n\t\t\t\t+ \", email=\" + email + \", deptAddr=\" + deptAddr + \", deptmanager=\" + deptmanager + \"]\";\n\t}\n\n\t\n//\tpublic Date getStartTime() {\n//\t\treturn startTime;\n//\t}\n//\n//\tpublic void setStartTime(Date startTime) {\n//\t\tthis.startTime = startTime;\n//\t}\n\n//\tpublic Date getEndTime() {\n//\t\treturn endTime;\n//\t}\n//\n//\tpublic void setEndTime(Date endTime) {\n//\t\tthis.endTime = endTime;\n//\t}\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/note/Attachment.java\n@Entity\n@Table(name=\"aoa_attachment_list\")\npublic class Attachment {\n\n\t@Id\n\t@Column(name=\"attachment_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long attachmentId; //附件id\n\t\n\t@Column(name=\"user_id\")\n\tprivate String userId; //用户id 在没有连接外键只是用来\n\t\t\t\t\t\t\t\t//查询用户表的\n\t\n\t@Column(name=\"attachment_name\")\n\tprivate String attachmentName; //附件名字\n\t\n\t@Column(name=\"attachment_path\")\n\tprivate String attachmentPath; //附件存储路径\n\t\n\t\n\t@Column(name=\"attachment_size\")\n\tprivate Long attachmentSize; //附件大小\n\t\n\t@Column(name=\"attachment_type\")\n\tprivate String attachmentType; //附件类型\n\t\n\t@Column(name=\"upload_time\")\n\tprivate Date uploadTime; //附件上传时间\n\t\n\tprivate String model; //所属模块\n\t\n\t@Column(name=\"attachment_shuffix\")\n\tprivate String attachmentShuffix; //附件后缀\n\n\tpublic Long getAttachmentId() {\n\t\treturn attachmentId;\n\t}\n\n\tpublic void setAttachmentId(Long attachmentId) {\n\t\tthis.attachmentId = attachmentId;\n\t}\n\n\tpublic String getUserId() {\n\t\treturn userId;\n\t}\n\n\tpublic void setUserId(String userId) {\n\t\tthis.userId = userId;\n\t}\n\n\tpublic String getAttachmentName() {\n\t\treturn attachmentName;\n\t}\n\n\tpublic void setAttachmentName(String attachmentName) {\n\t\tthis.attachmentName = attachmentName;\n\t}\n\n\tpublic String getAttachmentPath() {\n\t\treturn attachmentPath;\n\t}\n\n\tpublic void setAttachmentPath(String attachmentPath) {\n\t\tthis.attachmentPath = attachmentPath;\n\t}\n\n\tpublic Long getAttachmentSize() {\n\t\treturn attachmentSize;\n\t}\n\n\tpublic void setAttachmentSize(Long attachmentSize) {\n\t\tthis.attachmentSize = attachmentSize;\n\t}\n\n\tpublic String getAttachmentType() {\n\t\treturn attachmentType;\n\t}\n\n\tpublic void setAttachmentType(String attachmentType) {\n\t\tthis.attachmentType = attachmentType;\n\t}\n\n\tpublic Date getUploadTime() {\n\t\treturn uploadTime;\n\t}\n\n\tpublic void setUploadTime(Date uploadTime) {\n\t\tthis.uploadTime = uploadTime;\n\t}\n\n\tpublic String getModel() {\n\t\treturn model;\n\t}\n\n\tpublic void setModel(String model) {\n\t\tthis.model = model;\n\t}\n\n\tpublic String getAttachmentShuffix() {\n\t\treturn attachmentShuffix;\n\t}\n\n\tpublic void setAttachmentShuffix(String attachmentShuffix) {\n\t\tthis.attachmentShuffix = attachmentShuffix;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Attachment [attachmentId=\" + attachmentId + \", attachmentName=\" + attachmentName + \", attachmentPath=\"\n\t\t\t\t+ attachmentPath + \", attachmentSize=\" + attachmentSize + \", attachmentType=\" + attachmentType\n\t\t\t\t+ \", uploadTime=\" + uploadTime + \", model=\" + model + \", attachmentShuffix=\" + attachmentShuffix + \"]\";\n\t}\n\n\tpublic Attachment(Long attachmentId, String attachmentName, String attachmentPath, long attachmentSize,\n\t\t\tString attachmentType, Date uploadTime, String model, String attachmentShuffix) {\n\t\tsuper();\n\t\tthis.attachmentId = attachmentId;\n\t\tthis.attachmentName = attachmentName;\n\t\tthis.attachmentPath = attachmentPath;\n\t\tthis.attachmentSize = attachmentSize;\n\t\tthis.attachmentType = attachmentType;\n\t\tthis.uploadTime = uploadTime;\n\t\tthis.model = model;\n\t\tthis.attachmentShuffix = attachmentShuffix;\n\t}\n\n\tpublic Attachment() {\n\t\tsuper();\n\t\t// TODO Auto-generated constructor stub\n\t}\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/services/process/ProcessService.java\n@Service\n@Transactional\npublic class ProcessService {\n\t@Autowired\n\tprivate UserDao udao;\n\t@Autowired\n\tprivate DeptDao ddao;\n\t@Autowired\n\tprivate RoleDao rdao;\n\t@Autowired\n\tprivate PositionDao pdao;\n\t@Autowired\n\tprivate SubjectDao sudao;\n\t@Autowired\n\tprivate StatusDao sdao;\n\t@Autowired\n\tprivate TypeDao tydao;\n\t@Autowired\n\tprivate ReviewedDao redao;\n\t@Autowired\n\tprivate AttachmentDao AttDao;\n\t@Autowired\n\tprivate BursementDao budao;\n\t@Autowired\n\tprivate MailServices mservice;\n\t@Autowired\n\tprivate ProcessListDao prodao;\n\t /**\n * 汉语中数字大写\n */\n private static final String[] CN_UPPER_NUMBER = { \"零\", \"壹\", \"贰\", \"叁\", \"肆\",\n \"伍\", \"陆\", \"柒\", \"捌\", \"玖\" };\n /**\n * 汉语中货币单位大写,这样的设计类似于占位符\n */\n private static final String[] CN_UPPER_MONETRAY_UNIT = { \"分\", \"角\", \"元\",\n \"拾\", \"佰\", \"仟\", \"万\", \"拾\", \"佰\", \"仟\", \"亿\", \"拾\", \"佰\", \"仟\", \"兆\", \"拾\",\n \"佰\", \"仟\" };\n /**\n * 特殊字符:整\n */\n private static final String CN_FULL = \"整\";\n /**\n * 特殊字符:负\n */\n private static final String CN_NEGATIVE = \"负\";\n /**\n * 金额的精度,默认值为2\n */\n private static final int MONEY_PRECISION = 2;\n /**\n * 特殊字符:零元整\n */\n private static final String CN_ZEOR_FULL = \"零元\" + CN_FULL;\n \n\n\t/**\n\t * 写文件 方法\n\t * \n\t * @param response\n\t * @param file\n\t * @throws IOException \n\t */\n\tpublic void writefile(HttpServletResponse response, File file) {\n\t\tServletOutputStream sos = null;\n\t\tFileInputStream aa = null;\n\t\ttry {\n\t\t\taa = new FileInputStream(file);\n\t\t\tsos = response.getOutputStream();\n\t\t\t// 读取文件问字节码\n\t\t\tbyte[] data = new byte[(int) file.length()];\n\t\t\tIOUtils.readFully(aa, data);\n\t\t\t// 将文件流输出到浏览器\n\t\t\tIOUtils.write(data, sos);\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}finally{\n\t\t\ttry {\n\t\t\t\tsos.close();\n\t\t\t\taa.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\n\t}\n /**\n * 用户封装\n * @param user\n * @param page\n * @param size\n * @param val\n * @return\n */\n\tpublic void user(int page,int size,Model model){\n\t\tPageable pa=new PageRequest(page, size);\n\t\t//查看用户并分页\n\t\tPage pageuser=udao.findAll(pa);\n\t\tList userlist=pageuser.getContent();\n\t\t// 查询部门表\n\t\tIterable deptlist = ddao.findAll();\n\t\t// 查职位表\n\t\tIterable poslist = pdao.findAll();\n\t\tmodel.addAttribute(\"page\", pageuser);\n\t\tmodel.addAttribute(\"emplist\", userlist);\n\t\tmodel.addAttribute(\"deptlist\", deptlist);\n\t\tmodel.addAttribute(\"poslist\", poslist);\n\t\tmodel.addAttribute(\"url\", \"names\");\n\t}\n\t\n\t\n\tpublic Page index(User user,int page,int size,String val,Model model){\n\t\tPageable pa=new PageRequest(page, size);\n\t\tPage pagelist=null;\n\t\tPage pagelist2=null;\n\t\tList orders = new ArrayList<>();\n\t\tUser u=udao.findByUserName(val);//找用户\n\t\tSystemStatusList status=sdao.findByStatusModelAndStatusName(\"aoa_process_list\", val);\n\t\tif(StringUtil.isEmpty(val)){\n\t\t\torders.add(new Order(Direction.DESC, \"applyTime\"));\n\t\t\tSort sort = new Sort(orders);\n\t\t\tpa=new PageRequest(page, size,sort);\n\t\t\tpagelist=redao.findByUserIdOrderByStatusId(user,false, pa);\n\t\t}else if(!Objects.isNull(u)){\n\t\t\tpagelist=redao.findprocesslist(user,u,false,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}else if(!Objects.isNull(status)){\n\t\t\tpagelist=redao.findbystatusprocesslist(user,status.getStatusId(),false,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}else{\n\t\t\tpagelist2=redao.findbytypenameprocesslist(user, val,false, pa);\n\t\t\tif(!pagelist2.hasContent()){\n\t\t\t\tpagelist2=redao.findbyprocessnameprocesslist(user, val,false, pa);\n\t\t\t}\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t\treturn pagelist2;\n\t\t}\n\t\treturn pagelist;\n\t}\n\n\tpublic List> index2(Page page,User user){\n\t\tList> list = new ArrayList<>();\n\t\tList prolist=page.getContent();\n\t\tfor (int i = 0; i < prolist.size(); i++) {\n\t\t\tString harryname=tydao.findname(prolist.get(i).getDeeply());\n\t\t\tSystemStatusList status=sdao.findOne(prolist.get(i).getStatusId());\n\t\t\tMap result=new HashMap<>();\n\t\t\tresult.put(\"typename\", prolist.get(i).getTypeNmae());\n\t\t\tresult.put(\"title\", prolist.get(i).getProcessName());\n\t\t\tresult.put(\"pushuser\", prolist.get(i).getUserName());\n\t\t\tresult.put(\"applytime\", prolist.get(i).getApplyTime());\n\t\t\tresult.put(\"harry\", harryname);\n\t\t\tresult.put(\"statusname\", status.getStatusName());\n\t\t\tresult.put(\"statuscolor\", status.getStatusColor());\n\t\t\tresult.put(\"proid\", prolist.get(i).getProcessId());\n\t\t\tlist.add(result);\n\t\t\t\n\t\t}\n\t\treturn list;\n\t}\n\t/**\n\t * 审核人封装\n\t */\n\tpublic List> index4(ProcessList process){\n\t\tList> relist=new ArrayList<>();\n\t\tList revie=redao.findByReviewedTimeNotNullAndProId(process);\n\t\tfor (int i = 0; i result=new HashMap<>();\n\t\t\tUser u=udao.findOne(revie.get(i).getUserId().getUserId());\n\t\t\tPosition po=pdao.findOne(u.getPosition().getId());\n\t\t\tSystemStatusList status=sdao.findOne(revie.get(i).getStatusId());\n\t\t\tresult.put(\"poname\", po.getName());\n\t\t\tresult.put(\"username\", u.getUserName());\n\t\t\tresult.put(\"retime\",revie.get(i).getReviewedTime());\n\t\t\tresult.put(\"restatus\",status.getStatusName());\n\t\t\tresult.put(\"statuscolor\",status.getStatusColor());\n\t\t\tresult.put(\"des\", revie.get(i).getAdvice());\n\t\t\tresult.put(\"img\",u.getImgPath());\n\t\t\tresult.put(\"positionid\",u.getPosition().getId());\n\t\t\trelist.add(result);\n\t\t}\n\t\treturn relist;\n\t}\n\t/**\n\t * process数据封装\n\t */\n\t\n\tpublic Map index3(String name,User user,String typename,ProcessList process){\n\t\tSystem.out.println(name);\n\t\tMap result=new HashMap<>();\n\t\tString harryname=tydao.findname(process.getDeeply());\n\t\tresult.put(\"proId\", process.getProcessId());\n\t\tresult.put(\"harryname\", harryname);\n\t\tresult.put(\"processName\", process.getProcessName());\n\t\tresult.put(\"processDescribe\",process.getProcessDescribe());\n\t\tif((\"审核\").equals(name)){\n\t\t\tresult.put(\"username\", process.getUserId().getUserName());//提单人员\n\t\t\tresult.put(\"deptname\", ddao.findname(process.getUserId().getDept().getDeptId()));//部门\n\t\t}else if((\"申请\").equals(name)){\n\t\t\tresult.put(\"username\", user.getUserName());\n\t\t\tresult.put(\"deptname\", ddao.findname(process.getUserId().getDept().getDeptId()));\n\t\t}\n\t\tresult.put(\"applytime\", process.getApplyTime());\n\t\tif(!Objects.isNull(process.getProFileid())){\n\t\t\tresult.put(\"file\", process.getProFileid());\n\t\t}else{\n\t\t\tresult.put(\"file\", \"file\");\n\t\t}\n\t\tresult.put(\"name\", name);\n\t\tresult.put(\"typename\", process.getTypeNmae());\n\t\tresult.put(\"startime\", process.getStartTime());\n\t\tresult.put(\"endtime\", process.getEndTime());\n\t\tresult.put(\"tianshu\", process.getProcseeDays());\n\t\tresult.put(\"statusid\", process.getStatusId());\n\t\tif( process.getProFileid()!=null){\n\t\t result.put(\"filepath\", process.getProFileid().getAttachmentPath());\n\t\t\tif(process.getProFileid().getAttachmentType().startsWith(\"image\")){\n\t\t\t\tresult.put(\"filetype\", \"img\");\n\t\t\t}else{\n\t\t\t\tresult.put(\"filetype\", \"appli\");\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t * 公用\n\t */\n\tpublic void index6(Model model,Long id,int page,int size){\n\t\tUser lu=udao.findOne(id);//申请人\n\t\tPageable pa=new PageRequest(page, size);\n\t\tList harrylist=tydao.findByTypeModel(\"aoa_process_list\");\n\t\t//查看用户并分页\n\t\tPage pageuser=udao.findAll(pa);\n\t\tList userlist=pageuser.getContent();\n\t\t// 查询部门表\n\t\tIterable deptlist = ddao.findAll();\n\t\t// 查职位表\n\t\tIterable poslist = pdao.findAll();\n\t\tmodel.addAttribute(\"page\", pageuser);\n\t\tmodel.addAttribute(\"emplist\", userlist);\n\t\tmodel.addAttribute(\"deptlist\", deptlist);\n\t\tmodel.addAttribute(\"poslist\", poslist);\n\t\tmodel.addAttribute(\"url\", \"names\");\n\t\tmodel.addAttribute(\"username\", lu.getUserName());\n\t\tmodel.addAttribute(\"harrylist\", harrylist);\n\t}\n\t/**\n\t * 存表\n\t * @throws IOException \n\t * @throws IllegalStateException \n\t */\n\tpublic void index5(ProcessList pro,String val,User lu,MultipartFile filePath,String name) throws IllegalStateException, IOException{\n\t\t\n\t\tpro.setTypeNmae(val);\n\t\tpro.setApplyTime(new Date());\n\t\tpro.setUserId(lu);\n\t\tpro.setStatusId(23L);\n\t\tpro.setShenuser(name);\n\t\tAttachment attaid=null;\n\t\tif(!StringUtil.isEmpty(filePath.getOriginalFilename())){\n\t\t\tattaid=mservice.upload(filePath, lu);\n\t\t\tattaid.setModel(\"aoa_bursement\");\n\t\t\tAttDao.save(attaid);\n\t\t\tpro.setProFileid(attaid);\n\t\t}\n\t}\n\tpublic void index8(ProcessList pro,String val,User lu,String name) {\n\t\tpro.setTypeNmae(val);\n\t\tpro.setApplyTime(new Date());\n\t\tpro.setUserId(lu);\n\t\tpro.setStatusId(23L);\n\t\tpro.setShenuser(name);\n\t}\n\t/**\n\t * 存主表\n\t */\n\tpublic void save(Long proid,User u,Reviewed reviewed,ProcessList pro,User u2){\n\t\tReviewed re=redao.findByProIdAndUserId(proid,u);\n\t\tre.setAdvice(reviewed.getAdvice());\n\t\tre.setStatusId(reviewed.getStatusId());\n\t\tre.setReviewedTime(new Date());\n\t\tre.setStatusId(reviewed.getStatusId());\n\t\tredao.save(re);\n\t\t\n\t\t\n\t\tReviewed re2=new Reviewed();\n\t\tre2.setProId(pro);\n\t\tre2.setUserId(u2);\n\t\tre2.setStatusId(23L);\n\t\tredao.save(re2);\n\t\t\n\t\tpro.getShenuser();\n\t\tpro.setShenuser(pro.getShenuser()+\";\"+u2.getUserName());\n\t\tpro.setStatusId(24L);//改变主表的状态\n\t\tprodao.save(pro);\n\t}\n\t/**\n\t * 存审核表\n\t */\n\tpublic void index7(User reuser,ProcessList pro){\n\t\tReviewed revie=new Reviewed();\n\t\trevie.setUserId(reuser);\n\t\trevie.setStatusId(23L);\n\t\trevie.setProId(pro);\n\t\tredao.save(revie);\n\t}\n\t/**\n\t * 把输入的金额转换为汉语中人民币的大写\n\t * \n\t * @param numberOfMoney\n\t * 输入的金额\n\t * @return 对应的汉语大写\n\t */\n\t public static String number2CNMontrayUnit(BigDecimal numberOfMoney) {\n\t StringBuffer sb = new StringBuffer();\n\t // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or\n\t // positive.\n\t int signum = numberOfMoney.signum();\n\t // 零元整的情况\n\t if (signum == 0) {\n\t return CN_ZEOR_FULL;\n\t }\n\t //这里会进行金额的四舍五入\n\t long number = numberOfMoney.movePointRight(MONEY_PRECISION)\n\t .setScale(0, 4).abs().longValue();\n\t // 得到小数点后两位值\n\t long scale = number % 100;\n\t int numUnit = 0;\n\t int numIndex = 0;\n\t boolean getZero = false;\n\t // 判断最后两位数,一共有四中情况:00 = 0, 01 = 1, 10, 11\n\t if (!(scale > 0)) {\n\t numIndex = 2;\n\t number = number / 100;\n\t getZero = true;\n\t }\n\t if ((scale > 0) && (!(scale % 10 > 0))) {\n\t numIndex = 1;\n\t number = number / 10;\n\t getZero = true;\n\t }\n\t int zeroSize = 0;\n\t while (true) {\n\t if (number <= 0) {\n\t break;\n\t }\n\t // 每次获取到最后一个数\n\t numUnit = (int) (number % 10);\n\t if (numUnit > 0) {\n\t if ((numIndex == 9) && (zeroSize >= 3)) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);\n\t }\n\t if ((numIndex == 13) && (zeroSize >= 3)) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);\n\t }\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);\n\t sb.insert(0, CN_UPPER_NUMBER[numUnit]);\n\t getZero = false;\n\t zeroSize = 0;\n\t } else {\n\t ++zeroSize;\n\t if (!(getZero)) {\n\t sb.insert(0, CN_UPPER_NUMBER[numUnit]);\n\t }\n\t if (numIndex == 2) {\n\t if (number > 0) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);\n\t }\n\t } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);\n\t }\n\t getZero = true;\n\t }\n\t // 让number每次都去掉最后一个数\n\t number = number / 10;\n\t ++numIndex;\n\t }\n\t // 如果signum == -1,则说明输入的数字为负数,就在最前面追加特殊字符:负\n\t if (signum == -1) {\n\t sb.insert(0, CN_NEGATIVE);\n\t }\n\t // 输入的数字小数点后两位为\"00\"的情况,则要在最后追加特殊字符:整\n\t if (!(scale > 0)) {\n\t sb.append(CN_FULL);\n\t }\n\t return sb.toString();\n\t }\n\t \n\t public static String numbertocn(Double money){\n\t \tBigDecimal numberOfMoney = new BigDecimal(money);\n\t String s = number2CNMontrayUnit(numberOfMoney);\n\t System.out.println(\"你输入的金额为:【\"+ money +\"】 #--# [\" +s.toString()+\"]\");\n\t return s.toString();\n\t }\t\n\n\t\n\t\n}", "answers": ["\tprivate MailreciverDao mrdao;"], "length": 4000, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "a99a9287-af59-462b-b5bb-1e441b6e521b", "reasoning": "The controller class is listing its @Autowired dependencies. It has just declared @Autowired for InMailDao imdao; the next dependency likely is the MailreciverDao used for handling mail recipients, matching the imported DAOs. Therefore the next line should declare the field with the @Autowired already applied: \"private MailreciverDao mrdao;\".", "reasoning_model_answer": "private MailreciverDao mrdao;", "assistant_with_reasoning": "\nThe controller class is listing its @Autowired dependencies. It has just declared @Autowired for InMailDao imdao; the next dependency likely is the MailreciverDao used for handling mail recipients, matching the imported DAOs. Therefore the next line should declare the field with the @Autowired already applied: \"private MailreciverDao mrdao;\".\n\nprivate MailreciverDao mrdao;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.074, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 38297, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private MailreciverDao mrdao;", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import android.content.Intent;\nimport android.view.View;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport com.buaa.food.CommentPreview;\nimport com.buaa.food.DataBaseHelper;\nimport com.buaa.food.DishPreview;\nimport com.buaa.food.R;\nimport com.buaa.food.app.AppActivity;\nimport com.buaa.food.app.TitleBarFragment;\nimport com.buaa.food.ui.activity.CommentActivity;\nimport com.buaa.food.ui.activity.DishDetailActivity;\nimport com.buaa.food.ui.activity.admin.DishUploadActivity;\nimport com.buaa.food.ui.adapter.CommentsAdapter;\nimport com.buaa.food.ui.adapter.DishesAdapter;\nimport com.hjq.base.BaseAdapter;\nimport com.hjq.widget.layout.WrapRecyclerView;\nimport com.scwang.smart.refresh.layout.SmartRefreshLayout;\nimport com.scwang.smart.refresh.layout.api.RefreshLayout;\nimport com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;\nimport java.util.ArrayList;\nimport java.util.List;\nimport timber.log.Timber;", "context": "app/src/main/java/com/buaa/food/ui/fragment/CommentsFragment.java\npackage com.buaa.food.ui.fragment;\n\n\n\n\n\n\npublic final class CommentsFragment extends TitleBarFragment\n implements OnRefreshLoadMoreListener,\n BaseAdapter.OnItemClickListener {\n\n public enum StatusType {\n CommentOne,\n CommentTwo\n }\n\n private final int id;\n private final StatusType type;\n\n private List allComments;\n\n public static CommentsFragment newInstance(int id, StatusType type) {\n return new CommentsFragment(id, type);\n }\n\n public CommentsFragment(int id, StatusType type) {\n this.id = id;\n this.type = type;\n }\n\n private SmartRefreshLayout mRefreshLayout;\n private WrapRecyclerView mRecyclerView;\n\n private CommentsAdapter mAdapter;\n\n // 添加数据库连接\n private DataBaseHelper dataBaseHelper;\n\n @Override\n protected int getLayoutId() {\n return R.layout.status_fragment_comment;\n }\n\n @Override\n protected void initView() {\n mRefreshLayout = findViewById(R.id.rl_status_refresh_comment);\n mRecyclerView = findViewById(R.id.rv_status_list_comment);\n\n mAdapter = new CommentsAdapter(getAttachActivity());\n mAdapter.setOnItemClickListener(this);\n mRecyclerView.setAdapter(mAdapter);\n\n mRefreshLayout.setOnRefreshLoadMoreListener(this);\n\n this.dataBaseHelper = new DataBaseHelper(this.getContext());\n }\n\n @Override\n protected void initData() {\n mAdapter.setData(analogData());\n }\n\n private List analogData() {\n\napp/src/main/java/com/buaa/food/CommentPreview.java\npublic class CommentPreview implements Comparable {\n int dishId;\n int commentId;\n String userName;\n String comment;\n String time;\n\n public CommentPreview(int dishId, int commentId, String userName, String comment, String time) {\n this.dishId = dishId;\n this.commentId = commentId;\n this.userName = userName;\n this.comment = comment;\n this.time = time;\n }\n\n public int getDishId() {\n return dishId;\n }\n\n public int getCommentId() {\n return commentId;\n }\n\n public String getUserName() {\n return userName;\n }\n\n\n public String getComment() {\n return comment;\n }\n\n public String getTime() {\n return time;\n }\n\n @Override\n public int compareTo(CommentPreview other) {\n return Integer.compare(this.commentId, other.commentId);\n }\n}\n\napp/src/main/java/com/buaa/food/ui/adapter/CommentsAdapter.java\npublic final class CommentsAdapter extends AppAdapter {\n\n public CommentsAdapter(Context context) {\n super(context);\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n return new ViewHolder();\n }\n\n private final class ViewHolder extends AppAdapter.ViewHolder {\n\n private final TextView mCommentText;\n private final TextView mUserText;\n\n private ViewHolder() {\n super(R.layout.comment_item);\n mCommentText = findViewById(R.id.tv_comment_content);\n mUserText = findViewById(R.id.tv_comment_time);\n }\n\n @SuppressLint({\"SetTextI18n\", \"UseCompatLoadingForDrawables\"})\n @Override\n public void onBindView(int position) {\n mCommentText.setText(getItem(position).getComment());\n mUserText.setText(getItem(position).getUserName() + \" \" + getItem(position).getTime());\n }\n }\n}\n\napp/src/main/java/com/buaa/food/ui/activity/DishDetailActivity.java\npublic final class DishDetailActivity extends AppActivity {\n\n private int dishId;\n boolean isCollected = false;\n\n private AppCompatImageView mDishImageView;\n private AppCompatTextView mDishNameView;\n private AppCompatTextView mDishPriceView;\n private AppCompatTextView mDishRemainingView;\n private AppCompatTextView mDishCanteenView;\n private AppCompatTextView mDishWindowView;\n private SettingBar mCommentEnterBar;\n private AppCompatButton mBuyBtn;\n private AppCompatImageView mCollectionView;\n\n private DataBaseHelper dataBaseHelper;\n\n @Override\n protected int getLayoutId() {\n return R.layout.dish_detail_activity;\n }\n\n @Override\n protected void initView() {\n dishId = getIntent().getIntExtra(\"dishId\", 0);\n\n mDishImageView = findViewById(R.id.iv_dish_image);\n mDishNameView = findViewById(R.id.tv_dish_name);\n mDishPriceView = findViewById(R.id.tv_dish_price);\n mDishRemainingView = findViewById(R.id.tv_dish_remaining);\n mDishCanteenView = findViewById(R.id.tv_dish_canteen);\n mDishWindowView = findViewById(R.id.tv_dish_window);\n mCommentEnterBar = findViewById(R.id.sb_comment_enter);\n mBuyBtn = findViewById(R.id.btn_buy);\n mCollectionView = findViewById(R.id.iv_collection);\n\n setOnClickListener(mCommentEnterBar, mBuyBtn, mCollectionView, mCommentEnterBar);\n\n dataBaseHelper = new DataBaseHelper(this);\n }\n\n @SuppressLint(\"SetTextI18n\")\n @Override\n protected void initData() {\n byte[] imgByte = dataBaseHelper.getDishImage(dishId);\n if (imgByte != null && imgByte.length > 0) {\n Bitmap imgBitmap = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);\n\n GlideApp.with(getActivity())\n .load(imgBitmap)\n .placeholder(R.drawable.dish_1)\n .error(R.drawable.dish_1)\n .transform(new MultiTransformation<>(new CenterCrop()))\n .into(mDishImageView);\n } else {\n GlideApp.with(getActivity())\n .load(R.drawable.default1)\n .placeholder(R.drawable.dish_1)\n .error(R.drawable.dish_1)\n .transform(new MultiTransformation<>(new CenterCrop()))\n .into(mDishImageView);\n }\n\n mDishNameView.setText(dataBaseHelper.getDishName(dishId));\n mDishPriceView.setText(dataBaseHelper.getDishPrice(dishId) + \" 元\");\n mDishRemainingView.setText(dataBaseHelper.getDishRemaining(dishId) + \" 份\");\n mDishCanteenView.setText(dataBaseHelper.getDishCanteen(dishId));\n mDishWindowView.setText(dataBaseHelper.getDishWindow(dishId));\n\n // TODO : init mCollectionView ==> has done\n // isCollected = dataBaseHelper.isDishCollected(dishId);\n int curViewed = dataBaseHelper.getDishViewed(dishId);\n if (curViewed != -1) {\n dataBaseHelper.updateDishViewed(dishId, curViewed + 1);\n }\n\n isCollected = dataBaseHelper.isFavorite(dishId);\n\n if (isCollected) {\n mCollectionView.setImageResource(R.drawable.collected);\n } else {\n mCollectionView.setImageResource(R.drawable.collection_icon);\n }\n }\n\n @SingleClick\n @Override\n public void onClick(View view) {\n if (view == mBuyBtn) {\n if (dataBaseHelper.checkDishRemaining(dishId)) {\n int curRemain = dataBaseHelper.getDishRemaining(dishId);\n int curOrdered = dataBaseHelper.getDishOrdered(dishId);\n if (curOrdered != -1 && curRemain != -1) {\n dataBaseHelper.updateDishRemaining(dishId, curRemain - 1);\n dataBaseHelper.updateDishOrdered(dishId, curOrdered + 1);\n Toast.makeText(DishDetailActivity.this, \"菜品购买成功\", Toast.LENGTH_SHORT).show();\n dataBaseHelper.uploadHistory(dishId);\n } else {\n Toast.makeText(DishDetailActivity.this, \"菜品购买失败\", Toast.LENGTH_SHORT).show();\n }\n } else {\n Toast.makeText(DishDetailActivity.this, \"购买失败,菜品余量不足\", Toast.LENGTH_SHORT).show();\n }\n\n // dataBaseHelper.updateDishViewed(dishId, dataBaseHelper.getDishViewed(dishId) + 1);\n\n // TODO : Add to user's history ==> has done\n finish();\n\n } else if (view == mCommentEnterBar) {\n Intent intent = new Intent(getActivity(), CommentActivity.class);\n intent.putExtra(\"dishId\", dishId);\n intent.putExtra(\"commentId\", 0);\n startActivity(intent);\n } else if (view == mCollectionView) {\n // dataBaseHelper.uploadFavorite(dishId);\n\n // TODO : Add to user's collection or cancel collection ==> has done\n\n if (isCollected) {\n dataBaseHelper.deleteCollection(dishId);\n toast(\"取消收藏\");\n mCollectionView.setImageResource(R.drawable.collection_icon);\n isCollected = false;\n } else {\n dataBaseHelper.uploadFavorite(dishId);\n toast(\"收藏成功\");\n mCollectionView.setImageResource(R.drawable.collected);\n isCollected = true;\n }\n\n }\n }\n}\n\nlibrary/widget/src/main/java/com/hjq/widget/layout/WrapRecyclerView.java\n@SuppressWarnings(\"rawtypes\")\npublic final class WrapRecyclerView extends RecyclerView {\n\n /** 原有的适配器 */\n private RecyclerView.Adapter mRealAdapter;\n\n /** 支持添加头部和底部的适配器 */\n private final WrapRecyclerAdapter mWrapAdapter = new WrapRecyclerAdapter();\n\n public WrapRecyclerView(Context context) {\n super(context);\n }\n\n public WrapRecyclerView(Context context, @Nullable AttributeSet attrs) {\n super(context, attrs);\n }\n\n public WrapRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n @Override\n public void setAdapter(Adapter adapter) {\n mRealAdapter = adapter;\n // 偷梁换柱\n mWrapAdapter.setRealAdapter(mRealAdapter);\n // 禁用条目动画\n setItemAnimator(null);\n super.setAdapter(mWrapAdapter);\n }\n\n @Override\n public Adapter getAdapter() {\n return mRealAdapter;\n }\n\n /**\n * 添加头部View\n */\n public void addHeaderView(View view) {\n mWrapAdapter.addHeaderView(view);\n }\n\n @SuppressWarnings(\"unchecked\")\n public V addHeaderView(@LayoutRes int id) {\n View headerView = LayoutInflater.from(getContext()).inflate(id, this, false);\n addHeaderView(headerView);\n return (V) headerView;\n }\n\n /**\n * 移除头部View\n */\n public void removeHeaderView(View view) {\n mWrapAdapter.removeHeaderView(view);\n }\n\n /**\n * 添加底部View\n */\n public void addFooterView(View view) {\n mWrapAdapter.addFooterView(view);\n }\n\n @SuppressWarnings(\"unchecked\")\n public V addFooterView(@LayoutRes int id) {\n View footerView = LayoutInflater.from(getContext()).inflate(id, this, false);\n addFooterView(footerView);\n return (V) footerView;\n }\n\n /**\n * 移除底部View\n */\n public void removeFooterView(View view) {\n mWrapAdapter.removeFooterView(view);\n }\n\n /**\n * 获取头部View总数\n */\n public int getHeaderViewsCount() {\n return mWrapAdapter.getHeaderViewsCount();\n }\n\n /**\n * 获取底部View总数\n */\n public int getFooterViewsCount() {\n return mWrapAdapter.getFooterViewsCount();\n }\n\n /**\n * 获取头部View集合\n */\n public List getHeaderViews() {\n return mWrapAdapter.getHeaderViews();\n }\n\n /**\n * 获取底部View集合\n */\n public List getFooterViews() {\n return mWrapAdapter.getFooterViews();\n }\n\n /**\n * 刷新头部和底部布局所有的 View 的状态\n */\n public void refreshHeaderFooterViews() {\n mWrapAdapter.notifyDataSetChanged();\n }\n\n /**\n * 设置在 GridLayoutManager 模式下头部和尾部都是独占一行的效果\n */\n public void adjustSpanSize() {\n final RecyclerView.LayoutManager layoutManager = getLayoutManager();\n if (!(layoutManager instanceof GridLayoutManager)) {\n return;\n }\n\n ((GridLayoutManager) layoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n\n @Override\n public int getSpanSize(int position) {\n return (position < mWrapAdapter.getHeaderViewsCount()\n || position >= mWrapAdapter.getHeaderViewsCount() + (mRealAdapter == null ? 0 : mRealAdapter.getItemCount()))\n ? ((GridLayoutManager) layoutManager).getSpanCount() : 1;\n }\n });\n }\n\n /**\n * 采用装饰设计模式,将原有的适配器包装起来\n */\n private static final class WrapRecyclerAdapter extends RecyclerView.Adapter {\n\n /** 头部条目类型 */\n private static final int HEADER_VIEW_TYPE = Integer.MIN_VALUE >> 1;\n /** 底部条目类型 */\n private static final int FOOTER_VIEW_TYPE = Integer.MAX_VALUE >> 1;\n\n /** 原有的适配器 */\n private RecyclerView.Adapter mRealAdapter;\n /** 头部View集合 */\n private final List mHeaderViews = new ArrayList<>();\n /** 底部View集合 */\n private final List mFooterViews = new ArrayList<>();\n /** 当前调用的位置 */\n private int mCurrentPosition;\n\n /** RecyclerView对象 */\n private RecyclerView mRecyclerView;\n\n /** 数据观察者对象 */\n private WrapAdapterDataObserver mObserver;\n\n private void setRealAdapter(RecyclerView.Adapter adapter) {\n if (mRealAdapter == adapter) {\n return;\n }\n\n if (mRealAdapter != null) {\n if (mObserver != null) {\n // 为原有的RecyclerAdapter移除数据监听对象\n mRealAdapter.unregisterAdapterDataObserver(mObserver);\n }\n }\n\n mRealAdapter = adapter;\n if (mRealAdapter == null) {\n return;\n }\n\n if (mObserver == null) {\n mObserver = new WrapAdapterDataObserver(this);\n }\n // 为原有的RecyclerAdapter添加数据监听对象\n mRealAdapter.registerAdapterDataObserver(mObserver);\n // 适配器不是第一次被绑定到RecyclerView上需要发送通知,因为第一次绑定会自动通知\n if (mRecyclerView != null) {\n notifyDataSetChanged();\n }\n }\n\n @Override\n public int getItemCount() {\n int itemCount = 0;\n if (mRealAdapter != null) {\n itemCount = mRealAdapter.getItemCount();\n }\n return getHeaderViewsCount() + itemCount + getFooterViewsCount();\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public int getItemViewType(int position) {\n mCurrentPosition = position;\n // 获取头部布局的总数\n int headerCount = getHeaderViewsCount();\n // 获取原有适配器的总数\n int adapterCount = mRealAdapter != null ? mRealAdapter.getItemCount() : 0;\n // 获取在原有适配器上的位置\n int adjPosition = position - headerCount;\n if (position < headerCount) {\n return HEADER_VIEW_TYPE;\n } else if (adjPosition < adapterCount) {\n return mRealAdapter.getItemViewType(adjPosition);\n }\n return FOOTER_VIEW_TYPE;\n }\n\n public int getPosition() {\n return mCurrentPosition;\n }\n\n @SuppressWarnings(\"all\")\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n switch (viewType) {\n case HEADER_VIEW_TYPE:\n return newWrapViewHolder(mHeaderViews.get(getPosition()));\n case FOOTER_VIEW_TYPE:\n return newWrapViewHolder(mFooterViews.get(getPosition() - getHeaderViewsCount() - (mRealAdapter != null ? mRealAdapter.getItemCount() : 0)));\n default:\n int itemViewType = mRealAdapter.getItemViewType(getPosition() - getHeaderViewsCount());\n if (itemViewType == HEADER_VIEW_TYPE || itemViewType == FOOTER_VIEW_TYPE) {\n throw new IllegalStateException(\"Please do not use this type as itemType\");\n }\n if (mRealAdapter == null) {\n return null;\n }\n return mRealAdapter.onCreateViewHolder(parent, itemViewType);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {\n if (mRealAdapter == null) {\n return;\n }\n int viewType = getItemViewType(position);\n switch (viewType) {\n case HEADER_VIEW_TYPE:\n case FOOTER_VIEW_TYPE:\n break;\n default:\n mRealAdapter.onBindViewHolder(holder, getPosition() - getHeaderViewsCount());\n break;\n }\n }\n\n private WrapViewHolder newWrapViewHolder(View view) {\n ViewParent parent = view.getParent();\n if (parent instanceof ViewGroup) {\n // IllegalStateException: ViewHolder views must not be attached when created.\n // Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot)\n ((ViewGroup) parent).removeView(view);\n }\n return new WrapViewHolder(view);\n }\n\n @Override\n public long getItemId(int position) {\n if (mRealAdapter != null && position > getHeaderViewsCount() - 1 && position < getHeaderViewsCount() + mRealAdapter.getItemCount()) {\n return mRealAdapter.getItemId(position - getHeaderViewsCount());\n }\n return super.getItemId(position);\n }\n\n @Override\n public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {\n mRecyclerView = recyclerView;\n if (mRealAdapter == null) {\n return;\n }\n mRealAdapter.onAttachedToRecyclerView(recyclerView);\n }\n\n @Override\n public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {\n mRecyclerView = null;\n if (mRealAdapter == null) {\n return;\n }\n mRealAdapter.onDetachedFromRecyclerView(recyclerView);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public void onViewRecycled(@NonNull ViewHolder holder) {\n if (holder instanceof WrapViewHolder) {\n // 防止这个 ViewHolder 被 RecyclerView 拿去复用\n holder.setIsRecyclable(false);\n return;\n }\n if (mRealAdapter == null) {\n return;\n }\n mRealAdapter.onViewRecycled(holder);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public boolean onFailedToRecycleView(@NonNull ViewHolder holder) {\n if (mRealAdapter == null) {\n return super.onFailedToRecycleView(holder);\n }\n return mRealAdapter.onFailedToRecycleView(holder);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public void onViewAttachedToWindow(@NonNull ViewHolder holder) {\n if (mRealAdapter == null) {\n return;\n }\n mRealAdapter.onViewAttachedToWindow(holder);\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public void onViewDetachedFromWindow(@NonNull ViewHolder holder) {\n if (mRealAdapter == null) {\n return;\n }\n mRealAdapter.onViewDetachedFromWindow(holder);\n }\n\n /**\n * 添加头部View\n */\n private void addHeaderView(View view) {\n // 不能添加同一个View对象,否则会导致RecyclerView复用异常\n if (!mHeaderViews.contains(view) && !mFooterViews.contains(view)) {\n mHeaderViews.add(view);\n notifyDataSetChanged();\n }\n }\n\n /**\n * 移除头部View\n */\n private void removeHeaderView(View view) {\n if (mHeaderViews.remove(view)) {\n notifyDataSetChanged();\n }\n }\n\n /**\n * 添加底部View\n */\n private void addFooterView(View view) {\n // 不能添加同一个View对象,否则会导致RecyclerView复用异常\n if (!mFooterViews.contains(view) && !mHeaderViews.contains(view)) {\n mFooterViews.add(view);\n notifyDataSetChanged();\n }\n }\n\n /**\n * 移除底部View\n */\n private void removeFooterView(View view) {\n if (mFooterViews.remove(view)) {\n notifyDataSetChanged();\n }\n }\n\n /**\n * 获取头部View总数\n */\n private int getHeaderViewsCount() {\n return mHeaderViews.size();\n }\n\n /**\n * 获取底部View总数\n */\n private int getFooterViewsCount() {\n return mFooterViews.size();\n }\n\n /**\n * 获取头部View集合\n */\n private List getHeaderViews() {\n return mHeaderViews;\n }\n\n /**\n * 获取底部View集合\n */\n private List getFooterViews() {\n return mFooterViews;\n }\n }\n\n /**\n * 头部和底部通用的ViewHolder对象\n */\n private static final class WrapViewHolder extends RecyclerView.ViewHolder {\n\n private WrapViewHolder(View itemView) {\n super(itemView);\n }\n }\n\n /**\n * 数据改变监听器\n */\n private static final class WrapAdapterDataObserver extends RecyclerView.AdapterDataObserver {\n\n private final WrapRecyclerAdapter mWrapAdapter;\n\n private WrapAdapterDataObserver(WrapRecyclerAdapter adapter) {\n mWrapAdapter = adapter;\n }\n\n @Override\n public void onChanged() {\n mWrapAdapter.notifyDataSetChanged();\n }\n\n @Override\n public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {\n mWrapAdapter.notifyItemRangeChanged(mWrapAdapter.getHeaderViewsCount() + positionStart, itemCount, payload);\n }\n\n @Override\n public void onItemRangeChanged(int positionStart, int itemCount) {\n mWrapAdapter.notifyItemRangeChanged(mWrapAdapter.getHeaderViewsCount() + positionStart, itemCount);\n }\n\n @Override\n public void onItemRangeInserted(int positionStart, int itemCount) {\n mWrapAdapter.notifyItemRangeInserted(mWrapAdapter.getHeaderViewsCount() + positionStart, itemCount);\n }\n\n @Override\n public void onItemRangeRemoved(int positionStart, int itemCount) {\n mWrapAdapter.notifyItemRangeRemoved(mWrapAdapter.getHeaderViewsCount() + positionStart, itemCount);\n }\n\n @Override\n public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {\n mWrapAdapter.notifyItemMoved(mWrapAdapter.getHeaderViewsCount() + fromPosition, mWrapAdapter.getHeaderViewsCount() + toPosition);\n }\n }\n}\n\napp/src/main/java/com/buaa/food/app/TitleBarFragment.java\npublic abstract class TitleBarFragment extends AppFragment\n implements TitleBarAction {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 */\n private ImmersionBar mImmersionBar;\n\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n // 设置标题栏点击监听\n if (getTitleBar() != null) {\n getTitleBar().setOnTitleBarListener(this);\n }\n\n if (isStatusBarEnabled()) {\n // 初始化沉浸式状态栏\n getStatusBarConfig().init();\n\n if (getTitleBar() != null) {\n // 设置标题栏沉浸\n ImmersionBar.setTitleBar(this, getTitleBar());\n }\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n if (isStatusBarEnabled()) {\n // 重新初始化状态栏\n getStatusBarConfig().init();\n }\n }\n\n /**\n * 是否在 Fragment 使用沉浸式\n */\n public boolean isStatusBarEnabled() {\n return false;\n }\n\n /**\n * 获取状态栏沉浸的配置对象\n */\n @NonNull\n protected ImmersionBar getStatusBarConfig() {\n if (mImmersionBar == null) {\n mImmersionBar = createStatusBarConfig();\n }\n return mImmersionBar;\n }\n\n /**\n * 初始化沉浸式\n */\n @NonNull\n protected ImmersionBar createStatusBarConfig() {\n return ImmersionBar.with(this)\n // 默认状态栏字体颜色为黑色\n .statusBarDarkFont(isStatusBarDarkFont())\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white)\n // 状态栏字体和导航栏内容自动变色,必须指定状态栏颜色和导航栏颜色才可以自动变色\n .autoDarkModeEnable(true, 0.2f);\n }\n\n /**\n * 获取状态栏字体颜色\n */\n protected boolean isStatusBarDarkFont() {\n // 返回真表示黑色字体\n return getAttachActivity().isStatusBarDarkFont();\n }\n\n @Override\n @Nullable\n public TitleBar getTitleBar() {\n if (mTitleBar == null || !isLoading()) {\n mTitleBar = obtainTitleBar((ViewGroup) getView());\n }\n return mTitleBar;\n }\n}\n\napp/src/main/java/com/buaa/food/app/AppActivity.java\npublic abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 */\n private ImmersionBar mImmersionBar;\n\n /** 加载对话框 */\n private BaseDialog mDialog;\n /** 对话框数量 */\n private int mDialogCount;\n\n /**\n * 当前加载对话框是否在显示中\n */\n public boolean isShowDialog() {\n return mDialog != null && mDialog.isShowing();\n }\n\n /**\n * 显示加载对话框\n */\n public void showDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n mDialogCount++;\n postDelayed(() -> {\n if (mDialogCount <= 0 || isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialog == null) {\n mDialog = new WaitDialog.Builder(this)\n .setCancelable(false)\n .create();\n }\n if (!mDialog.isShowing()) {\n mDialog.show();\n }\n }, 300);\n }\n\n /**\n * 隐藏加载对话框\n */\n public void hideDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialogCount > 0) {\n mDialogCount--;\n }\n\n if (mDialogCount != 0 || mDialog == null || !mDialog.isShowing()) {\n return;\n }\n\n mDialog.dismiss();\n }\n\n @Override\n protected void initLayout() {\n super.initLayout();\n\n if (getTitleBar() != null) {\n getTitleBar().setOnTitleBarListener(this);\n }\n\n // 初始化沉浸式状态栏\n if (isStatusBarEnabled()) {\n getStatusBarConfig().init();\n\n // 设置标题栏沉浸\n if (getTitleBar() != null) {\n ImmersionBar.setTitleBar(this, getTitleBar());\n }\n }\n }\n\n /**\n * 是否使用沉浸式状态栏\n */\n protected boolean isStatusBarEnabled() {\n return true;\n }\n\n /**\n * 状态栏字体深色模式\n */\n protected boolean isStatusBarDarkFont() {\n return true;\n }\n\n /**\n * 获取状态栏沉浸的配置对象\n */\n @NonNull\n public ImmersionBar getStatusBarConfig() {\n if (mImmersionBar == null) {\n mImmersionBar = createStatusBarConfig();\n }\n return mImmersionBar;\n }\n\n /**\n * 初始化沉浸式状态栏\n */\n @NonNull\n protected ImmersionBar createStatusBarConfig() {\n return ImmersionBar.with(this)\n // 默认状态栏字体颜色为黑色\n .statusBarDarkFont(isStatusBarDarkFont())\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white)\n // 状态栏字体和导航栏内容自动变色,必须指定状态栏颜色和导航栏颜色才可以自动变色\n .autoDarkModeEnable(true, 0.2f);\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(@StringRes int id) {\n setTitle(getString(id));\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(CharSequence title) {\n super.setTitle(title);\n if (getTitleBar() != null) {\n getTitleBar().setTitle(title);\n }\n }\n\n @Override\n @Nullable\n public TitleBar getTitleBar() {\n if (mTitleBar == null) {\n mTitleBar = obtainTitleBar(getContentView());\n }\n return mTitleBar;\n }\n\n @Override\n public void onLeftClick(View view) {\n onBackPressed();\n }\n\n @Override\n public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {\n super.startActivityForResult(intent, requestCode, options);\n overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);\n }\n\n @Override\n public void finish() {\n super.finish();\n overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);\n }\n\n /**\n * {@link OnHttpListener}\n */\n\n @Override\n public void onStart(Call call) {\n showDialog();\n }\n\n @Override\n public void onSucceed(Object result) {\n if (result instanceof HttpData) {\n toast(((HttpData) result).getMessage());\n }\n }\n\n @Override\n public void onFail(Exception e) {\n toast(e.getMessage());\n }\n\n @Override\n public void onEnd(Call call) {\n hideDialog();\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n if (isShowDialog()) {\n hideDialog();\n }\n mDialog = null;\n }\n}\n\napp/src/main/java/com/buaa/food/DishPreview.java\npublic class DishPreview implements Comparable {\n int dishId;\n int ordered;\n int viewed;\n String dishName;\n String dishPrice;\n\n // TODO: implement dishImage\n // String dishImage;\n byte[] image;\n\n public DishPreview(int dishId, String dishName, String dishPrice, byte[] image,\n int ordered, int viewed) {\n this.dishId = dishId;\n this.dishName = dishName;\n this.dishPrice = dishPrice;\n this.image = image;\n this.ordered = ordered;\n this.viewed = viewed;\n }\n\n public DishPreview(String dishName, String dishPrice) {\n this.dishName = dishName;\n this.dishPrice = dishPrice;\n }\n\n public String getDishName() {\n return dishName;\n }\n\n public String getDishPrice() {\n return dishPrice;\n }\n\n public void setDishPrice(String dishPrice) {\n this.dishPrice = dishPrice;\n }\n\n public byte[] getImage() {\n return image;\n }\n\n public int getDishId() {\n return dishId;\n }\n\n @Override\n public int compareTo(DishPreview other) {\n // 比较规则:首先按照ordered属性升序排列,如果相同则按照viewed属性升序排列\n if (this.ordered + this.viewed != other.ordered + other.viewed) {\n return Integer.compare(other.ordered + other.viewed, this.ordered + this.viewed);\n } else {\n return Integer.compare(this.dishId, other.dishId);\n }\n }\n}\n\nlibrary/base/src/main/java/com/hjq/base/BaseAdapter.java\npublic abstract class BaseAdapter.ViewHolder>\n extends RecyclerView.Adapter implements ResourcesAction {\n\n /** 上下文对象 */\n private final Context mContext;\n\n /** RecyclerView 对象 */\n private RecyclerView mRecyclerView;\n\n /** 条目点击监听器 */\n @Nullable\n private OnItemClickListener mItemClickListener;\n /** 条目长按监听器 */\n @Nullable\n private OnItemLongClickListener mItemLongClickListener;\n\n /** 条目子 View 点击监听器 */\n @Nullable\n private SparseArray mChildClickListeners;\n /** 条目子 View 长按监听器 */\n @Nullable\n private SparseArray mChildLongClickListeners;\n\n /** ViewHolder 位置偏移值 */\n private int mPositionOffset = 0;\n\n public BaseAdapter(Context context) {\n mContext = context;\n if (mContext == null) {\n throw new IllegalArgumentException(\"are you ok?\");\n }\n }\n\n @Override\n public final void onBindViewHolder(@NonNull VH holder, int position) {\n // 根据 ViewHolder 绑定的位置和传入的位置进行对比\n // 一般情况下这两个位置值是相等的,但是有一种特殊的情况\n // 在外层添加头部 View 的情况下,这两个位置值是不对等的\n mPositionOffset = position - holder.getAdapterPosition();\n holder.onBindView(position);\n }\n\n /**\n * 获取 RecyclerView 对象\n */\n @Nullable\n public RecyclerView getRecyclerView() {\n return mRecyclerView;\n }\n\n @Override\n public Context getContext() {\n return mContext;\n }\n\n /**\n * 条目 ViewHolder,需要子类 ViewHolder 继承\n */\n public abstract class ViewHolder extends RecyclerView.ViewHolder\n implements View.OnClickListener, View.OnLongClickListener {\n\n public ViewHolder(@LayoutRes int id) {\n this(LayoutInflater.from(getContext()).inflate(id, mRecyclerView, false));\n }\n\n public ViewHolder(View itemView) {\n super(itemView);\n\n // 设置条目的点击和长按事件\n if (mItemClickListener != null) {\n itemView.setOnClickListener(this);\n }\n if (mItemLongClickListener != null) {\n itemView.setOnLongClickListener(this);\n }\n\n // 设置条目子 View 点击事件\n if (mChildClickListeners != null) {\n for (int i = 0; i < mChildClickListeners.size(); i++) {\n View childView = findViewById(mChildClickListeners.keyAt(i));\n if (childView != null) {\n childView.setOnClickListener(this);\n }\n }\n }\n\n // 设置条目子 View 长按事件\n if (mChildLongClickListeners != null) {\n for (int i = 0; i < mChildLongClickListeners.size(); i++) {\n View childView = findViewById(mChildLongClickListeners.keyAt(i));\n if (childView != null) {\n childView.setOnLongClickListener(this);\n }\n }\n }\n }\n\n /**\n * 数据绑定回调\n */\n public abstract void onBindView(int position);\n\n /**\n * 获取 ViewHolder 位置\n */\n protected final int getViewHolderPosition() {\n // 这里解释一下为什么用 getLayoutPosition 而不用 getAdapterPosition\n // 如果是使用 getAdapterPosition 会导致一个问题,那就是快速点击删除条目的时候会出现 -1 的情况,因为这个 ViewHolder 已经解绑了\n // 而使用 getLayoutPosition 则不会出现位置为 -1 的情况,因为解绑之后在布局中不会立马消失,所以不用担心在动画执行中获取位置有异常的情况\n return getLayoutPosition() + mPositionOffset;\n }\n\n /**\n * {@link View.OnClickListener}\n */\n\n @Override\n public void onClick(View view) {\n int position = getViewHolderPosition();\n if (position < 0 || position >= getItemCount()) {\n return;\n }\n\n if (view == getItemView()) {\n if(mItemClickListener != null) {\n mItemClickListener.onItemClick(mRecyclerView, view, position);\n }\n return;\n }\n\n if (mChildClickListeners != null) {\n OnChildClickListener listener = mChildClickListeners.get(view.getId());\n if (listener != null) {\n listener.onChildClick(mRecyclerView, view, position);\n }\n }\n }\n\n /**\n * {@link View.OnLongClickListener}\n */\n\n @Override\n public boolean onLongClick(View view) {\n int position = getViewHolderPosition();\n if (position < 0 || position >= getItemCount()) {\n return false;\n }\n\n if (view == getItemView()) {\n if (mItemLongClickListener != null) {\n return mItemLongClickListener.onItemLongClick(mRecyclerView, view, position);\n }\n return false;\n }\n\n if (mChildLongClickListeners != null) {\n OnChildLongClickListener listener = mChildLongClickListeners.get(view.getId());\n if (listener != null) {\n return listener.onChildLongClick(mRecyclerView, view, position);\n }\n }\n return false;\n }\n\n public final View getItemView() {\n return itemView;\n }\n\n public final V findViewById(@IdRes int id) {\n return getItemView().findViewById(id);\n }\n }\n\n @Override\n public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {\n mRecyclerView = recyclerView;\n // 判断当前的布局管理器是否为空,如果为空则设置默认的布局管理器\n if (mRecyclerView.getLayoutManager() == null) {\n RecyclerView.LayoutManager layoutManager = generateDefaultLayoutManager(mContext);\n if (layoutManager != null) {\n mRecyclerView.setLayoutManager(layoutManager);\n }\n }\n }\n\n @Override\n public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {\n mRecyclerView = null;\n }\n\n /**\n * 生成默认的布局摆放器\n */\n protected RecyclerView.LayoutManager generateDefaultLayoutManager(Context context) {\n return new LinearLayoutManager(context);\n }\n\n /**\n * 设置 RecyclerView 条目点击监听\n */\n public void setOnItemClickListener(@Nullable OnItemClickListener listener) {\n checkRecyclerViewState();\n mItemClickListener = listener;\n }\n\n /**\n * 设置 RecyclerView 条目子 View 点击监听\n */\n public void setOnChildClickListener(@IdRes int id, @Nullable OnChildClickListener listener) {\n checkRecyclerViewState();\n if (mChildClickListeners == null) {\n mChildClickListeners = new SparseArray<>();\n }\n mChildClickListeners.put(id, listener);\n }\n\n /**\n * 设置 RecyclerView 条目长按监听\n */\n public void setOnItemLongClickListener(@Nullable OnItemLongClickListener listener) {\n checkRecyclerViewState();\n mItemLongClickListener = listener;\n }\n\n /**\n * 设置 RecyclerView 条目子 View 长按监听\n */\n public void setOnChildLongClickListener(@IdRes int id, @Nullable OnChildLongClickListener listener) {\n checkRecyclerViewState();\n if (mChildLongClickListeners == null) {\n mChildLongClickListeners = new SparseArray<>();\n }\n mChildLongClickListeners.put(id, listener);\n }\n\n /**\n * 检查 RecyclerView 状态\n */\n private void checkRecyclerViewState() {\n if (mRecyclerView != null) {\n // 必须在 RecyclerView.setAdapter() 之前设置监听\n throw new IllegalStateException(\"are you ok?\");\n }\n }\n\n /**\n * RecyclerView 条目点击监听类\n */\n public interface OnItemClickListener{\n\n /**\n * 当 RecyclerView 某个条目被点击时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param itemView 被点击的条目对象\n * @param position 被点击的条目位置\n */\n void onItemClick(RecyclerView recyclerView, View itemView, int position);\n }\n\n /**\n * RecyclerView 条目长按监听类\n */\n public interface OnItemLongClickListener {\n\n /**\n * 当 RecyclerView 某个条目被长按时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param itemView 被点击的条目对象\n * @param position 被点击的条目位置\n * @return 是否拦截事件\n */\n boolean onItemLongClick(RecyclerView recyclerView, View itemView, int position);\n }\n\n /**\n * RecyclerView 条目子 View 点击监听类\n */\n public interface OnChildClickListener {\n\n /**\n * 当 RecyclerView 某个条目 子 View 被点击时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param childView 被点击的条目子 View\n * @param position 被点击的条目位置\n */\n void onChildClick(RecyclerView recyclerView, View childView, int position);\n }\n\n /**\n * RecyclerView 条目子 View 长按监听类\n */\n public interface OnChildLongClickListener {\n\n /**\n * 当 RecyclerView 某个条目子 View 被长按时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param childView 被点击的条目子 View\n * @param position 被点击的条目位置\n */\n boolean onChildLongClick(RecyclerView recyclerView, View childView, int position);\n }\n}\n\napp/src/main/java/com/buaa/food/ui/activity/CommentActivity.java\npublic class CommentActivity extends AppActivity implements TextView.OnEditorActionListener{\n private int dishId;\n private int commentId;\n private TitleBar mTitleBar;\n private LinearLayout mLinearLayout;\n private LinearLayout mCommentLinearLayout;\n private TextView commentView;\n private TextView userView;\n private ViewPager mViewPager;\n private FragmentPagerAdapter> mPagerAdapter;\n private DataBaseHelper dataBaseHelper;\n private AppCompatButton mCommentButton;\n\n protected int getLayoutId() {\n return R.layout.comment_activity;\n }\n\n protected void initView() {\n dataBaseHelper = new DataBaseHelper(this);\n\n dishId = getIntent().getIntExtra(\"dishId\", 0);\n commentId = getIntent().getIntExtra(\"commentId\", 0);\n\n mLinearLayout = findViewById(R.id.comment_activity);\n mCommentLinearLayout = findViewById(R.id.one_comment);\n\n mTitleBar = findViewById(R.id.comment);\n mViewPager = findViewById(R.id.vp_comment_pager);\n mPagerAdapter = new FragmentPagerAdapter<>(this);\n\n if (dishId != 0 && commentId == 0) {\n mTitleBar.setTitle(\"一级评论\");\n mPagerAdapter.addFragment(CommentsFragment.newInstance(dishId, CommentsFragment.StatusType.CommentOne));\n mLinearLayout.removeView(mCommentLinearLayout);\n } else if (dishId == 0 && commentId != 0) {\n mTitleBar.setTitle(\"二级评论\");\n mPagerAdapter.addFragment(CommentsFragment.newInstance(commentId, CommentsFragment.StatusType.CommentTwo));\n String comment = dataBaseHelper.getComment(commentId);\n String userName = dataBaseHelper.getCommentUserName(commentId);\n String time = dataBaseHelper.getCommentTime(commentId);\n commentView = findViewById(R.id.tv_comment_content);\n userView = findViewById(R.id.tv_comment_time);\n commentView.setText(comment);\n userView.setText(userName + \" \" + time);\n }\n\n mViewPager.setAdapter(mPagerAdapter);\n\n mCommentButton = findViewById(R.id.btn_comment);\n\n setOnClickListener(mCommentButton);\n }\n\n\n protected void initData() {\n }\n\n @SingleClick\n @Override\n public void onClick(View view) {\n if (view == mCommentButton) {\n new InputDialog.Builder(this)\n .setTitle(\"评论\")\n .setContent(\"请输入评论内容\")\n .setHint(\"评论内容\")\n .setConfirm(\"确定\")\n .setCancel(\"取消\")\n .setAutoDismiss(true)\n .setListener((dialog, content) -> {\n if (content.isEmpty()) {\n toast(\"请输入评论内容\");\n }\n if (dishId != 0 && commentId == 0) {\n dataBaseHelper.insertComment(dishId, content, dataBaseHelper\n .getUserId(UserAuth.getLocalUserPhone()));\n toast(\"评论成功\");\n finish();\n } else if (dishId == 0 && commentId != 0) {\n dataBaseHelper.insertSecondComment(commentId, content, dataBaseHelper\n .getUserId(UserAuth.getLocalUserPhone()));\n toast(\"评论成功\");\n finish();\n }\n })\n .show();\n }\n }\n\n @Override\n public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {\n return false;\n }\n}\n\napp/src/main/java/com/buaa/food/ui/activity/admin/DishUploadActivity.java\npublic final class DishUploadActivity extends AppActivity\n implements TextView.OnEditorActionListener {\n\n private int dishId;\n\n private AppCompatImageView mImageView;\n private EditText mNameView;\n private EditText mPriceView;\n private EditText mRemainingView;\n private AppCompatTextView mCanteenView;\n private AppCompatTextView mWindowView;\n private SubmitButton mUploadView;\n\n private DataBaseHelper dataBaseHelper;\n\n @Override\n protected int getLayoutId() {\n return R.layout.dish_upload_activity;\n }\n\n @Override\n protected void initView() {\n dishId = getIntent().getIntExtra(\"dishId\", -1);\n\n mImageView = findViewById(R.id.iv_dish_image);\n mNameView = findViewById(R.id.et_dish_name);\n mPriceView = findViewById(R.id.et_dish_price);\n mRemainingView = findViewById(R.id.et_dish_remaining);\n mCanteenView = findViewById(R.id.tv_canteen);\n mWindowView = findViewById(R.id.tv_window);\n mUploadView = findViewById(R.id.btn_dish_upload);\n\n dataBaseHelper = new DataBaseHelper(this);\n\n ImmersionBar.setTitleBar(this, findViewById(R.id.tv_register_title));\n\n InputTextManager.with(this)\n .addView(mNameView)\n .addView(mPriceView)\n .addView(mRemainingView)\n .setMain(mUploadView)\n .build();\n\n setOnClickListener(mImageView, mCanteenView, mWindowView, mUploadView);\n }\n\n @Override\n protected void initData() {\n if (dishId == -1) {\n // 添加菜品\n GlideApp.with(getActivity())\n .load(R.drawable.baseline_fastfood_24)\n .placeholder(R.drawable.baseline_fastfood_24)\n .error(R.drawable.baseline_fastfood_24)\n .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))\n .into(mImageView);\n } else {\n // 修改菜品\n byte[] image = dataBaseHelper.getDishImage(dishId);\n if (image != null && image.length > 0) {\n Bitmap imgBitmap = BitmapFactory.decodeByteArray(image, 0, image.length);\n\n GlideApp.with(getActivity())\n .load(imgBitmap)\n .placeholder(R.drawable.baseline_fastfood_24)\n .error(R.drawable.baseline_fastfood_24)\n .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))\n .into(mImageView);\n } else {\n GlideApp.with(getActivity())\n .load(R.drawable.baseline_fastfood_24)\n .placeholder(R.drawable.baseline_fastfood_24)\n .error(R.drawable.baseline_fastfood_24)\n .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))\n .into(mImageView);\n }\n\n mNameView.setText(dataBaseHelper.getDishName(dishId));\n mPriceView.setText(String.valueOf(dataBaseHelper.getDishPrice(dishId)));\n mRemainingView.setText(String.valueOf(dataBaseHelper.getDishRemaining(dishId)));\n mCanteenView.setText(dataBaseHelper.getDishCanteen(dishId));\n mWindowView.setText(dataBaseHelper.getDishWindow(dishId));\n }\n }\n\n @SingleClick\n @Override\n public void onClick(View view) {\n String canteen = mCanteenView.getText().toString();\n\n if (view == mUploadView) {\n\n String dishName = mNameView.getText().toString();\n float dishPrice = Float.parseFloat(mPriceView.getText().toString());\n int dishRemaining = Integer.parseInt(mRemainingView.getText().toString());\n int canteenId = dataBaseHelper.getCanteenId(canteen);\n int windowId = dataBaseHelper.getWindowId(mWindowView.getText().toString());\n\n hideKeyboard(getCurrentFocus()); // 隐藏软键盘\n\n if (dishId == -1) {\n dataBaseHelper.insertDish(dishName, dishPrice, dishRemaining, windowId, canteenId);\n Toast.makeText(DishUploadActivity.this, \"Upload Successfully\", Toast.LENGTH_SHORT).show();\n } else {\n dataBaseHelper.updateDish(dishId, dishName, dishPrice, dishRemaining, windowId, canteenId);\n Toast.makeText(DishUploadActivity.this, \"Edit Successfully\", Toast.LENGTH_SHORT).show();\n }\n\n mUploadView.showSucceed();\n finish();\n\n } else if (view == mImageView) {\n ImageSelectActivity.start(this, data -> {\n cropImageFile(new File(data.get(0)));\n });\n\n } else if (view == mCanteenView) {\n// mWindowView.setText(\"选择窗口\");\n\n int defaultSelect = 0;\n switch (canteen) {\n case \"学三食堂(B1层)\":\n break;\n case \"学五食堂(一层)\":\n defaultSelect = 1;\n break;\n case \"学六食堂(二层)\":\n defaultSelect = 2;\n break;\n case \"教工食堂(二层)\":\n defaultSelect = 3;\n break;\n }\n\n new SelectDialog.Builder(this)\n .setTitle(\"请选择菜品食堂\")\n .setList(\"学三食堂(B1层)\", \"学五食堂(一层)\", \"学六食堂(二层)\", \"教工食堂(二层)\")\n .setSingleSelect()\n .setSelect(defaultSelect)\n .setListener(new SelectDialog.OnListener() {\n\n @Override\n public void onSelected(BaseDialog dialog, HashMap data) {\n mCanteenView.setText(data.values().iterator().next());\n }\n\n @Override\n public void onCancel(BaseDialog dialog) {\n toast(\"取消选择\");\n }\n })\n .show();\n\n } else if (view == mWindowView) {\n if (canteen.equals(\"选择食堂\")) {\n toast(\"请先选择食堂\");\n } else {\n switch (canteen) {\n case \"学三食堂(B1层)\":\n new SelectDialog.Builder(this)\n .setTitle(\"请选择菜品窗口\")\n .setList(\n \"三颗糖\",\n \"不止一面\",\n \"原蛊蒸饭\",\n \"新疆炒米粉\",\n \"日鉴一面(牛肉面)\",\n \"炉石披萨\",\n \"炸鸡汉堡\",\n \"猪肚鸡\",\n \"王宏龙馋嘴鱼\",\n \"米大碗\",\n \"缘味先石锅饭\",\n \"胡椒小屋\"\n )\n .setSingleSelect()\n .setSelect(0)\n .setListener(new SelectDialog.OnListener() {\n\n @Override\n public void onSelected(BaseDialog dialog, HashMap data) {\n mWindowView.setText(data.values().iterator().next());\n }\n\n @Override\n public void onCancel(BaseDialog dialog) {\n toast(\"取消选择\");\n }\n })\n .show();\n break;\n case \"学五食堂(一层)\":\n new SelectDialog.Builder(this)\n .setTitle(\"请选择菜品窗口\")\n .setList(\n \"主食\",\n \"卤肉饭\",\n \"基本伙\",\n \"小碗菜\",\n \"渔粉\",\n \"滋补汤品\",\n \"熟食\",\n \"精品菜\",\n \"航味菜\",\n \"轻食套餐\",\n \"铁板拌饭\",\n \"面条\",\n \"麻辣香锅冒菜\"\n )\n .setSingleSelect()\n .setSelect(0)\n .setListener(new SelectDialog.OnListener() {\n\n @Override\n public void onSelected(BaseDialog dialog, HashMap data) {\n mWindowView.setText(data.values().iterator().next());\n }\n\n @Override\n public void onCancel(BaseDialog dialog) {\n toast(\"取消选择\");\n }\n })\n .show();\n break;\n case \"学六食堂(二层)\":\n new SelectDialog.Builder(this)\n .setTitle(\"请选择菜品窗口\")\n .setList(\n \"一品粥饼\",\n \"五谷渔粉\",\n \"千里香馄饨\",\n \"咖喱饭\",\n \"广式烧腊\",\n \"桂林米粉\",\n \"湖南小碗菜\",\n \"炒河粉\",\n \"煎饼豆浆\",\n \"猛火炒饭\",\n \"石锅拌饭\",\n \"酸菜鱼\",\n \"铁板饭\",\n \"闽南浇汁拌饭\",\n \"鱼籽饭\",\n \"黄焖鸡米饭\"\n )\n .setSingleSelect()\n .setSelect(0)\n .setListener(new SelectDialog.OnListener() {\n\n @Override\n public void onSelected(BaseDialog dialog, HashMap data) {\n mWindowView.setText(data.values().iterator().next());\n }\n\n @Override\n public void onCancel(BaseDialog dialog) {\n toast(\"取消选择\");\n }\n })\n .show();\n break;\n case \"教工食堂(二层)\":\n new SelectDialog.Builder(this)\n .setTitle(\"请选择菜品窗口\")\n .setList(\n \"统一窗口\"\n )\n .setSingleSelect()\n .setSelect(0)\n .setListener(new SelectDialog.OnListener() {\n\n @Override\n public void onSelected(BaseDialog dialog, HashMap data) {\n mWindowView.setText(data.values().iterator().next());\n }\n\n @Override\n public void onCancel(BaseDialog dialog) {\n toast(\"取消选择\");\n }\n })\n .show();\n break;\n }\n }\n }\n }\n\n @NonNull\n @Override\n protected ImmersionBar createStatusBarConfig() {\n return super.createStatusBarConfig()\n .navigationBarColor(R.color.white)\n .keyboardEnable(true);\n }\n\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n return false;\n }\n\n private void cropImageFile(File sourceFile) {\n ImageCropActivity.start(this, sourceFile, 1, 1, new ImageCropActivity.OnCropListener() {\n\n @Override\n public void onSucceed(Uri fileUri, String fileName) {\n File outputFile;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n outputFile = new FileContentResolver(getActivity(), fileUri, fileName);\n } else {\n try {\n outputFile = new File(new URI(fileUri.toString()));\n } catch (URISyntaxException e) {\n e.printStackTrace();\n outputFile = new File(fileUri.toString());\n }\n }\n updateCropImage(outputFile, true);\n }\n\n @Override\n public void onError(String details) {\n updateCropImage(sourceFile, false);\n }\n });\n }\n\n private void updateCropImage(File file, boolean deleteFile) {\n Uri mAvatarUrl;\n if (file instanceof FileContentResolver) {\n mAvatarUrl = ((FileContentResolver) file).getContentUri();\n } else {\n mAvatarUrl = Uri.fromFile(file);\n }\n GlideApp.with(getActivity())\n .load(mAvatarUrl)\n .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))\n .into(mImageView);\n\n try {\n Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mAvatarUrl);\n this.storeImage(bitmapImage);\n } catch (Exception e) {\n Toast.makeText(this, \"图片转换或上传出现问题\", Toast.LENGTH_SHORT).show();\n e.printStackTrace();\n }\n }\n\n private void storeImage(Bitmap bitmapImage) {\n if (mImageView.getDrawable() != null && bitmapImage != null) {\n dataBaseHelper.updateDishImage(dishId, bitmapImage);\n } else {\n Toast.makeText(this, \"图片为空\", Toast.LENGTH_SHORT).show();\n }\n }\n}", "answers": [" List data = new ArrayList<>();"], "length": 4091, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "5c2a632f-24b4-497c-92c8-aff474413e0e", "reasoning": "The method analogData() should start by creating a list to hold CommentPreview objects before populating it. The immediate next line after the method signature is the declaration and initialization of that list.", "reasoning_model_answer": "List list = new ArrayList<>();", "assistant_with_reasoning": "\nThe method analogData() should start by creating a list to hold CommentPreview objects before populating it. The immediate next line after the method signature is the declaration and initialization of that list.\n\nList list = new ArrayList<>();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.078, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36989, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "List list = new ArrayList<>();", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "import android.app.Activity;\nimport android.content.ClipData;\nimport android.content.Intent;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Environment;\nimport android.text.Editable;\nimport android.text.TextWatcher;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport androidx.activity.result.ActivityResultLauncher;\nimport androidx.activity.result.contract.ActivityResultContracts;\nimport androidx.annotation.Nullable;\nimport androidx.appcompat.widget.AppCompatImageButton;\nimport androidx.appcompat.widget.LinearLayoutCompat;\nimport androidx.appcompat.widget.PopupMenu;\nimport androidx.documentfile.provider.DocumentFile;\nimport androidx.fragment.app.Fragment;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport com.threethan.questpatcher.R;\nimport com.threethan.questpatcher.activities.APKInstallerActivity;\nimport com.threethan.questpatcher.activities.InstallerFilePickerActivity;\nimport com.threethan.questpatcher.adapters.APKsAdapter;\nimport com.threethan.questpatcher.utils.APKData;\nimport com.threethan.questpatcher.utils.APKEditorUtils;\nimport com.threethan.questpatcher.utils.APKExplorer;\nimport com.threethan.questpatcher.utils.AppData;\nimport com.threethan.questpatcher.utils.Common;\nimport com.threethan.questpatcher.utils.tasks.ExploreAPK;\nimport com.google.android.material.dialog.MaterialAlertDialogBuilder;\nimport com.google.android.material.tabs.TabLayout;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Objects;\nimport in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils;\nimport in.sunilpaulmathew.sCommon.CommonUtils.sExecutor;\nimport in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;", "context": "app/src/main/java/com/threethan/questpatcher/fragments/APKsFragment.java\npackage com.threethan.questpatcher.fragments;\n\n\n\n\n\n\n/*\n * Created by APK Explorer & Editor on March 04, 2021\n */\npublic class APKsFragment extends Fragment {\n\n private LinearLayoutCompat mProgress;\n private RecyclerView mRecyclerView;\n private APKsAdapter mRecycleViewAdapter;\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View mRootView = inflater.inflate(R.layout.fragment_apks, container, false);\n\n Common.initializeAPKsTitle(mRootView, R.id.app_title);\n Common.initializeAPKsSearchWord(mRootView, R.id.search_word);\n mProgress = mRootView.findViewById(R.id.progress_layout);\n AppCompatImageButton mSearchButton = mRootView.findViewById(R.id.search_button);\n AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort_button);\n AppCompatImageButton mAddButton = mRootView.findViewById(R.id.add_button);\n LinearLayoutCompat mBottomLayout = mRootView.findViewById(R.id.layout_bottom);\n TabLayout mTabLayout = mRootView.findViewById(R.id.tab_layout);\n mRecyclerView = mRootView.findViewById(R.id.recycler_view);\n\n mRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));\n\n Common.getAPKsTitle().setText(getString(R.string.apps_exported));\n mTabLayout.setVisibility(View.VISIBLE);\n\n mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.apks)));\n mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.bundles)));\n\n Objects.requireNonNull(mTabLayout.getTabAt(getTabPosition(requireActivity()))).select();\n\n mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {\n @Override\n public void onTabSelected(TabLayout.Tab tab) {\n String mStatus = sCommonUtils.getString(\"apkTypes\", \"apks\", requireActivity());\n switch (tab.getPosition()) {\n case 0:\n if (!mStatus.equals(\"apks\")) {\n sCommonUtils.saveString(\"apkTypes\", \"apks\", requireActivity());\n loadAPKs(requireActivity());\n }\n break;\n case 1:\n if (!mStatus.equals(\"bundles\")) {\n sCommonUtils.saveString(\"apkTypes\", \"bundles\", requireActivity());\n loadAPKs(requireActivity());\n }\n break;\n }\n }\n\n @Override\n public void onTabUnselected(TabLayout.Tab tab) {\n }\n\n @Override\n public void onTabReselected(TabLayout.Tab tab) {\n }\n });\n\n mSearchButton.setOnClickListener(v -> {\n if (Common.getAPKsSearchWord().getVisibility() == View.VISIBLE) {\n Common.getAPKsSearchWord().setVisibility(View.GONE);\n Common.getAPKsTitle().setVisibility(View.VISIBLE);\n if (Common.getAPKsSearchWord() != null) {\n Common.getAPKsSearchWord().setText(null);\n }\n AppData.toggleKeyboard(0, Common.getAPKsSearchWord(), requireActivity());\n } else {\n Common.getAPKsSearchWord().setVisibility(View.VISIBLE);\n Common.getAPKsSearchWord().requestFocus();\n Common.getAPKsTitle().setVisibility(View.GONE);\n AppData.toggleKeyboard(1, Common.getAPKsSearchWord(), requireActivity());\n }\n });\n\n\napp/src/main/java/com/threethan/questpatcher/utils/Common.java\npublic class Common {\n\n private static AppCompatEditText mSearchWordApks, mSearchWordApps, mSearchWordProjects;\n private static boolean mBuilding = false, mBusy = false, mCancel = false, mFinish = false,\n mPrivateKey = false, mReloading = false, mRSATemplate = false;\n private static List mFile = null;\n private static List mPackageData = null;\n private static final List mAPKList = new ArrayList<>(), mErrorList = new ArrayList<>();\n private static int mError = 0, mSuccess = 0;\n private static MaterialCardView mSelect;\n private static MaterialTextView mApksTitle, mAppsTitle, mProjectsTitle;\n private static String mAppID, mFilePath = null, mFileToReplace = null, mPackageName = null,\n mPath = null, mSearchWord, mStatus = null;\n\n public static AppCompatEditText getAPKsSearchWord() {\n return mSearchWordApks;\n }\n\n public static AppCompatEditText getAppsSearchWord() {\n return mSearchWordApps;\n }\n\n public static AppCompatEditText getProjectsSearchWord() {\n return mSearchWordProjects;\n }\n\n public static boolean isBuilding() {\n return mBuilding;\n }\n\n public static boolean isBusy() {\n return mBusy;\n }\n\n public static boolean isCancelled() {\n return mCancel;\n }\n\n public static boolean isFinished() {\n return mFinish;\n }\n\n public static boolean isReloading() {\n return mReloading;\n }\n\n public static boolean isTextMatched(String searchText, String searchWord) {\n for (int a = 0; a < searchText.length() - searchWord.length() + 1; a++) {\n if (searchWord.equalsIgnoreCase(searchText.substring(a, a + searchWord.length()))) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean hasPrivateKey() {\n return mPrivateKey;\n }\n\n public static boolean hasRASATemplate() {\n return mRSATemplate;\n }\n\n public static int getError() {\n return mError;\n }\n\n public static int getSuccess() {\n return mSuccess;\n }\n\n public static List getFiles() {\n return mFile;\n }\n\n public static List getPackageData() {\n return mPackageData;\n }\n\n public static List getAPKList() {\n return mAPKList;\n }\n\n public static List getErrorList() {\n return mErrorList;\n }\n\n public static MaterialCardView getSelectCard() {\n return mSelect;\n }\n\n public static MaterialTextView getAPKsTitle() {\n return mApksTitle;\n }\n\n public static MaterialTextView getAppsTitle() {\n return mAppsTitle;\n }\n\n public static MaterialTextView getProjectsTitle() {\n return mProjectsTitle;\n }\n\n public static String getAppID() {\n return mAppID;\n }\n\n public static String getFilePath() {\n return mFilePath;\n }\n\n public static String getFileToReplace() {\n return mFileToReplace;\n }\n\n public static String getPackageName() {\n return mPackageName;\n }\n\n public static String getPath() {\n return mPath;\n }\n\n public static String getSearchWord() {\n return mSearchWord;\n }\n\n public static String getStatus() {\n return mStatus;\n }\n\n public static void addToFilesList(File file) {\n if (mFile == null) {\n mFile = new ArrayList<>();\n }\n mFile.add(file);\n }\n\n public static void clearFilesList() {\n mFile = null;\n }\n\n public static void initializeAPKsSearchWord(View view, int id) {\n mSearchWordApks = view.findViewById(id);\n }\n\n public static void initializeAPKsTitle(View view, int id) {\n mApksTitle = view.findViewById(id);\n }\n\n public static void initializeAppsSearchWord(View view, int id) {\n mSearchWordApps = view.findViewById(id);\n }\n\n public static void initializeAppsTitle(View view, int id) {\n mAppsTitle = view.findViewById(id);\n }\n\n public static void initializeProjectsSearchWord(View view, int id) {\n mSearchWordProjects = view.findViewById(id);\n }\n\n public static void initializeProjectsTitle(View view, int id) {\n mProjectsTitle = view.findViewById(id);\n }\n\n public static void initializeView(View view, int id) {\n mSelect = view.findViewById(id);\n }\n\n public static void isBuilding(boolean b) {\n mBuilding = b;\n }\n\n public static void isCancelled(boolean b) {\n mCancel = b;\n }\n\n public static void isReloading(boolean b) {\n mReloading = b;\n }\n\n public static void removeFromFilesList(File file) {\n if (mFile == null || mFile.size() == 0) return;\n mFile.remove(file);\n }\n\n public static void setFinishStatus(boolean b) {\n mFinish = b;\n }\n\n public static void setPrivateKeyStatus(boolean b) {\n mPrivateKey = b;\n }\n\n public static void setRSATemplateStatus(boolean b) {\n mRSATemplate = b;\n }\n\n public static void setAppID(String appID) {\n mAppID = appID;\n }\n\n public static void setError(int i) {\n mError = i;\n }\n\n public static void setFilePath(String filePath) {\n mFilePath = filePath;\n }\n\n public static void setFileToReplace(String fileToReplace) {\n mFileToReplace = fileToReplace;\n }\n\n public static void setPackageName(String packageName) {\n mPackageName = packageName;\n }\n\n public static void setPackageData(List data) {\n mPackageData = data;\n }\n\n public static void setPath(String path) {\n mPath = path;\n }\n\n public static void setProgress(boolean b, View view) {\n mBusy = b;\n view.setVisibility(b ? View.VISIBLE : View.GONE);\n }\n\n public static void setSearchWord(String searchWord) {\n mSearchWord = searchWord;\n }\n\n public static void setStatus(String status) {\n mStatus = status;\n }\n\n public static void setSuccess(int i) {\n mSuccess = i;\n }\n\n}\n\napp/src/main/java/com/threethan/questpatcher/activities/APKInstallerActivity.java\npublic class APKInstallerActivity extends AppCompatActivity {\n\n private AppCompatImageButton mExploreIcon;\n private AppCompatImageView mAppIcon;\n private APKParser mAPKParser;\n private File mFile = null;\n private LinearLayoutCompat mMainLayout, mIconsLayout;\n private MaterialCardView mCancel, mInstall;\n private MaterialTextView mAppName, mInstallText, mPackageID;\n private TabLayout mTabLayout;\n private ViewPager mViewPager;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_apkdetails);\n\n mExploreIcon = findViewById(R.id.explore);\n mAppIcon = findViewById(R.id.app_image);\n mAppName = findViewById(R.id.app_title);\n mPackageID = findViewById(R.id.package_id);\n mMainLayout = findViewById(R.id.main_layout);\n mIconsLayout = findViewById(R.id.icons_layout);\n mInstall = findViewById(R.id.install);\n mInstallText = findViewById(R.id.install_text);\n mCancel = findViewById(R.id.cancel);\n mTabLayout = findViewById(R.id.tab_Layout);\n mViewPager = findViewById(R.id.view_pager);\n\n Bundle bundle = getIntent().getExtras();\n if (bundle != null && bundle.containsKey(\"apkFileUri\") && bundle.getString(\"apkFileUri\") != null) {\n manageInstallation(Uri.parse(bundle.getString(\"apkFileUri\")), null, this).execute();\n } else if (bundle != null && bundle.containsKey(\"apkFilePath\") && bundle.getString(\"apkFilePath\") != null) {\n manageInstallation(null, bundle.getString(\"apkFilePath\"), this).execute();\n } else if (getIntent().getData() != null) {\n manageInstallation(getIntent().getData(), null, this).execute();\n }\n }\n\n private sExecutor manageInstallation(Uri uri, String filePath, Activity activity) {\n return new sExecutor() {\n private ProgressDialog mProgressDialog;\n\n @Override\n public void onPreExecute() {\n mProgressDialog = new ProgressDialog(activity);\n mProgressDialog.setMessage(activity.getString(R.string.loading));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIcon(R.mipmap.ic_launcher);\n mProgressDialog.setTitle(R.string.app_name);\n mProgressDialog.setIndeterminate(true);\n mProgressDialog.setCancelable(false);\n mProgressDialog.show();\n\n sFileUtils.delete(getExternalFilesDir(\"APK\"));\n if (filePath == null) {\n String fileName = Objects.requireNonNull(DocumentFile.fromSingleUri(activity, uri)).getName();\n mFile = new File(getExternalFilesDir(\"APK\"), Objects.requireNonNull(fileName));\n }\n Common.getAPKList().clear();\n }\n\n @Override\n public void doInBackground() {\n if (filePath != null) {\n mFile = new File(filePath);\n } else {\n sFileUtils.copy(uri, mFile, activity);\n }\n try {\n mAPKParser = new APKParser();\n mAPKParser.parse(mFile.getAbsolutePath(), activity);\n } catch (Exception ignored) {\n }\n }\n\n @Override\n public void onPostExecute() {\n try {\n mProgressDialog.dismiss();\n } catch (IllegalArgumentException ignored) {\n }\n if (mFile.exists()) {\n if (mAPKParser.isParsed()) {\n loadAPKDetails(activity);\n if (sPackageUtils.isPackageInstalled(mAPKParser.getPackageName(), activity)) {\n mInstallText.setText(getString(R.string.update));\n }\n } else if (mFile.getName().endsWith(\"apkm\") || mFile.getName().endsWith(\"apks\") || mFile.getName().endsWith(\"xapk\")) {\n new SelectBundleDialog(mFile.getAbsolutePath(), true, activity).show();\n } else {\n new InvalidFileDialog(true, activity).show();\n }\n } else {\n new MaterialAlertDialogBuilder(activity)\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.split_apk_installer)\n .setMessage(getString(R.string.file_path_error))\n .setCancelable(false)\n .setPositiveButton(R.string.cancel, (dialogInterface, i) -> finish()).show();\n }\n }\n };\n }\n\n private void loadAPKDetails(Activity activity) {\n sPagerAdapter adapter = new sPagerAdapter(getSupportFragmentManager());\n try {\n if (sPackageUtils.isPackageInstalled(mAPKParser.getPackageName(), activity)) {\n mAppName.setText(sPackageUtils.getAppName(mAPKParser.getPackageName(), activity));\n mPackageID.setText(mAPKParser.getPackageName());\n mAppIcon.setImageDrawable(sPackageUtils.getAppIcon(mAPKParser.getPackageName(), activity));\n mPackageID.setVisibility(View.VISIBLE);\n } else {\n mAppName.setText(mAPKParser.getPackageName());\n mAppIcon.setImageDrawable(mAPKParser.getAppIcon());\n }\n\n adapter.AddFragment(new APKDetailsFragment(), getString(R.string.details));\n if (mAPKParser.getPermissions() != null) {\n adapter.AddFragment(new PermissionsFragment(), getString(R.string.permissions));\n }\n if (mAPKParser.getManifest() != null) {\n adapter.AddFragment(new ManifestFragment(), getString(R.string.manifest));\n }\n if (mAPKParser.getCertificate() != null) {\n adapter.AddFragment(new CertificateFragment(), getString(R.string.certificate));\n }\n } catch (Exception ignored) {}\n\n mViewPager.setAdapter(adapter);\n mTabLayout.setupWithViewPager(mViewPager);\n mMainLayout.setVisibility(View.VISIBLE);\n mIconsLayout.setVisibility(View.VISIBLE);\n\n mCancel.setOnClickListener(v -> finish());\n mInstall.setOnClickListener(v -> {\n Common.getAPKList().add(mFile.getAbsolutePath());\n APKExplorer.handleAPKs(true, activity);\n });\n\n mExploreIcon.setOnClickListener(v -> {\n new ExploreAPK(null, mFile, null, activity).execute();\n activity.finish();\n });\n }\n\n @Override\n public void onBackPressed() {\n finish();\n }\n\n}\n\napp/src/main/java/com/threethan/questpatcher/utils/APKExplorer.java\npublic class APKExplorer {\n\n public static List getData(File[] files, boolean supported, Activity activity) {\n List mData = new ArrayList<>(), mDir = new ArrayList<>(), mFiles = new ArrayList<>();\n try {\n // Add directories\n for (File mFile : files) {\n if (mFile.isDirectory() && !mFile.getName().matches(\".aeeBackup|.aeeBuild\")) {\n mDir.add(mFile.getAbsolutePath());\n }\n }\n Collections.sort(mDir, String.CASE_INSENSITIVE_ORDER);\n if (!sCommonUtils.getBoolean(\"az_order\", true, activity)) {\n Collections.reverse(mDir);\n }\n mData.addAll(mDir);\n // Add files\n for (File mFile :files) {\n if (supported) {\n if (mFile.isFile()) {\n mFiles.add(mFile.getAbsolutePath());\n }\n } else if (mFile.isFile() && isSupportedFile(mFile.getAbsolutePath())) {\n mFiles.add(mFile.getAbsolutePath());\n\n }\n }\n Collections.sort(mFiles, String.CASE_INSENSITIVE_ORDER);\n if (!sCommonUtils.getBoolean(\"az_order\", true, activity)) {\n Collections.reverse(mFiles);\n }\n mData.addAll(mFiles);\n } catch (NullPointerException ignored) {\n activity.finish();\n }\n return mData;\n }\n\n public static boolean isTextFile(String path) {\n return path.endsWith(\".txt\") || path.endsWith(\".xml\") || path.endsWith(\".json\") || path.endsWith(\".properties\")\n || path.endsWith(\".version\") || path.endsWith(\".sh\") || path.endsWith(\".MF\") || path.endsWith(\".SF\")\n || path.endsWith(\".html\") || path.endsWith(\".ini\") || path.endsWith(\".smali\");\n }\n\n public static boolean isImageFile(String path) {\n return path.endsWith(\".bmp\") || path.endsWith(\".png\") || path.endsWith(\".jpg\");\n }\n\n public static boolean isBinaryXML(String path) {\n return path.endsWith(\".xml\") && (new File(path).getName().equals(\"AndroidManifest.xml\") || path.contains(Common.getAppID() + \"/res/\"));\n }\n\n public static boolean isSmaliEdited(String path) {\n if (getAppData(path) == null) return false;\n try {\n return Objects.requireNonNull(getAppData(path)).getBoolean(\"smali_edited\");\n } catch (JSONException ignored) {\n }\n return false;\n }\n\n public static Bitmap getAppIcon(String path) {\n if (getAppData(path) == null) return null;\n try {\n return stringToBitmap(Objects.requireNonNull(getAppData(path)).getString(\"app_icon\"));\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static Bitmap stringToBitmap(String string) {\n try {\n byte[] imageAsBytes = Base64.decode(string.getBytes(), Base64.DEFAULT);\n return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);\n } catch (Exception ignored) {}\n return null;\n }\n\n private static boolean isSupportedFile(String path) {\n return path.endsWith(\".apk\") || path.endsWith(\".apks\") || path.endsWith(\".apkm\") || path.endsWith(\".xapk\");\n }\n\n public static JSONObject getAppData(String path) {\n if (sFileUtils.read(new File(path)) == null) return null;\n try {\n return new JSONObject(sFileUtils.read(new File(path)));\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static void setIcon(AppCompatImageButton icon, Drawable drawable, Context context) {\n icon.setImageDrawable(drawable);\n icon.setColorFilter(sThemeUtils.isDarkTheme(context) ? ContextCompat.getColor(context, R.color.colorWhite) :\n ContextCompat.getColor(context, R.color.colorBlack));\n }\n\n public static int getSpanCount(Activity activity) {\n return sCommonUtils.getOrientation(activity) == Configuration.ORIENTATION_LANDSCAPE ? 2 : 1;\n }\n\n public static String getAppName(String path) {\n if (getAppData(path) == null) return null;\n try {\n return Objects.requireNonNull(getAppData(path)).getString(\"app_name\");\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static String getPackageName(String path) {\n if (getAppData(path) == null) return null;\n try {\n return Objects.requireNonNull(getAppData(path)).getString(\"package_name\");\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static List getTextViewData(String path, String searchWord, boolean parsedManifest, Context context) {\n List mData = new ArrayList<>();\n String text = null;\n if (isBinaryXML(path)) {\n try (FileInputStream inputStream = new FileInputStream(path)) {\n text = new aXMLDecoder().decode(inputStream).trim();\n } catch (Exception e) {\n sCommonUtils.toast(context.getString(R.string.xml_decode_failed, new File(path).getName()), context).show();\n }\n } else if (parsedManifest) {\n text = path;\n } else {\n text = sFileUtils.read(new File(path));\n }\n if (text != null) {\n for (String line : text.split(\"\\\\r?\\\\n\")) {\n if (searchWord == null) {\n mData.add(line);\n } else if (Common.isTextMatched(line, searchWord)) {\n mData.add(line);\n }\n }\n }\n return mData;\n }\n\n public static Uri getIconFromPath(String path) {\n File mFile = new File(path);\n if (mFile.exists()) {\n return Uri.fromFile(mFile);\n }\n return null;\n }\n\n public static void saveImage(Bitmap bitmap, String dest, Context context) {\n try {\n OutputStream imageOutStream;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n ContentValues values = new ContentValues();\n values.put(MediaStore.MediaColumns.DISPLAY_NAME, new File(dest).getName());\n values.put(MediaStore.MediaColumns.MIME_TYPE, \"image/png\");\n values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);\n Uri uri = context.getContentResolver().insert(MediaStore.Files.getContentUri(\"external\"), values);\n imageOutStream = context.getContentResolver().openOutputStream(uri);\n } else {\n File image = new File(dest);\n imageOutStream = new FileOutputStream(image);\n }\n bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageOutStream);\n imageOutStream.close();\n } catch(Exception ignored) {\n }\n }\n\n public static Bitmap drawableToBitmap(Drawable drawable) {\n Bitmap bitmap;\n if (drawable instanceof BitmapDrawable) {\n BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;\n if(bitmapDrawable.getBitmap() != null) {\n return bitmapDrawable.getBitmap();\n }\n }\n if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {\n bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);\n } else {\n bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);\n }\n Canvas canvas = new Canvas(bitmap);\n drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n drawable.draw(canvas);\n return bitmap;\n }\n\n private static void installAPKs(boolean exit, Activity activity) {\n SplitAPKInstaller.installSplitAPKs(exit, Common.getAPKList(), null, activity);\n }\n\n public static void handleAPKs(boolean exit, Activity activity) {\n if (APKEditorUtils.isFullVersion(activity)) {\n if (sCommonUtils.getString(\"installerAction\", null, activity) == null) {\n new sSingleItemDialog(0, null, new String[] {\n activity.getString(R.string.install),\n activity.getString(R.string.install_resign),\n activity.getString(R.string.resign_only)\n }, activity) {\n\n @Override\n public void onItemSelected(int itemPosition) {\n sCommonUtils.saveBoolean(\"firstSigning\", true, activity);\n if (itemPosition == 0) {\n installAPKs(exit, activity);\n } else if (itemPosition == 1) {\n if (!sCommonUtils.getBoolean(\"firstSigning\", false, activity)) {\n new SigningOptionsDialog(null, exit, activity).show();\n } else {\n new ResignAPKs(null, true, exit, activity).execute();\n }\n } else {\n if (!sCommonUtils.getBoolean(\"firstSigning\", false, activity)) {\n new SigningOptionsDialog(null, exit, activity).show();\n } else {\n new ResignAPKs(null, false, exit, activity).execute();\n }\n }\n }\n }.show();\n } else if (sCommonUtils.getString(\"installerAction\", null, activity).equals(activity.getString(R.string.install))) {\n installAPKs(exit, activity);\n } else {\n if (!sCommonUtils.getBoolean(\"firstSigning\", false, activity)) {\n new SigningOptionsDialog(null, exit, activity).show();\n } else {\n new ResignAPKs(null,true, exit, activity).execute();\n }\n }\n } else {\n installAPKs(exit, activity);\n }\n }\n\n}\n\napp/src/main/java/com/threethan/questpatcher/utils/AppData.java\npublic class AppData {\n\n public static List getRawData(ProgressBar progressBar, Context context) {\n List mData = new ArrayList<>();\n List packages = context.getPackageManager().getInstalledApplications(0);\n for (ApplicationInfo packageInfo: packages) {\n progressBar.setMax(packages.size());\n try {\n PackageItems pi = new PackageItems(\n packageInfo.packageName,\n context);\n // If PackageItems construction survived, then add\n mData.add(pi);\n } catch (Exception ignored) {\n }\n if (progressBar.getProgress() < packages.size()) {\n progressBar.setProgress(progressBar.getProgress() + 1);\n }\n }\n return mData;\n }\n\n public static List getData(Context context) {\n List mData = new ArrayList<>();\n try {\n boolean mAppType;\n for (PackageItems packageItem : Common.getPackageData()) {\n if (sCommonUtils.getString(\"appTypes\", \"all\", context).equals(\"system\")) {\n mAppType = sPackageUtils.isSystemApp(packageItem.getPackageName(), context);\n } else if (sCommonUtils.getString(\"appTypes\", \"all\", context).equals(\"user\")) {\n mAppType = !sPackageUtils.isSystemApp(packageItem.getPackageName(), context);\n } else {\n mAppType = true;\n }\n if (mAppType) {\n if (Common.getSearchWord() == null) {\n mData.add(packageItem);\n } else if (Common.isTextMatched(packageItem.getAppName(), Common.getSearchWord())\n || Common.isTextMatched(packageItem.getPackageName(), Common.getSearchWord())) {\n mData.add(packageItem);\n }\n }\n }\n if (sCommonUtils.getBoolean(\"sort_name\", false, context)) {\n Collections.sort(mData, (lhs, rhs) -> String.CASE_INSENSITIVE_ORDER.compare(lhs.getAppName(), rhs.getAppName()));\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && sCommonUtils.getBoolean(\"sort_size\", false, context)) {\n Collections.sort(mData, Comparator.comparingLong(PackageItems::getAPKSize));\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && sCommonUtils.getBoolean(\"sort_installed\", false, context)) {\n Collections.sort(mData, Comparator.comparingLong(PackageItems::getInstalledTime));\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && sCommonUtils.getBoolean(\"sort_updated\", false, context)) {\n Collections.sort(mData, Comparator.comparingLong(PackageItems::getUpdatedTime));\n } else {\n Collections.sort(mData, (lhs, rhs) -> String.CASE_INSENSITIVE_ORDER.compare(lhs.getPackageName(), rhs.getPackageName()));\n }\n if (!sCommonUtils.getBoolean(\"az_order\", true, context)) {\n Collections.reverse(mData);\n }\n } catch (NullPointerException ignored) {}\n return mData;\n }\n\n public static PackageInfo getPackageInfo(String packageName, Context context) {\n try {\n return context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);\n } catch (Exception ignored) {\n }\n return null;\n }\n\n /*\n * Based on the work of https://github.com/ZenerDeveloper\n * Ref: https://github.com/SmartPack/PackageManager/commit/1ac499d0ed8922c02875df029ead80a17f1c40e1\n */\n public static void toggleKeyboard(int mode, AppCompatEditText textView, Context context) {\n InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);\n if (mode == 1) {\n if (textView.requestFocus()) {\n imm.showSoftInput(textView, InputMethodManager.SHOW_IMPLICIT);\n }\n } else {\n imm.hideSoftInputFromWindow(textView.getWindowToken(), 0);\n }\n }\n\n}\n\napp/src/main/java/com/threethan/questpatcher/utils/APKEditorUtils.java\npublic class APKEditorUtils {\n\n public static int getThemeAccentColor(Context context) {\n TypedValue value = new TypedValue();\n context.getTheme().resolveAttribute(R.attr.colorAccent, value, true);\n return value.data;\n }\n\n public static boolean isFullVersion(Context context) {\n return true;\n }\n\n public static CharSequence fromHtml(String text) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n return Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);\n } else {\n return Html.fromHtml(text);\n }\n }\n\n public static void unzip(String zip, String path) {\n try (ZipFile zipFile = new ZipFile(zip)) {\n zipFile.extractAll(path);\n } catch (IOException ignored) {\n }\n }\n\n public static void zip(File path, File zip) {\n try (ZipFile zipFile = new ZipFile(zip)) {\n for (File mFile : Objects.requireNonNull(path.listFiles())) {\n if (mFile.isDirectory()) {\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setCompressionMethod(CompressionMethod.STORE);\n zipFile.addFolder(mFile, zipParameters);\n } else {\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setCompressionMethod(CompressionMethod.STORE);\n zipFile.addFile(mFile, zipParameters);\n }\n }\n } catch (IOException ignored) {\n }\n }\n\n public static boolean isDocumentsUI(Uri uri) {\n return \"com.android.providers.downloads.documents\".equals(uri.getAuthority());\n }\n\n}\n\napp/src/main/java/com/threethan/questpatcher/adapters/APKsAdapter.java\npublic class APKsAdapter extends RecyclerView.Adapter {\n\n private static List data;\n\n public APKsAdapter(List data) {\n APKsAdapter.data = data;\n }\n\n @NonNull\n @Override\n public APKsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View rowItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_view_apks, parent, false);\n return new ViewHolder(rowItem);\n }\n\n @SuppressLint({\"NotifyDataSetChanged\", \"StringFormatInvalid\"})\n @Override\n public void onBindViewHolder(@NonNull APKsAdapter.ViewHolder holder, int position) {\n try {\n if (new File(data.get(position)).isDirectory()) {\n if (sAPKUtils.getAPKIcon(data.get(position) + \"/base.apk\", holder.mAppName.getContext()) != null) {\n holder.mAppIcon.setImageDrawable(sAPKUtils.getAPKIcon(data.get(position) + \"/base.apk\", holder.mAppName.getContext()));\n } else {\n holder.mAppIcon.setImageDrawable(ContextCompat.getDrawable(holder.mAppIcon.getContext(), R.drawable.ic_android));\n holder.mAppIcon.setColorFilter(APKEditorUtils.getThemeAccentColor(holder.mAppIcon.getContext()));\n }\n if (Common.getSearchWord() != null && Common.isTextMatched(new File(data.get(position)).getName(), Common.getSearchWord())) {\n holder.mAppName.setText(APKEditorUtils.fromHtml(new File(data.get(position)).getName().replace(Common.getSearchWord(),\n \"\" + Common.getSearchWord() + \"\")));\n } else {\n holder.mAppName.setText(new File(data.get(position)).getName());\n }\n if (sAPKUtils.getPackageName(data.get(position) + \"/base.apk\", holder.mAppName.getContext()) == null) {\n holder.mAppName.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);\n holder.mCard.setOnClickListener(v -> sCommonUtils.snackBar(v, v.getContext().getString(R.string.apk_corrupted)).show());\n }\n if (sAPKUtils.getVersionName(data.get(position) + \"/base.apk\", holder.mAppName.getContext()) != null) {\n holder.mVersion.setText(holder.mVersion.getContext().getString(R.string.version, sAPKUtils.getVersionName(data.get(position) + \"/base.apk\", holder.mAppName.getContext())));\n }\n holder.mCard.setOnClickListener(v -> {\n if (APKEditorUtils.isFullVersion(v.getContext())) {\n if (data.get(position).contains(\"_aee-signed\") && !sCommonUtils.getBoolean(\"signature_warning\", false, v.getContext())) {\n new SignatureMismatchDialog(v.getContext()).show();\n } else {\n new MaterialAlertDialogBuilder(v.getContext())\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.app_name)\n .setMessage(v.getContext().getString(R.string.install_question, new File(data.get(position)).getName()))\n .setNegativeButton(R.string.cancel, (dialog, id) -> {\n })\n .setPositiveButton(R.string.install, (dialog, id) -> SplitAPKInstaller.installSplitAPKs(false, null,\n data.get(position) + \"/base.apk\", (Activity) v.getContext())\n ).show();\n }\n } else {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n new BundleOptionsMenu(data.get(position), v);\n } else {\n new ShareBundleDialog(data.get(position), holder.mCard.getContext()).show();\n }\n }\n });\n holder.mCard.setOnLongClickListener(v -> {\n if (APKEditorUtils.isFullVersion(v.getContext())) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n new BundleOptionsMenu(data.get(position), v);\n } else {\n new ShareBundleDialog(data.get(position), holder.mCard.getContext()).show();\n }\n }\n return false;\n });\n } else {\n if (sAPKUtils.getAPKIcon(data.get(position), holder.mAppName.getContext()) != null) {\n holder.mAppIcon.setImageDrawable(sAPKUtils.getAPKIcon(data.get(position), holder.mAppName.getContext()));\n } else {\n holder.mAppIcon.setImageDrawable(ContextCompat.getDrawable(holder.mAppIcon.getContext(), R.drawable.ic_android));\n holder.mAppIcon.setColorFilter(APKEditorUtils.getThemeAccentColor(holder.mAppIcon.getContext()));\n }\n if (sAPKUtils.getAPKName(data.get(position), holder.mAppName.getContext()) != null) {\n if (Common.getSearchWord() != null && Common.isTextMatched(Objects.requireNonNull(sAPKUtils.getAPKName(data.get(position), holder.mAppName.getContext())).toString(), Common.getSearchWord())) {\n holder.mAppName.setText(APKEditorUtils.fromHtml(Objects.requireNonNull(sAPKUtils.getAPKName(data.get(position), holder.mAppName.getContext())).toString().replace(Common.getSearchWord(),\n \"\" + Common.getSearchWord() + \"\")));\n } else {\n holder.mAppName.setText(sAPKUtils.getAPKName(data.get(position), holder.mAppName.getContext()));\n }\n } else {\n if (Common.getSearchWord() != null && Common.isTextMatched(new File(data.get(position)).getName(), Common.getSearchWord())) {\n holder.mAppName.setText(APKEditorUtils.fromHtml(new File(data.get(position)).getName().replace(Common.getSearchWord(),\n \"\" + Common.getSearchWord() + \"\")));\n } else {\n holder.mAppName.setText(new File(data.get(position)).getName());\n }\n holder.mAppName.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);\n holder.mCard.setOnClickListener(v -> sCommonUtils.snackBar(v, v.getContext().getString(R.string.apk_corrupted)).show());\n }\n if (sAPKUtils.getVersionName(data.get(position), holder.mAppName.getContext()) != null) {\n holder.mVersion.setText(holder.mVersion.getContext().getString(R.string.version, sAPKUtils.getVersionName(data.get(position), holder.mAppName.getContext())));\n }\n holder.mSize.setText(holder.mSize.getContext().getString(R.string.size, sAPKUtils.getAPKSize(new File(data.get(position)).length())));\n holder.mSize.setTextColor(sThemeUtils.isDarkTheme(holder.mSize.getContext()) ? Color.GREEN : Color.BLACK);\n holder.mSize.setVisibility(View.VISIBLE);\n holder.mCard.setOnClickListener(v -> {\n if (APKEditorUtils.isFullVersion(v.getContext())) {\n if (data.get(position).contains(\"_aee-signed.apk\") && !sCommonUtils.getBoolean(\"signature_warning\", false, v.getContext())) {\n new SignatureMismatchDialog(v.getContext()).show();\n } else {\n new MaterialAlertDialogBuilder(v.getContext())\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.app_name)\n .setMessage(v.getContext().getString(R.string.install_question, new File(data.get(position)).getName()))\n .setNegativeButton(R.string.cancel, (dialog, id) -> {\n })\n .setPositiveButton(R.string.install, (dialog, id) -> SplitAPKInstaller.installAPK(false, new File(data.get(position)), (Activity) v.getContext())).show();\n }\n } else {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n new APKOptionsMenu(new File(data.get(position)), v);\n } else {\n APKData.shareFile(new File(data.get(position)), \"application/java-archive\", v.getContext());\n }\n }\n });\n holder.mCard.setOnLongClickListener(v -> {\n if (APKEditorUtils.isFullVersion(v.getContext())) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n new APKOptionsMenu(new File(data.get(position)), v);\n } else {\n APKData.shareFile(new File(data.get(position)), \"application/java-archive\", v.getContext());\n }\n }\n return false;\n });\n }\n holder.mCard.setCardBackgroundColor(sThemeUtils.isDarkTheme(holder.mCard.getContext()) ? Color.DKGRAY : Color.LTGRAY);\n holder.mCard.setStrokeColor(sThemeUtils.isDarkTheme(holder.mCard.getContext()) ? Color.DKGRAY : Color.LTGRAY);\n holder.mVersion.setVisibility(View.VISIBLE);\n } catch (NullPointerException ignored) {\n }\n holder.mDelete.setOnClickListener(v -> new MaterialAlertDialogBuilder(v.getContext())\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.app_name)\n .setMessage(v.getContext().getString(R.string.delete_question, new File(data.get(position)).getName()))\n .setNegativeButton(R.string.cancel, (dialog, id) -> {\n })\n .setPositiveButton(R.string.delete, (dialog, id) -> {\n sFileUtils.delete(new File(data.get(position)));\n data.remove(position);\n notifyItemRemoved(position);\n notifyDataSetChanged();\n }).show());\n holder.mDelete.setColorFilter(Color.RED);\n }\n\n @Override\n public int getItemCount() {\n return data.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n private final AppCompatImageButton mAppIcon, mDelete;\n private final MaterialCardView mCard;\n private final MaterialTextView mAppName, mSize, mVersion;\n\n public ViewHolder(View view) {\n super(view);\n this.mCard = view.findViewById(R.id.card);\n this.mAppIcon = view.findViewById(R.id.icon);\n this.mDelete = view.findViewById(R.id.delete);\n this.mAppName = view.findViewById(R.id.title);\n this.mSize = view.findViewById(R.id.size);\n this.mVersion = view.findViewById(R.id.version);\n }\n }\n\n}\n\napp/src/main/java/com/threethan/questpatcher/activities/InstallerFilePickerActivity.java\npublic class InstallerFilePickerActivity extends AppCompatActivity {\n\n private LinearLayoutCompat mProgressLayout;\n private InstallerFilePickerAdapter mRecycleViewAdapter;\n private MaterialTextView mTitle;\n private RecyclerView mRecyclerView;\n public static final String TITLE_INTENT = \"title\";\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_installerfilepicker);\n\n AppCompatImageButton mBack = findViewById(R.id.back);\n mTitle = findViewById(R.id.title);\n AppCompatImageButton mSortButton = findViewById(R.id.sort);\n Common.initializeView(findViewById(android.R.id.content), R.id.select);\n mProgressLayout = findViewById(R.id.progress_layout);\n mRecyclerView = findViewById(R.id.recycler_view);\n\n mBack.setOnClickListener(v -> super.onBackPressed());\n\n if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,this)) {\n LinearLayoutCompat mPermissionLayout = findViewById(R.id.permission_layout);\n View mPermissionGrant = findViewById(R.id.grant_card);\n mPermissionLayout.setVisibility(View.VISIBLE);\n mRecyclerView.setVisibility(View.GONE);\n mPermissionGrant.setOnClickListener(v -> sPermissionUtils.requestPermission(\n new String[] {\n android.Manifest.permission.WRITE_EXTERNAL_STORAGE\n },this));\n return;\n }\n\n mRecyclerView.setLayoutManager(new GridLayoutManager(this, APKExplorer.getSpanCount(this)));\n mRecycleViewAdapter = new InstallerFilePickerAdapter(APKExplorer.getData(getFilesList(), false, this));\n mRecyclerView.setAdapter(mRecycleViewAdapter);\n\n if (getIntent().getStringExtra(TITLE_INTENT) != null) {\n mTitle.setText(getIntent().getStringExtra(TITLE_INTENT));\n } else {\n mTitle.setText(Common.getPath().equals(Environment.getExternalStorageDirectory().toString() + File.separator) ? getString(R.string.sdcard) : new File(Common.getPath()).getName());\n }\n\n mRecycleViewAdapter.setOnItemClickListener((position, v) -> {\n if (new File(APKExplorer.getData(getFilesList(), false, this).get(position)).isDirectory()) {\n Common.setPath(APKExplorer.getData(getFilesList(), false, this).get(position));\n reload(this);\n } else if (APKExplorer.getData(getFilesList(), false, this).get(position).endsWith(\".apks\") || APKExplorer.getData(getFilesList(), false,\n this).get(position).endsWith(\".apkm\") || APKExplorer.getData(getFilesList(), false, this).get(position).endsWith(\".xapk\")) {\n new MaterialAlertDialogBuilder(this)\n .setMessage(getString(R.string.bundle_install_question, new File(APKExplorer.getData(getFilesList(), false, this).get(position)).getName()))\n .setNegativeButton(getString(R.string.cancel), (dialogInterface, i) -> {\n })\n .setPositiveButton(getString(R.string.install), (dialogInterface, i) -> SplitAPKInstaller.handleAppBundle(true, APKExplorer.getData(\n getFilesList(), false, this).get(position), this)).show();\n } else if (APKExplorer.getData(getFilesList(), false, this).get(position).endsWith(\".apk\")) {\n if (Common.getAPKList().contains(APKExplorer.getData(getFilesList(), false, this).get(position))) {\n Common.getAPKList().remove(APKExplorer.getData(getFilesList(), false, this).get(position));\n } else {\n Common.getAPKList().add(APKExplorer.getData(getFilesList(), false, this).get(position));\n }\n mRecycleViewAdapter.notifyItemChanged(position);\n Common.getSelectCard().setVisibility(Common.getAPKList().isEmpty() ? View.GONE : View.VISIBLE);\n } else {\n sCommonUtils.snackBar(findViewById(android.R.id.content), getString(R.string.wrong_extension, \".apks/.apkm/.xapk\")).show();\n }\n });\n\n Common.getSelectCard().setOnClickListener(v -> {\n if (APKData.findPackageName(this) != null) {\n if (Common.getAPKList().size() > 1) {\n APKExplorer.handleAPKs(true, this);\n } else {\n Intent intent = new Intent(this, APKInstallerActivity.class);\n intent.putExtra(\"apkFilePath\", Common.getAPKList().get(0));\n startActivity(intent);\n finish();\n }\n } else {\n sCommonUtils.snackBar(findViewById(android.R.id.content), getString(R.string.installation_status_bad_apks)).show();\n }\n });\n\n mSortButton.setOnClickListener(v -> {\n PopupMenu popupMenu = new PopupMenu(this, mSortButton);\n Menu menu = popupMenu.getMenu();\n menu.add(Menu.NONE, 0, Menu.NONE, getString(R.string.sort_order)).setCheckable(true)\n .setChecked(sCommonUtils.getBoolean(\"az_order\", true, this));\n popupMenu.setOnMenuItemClickListener(item -> {\n if (item.getItemId() == 0) {\n sCommonUtils.saveBoolean(\"az_order\", !sCommonUtils.getBoolean(\"az_order\", true, this), this);\n reload(this);\n }\n return false;\n });\n popupMenu.show();\n });\n }\n\n private File[] getFilesList() {\n if (!Common.getPath().endsWith(File.separator)) {\n Common.setPath(Common.getPath() + File.separator);\n }\n return new File(Common.getPath()).listFiles();\n }\n\n private void reload(Activity activity) {\n new sExecutor() {\n\n @Override\n public void onPreExecute() {\n APKExplorer.getData(getFilesList(), false, activity).clear();\n mProgressLayout.setVisibility(View.VISIBLE);\n mRecyclerView.setVisibility(View.GONE);\n }\n\n @Override\n public void doInBackground() {\n mRecycleViewAdapter = new InstallerFilePickerAdapter(APKExplorer.getData(getFilesList(), false, activity));\n }\n\n @Override\n public void onPostExecute() {\n mRecyclerView.setAdapter(mRecycleViewAdapter);\n if (getIntent().getStringExtra(TITLE_INTENT) != null) {\n mTitle.setText(getIntent().getStringExtra(TITLE_INTENT));\n } else {\n mTitle.setText(Common.getPath().equals(Environment.getExternalStorageDirectory().toString() + File.separator) ? getString(R.string.sdcard)\n : new File(Common.getPath()).getName());\n }\n if (Common.getAPKList().isEmpty()) {\n Common.getSelectCard().setVisibility(View.GONE);\n } else {\n Common.getSelectCard().setVisibility(View.VISIBLE);\n }\n mRecyclerView.setVisibility(View.VISIBLE);\n mProgressLayout.setVisibility(View.GONE);\n }\n }.execute();\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,\n @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n if (requestCode == 1 && Build.VERSION.SDK_INT < 30 && grantResults.length > 0\n && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n this.recreate();\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n if (Common.isFinished()) {\n Common.setFinishStatus(false);\n finish();\n }\n }\n\n @Override\n public void onBackPressed() {\n if (Common.getPath().equals(getCacheDir().getPath() + \"/splits/\")) {\n new MaterialAlertDialogBuilder(this)\n .setMessage(getString(R.string.installation_cancel_message))\n .setNegativeButton(getString(R.string.cancel), (dialogInterface, i) -> {\n })\n .setPositiveButton(getString(R.string.yes), (dialogInterface, i) -> finish()).show();\n } else if (Common.getPath().equals(Environment.getExternalStorageDirectory().toString() + File.separator)) {\n super.onBackPressed();\n } else {\n Common.setPath(Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath());\n Common.getAPKList().clear();\n reload(this);\n }\n }\n\n}\n\napp/src/main/java/com/threethan/questpatcher/utils/APKData.java\npublic class APKData {\n\n public static List getData(Context context) {\n List mData = new ArrayList<>();\n for (File mFile : getAPKList(context)) {\n if (sCommonUtils.getString(\"apkTypes\", \"apks\", context).equals(\"bundles\")) {\n if (mFile.exists() && mFile.isDirectory() && sFileUtils.exist(new File(mFile.toString(), \"base.apk\"))) {\n if (Common.getSearchWord() == null) {\n mData.add(mFile.getAbsolutePath());\n } else if (Common.isTextMatched(mFile.getAbsolutePath(), Common.getSearchWord())) {\n mData.add(mFile.getAbsolutePath());\n }\n }\n } else {\n if (mFile.exists() && mFile.getName().endsWith(\".apk\")) {\n if (Common.getSearchWord() == null) {\n mData.add(mFile.getAbsolutePath());\n } else if (sAPKUtils.getAPKName(mFile.getAbsolutePath(), context) != null && Common.isTextMatched(Objects.requireNonNull(sAPKUtils.getAPKName(\n mFile.getAbsolutePath(), context)).toString(), Common.getSearchWord())) {\n mData.add(mFile.getAbsolutePath());\n } else if (Common.isTextMatched(mFile.getName(), Common.getSearchWord())) {\n mData.add(mFile.getAbsolutePath());\n }\n }\n }\n }\n Collections.sort(mData);\n if (!sCommonUtils.getBoolean(\"az_order\", true, context)) {\n Collections.reverse(mData);\n }\n return mData;\n }\n\n private static File[] getAPKList(Context context) {\n if (!getExportAPKsPath(context).exists()) {\n sFileUtils.mkdir(getExportAPKsPath(context));\n }\n return getExportAPKsPath(context).listFiles();\n }\n\n public static File getExportAPKsPath(Context context) {\n if (Build.VERSION.SDK_INT < 29 && sCommonUtils.getString(\"exportAPKsPath\", \"externalFiles\", context).equals(\"internalStorage\")) {\n return new File(Environment.getExternalStorageDirectory(), \"/AEE/exportedAPKs\");\n } else {\n return context.getExternalFilesDir(\"\");\n }\n }\n\n public static void signApks(File apk, File signedAPK, Context context) {\n try {\n checkAndPrepareSigningEnvironment(context);\n\n APKSigner apkSigner = new APKSigner(context);\n apkSigner.sign(apk, signedAPK);\n } catch (Exception ignored) {}\n }\n\n private static void checkAndPrepareSigningEnvironment(Context context) {\n File privateKey = new File(getSigningEnvironmentDir(context), \"APKEditor.pk8\");\n\n if (privateKey.exists()) {\n return;\n }\n\n sFileUtils.mkdir(getSigningEnvironmentDir(context));\n\n sFileUtils.copyAssetFile(\"APKEditor.pk8\", privateKey, context);\n }\n\n private static File getSigningEnvironmentDir(Context context) {\n return new File(context.getFilesDir(), \"signing\");\n }\n\n private static String getParentFile(String path) {\n return Objects.requireNonNull(new File(path).getParentFile()).toString();\n }\n\n public static String findPackageName(Context context) {\n String name = null;\n for (String mAPKs : Common.getAPKList()) {\n if (sAPKUtils.getPackageName(mAPKs, context) != null) {\n name = Objects.requireNonNull(sAPKUtils.getPackageName(mAPKs, context));\n }\n }\n return name;\n }\n\n public static List splitApks(String path) {\n List list = new ArrayList<>();\n if (new File(path).getName().equals(\"base.apk\") && new File(path).exists()) {\n for (File mFile : Objects.requireNonNull(new File(getParentFile(path)).listFiles())) {\n if (mFile.getName().endsWith(\".apk\")) {\n list.add(mFile.getAbsolutePath());\n }\n }\n }\n return list;\n }\n\n public static boolean isAppBundle(String path) {\n return splitApks(path).size() > 1;\n }\n\n private static boolean fileToExclude(File file) {\n return file.isDirectory() && file.getName().equals(\".aeeBackup\") || file.isDirectory() && file.getName().equals(\".aeeBuild\")\n || file.isDirectory() && file.getName().equals(\"META-INF\") || file.isDirectory() && file.getName().startsWith(\"classes\")\n && file.getName().endsWith(\".dex\");\n }\n\n public static void shareFile(File file, String type, Context context) {\n Uri uriFile = FileProvider.getUriForFile(context,\n BuildConfig.APPLICATION_ID + \".provider\", file);\n Intent share = new Intent(Intent.ACTION_SEND);\n share.setType(type);\n share.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.share_summary, BuildConfig.VERSION_NAME));\n share.putExtra(Intent.EXTRA_STREAM, uriFile);\n share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n context.startActivity(Intent.createChooser(share, context.getString(R.string.share_with)));\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n public static void prepareSource(File buildDir, File exportPath, File backupPath, Context context) {\n if (!Common.isCancelled()) {\n for (File file : Objects.requireNonNull(exportPath.listFiles())) {\n if (file.isDirectory() && file.getName().startsWith(\"classes\") && file.getName().endsWith(\".dex\")) {\n // Build new dex file if the smali files are modified\n if (APKExplorer.isSmaliEdited(new File(context.getCacheDir(), Common.getAppID() + \"/.aeeBackup/appData\").getAbsolutePath())) {\n Common.setStatus(context.getString(R.string.building, file.getName()));\n new SmaliToDex(file, new File(buildDir, file.getName()), 0, context).execute();\n } else {\n // Otherwise, use the original one from the backup folder\n if (sFileUtils.exist(new File(backupPath, file.getName()))) {\n sFileUtils.copy(new File(backupPath, file.getName()), new File(buildDir, file.getName()));\n }\n }\n } else if (file.isDirectory() && file.getName().equals(\"META-INF\")) {\n if (new File(file, \"services\").exists()) {\n sFileUtils.copyDir(new File(file, \"services\"), new File(buildDir, \"META-INF/services\"));\n }\n } else {\n if (!fileToExclude(file)) {\n if (file.isDirectory()) {\n sFileUtils.copyDir(file, new File(buildDir, file.getName()));\n } else {\n sFileUtils.copy(file, new File(buildDir, file.getName()));\n }\n }\n }\n }\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.Q)\n public static void saveToDownload(File file, String name, Context context) {\n try {\n FileInputStream inputStream = new FileInputStream(file);\n ContentValues values = new ContentValues();\n values.put(MediaStore.MediaColumns.DISPLAY_NAME, name);\n values.put(MediaStore.MediaColumns.MIME_TYPE, \"*/*\");\n values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);\n Uri uri = context.getContentResolver().insert(MediaStore.Files.getContentUri(\"external\"), values);\n OutputStream outputStream = context.getContentResolver().openOutputStream(uri);\n sFileUtils.copyStream(inputStream, outputStream);\n } catch (IOException ignored) {\n }\n }\n\n}", "answers": [" mSortButton.setOnClickListener(v -> {"], "length": 3943, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "da76a051-ee61-4409-88a1-1a53fa04929f", "reasoning": "The provided snippet ends with the closing of the mSearchButton click listener. In the APKsFragment, the next UI element to be configured is the sort button, which follows the same pattern of setting an OnClickListener. Therefore the next line of code is the start of that listener.", "reasoning_model_answer": "mSortButton.setOnClickListener(v -> {", "assistant_with_reasoning": "\nThe provided snippet ends with the closing of the mSearchButton click listener. In the APKsFragment, the next UI element to be configured is the sort button, which follows the same pattern of setting an OnClickListener. Therefore the next line of code is the start of that listener.\n\nmSortButton.setOnClickListener(v -> {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.051, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37869, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "mSortButton.setOnClickListener(v -> {", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "import emu.lunarcore.game.battle.Battle;\nimport emu.lunarcore.proto.PVEBattleResultCsReqOuterClass.PVEBattleResultCsReq;\nimport emu.lunarcore.server.game.GameSession;\nimport emu.lunarcore.server.packet.CmdId;\nimport emu.lunarcore.server.packet.Opcodes;\nimport emu.lunarcore.server.packet.PacketHandler;\nimport emu.lunarcore.server.packet.send.PacketPVEBattleResultScRsp;", "context": "src/main/java/emu/lunarcore/server/packet/recv/HandlerPVEBattleResultCsReq.java\npackage emu.lunarcore.server.packet.recv;\n\n\n@Opcodes(CmdId.PVEBattleResultCsReq)\npublic class HandlerPVEBattleResultCsReq extends PacketHandler {\n\n @Override\n public void handle(GameSession session, byte[] data) throws Exception {\n var req = PVEBattleResultCsReq.parseFrom(data);\n\n Battle battle = session.getServer().getBattleService().finishBattle(\n session.getPlayer(),\n req.getEndStatus(),\n req.getStt()\n );\n\n if (battle != null) {\n\nsrc/main/java/emu/lunarcore/game/battle/Battle.java\n@Getter\npublic class Battle {\n private final int id;\n private final Player player;\n private final PlayerLineup lineup;\n private final List npcMonsters;\n private final List buffs;\n private final List waves;\n private final List drops;\n private final long timestamp;\n \n private StageExcel stage; // Main battle stage\n private IntList battleEvents; // TODO maybe turn it into a map?\n private Int2ObjectMap battleTargets; // TODO use custom battle target object as value type in case we need to save battles to the db\n \n // Internal battle data\n @Setter private BattleEndStatus result;\n @Setter private int staminaCost;\n @Setter private int roundsLimit;\n \n // Used for calculating cocoon/farm element drops\n @Setter private int mappingInfoId;\n @Setter private int worldLevel;\n @Setter private int cocoonWave;\n \n // OnFinish Callback\n @Setter private Consumer onFinish;\n \n private Battle(Player player, PlayerLineup lineup) {\n this.id = player.getNextBattleId();\n this.player = player;\n this.lineup = lineup;\n this.npcMonsters = new ArrayList<>();\n this.buffs = new ArrayList<>();\n this.waves = new ArrayList<>();\n this.drops = new ArrayList<>();\n this.timestamp = System.currentTimeMillis();\n }\n \n public Battle(Player player, PlayerLineup lineup, StageExcel stage) {\n this(player, lineup, stage, true);\n }\n \n public Battle(Player player, PlayerLineup lineup, StageExcel stage, boolean loadStage) {\n this(player, lineup);\n this.stage = stage;\n \n if (loadStage) {\n this.loadStage(stage); \n }\n }\n \n public Battle(Player player, PlayerLineup lineup, List stages) {\n this(player, lineup);\n this.stage = stages.get(0);\n \n for (StageExcel stage : stages) {\n this.loadStage(stage);\n }\n }\n \n public Battle(Player player, PlayerLineup lineup, Collection npcMonsters) {\n this(player, lineup);\n \n // Parse npc monster\n for (EntityMonster npcMonster : npcMonsters) {\n // Add monster\n this.npcMonsters.add(npcMonster);\n\n // Check farm element\n if (npcMonster.getFarmElementId() != 0) {\n this.setMappingInfoId(npcMonster.getFarmElementId());\n this.setWorldLevel(npcMonster.getWorldLevel());\n this.setStaminaCost(GameConstants.FARM_ELEMENT_STAMINA_COST);\n }\n \n // Get stage\n StageExcel stage = GameData.getStageExcelMap().get(npcMonster.getStageId());\n if (stage == null) continue;\n \n // Set main battle stage if we havent already\n if (this.stage == null) {\n this.stage = stage;\n }\n \n // Create monster waves from stage\n this.loadStage(stage, npcMonster);\n }\n }\n \n private void loadStage(StageExcel stage) {\n this.loadStage(stage, null);\n }\n \n private void loadStage(StageExcel stage, EntityMonster npcMonster) {\n // Build monster waves\n for (IntList stageMonsterWave : stage.getMonsterWaves()) {\n // Create battle wave\n var wave = new BattleMonsterWave(stage);\n wave.getMonsters().addAll(stageMonsterWave);\n \n // Handle npc monster\n if (npcMonster != null) {\n // Set wave custom level\n wave.setCustomLevel(npcMonster.getCustomLevel());\n \n // Handle monster buffs\n npcMonster.applyBuffs(this, this.getWaves().size());\n }\n \n // Finally add wave to battle\n this.getWaves().add(wave);\n }\n }\n \n public IntList getBattleEvents() {\n if (this.battleEvents == null) {\n this.battleEvents = new IntArrayList();\n }\n return this.battleEvents;\n }\n \n public Int2ObjectMap getBattleTargets() {\n if (this.battleTargets == null) {\n this.battleTargets = new Int2ObjectOpenHashMap<>();\n }\n return this.battleTargets;\n }\n \n public void addBattleTarget(int key, int targetId, int progress) {\n var list = getBattleTargets().computeIfAbsent(key, i -> BattleTargetList.newInstance());\n var battleTarget = BattleTarget.newInstance()\n .setId(targetId)\n .setProgress(progress);\n \n list.addBattleTargetList(battleTarget);\n }\n \n public void setCustomLevel(int level) {\n for (var wave : this.getWaves()) {\n wave.setCustomLevel(level);\n }\n }\n \n // Battle buffs\n \n public MazeBuff addBuff(int buffId) {\n return addBuff(buffId, -1, 0xffffffff);\n }\n \n public MazeBuff addBuff(int buffId, int ownerIndex) {\n return addBuff(buffId, ownerIndex, 0xffffffff);\n }\n \n public MazeBuff addBuff(int buffId, int ownerIndex, int waveFlag) {\n MazeBuff buff = new MazeBuff(buffId, 1, ownerIndex, waveFlag);\n return addBuff(buff);\n }\n \n public MazeBuff addBuff(MazeBuff buff) {\n this.buffs.add(buff);\n return buff;\n }\n \n public boolean hasBuff(int buffId) {\n return this.buffs.stream().filter(buff -> buff.getId() == buffId).findFirst().isPresent();\n }\n \n public void clearBuffs() {\n this.buffs.clear();\n }\n \n // Serialization\n \n public SceneBattleInfo toProto() {\n // Build battle info\n var proto = SceneBattleInfo.newInstance()\n .setBattleId(this.getId())\n .setStageId(this.getStage().getId())\n .setRoundsLimit(this.getRoundsLimit())\n .setLogicRandomSeed(Utils.randomRange(1, Short.MAX_VALUE))\n .setWorldLevel(player.getWorldLevel());\n\n // Add monster waves\n for (var wave : this.getWaves()) {\n proto.addMonsterWaveList(wave.toProto());\n }\n \n // Avatars\n for (int i = 0; i < lineup.getAvatars().size(); i++) {\n GameAvatar avatar = getPlayer().getAvatarById(lineup.getAvatars().get(i));\n if (avatar == null) continue;\n \n // Add to proto\n proto.addBattleAvatarList(avatar.toBattleProto(lineup, i));\n \n // Add buffs from avatars\n if (avatar.getBuffs().size() > 0) {\n for (var buffEntry : avatar.getBuffs().int2LongEntrySet()) {\n // Check expiry for buff\n if (buffEntry.getLongValue() < this.timestamp) {\n continue;\n }\n \n MazeBuff buff = this.addBuff(buffEntry.getIntKey(), i);\n if (buff != null) {\n buff.addTargetIndex(i);\n }\n }\n }\n }\n \n // Apply food buffs to battle\n if (player.getFoodBuffs().size() > 0) {\n for (var buff : player.getFoodBuffs().values()) {\n this.addBuff(buff.getBuffId(), -1);\n }\n }\n \n // Buffs\n for (MazeBuff buff : this.getBuffs()) {\n proto.addBuffList(buff.toProto());\n }\n \n // Client turn snapshots\n if (this.battleEvents != null) {\n for (int id : this.battleEvents) {\n var event = BattleEventBattleInfo.newInstance()\n .setBattleEventId(id);\n \n // Temp solution\n event.getMutableStatus().getMutableSpBar()\n .setCurSp(10000)\n .setMaxSp(10000);\n \n proto.addEventBattleInfoList(event);\n }\n }\n \n // Battle target map\n if (this.battleTargets != null) {\n // Build battle target map\n for (int i = 1; i <= 5; i++) {\n var battleTargetList = this.battleTargets.get(i);\n var battleTargetEntry = BattleTargetInfoEntry.newInstance().setKey(i);\n \n if (battleTargetList == null) {\n battleTargetEntry.getMutableValue();\n } else {\n battleTargetEntry.setValue(battleTargetList);\n }\n \n proto.addBattleTargetInfo(battleTargetEntry);\n }\n }\n \n return proto;\n }\n}\n\nsrc/main/java/emu/lunarcore/server/game/GameSession.java\n@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\n private Player player;\n\n // Network\n @Getter(AccessLevel.PRIVATE) private Ukcp ukcp;\n \n // Flags\n private SessionState state = SessionState.WAITING_FOR_TOKEN;\n private boolean useSecretKey;\n\n private GameSession(GameServer server) {\n this.server = server;\n this.packetCooldown = new Int2LongOpenHashMap();\n }\n\n public GameSession(GameServer server, Ukcp ukcp) {\n this(server);\n this.ukcp = ukcp;\n this.address = this.ukcp.user().getRemoteAddress();\n }\n\n public int getUid() {\n return this.player.getUid();\n }\n\n public boolean useSecretKey() {\n return useSecretKey;\n }\n\n public void setAccount(Account account) {\n this.account = account;\n }\n\n public void setPlayer(Player player) {\n this.player = player;\n this.player.setSession(this);\n this.getServer().registerPlayer(player);\n }\n\n public void setUseSecretKey(boolean key) {\n this.useSecretKey = key;\n }\n\n public void setState(SessionState state) {\n this.state = state;\n }\n\n public void onConnect() {\n if (LunarCore.getConfig().getLogOptions().connections) {\n LunarCore.getLogger().info(\"Client connected from \" + address.getHostString());\n }\n }\n\n public void onDisconnect() {\n if (LunarCore.getConfig().getLogOptions().connections) {\n LunarCore.getLogger().info(\"Client disconnected from \" + address.getHostString());\n }\n\n this.state = SessionState.INACTIVE;\n\n if (player != null) {\n // Handle player logout event\n player.onLogout();\n \n // Save first\n player.save();\n \n // Deregister player from server\n this.getServer().deregisterPlayer(player);\n }\n }\n\n public void onMessage(ByteBuf packet) {\n try {\n // Decrypt and turn back into a packet\n // Crypto.xor(packet.array(), useSecretKey() ? Crypto.ENCRYPT_KEY : Crypto.DISPATCH_KEY);\n\n // Decode\n while (packet.readableBytes() > 0) {\n // Length\n if (packet.readableBytes() < 16) {\n return;\n }\n\n // Packet header sanity check\n int constHeader = packet.readInt();\n if (constHeader != BasePacket.HEADER_CONST) {\n return; // Bad packet\n }\n\n // Data\n int opcode = packet.readShort();\n int headerLength = packet.readShort();\n int dataLength = packet.readInt();\n \n byte[] data = new byte[dataLength];\n\n packet.skipBytes(headerLength);\n packet.readBytes(data);\n\n // Packet tail sanity check\n int constTail = packet.readInt();\n if (constTail != BasePacket.TAIL_CONST) {\n return; // Bad packet\n }\n\n // Log packet\n if (LunarCore.getConfig().getLogOptions().packets) {\n if (!(LunarCore.getConfig().getLogOptions().filterLoopingPackets && CmdIdUtils.IGNORED_LOG_PACKETS.contains(opcode))) {\n logPacket(\"RECV\", opcode, data);\n }\n }\n\n // Handle\n getServer().getPacketHandler().handle(this, opcode, data);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n // packet.release();\n }\n }\n\n public void send(BasePacket packet) {\n // Test\n if (packet.getCmdId() <= 0) {\n LunarCore.getLogger().warn(\"Tried to send packet with missing cmd id!\");\n return;\n }\n\n // Send\n this.send(packet.build());\n\n // Log\n if (LunarCore.getConfig().getLogOptions().packets) {\n if (!(LunarCore.getConfig().getLogOptions().filterLoopingPackets && CmdIdUtils.IGNORED_LOG_PACKETS.contains(packet.getCmdId()))) {\n logPacket(\"SEND\", packet.getCmdId(), packet.getData());\n }\n }\n }\n \n /**\n * Sends a cached packet with the specified cmd id. If the packet isnt cacheable, then an empty packet is sent.\n * @param cmdId\n */\n public void send(int cmdId) {\n // Get packet from the server's packet cache. This will allow us to reuse empty packets if needed.\n if (this.ukcp != null) {\n this.ukcp.write(getServer().getPacketCache().getCachedPacket(cmdId));\n }\n \n // Log\n if (LunarCore.getConfig().getLogOptions().packets) {\n if (!(LunarCore.getConfig().getLogOptions().filterLoopingPackets && CmdIdUtils.IGNORED_LOG_PACKETS.contains(cmdId))) {\n logPacket(\"SEND\", cmdId, Utils.EMPTY_BYTE_ARRAY);\n }\n }\n }\n\n public void send(byte[] bytes) {\n if (this.ukcp != null) {\n ByteBuf buf = Unpooled.wrappedBuffer(bytes);\n this.ukcp.write(buf);\n buf.release();\n }\n }\n \n public void logPacket(String sendOrRecv, int opcode, ProtoMessage payload) {\n logPacket(sendOrRecv, opcode, payload != null ? payload.toByteArray() : Utils.EMPTY_BYTE_ARRAY);\n }\n\n public void logPacket(String sendOrRecv, int opcode, byte[] payload) {\n LunarCore.getLogger().info(sendOrRecv + \": \" + CmdIdUtils.getCmdIdName(opcode) + \" (\" + opcode + \")\" + System.lineSeparator() + Utils.bytesToHex(payload));\n }\n\n public void close() {\n if (this.ukcp != null) {\n this.ukcp.close();\n }\n }\n}\n\nsrc/main/java/emu/lunarcore/server/packet/PacketHandler.java\npublic abstract class PacketHandler {\n public abstract void handle(GameSession session, byte[] data) throws Exception;\n}\n\nsrc/main/java/emu/lunarcore/server/packet/send/PacketPVEBattleResultScRsp.java\npublic class PacketPVEBattleResultScRsp extends BasePacket {\n \n public PacketPVEBattleResultScRsp() {\n super(CmdId.PVEBattleResultScRsp);\n\n var data = PVEBattleResultScRsp.newInstance()\n .setRetcode(1);\n\n this.setData(data);\n }\n\n public PacketPVEBattleResultScRsp(PVEBattleResultCsReq req, Battle battle) {\n super(CmdId.PVEBattleResultScRsp);\n \n // Item drop list data\n ItemList dropData = ItemList.newInstance();\n \n for (GameItem drop : battle.getDrops()) {\n dropData.addItemList(drop.toProto());\n }\n\n // Battle result\n var data = PVEBattleResultScRsp.newInstance()\n .setDropData(dropData)\n .setResVersion(Integer.toString(req.getClientResVersion()))\n .setBinVersion(\"\")\n .setBattleId(req.getBattleId())\n .setStageId(req.getStageId())\n .setEndStatus(req.getEndStatus())\n .setCheckIdentical(true);\n\n // Set these\n data.getMutableUnk1();\n data.getMutableUnk2();\n data.getMutableUnk3();\n \n this.setData(data);\n }\n}\n\nsrc/generated/main/emu/lunarcore/proto/PVEBattleResultCsReqOuterClass.java\npublic static final class PVEBattleResultCsReq extends ProtoMessage implements Cloneable {\n private static final long serialVersionUID = 0L;\n\n /**\n * optional uint32 stage_id = 2;\n */\n private int stageId;\n\n /**\n * optional uint32 battle_id = 10;\n */\n private int battleId;\n\n /**\n * optional uint32 client_res_version = 12;\n */\n private int clientResVersion;\n\n /**\n * optional uint32 cost_time = 14;\n */\n private int costTime;\n\n /**\n * optional .BattleEndStatus end_status = 11;\n */\n private int endStatus;\n\n /**\n * optional bool is_ai_consider_ultra_skill = 13;\n */\n private boolean isAiConsiderUltraSkill;\n\n /**\n * optional .BattleStatistics stt = 1;\n */\n private final BattleStatisticsOuterClass.BattleStatistics stt = BattleStatisticsOuterClass.BattleStatistics.newInstance();\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n */\n private final RepeatedByte turnSnapshotHash = RepeatedByte.newEmptyInstance();\n\n /**\n * repeated .BattleOp op_list = 4;\n */\n private final RepeatedMessage opList = RepeatedMessage.newEmptyInstance(BattleOpOuterClass.BattleOp.getFactory());\n\n private PVEBattleResultCsReq() {\n }\n\n /**\n * @return a new empty instance of {@code PVEBattleResultCsReq}\n */\n public static PVEBattleResultCsReq newInstance() {\n return new PVEBattleResultCsReq();\n }\n\n /**\n * optional uint32 stage_id = 2;\n * @return whether the stageId field is set\n */\n public boolean hasStageId() {\n return (bitField0_ & 0x00000001) != 0;\n }\n\n /**\n * optional uint32 stage_id = 2;\n * @return this\n */\n public PVEBattleResultCsReq clearStageId() {\n bitField0_ &= ~0x00000001;\n stageId = 0;\n return this;\n }\n\n /**\n * optional uint32 stage_id = 2;\n * @return the stageId\n */\n public int getStageId() {\n return stageId;\n }\n\n /**\n * optional uint32 stage_id = 2;\n * @param value the stageId to set\n * @return this\n */\n public PVEBattleResultCsReq setStageId(final int value) {\n bitField0_ |= 0x00000001;\n stageId = value;\n return this;\n }\n\n /**\n * optional uint32 battle_id = 10;\n * @return whether the battleId field is set\n */\n public boolean hasBattleId() {\n return (bitField0_ & 0x00000002) != 0;\n }\n\n /**\n * optional uint32 battle_id = 10;\n * @return this\n */\n public PVEBattleResultCsReq clearBattleId() {\n bitField0_ &= ~0x00000002;\n battleId = 0;\n return this;\n }\n\n /**\n * optional uint32 battle_id = 10;\n * @return the battleId\n */\n public int getBattleId() {\n return battleId;\n }\n\n /**\n * optional uint32 battle_id = 10;\n * @param value the battleId to set\n * @return this\n */\n public PVEBattleResultCsReq setBattleId(final int value) {\n bitField0_ |= 0x00000002;\n battleId = value;\n return this;\n }\n\n /**\n * optional uint32 client_res_version = 12;\n * @return whether the clientResVersion field is set\n */\n public boolean hasClientResVersion() {\n return (bitField0_ & 0x00000004) != 0;\n }\n\n /**\n * optional uint32 client_res_version = 12;\n * @return this\n */\n public PVEBattleResultCsReq clearClientResVersion() {\n bitField0_ &= ~0x00000004;\n clientResVersion = 0;\n return this;\n }\n\n /**\n * optional uint32 client_res_version = 12;\n * @return the clientResVersion\n */\n public int getClientResVersion() {\n return clientResVersion;\n }\n\n /**\n * optional uint32 client_res_version = 12;\n * @param value the clientResVersion to set\n * @return this\n */\n public PVEBattleResultCsReq setClientResVersion(final int value) {\n bitField0_ |= 0x00000004;\n clientResVersion = value;\n return this;\n }\n\n /**\n * optional uint32 cost_time = 14;\n * @return whether the costTime field is set\n */\n public boolean hasCostTime() {\n return (bitField0_ & 0x00000008) != 0;\n }\n\n /**\n * optional uint32 cost_time = 14;\n * @return this\n */\n public PVEBattleResultCsReq clearCostTime() {\n bitField0_ &= ~0x00000008;\n costTime = 0;\n return this;\n }\n\n /**\n * optional uint32 cost_time = 14;\n * @return the costTime\n */\n public int getCostTime() {\n return costTime;\n }\n\n /**\n * optional uint32 cost_time = 14;\n * @param value the costTime to set\n * @return this\n */\n public PVEBattleResultCsReq setCostTime(final int value) {\n bitField0_ |= 0x00000008;\n costTime = value;\n return this;\n }\n\n /**\n * optional .BattleEndStatus end_status = 11;\n * @return whether the endStatus field is set\n */\n public boolean hasEndStatus() {\n return (bitField0_ & 0x00000010) != 0;\n }\n\n /**\n * optional .BattleEndStatus end_status = 11;\n * @return this\n */\n public PVEBattleResultCsReq clearEndStatus() {\n bitField0_ &= ~0x00000010;\n endStatus = 0;\n return this;\n }\n\n /**\n * optional .BattleEndStatus end_status = 11;\n * @return the endStatus\n */\n public BattleEndStatusOuterClass.BattleEndStatus getEndStatus() {\n return BattleEndStatusOuterClass.BattleEndStatus.forNumber(endStatus);\n }\n\n /**\n * Gets the value of the internal enum store. The result is\n * equivalent to {@link PVEBattleResultCsReq#getEndStatus()}.getNumber().\n *\n * @return numeric wire representation\n */\n public int getEndStatusValue() {\n return endStatus;\n }\n\n /**\n * Sets the value of the internal enum store. This does not\n * do any validity checks, so be sure to use appropriate value\n * constants from {@link BattleEndStatusOuterClass.BattleEndStatus}. Setting an invalid value\n * can cause {@link PVEBattleResultCsReq#getEndStatus()} to return null\n *\n * @param value the numeric wire value to set\n * @return this\n */\n public PVEBattleResultCsReq setEndStatusValue(final int value) {\n bitField0_ |= 0x00000010;\n endStatus = value;\n return this;\n }\n\n /**\n * optional .BattleEndStatus end_status = 11;\n * @param value the endStatus to set\n * @return this\n */\n public PVEBattleResultCsReq setEndStatus(\n final BattleEndStatusOuterClass.BattleEndStatus value) {\n bitField0_ |= 0x00000010;\n endStatus = value.getNumber();\n return this;\n }\n\n /**\n * optional bool is_ai_consider_ultra_skill = 13;\n * @return whether the isAiConsiderUltraSkill field is set\n */\n public boolean hasIsAiConsiderUltraSkill() {\n return (bitField0_ & 0x00000020) != 0;\n }\n\n /**\n * optional bool is_ai_consider_ultra_skill = 13;\n * @return this\n */\n public PVEBattleResultCsReq clearIsAiConsiderUltraSkill() {\n bitField0_ &= ~0x00000020;\n isAiConsiderUltraSkill = false;\n return this;\n }\n\n /**\n * optional bool is_ai_consider_ultra_skill = 13;\n * @return the isAiConsiderUltraSkill\n */\n public boolean getIsAiConsiderUltraSkill() {\n return isAiConsiderUltraSkill;\n }\n\n /**\n * optional bool is_ai_consider_ultra_skill = 13;\n * @param value the isAiConsiderUltraSkill to set\n * @return this\n */\n public PVEBattleResultCsReq setIsAiConsiderUltraSkill(final boolean value) {\n bitField0_ |= 0x00000020;\n isAiConsiderUltraSkill = value;\n return this;\n }\n\n /**\n * optional .BattleStatistics stt = 1;\n * @return whether the stt field is set\n */\n public boolean hasStt() {\n return (bitField0_ & 0x00000040) != 0;\n }\n\n /**\n * optional .BattleStatistics stt = 1;\n * @return this\n */\n public PVEBattleResultCsReq clearStt() {\n bitField0_ &= ~0x00000040;\n stt.clear();\n return this;\n }\n\n /**\n * optional .BattleStatistics stt = 1;\n *\n * This method returns the internal storage object without modifying any has state.\n * The returned object should not be modified and be treated as read-only.\n *\n * Use {@link #getMutableStt()} if you want to modify it.\n *\n * @return internal storage object for reading\n */\n public BattleStatisticsOuterClass.BattleStatistics getStt() {\n return stt;\n }\n\n /**\n * optional .BattleStatistics stt = 1;\n *\n * This method returns the internal storage object and sets the corresponding\n * has state. The returned object will become part of this message and its\n * contents may be modified as long as the has state is not cleared.\n *\n * @return internal storage object for modifications\n */\n public BattleStatisticsOuterClass.BattleStatistics getMutableStt() {\n bitField0_ |= 0x00000040;\n return stt;\n }\n\n /**\n * optional .BattleStatistics stt = 1;\n * @param value the stt to set\n * @return this\n */\n public PVEBattleResultCsReq setStt(final BattleStatisticsOuterClass.BattleStatistics value) {\n bitField0_ |= 0x00000040;\n stt.copyFrom(value);\n return this;\n }\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n * @return whether the turnSnapshotHash field is set\n */\n public boolean hasTurnSnapshotHash() {\n return (bitField0_ & 0x00000080) != 0;\n }\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n * @return this\n */\n public PVEBattleResultCsReq clearTurnSnapshotHash() {\n bitField0_ &= ~0x00000080;\n turnSnapshotHash.clear();\n return this;\n }\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n *\n * This method returns the internal storage object without modifying any has state.\n * The returned object should not be modified and be treated as read-only.\n *\n * Use {@link #getMutableTurnSnapshotHash()} if you want to modify it.\n *\n * @return internal storage object for reading\n */\n public RepeatedByte getTurnSnapshotHash() {\n return turnSnapshotHash;\n }\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n *\n * This method returns the internal storage object and sets the corresponding\n * has state. The returned object will become part of this message and its\n * contents may be modified as long as the has state is not cleared.\n *\n * @return internal storage object for modifications\n */\n public RepeatedByte getMutableTurnSnapshotHash() {\n bitField0_ |= 0x00000080;\n return turnSnapshotHash;\n }\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n * @param value the turnSnapshotHash to add\n * @return this\n */\n public PVEBattleResultCsReq addTurnSnapshotHash(final byte value) {\n bitField0_ |= 0x00000080;\n turnSnapshotHash.add(value);\n return this;\n }\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n * @param values the turnSnapshotHash to add\n * @return this\n */\n public PVEBattleResultCsReq addAllTurnSnapshotHash(final byte... values) {\n bitField0_ |= 0x00000080;\n turnSnapshotHash.addAll(values);\n return this;\n }\n\n /**\n * optional bytes turn_snapshot_hash = 3;\n * @param values the turnSnapshotHash to set\n * @return this\n */\n public PVEBattleResultCsReq setTurnSnapshotHash(final byte... values) {\n bitField0_ |= 0x00000080;\n turnSnapshotHash.copyFrom(values);\n return this;\n }\n\n /**\n * repeated .BattleOp op_list = 4;\n * @return whether the opList field is set\n */\n public boolean hasOpList() {\n return (bitField0_ & 0x00000100) != 0;\n }\n\n /**\n * repeated .BattleOp op_list = 4;\n * @return this\n */\n public PVEBattleResultCsReq clearOpList() {\n bitField0_ &= ~0x00000100;\n opList.clear();\n return this;\n }\n\n /**\n * repeated .BattleOp op_list = 4;\n *\n * This method returns the internal storage object without modifying any has state.\n * The returned object should not be modified and be treated as read-only.\n *\n * Use {@link #getMutableOpList()} if you want to modify it.\n *\n * @return internal storage object for reading\n */\n public RepeatedMessage getOpList() {\n return opList;\n }\n\n /**\n * repeated .BattleOp op_list = 4;\n *\n * This method returns the internal storage object and sets the corresponding\n * has state. The returned object will become part of this message and its\n * contents may be modified as long as the has state is not cleared.\n *\n * @return internal storage object for modifications\n */\n public RepeatedMessage getMutableOpList() {\n bitField0_ |= 0x00000100;\n return opList;\n }\n\n /**\n * repeated .BattleOp op_list = 4;\n * @param value the opList to add\n * @return this\n */\n public PVEBattleResultCsReq addOpList(final BattleOpOuterClass.BattleOp value) {\n bitField0_ |= 0x00000100;\n opList.add(value);\n return this;\n }\n\n /**\n * repeated .BattleOp op_list = 4;\n * @param values the opList to add\n * @return this\n */\n public PVEBattleResultCsReq addAllOpList(final BattleOpOuterClass.BattleOp... values) {\n bitField0_ |= 0x00000100;\n opList.addAll(values);\n return this;\n }\n\n @Override\n public PVEBattleResultCsReq copyFrom(final PVEBattleResultCsReq other) {\n cachedSize = other.cachedSize;\n if ((bitField0_ | other.bitField0_) != 0) {\n bitField0_ = other.bitField0_;\n stageId = other.stageId;\n battleId = other.battleId;\n clientResVersion = other.clientResVersion;\n costTime = other.costTime;\n endStatus = other.endStatus;\n isAiConsiderUltraSkill = other.isAiConsiderUltraSkill;\n stt.copyFrom(other.stt);\n turnSnapshotHash.copyFrom(other.turnSnapshotHash);\n opList.copyFrom(other.opList);\n }\n return this;\n }\n\n @Override\n public PVEBattleResultCsReq mergeFrom(final PVEBattleResultCsReq other) {\n if (other.isEmpty()) {\n return this;\n }\n cachedSize = -1;\n if (other.hasStageId()) {\n setStageId(other.stageId);\n }\n if (other.hasBattleId()) {\n setBattleId(other.battleId);\n }\n if (other.hasClientResVersion()) {\n setClientResVersion(other.clientResVersion);\n }\n if (other.hasCostTime()) {\n setCostTime(other.costTime);\n }\n if (other.hasEndStatus()) {\n setEndStatusValue(other.endStatus);\n }\n if (other.hasIsAiConsiderUltraSkill()) {\n setIsAiConsiderUltraSkill(other.isAiConsiderUltraSkill);\n }\n if (other.hasStt()) {\n getMutableStt().mergeFrom(other.stt);\n }\n if (other.hasTurnSnapshotHash()) {\n getMutableTurnSnapshotHash().copyFrom(other.turnSnapshotHash);\n }\n if (other.hasOpList()) {\n getMutableOpList().addAll(other.opList);\n }\n return this;\n }\n\n @Override\n public PVEBattleResultCsReq clear() {\n if (isEmpty()) {\n return this;\n }\n cachedSize = -1;\n bitField0_ = 0;\n stageId = 0;\n battleId = 0;\n clientResVersion = 0;\n costTime = 0;\n endStatus = 0;\n isAiConsiderUltraSkill = false;\n stt.clear();\n turnSnapshotHash.clear();\n opList.clear();\n return this;\n }\n\n @Override\n public PVEBattleResultCsReq clearQuick() {\n if (isEmpty()) {\n return this;\n }\n cachedSize = -1;\n bitField0_ = 0;\n stt.clearQuick();\n turnSnapshotHash.clear();\n opList.clearQuick();\n return this;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof PVEBattleResultCsReq)) {\n return false;\n }\n PVEBattleResultCsReq other = (PVEBattleResultCsReq) o;\n return bitField0_ == other.bitField0_\n && (!hasStageId() || stageId == other.stageId)\n && (!hasBattleId() || battleId == other.battleId)\n && (!hasClientResVersion() || clientResVersion == other.clientResVersion)\n && (!hasCostTime() || costTime == other.costTime)\n && (!hasEndStatus() || endStatus == other.endStatus)\n && (!hasIsAiConsiderUltraSkill() || isAiConsiderUltraSkill == other.isAiConsiderUltraSkill)\n && (!hasStt() || stt.equals(other.stt))\n && (!hasTurnSnapshotHash() || turnSnapshotHash.equals(other.turnSnapshotHash))\n && (!hasOpList() || opList.equals(other.opList));\n }\n\n @Override\n public void writeTo(final ProtoSink output) throws IOException {\n if ((bitField0_ & 0x00000001) != 0) {\n output.writeRawByte((byte) 16);\n output.writeUInt32NoTag(stageId);\n }\n if ((bitField0_ & 0x00000002) != 0) {\n output.writeRawByte((byte) 80);\n output.writeUInt32NoTag(battleId);\n }\n if ((bitField0_ & 0x00000004) != 0) {\n output.writeRawByte((byte) 96);\n output.writeUInt32NoTag(clientResVersion);\n }\n if ((bitField0_ & 0x00000008) != 0) {\n output.writeRawByte((byte) 112);\n output.writeUInt32NoTag(costTime);\n }\n if ((bitField0_ & 0x00000010) != 0) {\n output.writeRawByte((byte) 88);\n output.writeEnumNoTag(endStatus);\n }\n if ((bitField0_ & 0x00000020) != 0) {\n output.writeRawByte((byte) 104);\n output.writeBoolNoTag(isAiConsiderUltraSkill);\n }\n if ((bitField0_ & 0x00000040) != 0) {\n output.writeRawByte((byte) 10);\n output.writeMessageNoTag(stt);\n }\n if ((bitField0_ & 0x00000080) != 0) {\n output.writeRawByte((byte) 26);\n output.writeBytesNoTag(turnSnapshotHash);\n }\n if ((bitField0_ & 0x00000100) != 0) {\n for (int i = 0; i < opList.length(); i++) {\n output.writeRawByte((byte) 34);\n output.writeMessageNoTag(opList.get(i));\n }\n }\n }\n\n @Override\n protected int computeSerializedSize() {\n int size = 0;\n if ((bitField0_ & 0x00000001) != 0) {\n size += 1 + ProtoSink.computeUInt32SizeNoTag(stageId);\n }\n if ((bitField0_ & 0x00000002) != 0) {\n size += 1 + ProtoSink.computeUInt32SizeNoTag(battleId);\n }\n if ((bitField0_ & 0x00000004) != 0) {\n size += 1 + ProtoSink.computeUInt32SizeNoTag(clientResVersion);\n }\n if ((bitField0_ & 0x00000008) != 0) {\n size += 1 + ProtoSink.computeUInt32SizeNoTag(costTime);\n }\n if ((bitField0_ & 0x00000010) != 0) {\n size += 1 + ProtoSink.computeEnumSizeNoTag(endStatus);\n }\n if ((bitField0_ & 0x00000020) != 0) {\n size += 2;\n }\n if ((bitField0_ & 0x00000040) != 0) {\n size += 1 + ProtoSink.computeMessageSizeNoTag(stt);\n }\n if ((bitField0_ & 0x00000080) != 0) {\n size += 1 + ProtoSink.computeBytesSizeNoTag(turnSnapshotHash);\n }\n if ((bitField0_ & 0x00000100) != 0) {\n size += (1 * opList.length()) + ProtoSink.computeRepeatedMessageSizeNoTag(opList);\n }\n return size;\n }\n\n @Override\n @SuppressWarnings(\"fallthrough\")\n public PVEBattleResultCsReq mergeFrom(final ProtoSource input) throws IOException {\n // Enabled Fall-Through Optimization (QuickBuffers)\n int tag = input.readTag();\n while (true) {\n switch (tag) {\n case 16: {\n // stageId\n stageId = input.readUInt32();\n bitField0_ |= 0x00000001;\n tag = input.readTag();\n if (tag != 80) {\n break;\n }\n }\n case 80: {\n // battleId\n battleId = input.readUInt32();\n bitField0_ |= 0x00000002;\n tag = input.readTag();\n if (tag != 96) {\n break;\n }\n }\n case 96: {\n // clientResVersion\n clientResVersion = input.readUInt32();\n bitField0_ |= 0x00000004;\n tag = input.readTag();\n if (tag != 112) {\n break;\n }\n }\n case 112: {\n // costTime\n costTime = input.readUInt32();\n bitField0_ |= 0x00000008;\n tag = input.readTag();\n if (tag != 88) {\n break;\n }\n }\n case 88: {\n // endStatus\n final int value = input.readInt32();\n if (BattleEndStatusOuterClass.BattleEndStatus.forNumber(value) != null) {\n endStatus = value;\n bitField0_ |= 0x00000010;\n }\n tag = input.readTag();\n if (tag != 104) {\n break;\n }\n }\n case 104: {\n // isAiConsiderUltraSkill\n isAiConsiderUltraSkill = input.readBool();\n bitField0_ |= 0x00000020;\n tag = input.readTag();\n if (tag != 10) {\n break;\n }\n }\n case 10: {\n // stt\n input.readMessage(stt);\n bitField0_ |= 0x00000040;\n tag = input.readTag();\n if (tag != 26) {\n break;\n }\n }\n case 26: {\n // turnSnapshotHash\n input.readBytes(turnSnapshotHash);\n bitField0_ |= 0x00000080;\n tag = input.readTag();\n if (tag != 34) {\n break;\n }\n }\n case 34: {\n // opList\n tag = input.readRepeatedMessage(opList, tag);\n bitField0_ |= 0x00000100;\n if (tag != 0) {\n break;\n }\n }\n case 0: {\n return this;\n }\n default: {\n if (!input.skipField(tag)) {\n return this;\n }\n tag = input.readTag();\n break;\n }\n }\n }\n }\n\n @Override\n public void writeTo(final JsonSink output) throws IOException {\n output.beginObject();\n if ((bitField0_ & 0x00000001) != 0) {\n output.writeUInt32(FieldNames.stageId, stageId);\n }\n if ((bitField0_ & 0x00000002) != 0) {\n output.writeUInt32(FieldNames.battleId, battleId);\n }\n if ((bitField0_ & 0x00000004) != 0) {\n output.writeUInt32(FieldNames.clientResVersion, clientResVersion);\n }\n if ((bitField0_ & 0x00000008) != 0) {\n output.writeUInt32(FieldNames.costTime, costTime);\n }\n if ((bitField0_ & 0x00000010) != 0) {\n output.writeEnum(FieldNames.endStatus, endStatus, BattleEndStatusOuterClass.BattleEndStatus.converter());\n }\n if ((bitField0_ & 0x00000020) != 0) {\n output.writeBool(FieldNames.isAiConsiderUltraSkill, isAiConsiderUltraSkill);\n }\n if ((bitField0_ & 0x00000040) != 0) {\n output.writeMessage(FieldNames.stt, stt);\n }\n if ((bitField0_ & 0x00000080) != 0) {\n output.writeBytes(FieldNames.turnSnapshotHash, turnSnapshotHash);\n }\n if ((bitField0_ & 0x00000100) != 0) {\n output.writeRepeatedMessage(FieldNames.opList, opList);\n }\n output.endObject();\n }\n\n @Override\n public PVEBattleResultCsReq mergeFrom(final JsonSource input) throws IOException {\n if (!input.beginObject()) {\n return this;\n }\n while (!input.isAtEnd()) {\n switch (input.readFieldHash()) {\n case -1897528135:\n case 1306191356: {\n if (input.isAtField(FieldNames.stageId)) {\n if (!input.trySkipNullValue()) {\n stageId = input.readUInt32();\n bitField0_ |= 0x00000001;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case -1678308365:\n case -487930366: {\n if (input.isAtField(FieldNames.battleId)) {\n if (!input.trySkipNullValue()) {\n battleId = input.readUInt32();\n bitField0_ |= 0x00000002;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case -2005674429:\n case -349907515: {\n if (input.isAtField(FieldNames.clientResVersion)) {\n if (!input.trySkipNullValue()) {\n clientResVersion = input.readUInt32();\n bitField0_ |= 0x00000004;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case -424687558:\n case -269929473: {\n if (input.isAtField(FieldNames.costTime)) {\n if (!input.trySkipNullValue()) {\n costTime = input.readUInt32();\n bitField0_ |= 0x00000008;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case 1608709293:\n case 378841046: {\n if (input.isAtField(FieldNames.endStatus)) {\n if (!input.trySkipNullValue()) {\n final BattleEndStatusOuterClass.BattleEndStatus value = input.readEnum(BattleEndStatusOuterClass.BattleEndStatus.converter());\n if (value != null) {\n endStatus = value.getNumber();\n bitField0_ |= 0x00000010;\n } else {\n input.skipUnknownEnumValue();\n }\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case -792003792:\n case 524172826: {\n if (input.isAtField(FieldNames.isAiConsiderUltraSkill)) {\n if (!input.trySkipNullValue()) {\n isAiConsiderUltraSkill = input.readBool();\n bitField0_ |= 0x00000020;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case 114227: {\n if (input.isAtField(FieldNames.stt)) {\n if (!input.trySkipNullValue()) {\n input.readMessage(stt);\n bitField0_ |= 0x00000040;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case 716212751:\n case 397070951: {\n if (input.isAtField(FieldNames.turnSnapshotHash)) {\n if (!input.trySkipNullValue()) {\n input.readBytes(turnSnapshotHash);\n bitField0_ |= 0x00000080;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n case -1011328481:\n case -1268785092: {\n if (input.isAtField(FieldNames.opList)) {\n if (!input.trySkipNullValue()) {\n input.readRepeatedMessage(opList);\n bitField0_ |= 0x00000100;\n }\n } else {\n input.skipUnknownField();\n }\n break;\n }\n default: {\n input.skipUnknownField();\n break;\n }\n }\n }\n input.endObject();\n return this;\n }\n\n @Override\n public PVEBattleResultCsReq clone() {\n return new PVEBattleResultCsReq().copyFrom(this);\n }\n\n @Override\n public boolean isEmpty() {\n return ((bitField0_) == 0);\n }\n\n public static PVEBattleResultCsReq parseFrom(final byte[] data) throws\n InvalidProtocolBufferException {\n return ProtoMessage.mergeFrom(new PVEBattleResultCsReq(), data).checkInitialized();\n }\n\n public static PVEBattleResultCsReq parseFrom(final ProtoSource input) throws IOException {\n return ProtoMessage.mergeFrom(new PVEBattleResultCsReq(), input).checkInitialized();\n }\n\n public static PVEBattleResultCsReq parseFrom(final JsonSource input) throws IOException {\n return ProtoMessage.mergeFrom(new PVEBattleResultCsReq(), input).checkInitialized();\n }\n\n /**\n * @return factory for creating PVEBattleResultCsReq messages\n */\n public static MessageFactory getFactory() {\n return PVEBattleResultCsReqFactory.INSTANCE;\n }\n\n private enum PVEBattleResultCsReqFactory implements MessageFactory {\n INSTANCE;\n\n @Override\n public PVEBattleResultCsReq create() {\n return PVEBattleResultCsReq.newInstance();\n }\n }\n\n /**\n * Contains name constants used for serializing JSON\n */\n static class FieldNames {\n static final FieldName stageId = FieldName.forField(\"stageId\", \"stage_id\");\n\n static final FieldName battleId = FieldName.forField(\"battleId\", \"battle_id\");\n\n static final FieldName clientResVersion = FieldName.forField(\"clientResVersion\", \"client_res_version\");\n\n static final FieldName costTime = FieldName.forField(\"costTime\", \"cost_time\");\n\n static final FieldName endStatus = FieldName.forField(\"endStatus\", \"end_status\");\n\n static final FieldName isAiConsiderUltraSkill = FieldName.forField(\"isAiConsiderUltraSkill\", \"is_ai_consider_ultra_skill\");\n\n static final FieldName stt = FieldName.forField(\"stt\");\n\n static final FieldName turnSnapshotHash = FieldName.forField(\"turnSnapshotHash\", \"turn_snapshot_hash\");\n\n static final FieldName opList = FieldName.forField(\"opList\", \"op_list\");\n }\n}", "answers": [" session.send(new PacketPVEBattleResultScRsp(req, battle));"], "length": 4221, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "bd4aed57-ec0f-4ce3-84fc-f89458301318", "reasoning": "The handler checks if a Battle object was returned. If it is non‑null, it should respond to the client with the battle result packet that includes the request and battle data. The appropriate call is to send a new PacketPVEBattleResultScRsp constructed with the request and battle. This is the immediate next line inside the if block.", "reasoning_model_answer": "session.send(new PacketPVEBattleResultScRsp(req, battle));", "assistant_with_reasoning": "\nThe handler checks if a Battle object was returned. If it is non‑null, it should respond to the client with the battle result packet that includes the request and battle data. The appropriate call is to send a new PacketPVEBattleResultScRsp constructed with the request and battle. This is the immediate next line inside the if block.\n\nsession.send(new PacketPVEBattleResultScRsp(req, battle));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.704, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36397, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "session.send(new PacketPVEBattleResultScRsp(req, battle));", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "import javax.annotation.Generated;\nimport javax.annotation.Nullable;\nimport javax.validation.Valid;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonPropertyOrder;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport io.fabric8.kubernetes.api.model.Container;\nimport io.fabric8.kubernetes.api.model.ContainerPort;\nimport io.fabric8.kubernetes.api.model.EnvVar;\nimport io.fabric8.kubernetes.api.model.IntOrString;\nimport io.fabric8.kubernetes.api.model.LabelSelector;\nimport io.fabric8.kubernetes.api.model.LocalObjectReference;\nimport io.fabric8.kubernetes.api.model.ObjectMeta;\nimport io.fabric8.kubernetes.api.model.ObjectReference;\nimport io.fabric8.kubernetes.api.model.PersistentVolumeClaim;\nimport io.fabric8.kubernetes.api.model.PodTemplateSpec;\nimport io.fabric8.kubernetes.api.model.ResourceRequirements;\nimport io.fabric8.kubernetes.api.model.Volume;\nimport io.fabric8.kubernetes.api.model.VolumeMount;\nimport io.k8s.sparkoperator.v1beta2.ApplicationState;\nimport io.k8s.sparkoperator.v1beta2.BatchSchedulerConfiguration;\nimport io.k8s.sparkoperator.v1beta2.Dependencies;\nimport io.k8s.sparkoperator.v1beta2.DriverInfo;\nimport io.k8s.sparkoperator.v1beta2.DriverSpec;\nimport io.k8s.sparkoperator.v1beta2.DynamicAllocation;\nimport io.k8s.sparkoperator.v1beta2.ExecutorSpec;\nimport io.k8s.sparkoperator.v1beta2.GPUSpec;\nimport io.k8s.sparkoperator.v1beta2.MonitoringSpec;\nimport io.k8s.sparkoperator.v1beta2.NameKey;\nimport io.k8s.sparkoperator.v1beta2.NamePath;\nimport io.k8s.sparkoperator.v1beta2.Port;\nimport io.k8s.sparkoperator.v1beta2.PrometheusSpec;\nimport io.k8s.sparkoperator.v1beta2.RestartPolicy;\nimport io.k8s.sparkoperator.v1beta2.ScheduledSparkApplication;\nimport io.k8s.sparkoperator.v1beta2.ScheduledSparkApplicationList;\nimport io.k8s.sparkoperator.v1beta2.ScheduledSparkApplicationSpec;\nimport io.k8s.sparkoperator.v1beta2.ScheduledSparkApplicationStatus;\nimport io.k8s.sparkoperator.v1beta2.SecretInfo;\nimport io.k8s.sparkoperator.v1beta2.SparkApplication;\nimport io.k8s.sparkoperator.v1beta2.SparkApplicationList;\nimport io.k8s.sparkoperator.v1beta2.SparkApplicationSpec;\nimport io.k8s.sparkoperator.v1beta2.SparkApplicationStatus;\nimport io.k8s.sparkoperator.v1beta2.SparkUIConfiguration;\nimport io.sundr.builder.annotations.Buildable;\nimport io.sundr.builder.annotations.BuildableReference;\nimport lombok.EqualsAndHashCode;\nimport lombok.Setter;\nimport lombok.ToString;\nimport lombok.experimental.Accessors;", "context": "spark-model/src/main/java/io/k8s/sparkoperator/api/model/SparkSchema.java\n\npackage io.k8s.sparkoperator.api.model;\n\n\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ApplicationState\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_BatchSchedulerConfiguration\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_Dependencies\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_DriverInfo\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_DriverSpec\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_DynamicAllocation\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ExecutorSpec\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_GPUSpec\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_MonitoringSpec\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_NameKey\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_NamePath\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_Port\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_PrometheusSpec\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_RestartPolicy\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ScheduledSparkApplication\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ScheduledSparkApplicationList\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ScheduledSparkApplicationSpec\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ScheduledSparkApplicationStatus\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_SecretInfo\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_SparkApplication\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_SparkApplicationList\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_SparkApplicationSpec\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_SparkApplicationStatus\",\n \"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_SparkUIConfiguration\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class SparkSchema {\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ApplicationState\")\n @Valid\n private ApplicationState githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2ApplicationState;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_BatchSchedulerConfiguration\")\n @Valid\n private BatchSchedulerConfiguration githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2BatchSchedulerConfiguration;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_Dependencies\")\n @Valid\n private Dependencies githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2Dependencies;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_DriverInfo\")\n @Valid\n private DriverInfo githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2DriverInfo;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_DriverSpec\")\n @Valid\n private DriverSpec githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2DriverSpec;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_DynamicAllocation\")\n @Valid\n private DynamicAllocation githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2DynamicAllocation;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"github_com_GoogleCloudPlatform_spark-on-k8s-operator_pkg_apis_sparkoperator_k8s_io_v1beta2_ExecutorSpec\")\n @Valid\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/PrometheusSpec.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"configFile\",\n \"configuration\",\n \"jmxExporterJar\",\n \"port\",\n \"portName\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class PrometheusSpec implements KubernetesResource\n{\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"configFile\")\n private String configFile;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"configuration\")\n private String configuration;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"jmxExporterJar\")\n private java.lang.String jmxExporterJar;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"port\")\n private Integer port;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"portName\")\n private String portName;\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public PrometheusSpec() {\n }\n\n public PrometheusSpec(String configFile, String configuration, java.lang.String jmxExporterJar, Integer port, String portName) {\n super();\n this.configFile = configFile;\n this.configuration = configuration;\n this.jmxExporterJar = jmxExporterJar;\n this.port = port;\n this.portName = portName;\n }\n\n @JsonProperty(\"configFile\")\n public String getConfigFile() {\n return configFile;\n }\n\n @JsonProperty(\"configFile\")\n public void setConfigFile(String configFile) {\n this.configFile = configFile;\n }\n\n @JsonProperty(\"configuration\")\n public String getConfiguration() {\n return configuration;\n }\n\n @JsonProperty(\"configuration\")\n public void setConfiguration(String configuration) {\n this.configuration = configuration;\n }\n\n @JsonProperty(\"jmxExporterJar\")\n public java.lang.String getJmxExporterJar() {\n return jmxExporterJar;\n }\n\n @JsonProperty(\"jmxExporterJar\")\n public void setJmxExporterJar(java.lang.String jmxExporterJar) {\n this.jmxExporterJar = jmxExporterJar;\n }\n\n @JsonProperty(\"port\")\n public Integer getPort() {\n return port;\n }\n\n @JsonProperty(\"port\")\n public void setPort(Integer port) {\n this.port = port;\n }\n\n @JsonProperty(\"portName\")\n public String getPortName() {\n return portName;\n }\n\n @JsonProperty(\"portName\")\n public void setPortName(String portName) {\n this.portName = portName;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(java.lang.String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/NameKey.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"key\",\n \"name\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class NameKey implements KubernetesResource\n{\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"key\")\n private String key;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"name\")\n private String name;\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public NameKey() {\n }\n\n public NameKey(String key, String name) {\n super();\n this.key = key;\n this.name = name;\n }\n\n @JsonProperty(\"key\")\n public String getKey() {\n return key;\n }\n\n @JsonProperty(\"key\")\n public void setKey(String key) {\n this.key = key;\n }\n\n @JsonProperty(\"name\")\n public String getName() {\n return name;\n }\n\n @JsonProperty(\"name\")\n public void setName(String name) {\n this.name = name;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/SparkApplicationStatus.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"applicationState\",\n \"driverInfo\",\n \"executionAttempts\",\n \"executorState\",\n \"lastSubmissionAttemptTime\",\n \"sparkApplicationId\",\n \"submissionAttempts\",\n \"submissionID\",\n \"terminationTime\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class SparkApplicationStatus implements KubernetesResource\n{\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"applicationState\")\n @Valid\n private ApplicationState applicationState;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"driverInfo\")\n @Valid\n private DriverInfo driverInfo;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"executionAttempts\")\n private Integer executionAttempts;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"executorState\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private Map executorState = new LinkedHashMap();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"lastSubmissionAttemptTime\")\n private java.lang.String lastSubmissionAttemptTime;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"sparkApplicationId\")\n private java.lang.String sparkApplicationId;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"submissionAttempts\")\n private Integer submissionAttempts;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"submissionID\")\n private java.lang.String submissionID;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"terminationTime\")\n private java.lang.String terminationTime;\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public SparkApplicationStatus() {\n }\n\n public SparkApplicationStatus(ApplicationState applicationState, DriverInfo driverInfo, Integer executionAttempts, Map executorState, java.lang.String lastSubmissionAttemptTime, java.lang.String sparkApplicationId, Integer submissionAttempts, java.lang.String submissionID, java.lang.String terminationTime) {\n super();\n this.applicationState = applicationState;\n this.driverInfo = driverInfo;\n this.executionAttempts = executionAttempts;\n this.executorState = executorState;\n this.lastSubmissionAttemptTime = lastSubmissionAttemptTime;\n this.sparkApplicationId = sparkApplicationId;\n this.submissionAttempts = submissionAttempts;\n this.submissionID = submissionID;\n this.terminationTime = terminationTime;\n }\n\n @JsonProperty(\"applicationState\")\n public ApplicationState getApplicationState() {\n return applicationState;\n }\n\n @JsonProperty(\"applicationState\")\n public void setApplicationState(ApplicationState applicationState) {\n this.applicationState = applicationState;\n }\n\n @JsonProperty(\"driverInfo\")\n public DriverInfo getDriverInfo() {\n return driverInfo;\n }\n\n @JsonProperty(\"driverInfo\")\n public void setDriverInfo(DriverInfo driverInfo) {\n this.driverInfo = driverInfo;\n }\n\n @JsonProperty(\"executionAttempts\")\n public Integer getExecutionAttempts() {\n return executionAttempts;\n }\n\n @JsonProperty(\"executionAttempts\")\n public void setExecutionAttempts(Integer executionAttempts) {\n this.executionAttempts = executionAttempts;\n }\n\n @JsonProperty(\"executorState\")\n public Map getExecutorState() {\n return executorState;\n }\n\n @JsonProperty(\"executorState\")\n public void setExecutorState(Map executorState) {\n this.executorState = executorState;\n }\n\n @JsonProperty(\"lastSubmissionAttemptTime\")\n public java.lang.String getLastSubmissionAttemptTime() {\n return lastSubmissionAttemptTime;\n }\n\n @JsonProperty(\"lastSubmissionAttemptTime\")\n public void setLastSubmissionAttemptTime(java.lang.String lastSubmissionAttemptTime) {\n this.lastSubmissionAttemptTime = lastSubmissionAttemptTime;\n }\n\n @JsonProperty(\"sparkApplicationId\")\n public java.lang.String getSparkApplicationId() {\n return sparkApplicationId;\n }\n\n @JsonProperty(\"sparkApplicationId\")\n public void setSparkApplicationId(java.lang.String sparkApplicationId) {\n this.sparkApplicationId = sparkApplicationId;\n }\n\n @JsonProperty(\"submissionAttempts\")\n public Integer getSubmissionAttempts() {\n return submissionAttempts;\n }\n\n @JsonProperty(\"submissionAttempts\")\n public void setSubmissionAttempts(Integer submissionAttempts) {\n this.submissionAttempts = submissionAttempts;\n }\n\n @JsonProperty(\"submissionID\")\n public java.lang.String getSubmissionID() {\n return submissionID;\n }\n\n @JsonProperty(\"submissionID\")\n public void setSubmissionID(java.lang.String submissionID) {\n this.submissionID = submissionID;\n }\n\n @JsonProperty(\"terminationTime\")\n public java.lang.String getTerminationTime() {\n return terminationTime;\n }\n\n @JsonProperty(\"terminationTime\")\n public void setTerminationTime(java.lang.String terminationTime) {\n this.terminationTime = terminationTime;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(java.lang.String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/NamePath.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"name\",\n \"path\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class NamePath implements KubernetesResource\n{\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"name\")\n private String name;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"path\")\n private String path;\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public NamePath() {\n }\n\n public NamePath(String name, String path) {\n super();\n this.name = name;\n this.path = path;\n }\n\n @JsonProperty(\"name\")\n public String getName() {\n return name;\n }\n\n @JsonProperty(\"name\")\n public void setName(String name) {\n this.name = name;\n }\n\n @JsonProperty(\"path\")\n public String getPath() {\n return path;\n }\n\n @JsonProperty(\"path\")\n public void setPath(String path) {\n this.path = path;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/SparkApplicationList.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"items\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@TemplateTransformations({\n @TemplateTransformation(value = \"/manifest.vm\", outputPath = \"META-INF/services/io.fabric8.kubernetes.api.model.KubernetesResource\", gather = true)\n})\n@Version(\"v1beta2\")\n@Group(\"sparkoperator.k8s.io\")\n@Generated(\"jsonschema2pojo\")\npublic class SparkApplicationList implements KubernetesResource, KubernetesResourceList\n{\n\n /**\n * \n * (Required)\n * \n */\n @NotNull\n @Nonnull\n @JsonProperty(\"apiVersion\")\n private String apiVersion = \"sparkoperator.k8s.io/v1beta2\";\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"items\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private List items = new ArrayList();\n /**\n * \n * (Required)\n * \n */\n @NotNull\n @Nonnull\n @JsonProperty(\"kind\")\n private String kind = \"SparkApplicationList\";\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"metadata\")\n private ListMeta metadata;\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public SparkApplicationList() {\n }\n\n public SparkApplicationList(String apiVersion, List items, String kind, ListMeta metadata) {\n super();\n this.apiVersion = apiVersion;\n this.items = items;\n this.kind = kind;\n this.metadata = metadata;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"apiVersion\")\n public String getApiVersion() {\n return apiVersion;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"apiVersion\")\n public void setApiVersion(String apiVersion) {\n this.apiVersion = apiVersion;\n }\n\n @JsonProperty(\"items\")\n public List getItems() {\n return items;\n }\n\n @JsonProperty(\"items\")\n public void setItems(List items) {\n this.items = items;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"kind\")\n public String getKind() {\n return kind;\n }\n\n /**\n * \n * (Required)\n * \n */\n @JsonProperty(\"kind\")\n public void setKind(String kind) {\n this.kind = kind;\n }\n\n @JsonProperty(\"metadata\")\n public ListMeta getMetadata() {\n return metadata;\n }\n\n @JsonProperty(\"metadata\")\n public void setMetadata(ListMeta metadata) {\n this.metadata = metadata;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/SecretInfo.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"name\",\n \"path\",\n \"secretType\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class SecretInfo implements KubernetesResource\n{\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"name\")\n private String name;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"path\")\n private String path;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"secretType\")\n private String secretType;\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public SecretInfo() {\n }\n\n public SecretInfo(String name, String path, String secretType) {\n super();\n this.name = name;\n this.path = path;\n this.secretType = secretType;\n }\n\n @JsonProperty(\"name\")\n public String getName() {\n return name;\n }\n\n @JsonProperty(\"name\")\n public void setName(String name) {\n this.name = name;\n }\n\n @JsonProperty(\"path\")\n public String getPath() {\n return path;\n }\n\n @JsonProperty(\"path\")\n public void setPath(String path) {\n this.path = path;\n }\n\n @JsonProperty(\"secretType\")\n public String getSecretType() {\n return secretType;\n }\n\n @JsonProperty(\"secretType\")\n public void setSecretType(String secretType) {\n this.secretType = secretType;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/ScheduledSparkApplicationStatus.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"lastRun\",\n \"lastRunName\",\n \"nextRun\",\n \"pastFailedRunNames\",\n \"pastSuccessfulRunNames\",\n \"reason\",\n \"scheduleState\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class ScheduledSparkApplicationStatus implements KubernetesResource\n{\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"lastRun\")\n private String lastRun;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"lastRunName\")\n private String lastRunName;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"nextRun\")\n private String nextRun;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"pastFailedRunNames\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private List pastFailedRunNames = new ArrayList();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"pastSuccessfulRunNames\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private List pastSuccessfulRunNames = new ArrayList();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"reason\")\n private String reason;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"scheduleState\")\n private String scheduleState;\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public ScheduledSparkApplicationStatus() {\n }\n\n public ScheduledSparkApplicationStatus(String lastRun, String lastRunName, String nextRun, List pastFailedRunNames, List pastSuccessfulRunNames, String reason, String scheduleState) {\n super();\n this.lastRun = lastRun;\n this.lastRunName = lastRunName;\n this.nextRun = nextRun;\n this.pastFailedRunNames = pastFailedRunNames;\n this.pastSuccessfulRunNames = pastSuccessfulRunNames;\n this.reason = reason;\n this.scheduleState = scheduleState;\n }\n\n @JsonProperty(\"lastRun\")\n public String getLastRun() {\n return lastRun;\n }\n\n @JsonProperty(\"lastRun\")\n public void setLastRun(String lastRun) {\n this.lastRun = lastRun;\n }\n\n @JsonProperty(\"lastRunName\")\n public String getLastRunName() {\n return lastRunName;\n }\n\n @JsonProperty(\"lastRunName\")\n public void setLastRunName(String lastRunName) {\n this.lastRunName = lastRunName;\n }\n\n @JsonProperty(\"nextRun\")\n public String getNextRun() {\n return nextRun;\n }\n\n @JsonProperty(\"nextRun\")\n public void setNextRun(String nextRun) {\n this.nextRun = nextRun;\n }\n\n @JsonProperty(\"pastFailedRunNames\")\n public List getPastFailedRunNames() {\n return pastFailedRunNames;\n }\n\n @JsonProperty(\"pastFailedRunNames\")\n public void setPastFailedRunNames(List pastFailedRunNames) {\n this.pastFailedRunNames = pastFailedRunNames;\n }\n\n @JsonProperty(\"pastSuccessfulRunNames\")\n public List getPastSuccessfulRunNames() {\n return pastSuccessfulRunNames;\n }\n\n @JsonProperty(\"pastSuccessfulRunNames\")\n public void setPastSuccessfulRunNames(List pastSuccessfulRunNames) {\n this.pastSuccessfulRunNames = pastSuccessfulRunNames;\n }\n\n @JsonProperty(\"reason\")\n public String getReason() {\n return reason;\n }\n\n @JsonProperty(\"reason\")\n public void setReason(String reason) {\n this.reason = reason;\n }\n\n @JsonProperty(\"scheduleState\")\n public String getScheduleState() {\n return scheduleState;\n }\n\n @JsonProperty(\"scheduleState\")\n public void setScheduleState(String scheduleState) {\n this.scheduleState = scheduleState;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}\n\nspark-model/src/main/java/io/k8s/sparkoperator/v1beta2/SparkApplicationSpec.java\n@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"apiVersion\",\n \"kind\",\n \"metadata\",\n \"arguments\",\n \"batchScheduler\",\n \"batchSchedulerOptions\",\n \"deps\",\n \"driver\",\n \"dynamicAllocation\",\n \"executor\",\n \"failureRetries\",\n \"hadoopConf\",\n \"hadoopConfigMap\",\n \"image\",\n \"imagePullPolicy\",\n \"imagePullSecrets\",\n \"mainApplicationFile\",\n \"mainClass\",\n \"memoryOverheadFactor\",\n \"mode\",\n \"monitoring\",\n \"nodeSelector\",\n \"proxyUser\",\n \"pythonVersion\",\n \"restartPolicy\",\n \"retryInterval\",\n \"sparkConf\",\n \"sparkConfigMap\",\n \"sparkUIOptions\",\n \"sparkVersion\",\n \"timeToLiveSeconds\",\n \"type\",\n \"volumes\"\n})\n@ToString\n@EqualsAndHashCode\n@Setter\n@Accessors(prefix = {\n \"_\",\n \"\"\n})\n@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = \"io.fabric8.kubernetes.api.builder\", refs = {\n @BuildableReference(ObjectMeta.class),\n @BuildableReference(LabelSelector.class),\n @BuildableReference(Container.class),\n @BuildableReference(PodTemplateSpec.class),\n @BuildableReference(ResourceRequirements.class),\n @BuildableReference(IntOrString.class),\n @BuildableReference(ObjectReference.class),\n @BuildableReference(LocalObjectReference.class),\n @BuildableReference(PersistentVolumeClaim.class),\n @BuildableReference(EnvVar.class),\n @BuildableReference(ContainerPort.class),\n @BuildableReference(io.fabric8.kubernetes.api.model.Volume.class),\n @BuildableReference(VolumeMount.class)\n})\n@Generated(\"jsonschema2pojo\")\npublic class SparkApplicationSpec implements KubernetesResource\n{\n\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"arguments\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private List arguments = new ArrayList();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"batchScheduler\")\n private String batchScheduler;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"batchSchedulerOptions\")\n @Valid\n private BatchSchedulerConfiguration batchSchedulerOptions;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"deps\")\n @Valid\n private Dependencies deps;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"driver\")\n @Valid\n private DriverSpec driver;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"dynamicAllocation\")\n @Valid\n private DynamicAllocation dynamicAllocation;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"executor\")\n @Valid\n private ExecutorSpec executor;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"failureRetries\")\n private Integer failureRetries;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"hadoopConf\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private Map hadoopConf = new LinkedHashMap();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"hadoopConfigMap\")\n private String hadoopConfigMap;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"image\")\n private String image;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"imagePullPolicy\")\n private String imagePullPolicy;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"imagePullSecrets\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private List imagePullSecrets = new ArrayList();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"mainApplicationFile\")\n private String mainApplicationFile;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"mainClass\")\n private String mainClass;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"memoryOverheadFactor\")\n private String memoryOverheadFactor;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"mode\")\n private java.lang.String mode;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"monitoring\")\n @Valid\n private MonitoringSpec monitoring;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"nodeSelector\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private Map nodeSelector = new LinkedHashMap();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"proxyUser\")\n private String proxyUser;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"pythonVersion\")\n private String pythonVersion;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"restartPolicy\")\n @Valid\n private RestartPolicy restartPolicy;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"retryInterval\")\n private Long retryInterval;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"sparkConf\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private Map sparkConf = new LinkedHashMap();\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"sparkConfigMap\")\n private String sparkConfigMap;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"sparkUIOptions\")\n @Valid\n private SparkUIConfiguration sparkUIOptions;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"sparkVersion\")\n private java.lang.String sparkVersion;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"timeToLiveSeconds\")\n private Long timeToLiveSeconds;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"type\")\n private java.lang.String type;\n /**\n * \n * (Can be null)\n * \n */\n @Nullable\n @JsonProperty(\"volumes\")\n @JsonInclude(JsonInclude.Include.NON_EMPTY)\n @Valid\n private List volumes = new ArrayList();\n @JsonIgnore\n @Valid\n private Map additionalProperties = new LinkedHashMap();\n\n /**\n * No args constructor for use in serialization\n * \n */\n public SparkApplicationSpec() {\n }\n\n public SparkApplicationSpec(List arguments, String batchScheduler, BatchSchedulerConfiguration batchSchedulerOptions, Dependencies deps, DriverSpec driver, DynamicAllocation dynamicAllocation, ExecutorSpec executor, Integer failureRetries, Map hadoopConf, String hadoopConfigMap, String image, String imagePullPolicy, List imagePullSecrets, String mainApplicationFile, String mainClass, String memoryOverheadFactor, java.lang.String mode, MonitoringSpec monitoring, Map nodeSelector, String proxyUser, String pythonVersion, RestartPolicy restartPolicy, Long retryInterval, Map sparkConf, String sparkConfigMap, SparkUIConfiguration sparkUIOptions, java.lang.String sparkVersion, Long timeToLiveSeconds, java.lang.String type, List volumes) {\n super();\n this.arguments = arguments;\n this.batchScheduler = batchScheduler;\n this.batchSchedulerOptions = batchSchedulerOptions;\n this.deps = deps;\n this.driver = driver;\n this.dynamicAllocation = dynamicAllocation;\n this.executor = executor;\n this.failureRetries = failureRetries;\n this.hadoopConf = hadoopConf;\n this.hadoopConfigMap = hadoopConfigMap;\n this.image = image;\n this.imagePullPolicy = imagePullPolicy;\n this.imagePullSecrets = imagePullSecrets;\n this.mainApplicationFile = mainApplicationFile;\n this.mainClass = mainClass;\n this.memoryOverheadFactor = memoryOverheadFactor;\n this.mode = mode;\n this.monitoring = monitoring;\n this.nodeSelector = nodeSelector;\n this.proxyUser = proxyUser;\n this.pythonVersion = pythonVersion;\n this.restartPolicy = restartPolicy;\n this.retryInterval = retryInterval;\n this.sparkConf = sparkConf;\n this.sparkConfigMap = sparkConfigMap;\n this.sparkUIOptions = sparkUIOptions;\n this.sparkVersion = sparkVersion;\n this.timeToLiveSeconds = timeToLiveSeconds;\n this.type = type;\n this.volumes = volumes;\n }\n\n @JsonProperty(\"arguments\")\n public List getArguments() {\n return arguments;\n }\n\n @JsonProperty(\"arguments\")\n public void setArguments(List arguments) {\n this.arguments = arguments;\n }\n\n @JsonProperty(\"batchScheduler\")\n public String getBatchScheduler() {\n return batchScheduler;\n }\n\n @JsonProperty(\"batchScheduler\")\n public void setBatchScheduler(String batchScheduler) {\n this.batchScheduler = batchScheduler;\n }\n\n @JsonProperty(\"batchSchedulerOptions\")\n public BatchSchedulerConfiguration getBatchSchedulerOptions() {\n return batchSchedulerOptions;\n }\n\n @JsonProperty(\"batchSchedulerOptions\")\n public void setBatchSchedulerOptions(BatchSchedulerConfiguration batchSchedulerOptions) {\n this.batchSchedulerOptions = batchSchedulerOptions;\n }\n\n @JsonProperty(\"deps\")\n public Dependencies getDeps() {\n return deps;\n }\n\n @JsonProperty(\"deps\")\n public void setDeps(Dependencies deps) {\n this.deps = deps;\n }\n\n @JsonProperty(\"driver\")\n public DriverSpec getDriver() {\n return driver;\n }\n\n @JsonProperty(\"driver\")\n public void setDriver(DriverSpec driver) {\n this.driver = driver;\n }\n\n @JsonProperty(\"dynamicAllocation\")\n public DynamicAllocation getDynamicAllocation() {\n return dynamicAllocation;\n }\n\n @JsonProperty(\"dynamicAllocation\")\n public void setDynamicAllocation(DynamicAllocation dynamicAllocation) {\n this.dynamicAllocation = dynamicAllocation;\n }\n\n @JsonProperty(\"executor\")\n public ExecutorSpec getExecutor() {\n return executor;\n }\n\n @JsonProperty(\"executor\")\n public void setExecutor(ExecutorSpec executor) {\n this.executor = executor;\n }\n\n @JsonProperty(\"failureRetries\")\n public Integer getFailureRetries() {\n return failureRetries;\n }\n\n @JsonProperty(\"failureRetries\")\n public void setFailureRetries(Integer failureRetries) {\n this.failureRetries = failureRetries;\n }\n\n @JsonProperty(\"hadoopConf\")\n public Map getHadoopConf() {\n return hadoopConf;\n }\n\n @JsonProperty(\"hadoopConf\")\n public void setHadoopConf(Map hadoopConf) {\n this.hadoopConf = hadoopConf;\n }\n\n @JsonProperty(\"hadoopConfigMap\")\n public String getHadoopConfigMap() {\n return hadoopConfigMap;\n }\n\n @JsonProperty(\"hadoopConfigMap\")\n public void setHadoopConfigMap(String hadoopConfigMap) {\n this.hadoopConfigMap = hadoopConfigMap;\n }\n\n @JsonProperty(\"image\")\n public String getImage() {\n return image;\n }\n\n @JsonProperty(\"image\")\n public void setImage(String image) {\n this.image = image;\n }\n\n @JsonProperty(\"imagePullPolicy\")\n public String getImagePullPolicy() {\n return imagePullPolicy;\n }\n\n @JsonProperty(\"imagePullPolicy\")\n public void setImagePullPolicy(String imagePullPolicy) {\n this.imagePullPolicy = imagePullPolicy;\n }\n\n @JsonProperty(\"imagePullSecrets\")\n public List getImagePullSecrets() {\n return imagePullSecrets;\n }\n\n @JsonProperty(\"imagePullSecrets\")\n public void setImagePullSecrets(List imagePullSecrets) {\n this.imagePullSecrets = imagePullSecrets;\n }\n\n @JsonProperty(\"mainApplicationFile\")\n public String getMainApplicationFile() {\n return mainApplicationFile;\n }\n\n @JsonProperty(\"mainApplicationFile\")\n public void setMainApplicationFile(String mainApplicationFile) {\n this.mainApplicationFile = mainApplicationFile;\n }\n\n @JsonProperty(\"mainClass\")\n public String getMainClass() {\n return mainClass;\n }\n\n @JsonProperty(\"mainClass\")\n public void setMainClass(String mainClass) {\n this.mainClass = mainClass;\n }\n\n @JsonProperty(\"memoryOverheadFactor\")\n public String getMemoryOverheadFactor() {\n return memoryOverheadFactor;\n }\n\n @JsonProperty(\"memoryOverheadFactor\")\n public void setMemoryOverheadFactor(String memoryOverheadFactor) {\n this.memoryOverheadFactor = memoryOverheadFactor;\n }\n\n @JsonProperty(\"mode\")\n public java.lang.String getMode() {\n return mode;\n }\n\n @JsonProperty(\"mode\")\n public void setMode(java.lang.String mode) {\n this.mode = mode;\n }\n\n @JsonProperty(\"monitoring\")\n public MonitoringSpec getMonitoring() {\n return monitoring;\n }\n\n @JsonProperty(\"monitoring\")\n public void setMonitoring(MonitoringSpec monitoring) {\n this.monitoring = monitoring;\n }\n\n @JsonProperty(\"nodeSelector\")\n public Map getNodeSelector() {\n return nodeSelector;\n }\n\n @JsonProperty(\"nodeSelector\")\n public void setNodeSelector(Map nodeSelector) {\n this.nodeSelector = nodeSelector;\n }\n\n @JsonProperty(\"proxyUser\")\n public String getProxyUser() {\n return proxyUser;\n }\n\n @JsonProperty(\"proxyUser\")\n public void setProxyUser(String proxyUser) {\n this.proxyUser = proxyUser;\n }\n\n @JsonProperty(\"pythonVersion\")\n public String getPythonVersion() {\n return pythonVersion;\n }\n\n @JsonProperty(\"pythonVersion\")\n public void setPythonVersion(String pythonVersion) {\n this.pythonVersion = pythonVersion;\n }\n\n @JsonProperty(\"restartPolicy\")\n public RestartPolicy getRestartPolicy() {\n return restartPolicy;\n }\n\n @JsonProperty(\"restartPolicy\")\n public void setRestartPolicy(RestartPolicy restartPolicy) {\n this.restartPolicy = restartPolicy;\n }\n\n @JsonProperty(\"retryInterval\")\n public Long getRetryInterval() {\n return retryInterval;\n }\n\n @JsonProperty(\"retryInterval\")\n public void setRetryInterval(Long retryInterval) {\n this.retryInterval = retryInterval;\n }\n\n @JsonProperty(\"sparkConf\")\n public Map getSparkConf() {\n return sparkConf;\n }\n\n @JsonProperty(\"sparkConf\")\n public void setSparkConf(Map sparkConf) {\n this.sparkConf = sparkConf;\n }\n\n @JsonProperty(\"sparkConfigMap\")\n public String getSparkConfigMap() {\n return sparkConfigMap;\n }\n\n @JsonProperty(\"sparkConfigMap\")\n public void setSparkConfigMap(String sparkConfigMap) {\n this.sparkConfigMap = sparkConfigMap;\n }\n\n @JsonProperty(\"sparkUIOptions\")\n public SparkUIConfiguration getSparkUIOptions() {\n return sparkUIOptions;\n }\n\n @JsonProperty(\"sparkUIOptions\")\n public void setSparkUIOptions(SparkUIConfiguration sparkUIOptions) {\n this.sparkUIOptions = sparkUIOptions;\n }\n\n @JsonProperty(\"sparkVersion\")\n public java.lang.String getSparkVersion() {\n return sparkVersion;\n }\n\n @JsonProperty(\"sparkVersion\")\n public void setSparkVersion(java.lang.String sparkVersion) {\n this.sparkVersion = sparkVersion;\n }\n\n @JsonProperty(\"timeToLiveSeconds\")\n public Long getTimeToLiveSeconds() {\n return timeToLiveSeconds;\n }\n\n @JsonProperty(\"timeToLiveSeconds\")\n public void setTimeToLiveSeconds(Long timeToLiveSeconds) {\n this.timeToLiveSeconds = timeToLiveSeconds;\n }\n\n @JsonProperty(\"type\")\n public java.lang.String getType() {\n return type;\n }\n\n @JsonProperty(\"type\")\n public void setType(java.lang.String type) {\n this.type = type;\n }\n\n @JsonProperty(\"volumes\")\n public List getVolumes() {\n return volumes;\n }\n\n @JsonProperty(\"volumes\")\n public void setVolumes(List volumes) {\n this.volumes = volumes;\n }\n\n @JsonAnyGetter\n public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n @JsonAnySetter\n public void setAdditionalProperty(java.lang.String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n}", "answers": [" private ExecutorSpec githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2ExecutorSpec;"], "length": 3556, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "002a000c-d57e-4670-8fa5-b3d62c765611", "reasoning": "In SparkSchema.java, after the ExecutorSpec field the next property in the JSON order is GPUSpec. Following the pattern of previous fields, the code includes a comment block, @Nullable, @JsonProperty, and @Valid annotations, then declares the private field of type GPUSpec with a generated name matching the JSON property. Therefore the next line should be the field declaration for GPUSpec.", "reasoning_model_answer": "private GPUSpec githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2GPUSpec;", "assistant_with_reasoning": "\nIn SparkSchema.java, after the ExecutorSpec field the next property in the JSON order is GPUSpec. Following the pattern of previous fields, the code includes a comment block, @Nullable, @JsonProperty, and @Valid annotations, then declares the private field of type GPUSpec with a generated name matching the JSON property. Therefore the next line should be the field declaration for GPUSpec.\n\nprivate GPUSpec githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2GPUSpec;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.624, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 38586, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private GPUSpec githubComGoogleCloudPlatformSparkOnK8sOperatorPkgApisSparkoperatorK8sIoV1beta2GPUSpec;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "import org.jaudiotagger.StandardCharsets;\nimport org.jaudiotagger.audio.generic.Utils;\nimport org.jaudiotagger.audio.mp4.atom.Mp4BoxHeader;\nimport org.jaudiotagger.logging.ErrorMessage;\nimport org.jaudiotagger.tag.TagField;\nimport org.jaudiotagger.tag.TagTextField;\nimport org.jaudiotagger.tag.mp4.Mp4FieldKey;\nimport org.jaudiotagger.tag.mp4.Mp4TagField;\nimport org.jaudiotagger.tag.mp4.atom.Mp4DataBox;\nimport org.jaudiotagger.tag.mp4.atom.Mp4MeanBox;\nimport org.jaudiotagger.tag.mp4.atom.Mp4NameBox;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.Charset;", "context": "android/src/main/java/org/jaudiotagger/tag/mp4/field/Mp4TagReverseDnsField.java\npackage org.jaudiotagger.tag.mp4.field;\n\n\n\n/**\n * Represents reverse dns field, used for custom information\n *\n *

Originally only used by Itunes for information that was iTunes specific but now used in a wide range of uses,\n * for example Musicbrainz uses it for many of its fields.\n *\n * These fields have a more complex setup\n * Box ---- shows this is a reverse dns metadata field\n * Box mean the issuer in the form of reverse DNS domain (e.g com.apple.iTunes)\n * Box name descriptor identifying the type of contents\n * Box data contents\n *\n * The raw data passed starts from the mean box\n */\npublic class Mp4TagReverseDnsField extends Mp4TagField implements TagTextField\n{\n public static final String IDENTIFIER = \"----\";\n\n protected int dataSize;\n\n //Issuer\n private String issuer;\n\n //Descriptor\n private String descriptor;\n\n //Data Content,\n //TODO assuming always text at the moment\n protected String content;\n\n /**\n * Construct from existing file data\n *\n * @param parentHeader\n * @param data\n * @throws UnsupportedEncodingException\n */\n public Mp4TagReverseDnsField(Mp4BoxHeader parentHeader, ByteBuffer data) throws UnsupportedEncodingException\n {\n super(parentHeader, data);\n }\n\n /**\n * Newly created Reverse Dns field\n *\n * @param id\n * @param content\n */\n public Mp4TagReverseDnsField(Mp4FieldKey id, String content)\n {\n super(id.getFieldName());\n this.issuer = id.getIssuer();\n this.descriptor = id.getIdentifier();\n this.content = content;\n }\n\n /**\n * Newly created Reverse Dns field bypassing the Mp4TagField enum for creation of temporary reverse dns fields\n * @param fieldName\n * @param issuer\n * @param identifier\n * @param content\n */\n public Mp4TagReverseDnsField(final String fieldName, final String issuer, final String identifier, final String content)\n {\n super(fieldName);\n this.issuer = issuer;\n this.descriptor = identifier;\n this.content = content;\n }\n\n @Override\n public Mp4FieldType getFieldType()\n {\n //TODO always assuming text at moment but may not always be the case (though dont have any concrete\n //examples)\n return Mp4FieldType.TEXT;\n }\n\n @Override\n protected void build(ByteBuffer data) throws UnsupportedEncodingException\n {\n //Read mean box, set the issuer and skip over data\n Mp4BoxHeader meanBoxHeader = new Mp4BoxHeader(data);\n Mp4MeanBox meanBox = new Mp4MeanBox(meanBoxHeader, data);\n setIssuer(meanBox.getIssuer());\n data.position(data.position() + meanBoxHeader.getDataLength());\n\n //Read name box, identify what type of field it is\n Mp4BoxHeader nameBoxHeader = new Mp4BoxHeader(data);\n Mp4NameBox nameBox = new Mp4NameBox(nameBoxHeader, data);\n setDescriptor(nameBox.getName());\n data.position(data.position() + nameBoxHeader.getDataLength());\n\n //Issue 198:There is not actually a data atom there cannot cant be because no room for one\n if (parentHeader.getDataLength() == meanBoxHeader.getLength() + nameBoxHeader.getLength())\n {\n id = IDENTIFIER + \":\" + issuer + \":\" + descriptor;\n setContent(\"\");\n logger.warning(ErrorMessage.MP4_REVERSE_DNS_FIELD_HAS_NO_DATA.getMsg(id));\n }\n //Usual Case\n else\n {\n //Read data box, identify the data\n Mp4BoxHeader dataBoxHeader = new Mp4BoxHeader(data);\n Mp4DataBox dataBox = new Mp4DataBox(dataBoxHeader, data);\n setContent(dataBox.getContent());\n data.position(data.position() + dataBoxHeader.getDataLength());\n\n //Now calculate the id which in order to be unique needs to use all htree values\n id = IDENTIFIER + \":\" + issuer + \":\" + descriptor;\n }\n }\n\n @Override\n public void copyContent(TagField field)\n {\n if (field instanceof Mp4TagReverseDnsField)\n {\n this.issuer = ((Mp4TagReverseDnsField) field).getIssuer();\n this.descriptor = ((Mp4TagReverseDnsField) field).getDescriptor();\n this.content = ((Mp4TagReverseDnsField) field).getContent();\n }\n }\n\n @Override\n public String getContent()\n {\n return content;\n }\n\n @Override\n protected byte[] getDataBytes() throws UnsupportedEncodingException\n {\n return content.getBytes(getEncoding());\n }\n\n @Override\n public Charset getEncoding()\n {\n\nandroid/src/main/java/org/jaudiotagger/audio/generic/Utils.java\npublic class Utils {\n public static int BITS_IN_BYTE_MULTIPLIER = 8;\n public static int KILOBYTE_MULTIPLIER = 1000;\n\n private static final Logger logger = Logger.getLogger(\"org.jaudiotagger.audio.generic.utils\");\n private static final int MAX_BASE_TEMP_FILENAME_LENGTH = 20;\n\n /**\n * Returns the extension of the given file.\n * The extension is empty if there is no extension\n * The extension is the string after the last \".\"\n *\n * @param f The file whose extension is requested\n * @return The extension of the given file\n */\n public static String getExtension(final File f) {\n final String name = f.getName().toLowerCase();\n final int i = name.lastIndexOf(\".\");\n if (i == -1) {\n return \"\";\n }\n\n return name.substring(i + 1);\n }\n\n /**\n * Returns the extension of the given file based on the file signature.\n * The extension is empty if the file signature is not recognized.\n *\n * @param f The file whose extension is requested\n * @return The extension of the given file\n */\n public static String getMagicExtension(final File f) throws IOException {\n final String fileType = FileTypeUtil.getMagicFileType(f);\n return FileTypeUtil.getMagicExt(fileType);\n }\n\n /**\n * Computes a number whereby the 1st byte is the least signifcant and the last\n * byte is the most significant.\n * So if storing a number which only requires one byte it will be stored in the first\n * byte.\n *\n * @param b The byte array @param start The starting offset in b\n * (b[offset]). The less significant byte @param end The end index\n * (included) in b (b[end]). The most significant byte\n * @return a long number represented by the byte sequence.\n */\n public static long getLongLE(final ByteBuffer b, final int start, final int end) {\n long number = 0;\n for (int i = 0; i < (end - start + 1); i++) {\n number += ((b.get(start + i) & 0xFF) << i * 8);\n }\n\n return number;\n }\n\n /**\n * Computes a number whereby the 1st byte is the most significant and the last\n * byte is the least significant.\n *

\n * So if storing a number which only requires one byte it will be stored in the last\n * byte.\n *

\n * Will fail if end - start >= 8, due to the limitations of the long type.\n */\n public static long getLongBE(final ByteBuffer b, final int start, final int end) {\n long number = 0;\n for (int i = 0; i < (end - start + 1); i++) {\n number += ((long) ((b.get(end - i) & 0xFF)) << i * 8);\n }\n\n return number;\n }\n\n /**\n * Computes a number whereby the 1st byte is the least significant and the last\n * byte is the most significant. This version doesn't take a length,\n * and it returns an int rather than a long.\n *\n * @param b The byte array. Maximum length for valid results is 4 bytes.\n */\n public static int getIntLE(final byte[] b) {\n return (int) getLongLE(ByteBuffer.wrap(b), 0, b.length - 1);\n }\n\n /**\n * Computes a number whereby the 1st byte is the least significant and the last\n * byte is the most significant. end - start must be no greater than 4.\n *\n * @param b The byte array\n * @param start The starting offset in b (b[offset]). The less\n * significant byte\n * @param end The end index (included) in b (b[end])\n * @return a int number represented by the byte sequence.\n */\n public static int getIntLE(final byte[] b, final int start, final int end) {\n return (int) getLongLE(ByteBuffer.wrap(b), start, end);\n }\n\n /**\n * Computes a number whereby the 1st byte is the most significant and the last\n * byte is the least significant.\n *\n * @param b The ByteBuffer\n * @param start The starting offset in b. The less\n * significant byte\n * @param end The end index (included) in b\n * @return an int number represented by the byte sequence.\n */\n public static int getIntBE(final ByteBuffer b, final int start, final int end) {\n return (int) getLongBE(b, start, end);\n }\n\n /**\n * Computes a number whereby the 1st byte is the most significant and the last\n * byte is the least significant.\n *\n * @param b The ByteBuffer\n * @param start The starting offset in b. The less\n * significant byte\n * @param end The end index (included) in b\n * @return a short number represented by the byte sequence.\n */\n public static short getShortBE(final ByteBuffer b, final int start, final int end) {\n return (short) getIntBE(b, start, end);\n }\n\n /**\n * Convert int to byte representation - Big Endian (as used by mp4).\n *\n * @param size\n * @return byte representation\n */\n public static byte[] getSizeBEInt32(final int size) {\n final byte[] b = new byte[4];\n b[0] = (byte) ((size >> 24) & 0xFF);\n b[1] = (byte) ((size >> 16) & 0xFF);\n b[2] = (byte) ((size >> 8) & 0xFF);\n b[3] = (byte) (size & 0xFF);\n return b;\n }\n\n /**\n * Convert short to byte representation - Big Endian (as used by mp4).\n *\n * @param size number to convert\n * @return byte representation\n */\n public static byte[] getSizeBEInt16(final short size) {\n final byte[] b = new byte[2];\n b[0] = (byte) ((size >> 8) & 0xFF);\n b[1] = (byte) (size & 0xFF);\n return b;\n }\n\n /**\n * Convert int to byte representation - Little Endian (as used by ogg vorbis).\n *\n * @param size number to convert\n * @return byte representation\n */\n public static byte[] getSizeLEInt32(final int size) {\n final byte[] b = new byte[4];\n b[0] = (byte) (size & 0xff);\n b[1] = (byte) ((size >>> 8) & 0xffL);\n b[2] = (byte) ((size >>> 16) & 0xffL);\n b[3] = (byte) ((size >>> 24) & 0xffL);\n return b;\n }\n\n /**\n * Convert a byte array to a Pascal string. The first byte is the byte count,\n * followed by that many active characters.\n *\n * @param bb\n * @return\n * @throws IOException\n */\n public static String readPascalString(final ByteBuffer bb) throws IOException {\n final int len = Utils.u(bb.get()); //Read as unsigned value\n final byte[] buf = new byte[len];\n bb.get(buf);\n return new String(buf, 0, len, ISO_8859_1);\n }\n\n /**\n * Reads bytes from a ByteBuffer as if they were encoded in the specified CharSet.\n *\n * @param buffer\n * @param offset offset from current position\n * @param length size of data to process\n * @param encoding\n * @return\n */\n public static String getString(final ByteBuffer buffer, final int offset, final int length, final Charset encoding) {\n final byte[] b = new byte[length];\n buffer.position(buffer.position() + offset);\n buffer.get(b);\n return new String(b, 0, length, encoding);\n }\n\n /**\n * Reads bytes from a ByteBuffer as if they were encoded in the specified CharSet.\n *\n * @param buffer\n * @param encoding\n * @return\n */\n public static String getString(final ByteBuffer buffer, final Charset encoding) {\n final byte[] b = new byte[buffer.remaining()];\n buffer.get(b);\n return new String(b, 0, b.length, encoding);\n }\n\n /**\n * Read a 32-bit big-endian unsigned integer using a DataInput.\n *

\n * Reads 4 bytes but returns as long\n */\n public static long readUint32(final DataInput di) throws IOException {\n final byte[] buf8 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};\n di.readFully(buf8, 4, 4);\n return ByteBuffer.wrap(buf8).getLong();\n }\n\n /**\n * Read a 16-bit big-endian unsigned integer.\n *

\n * Reads 2 bytes but returns as an integer\n */\n public static int readUint16(final DataInput di) throws IOException {\n final byte[] buf = {0x00, 0x00, 0x00, 0x00};\n di.readFully(buf, 2, 2);\n return ByteBuffer.wrap(buf).getInt();\n }\n\n\n /**\n * Read a string of a specified number of ASCII bytes.\n */\n public static String readString(final DataInput di, final int charsToRead) throws IOException {\n final byte[] buf = new byte[charsToRead];\n di.readFully(buf);\n return new String(buf, US_ASCII);\n }\n\n /**\n * Get a base for temp file, this should be long enough so that it easy to work out later what file the temp file\n * was created for if it is left lying round, but not ridiculously long as this can cause problems with max filename\n * limits and is not very useful.\n *\n * @param file\n * @return\n */\n public static String getBaseFilenameForTempFile(final File file) {\n final String filename = getMinBaseFilenameAllowedForTempFile(file);\n if (filename.length() <= MAX_BASE_TEMP_FILENAME_LENGTH) {\n return filename;\n }\n return filename.substring(0, MAX_BASE_TEMP_FILENAME_LENGTH);\n }\n\n /**\n * @param file\n * @return filename with audioformat separator stripped of, lengthened to ensure not too small for valid tempfile\n * creation.\n */\n public static String getMinBaseFilenameAllowedForTempFile(final File file) {\n final String s = AudioFile.getBaseFilename(file);\n if (s.length() >= 3) {\n return s;\n }\n if (s.length() == 1) {\n return s + \"000\";\n } else if (s.length() == 1) {\n return s + \"00\";\n } else if (s.length() == 2) {\n return s + \"0\";\n }\n return s;\n }\n\n /**\n * Rename file, and if normal rename fails, try copy and delete instead.\n *\n * @param fromFile\n * @param toFile\n * @return\n */\n public static boolean rename(final File fromFile, final File toFile) {\n logger.log(Level.CONFIG, \"Renaming From:\" + fromFile.getAbsolutePath() + \" to \" + toFile.getAbsolutePath());\n\n if (toFile.exists()) {\n logger.log(Level.SEVERE, \"Destination File:\" + toFile + \" already exists\");\n return false;\n }\n\n //Rename File, could fail because being used or because trying to rename over filesystems\n final boolean result = fromFile.renameTo(toFile);\n if (!result) {\n // Might be trying to rename over filesystem, so try copy and delete instead\n if (copy(fromFile, toFile)) {\n //If copy works but deletion of original file fails then it is because the file is being used\n //so we need to delete the file we have just created\n boolean deleteResult = fromFile.delete();\n if (!deleteResult) {\n logger.log(Level.SEVERE, \"Unable to delete File:\" + fromFile);\n toFile.delete();\n return false;\n }\n return true;\n } else {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Copy a File.\n *

\n * ToDo refactor AbstractTestCase to use this method as it contains an exact duplicate.\n *\n * @param fromFile The existing File\n * @param toFile The new File\n * @return true if and only if the renaming succeeded;\n * false otherwise\n */\n public static boolean copy(final File fromFile, final File toFile) {\n try {\n copyThrowsOnException(fromFile, toFile);\n return true;\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * Reads 4 bytes and concatenates them into a String.\n * This pattern is used for ID's of various kinds.\n *\n * @param bytes\n * @return\n * @throws IOException\n */\n public static String readFourBytesAsChars(final ByteBuffer bytes) {\n byte[] b = new byte[4];\n bytes.get(b);\n return new String(b, ISO_8859_1);\n }\n\n /**\n * Reads 3 bytes and concatenates them into a String.\n * This pattern is used for ID's of various kinds.\n *\n * @param bytes\n * @return\n */\n public static String readThreeBytesAsChars(final ByteBuffer bytes) {\n byte[] b = new byte[3];\n bytes.get(b);\n return new String(b, ISO_8859_1);\n }\n\n /**\n * Used to convert (signed integer) to an long as if signed integer was unsigned hence allowing\n * it to represent full range of integral values.\n *\n * @param n\n * @return\n */\n public static long u(final int n) {\n return n & 0xffffffffl;\n }\n\n /**\n * Used to convert (signed short) to an integer as if signed short was unsigned hence allowing\n * it to represent values 0 -> 65536 rather than -32786 -> 32786\n *\n * @param n\n * @return\n */\n public static int u(final short n) {\n return n & 0xffff;\n }\n\n /**\n * Used to convert (signed byte) to an integer as if signed byte was unsigned hence allowing\n * it to represent values 0 -> 255 rather than -128 -> 127.\n *\n * @param n\n * @return\n */\n public static int u(final byte n) {\n return n & 0xff;\n }\n\n /**\n * @param fc\n * @param size\n * @return\n * @throws IOException\n */\n public static ByteBuffer readFileDataIntoBufferLE(FileChannel fc, final int size) throws IOException {\n final ByteBuffer tagBuffer = ByteBuffer.allocateDirect(size);\n fc.read(tagBuffer);\n tagBuffer.position(0);\n tagBuffer.order(ByteOrder.LITTLE_ENDIAN);\n return tagBuffer;\n }\n\n /**\n * @param fc\n * @param size\n * @return\n * @throws IOException\n */\n public static ByteBuffer readFileDataIntoBufferBE(FileChannel fc, final int size) throws IOException {\n final ByteBuffer tagBuffer = ByteBuffer.allocateDirect(size);\n fc.read(tagBuffer);\n tagBuffer.position(0);\n tagBuffer.order(ByteOrder.BIG_ENDIAN);\n return tagBuffer;\n }\n\n /**\n * Copy src file to dst file. FileChannels are used to maximize performance.\n *\n * @param source source File\n * @param destination destination File which will be created or truncated, before copying, if it already exists\n * @throws IOException if any error occurS\n */\n public static void copyThrowsOnException(final File source, final File destination) throws IOException {\n // Must be done in a loop as there's no guarantee that a request smaller than request count will complete in one invocation.\n // Setting the transfer size more than about 1MB is pretty pointless because there is no asymptotic benefit. What you're trying\n // to achieve with larger transfer sizes is fewer context switches, and every time you double the transfer size you halve the\n // context switch cost. Pretty soon it vanishes into the noise.\n FileInputStream inStream = null;\n FileOutputStream outStream = null;\n try {\n inStream = new FileInputStream(source);\n outStream = new FileOutputStream(destination);\n final FileChannel inChannel = inStream.getChannel();\n final FileChannel outChannel = outStream.getChannel();\n final long size = inChannel.size();\n long position = 0;\n while (position < size) {\n position += inChannel.transferTo(position, 1024L * 1024L, outChannel);\n }\n } finally { //Closeables closed exiting try block in all circumstances\n AudioFileIO.closeQuietly(inStream, outStream);\n }\n }\n\n /**\n * @param length\n * @return true if length is an odd number\n */\n public static boolean isOddLength(long length) {\n if ((length & 1) != 0) {\n return true;\n }\n return false;\n }\n}\n\nandroid/src/main/java/org/jaudiotagger/tag/mp4/atom/Mp4MeanBox.java\npublic class Mp4MeanBox extends AbstractMp4Box\n{\n public static final String IDENTIFIER = \"mean\";\n\n private String issuer;\n\n //TODO Are these misnamed, are these version flag bytes or just null bytes\n public static final int VERSION_LENGTH = 1;\n public static final int FLAGS_LENGTH = 3;\n public static final int PRE_DATA_LENGTH = VERSION_LENGTH + FLAGS_LENGTH;\n\n /**\n * @param header parentHeader info\n * @param dataBuffer data of box (doesnt include parentHeader data)\n */\n public Mp4MeanBox(Mp4BoxHeader header, ByteBuffer dataBuffer)\n {\n this.header = header;\n\n //Double check\n if (!header.getId().equals(IDENTIFIER))\n {\n throw new RuntimeException(\"Unable to process data box because identifier is:\" + header.getId());\n }\n\n //Make slice so operations here don't effect position of main buffer\n this.dataBuffer = dataBuffer.slice();\n\n //issuer\n this.issuer = Utils.getString(this.dataBuffer, PRE_DATA_LENGTH, header.getDataLength() - PRE_DATA_LENGTH, header.getEncoding());\n\n }\n\n public String getIssuer()\n {\n return issuer;\n }\n}\n\nandroid/src/main/java/org/jaudiotagger/audio/mp4/atom/Mp4BoxHeader.java\npublic class Mp4BoxHeader\n{\n // Logger Object\n public static Logger logger = Logger.getLogger(\"org.jaudiotagger.audio.mp4.atom\");\n\n public static final int OFFSET_POS = 0;\n public static final int IDENTIFIER_POS = 4;\n public static final int OFFSET_LENGTH = 4;\n public static final int IDENTIFIER_LENGTH = 4;\n public static final int HEADER_LENGTH = OFFSET_LENGTH + IDENTIFIER_LENGTH;\n\n //Box identifier\n private String id;\n\n //Box length\n protected int length;\n\n //If reading from file , this can be used to hold the headers position in the file\n private long filePos;\n\n //Raw Header data\n protected ByteBuffer dataBuffer;\n\n //Mp4 uses UTF-8 for all text\n public static final String CHARSET_UTF_8 = \"UTF-8\";\n\n /**\n * Construct empty header\n *\n * Can be populated later with update method\n */\n public Mp4BoxHeader()\n {\n\n }\n\n /**\n * Construct header to allow manual creation of header for writing to file\n *\n * @param id\n */\n public Mp4BoxHeader(String id)\n {\n if(id.length()!=IDENTIFIER_LENGTH)\n {\n throw new RuntimeException(\"Invalid length:atom idenifier should always be 4 characters long\");\n }\n dataBuffer = ByteBuffer.allocate(HEADER_LENGTH);\n try\n {\n this.id = id;\n dataBuffer.put(4, id.getBytes(\"ISO-8859-1\")[0]);\n dataBuffer.put(5, id.getBytes(\"ISO-8859-1\")[1]);\n dataBuffer.put(6, id.getBytes(\"ISO-8859-1\")[2]);\n dataBuffer.put(7, id.getBytes(\"ISO-8859-1\")[3]);\n }\n catch(UnsupportedEncodingException uee)\n {\n //Should never happen\n throw new RuntimeException(uee);\n }\n }\n\n /**\n * Construct header\n *\n * Create header using headerdata, expected to find header at headerdata current position\n *\n * Note after processing adjusts position to immediately after header\n *\n * @param headerData\n */\n public Mp4BoxHeader(ByteBuffer headerData)\n {\n update(headerData);\n }\n\n /**\n * Create header using headerdata, expected to find header at headerdata current position\n *\n * Note after processing adjusts position to immediately after header\n *\n * @param headerData\n */\n public void update(ByteBuffer headerData)\n {\n //Read header data into byte array\n byte[] b = new byte[HEADER_LENGTH];\n headerData.get(b);\n //Keep reference to copy of RawData\n dataBuffer = ByteBuffer.wrap(b);\n dataBuffer.order(ByteOrder.BIG_ENDIAN);\n\n //Calculate box size and id\n this.length = dataBuffer.getInt();\n this.id = Utils.readFourBytesAsChars(dataBuffer);\n\n logger.finest(\"Mp4BoxHeader id:\"+id+\":length:\"+length);\n if (id.equals(\"\\0\\0\\0\\0\"))\n {\n throw new NullBoxIdException(ErrorMessage.MP4_UNABLE_TO_FIND_NEXT_ATOM_BECAUSE_IDENTIFIER_IS_INVALID.getMsg(id));\n }\n\n if(length fc.size())\n {\n return null;\n }\n headerBuffer.rewind();\n bytesRead = fc.read(headerBuffer);\n logger.finer(\"Header Bytes Read:\" + bytesRead);\n headerBuffer.rewind();\n if (bytesRead == Mp4BoxHeader.HEADER_LENGTH)\n {\n boxHeader.update(headerBuffer);\n }\n else\n {\n return null;\n }\n }\n return boxHeader;\n }\n\n\n /**\n * Seek for box with the specified id starting from the current location of filepointer,\n *\n * Note it won't find the box if it is contained with a level below the current level, nor if we are\n * at a parent atom that also contains data and we havent yet processed the data. It will work\n * if we are at the start of a child box even if it not the required box as long as the box we are\n * looking for is the same level (or the level above in some cases).\n *\n * @param data\n * @param id\n * @throws IOException\n * @return\n */\n public static Mp4BoxHeader seekWithinLevel(ByteBuffer data, String id) throws IOException\n {\n logger.finer(\"Started searching for:\" + id + \" in bytebuffer at\" + data.position());\n\n Mp4BoxHeader boxHeader = new Mp4BoxHeader();\n if (data.remaining() >= Mp4BoxHeader.HEADER_LENGTH)\n {\n boxHeader.update(data);\n }\n else\n {\n return null;\n }\n while (!boxHeader.getId().equals(id))\n {\n logger.finer(\"Found:\" + boxHeader.getId() + \" Still searching for:\" + id + \" in bytebuffer at\" + data.position());\n //Something gone wrong probably not at the start of an atom so return null;\n if (boxHeader.getLength() < Mp4BoxHeader.HEADER_LENGTH)\n {\n return null;\n }\n if(data.remaining()<(boxHeader.getLength() - HEADER_LENGTH))\n {\n //i.e Could happen if Moov header had size incorrectly recorded\n return null; \n }\n data.position(data.position() + (boxHeader.getLength() - HEADER_LENGTH));\n if (data.remaining() >= Mp4BoxHeader.HEADER_LENGTH)\n {\n boxHeader.update(data);\n }\n else\n {\n return null;\n }\n }\n logger.finer(\"Found:\" + id + \" in bytebuffer at\" + data.position());\n\n return boxHeader;\n }\n\n /**\n * @return location in file of the start of atom header (i.e where the 4 byte length field starts)\n */\n public long getFilePos()\n {\n return filePos;\n }\n\n /**\n *\n * @return location in file of the end of atom\n */\n public long getFileEndPos()\n {\n return filePos + length;\n }\n\n /**\n * Set location in file of the start of file header (i.e where the 4 byte length field starts)\n *\n * @param filePos\n */\n public void setFilePos(long filePos)\n {\n this.filePos = filePos;\n }\n}", "answers": [" return StandardCharsets.UTF_8;"], "length": 3908, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "24273ef3-2b56-45a5-930c-ba80574b0564", "reasoning": "The method getEncoding() is declared to return a Charset. In MP4 handling the encoding is always UTF‑8. The class already imports org.jaudiotagger.StandardCharsets, which provides a UTF_8 constant. Therefore the next line should return that constant.", "reasoning_model_answer": "return StandardCharsets.UTF_8;", "assistant_with_reasoning": "\nThe method getEncoding() is declared to return a Charset. In MP4 handling the encoding is always UTF‑8. The class already imports org.jaudiotagger.StandardCharsets, which provides a UTF_8 constant. Therefore the next line should return that constant.\n\nreturn StandardCharsets.UTF_8;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.989, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 32497, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return StandardCharsets.UTF_8;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "import org.msh.etbm.commons.commands.CommandTypes;\nimport org.msh.etbm.commons.entities.EntityServiceEvent;\nimport org.msh.etbm.commons.entities.EntityValidationException;\nimport org.msh.etbm.commons.entities.ServiceResult;\nimport org.msh.etbm.commons.entities.cmdlog.Operation;\nimport org.msh.etbm.commons.forms.FormInitResponse;\nimport org.msh.etbm.commons.forms.FormService;\nimport org.msh.etbm.commons.models.ModelDAO;\nimport org.msh.etbm.commons.models.ModelDAOFactory;\nimport org.msh.etbm.commons.models.ModelDAOResult;\nimport org.msh.etbm.commons.models.db.RecordData;\nimport org.msh.etbm.db.entities.TbCase;\nimport org.msh.etbm.db.enums.CaseClassification;\nimport org.msh.etbm.db.enums.DiagnosisType;\nimport org.msh.etbm.services.cases.cases.data.CaseEditFormData;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.stereotype.Service;\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\nimport javax.transaction.Transactional;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.UUID;", "context": "src/main/java/org/msh/etbm/services/cases/cases/CaseEditService.java\npackage org.msh.etbm.services.cases.cases;\n\n\n\n/**\n * Created by Mauricio on 03/10/2016.\n */\n@Service\npublic class CaseEditService extends CaseValidator {\n\n @Autowired\n FormService formService;\n\n @Autowired\n ModelDAOFactory factory;\n\n\nsrc/main/java/org/msh/etbm/commons/models/ModelDAOResult.java\npublic class ModelDAOResult {\n\n private UUID id;\n private Errors errors;\n\n public ModelDAOResult(UUID id, Errors errors) {\n this.id = id;\n this.errors = errors;\n }\n\n public Errors getErrors() {\n return errors;\n }\n\n public UUID getId() {\n return id;\n }\n}\n\nsrc/main/java/org/msh/etbm/commons/entities/EntityServiceEvent.java\npublic class EntityServiceEvent extends ApplicationEvent {\n\n private ServiceResult result;\n\n public EntityServiceEvent(Object source, ServiceResult result) {\n super(source);\n this.result = result;\n }\n\n public ServiceResult getResult() {\n return result;\n }\n\n public void setResult(ServiceResult result) {\n this.result = result;\n }\n}\n\nsrc/main/java/org/msh/etbm/db/enums/DiagnosisType.java\npublic enum DiagnosisType implements MessageKey {\n\n SUSPECT,\n CONFIRMED;\n\n @Override\n public String getMessageKey() {\n return getClass().getSimpleName().concat(\".\" + name());\n }\n\n}\n\nsrc/main/java/org/msh/etbm/commons/commands/CommandTypes.java\npublic class CommandTypes {\n\n private CommandTypes() {\n // avoid this class being instantiated inadvertently\n }\n\n // main group commands\n public static final String INIT = \"init\";\n public static final String PUBLIC = \"pub\";\n public static final String CASES = \"cases\";\n public static final String INVENTORY = \"inventory\";\n public static final String ADMIN = \"admin\";\n public static final String SESSION = \"session\";\n public static final String OFFLINE = \"offline\";\n\n // initialization command types\n public static final String INIT_REGWORKSPACE = \"init.regworkspace\";\n\n\n // admin command types\n public static final String ADMIN_USERS = \"admin.users\";\n public static final String ADMIN_USERS_CHANGE_PWD = \"admin.users.changepwd\";\n public static final String ADMIN_UNITS = \"admin.units\";\n public static final String ADMIN_ADMINUNITS = \"admin.adminunits\";\n public static final String ADMIN_COUNTRYSTRUCTURES = \"admin.countrystr\";\n public static final String ADMIN_SOURCES = \"admin.sources\";\n public static final String ADMIN_AGERANGES = \"admin.ageranges\";\n public static final String ADMIN_PRODUCTS = \"admin.products\";\n public static final String ADMIN_REGIMENS = \"admin.regimens\";\n public static final String ADMIN_SUBSTANCES = \"admin.substances\";\n public static final String ADMIN_TAGS = \"admin.tags\";\n public static final String ADMIN_USERPROFILES = \"admin.profiles\";\n public static final String ADMIN_WORKSPACES = \"admin.workspaces\";\n\n public static final String SYSTEM_SETUP = \"admin.syssetup\";\n\n // case module\n public static final String CASES_CASE = \"cases.case\";\n public static final String CASES_CASE_CLOSE = \"cases.case.close\";\n public static final String CASES_CASE_REOPEN = \"cases.case.reopen\";\n public static final String CASES_CASE_TAG = \"cases.case.manualtags\";\n public static final String CASES_CASE_VALIDATE = \"cases.case.validate\";\n public static final String CASES_CASE_TRANSFER_OUT = \"cases.case.transferout\";\n public static final String CASES_CASE_TRANSFER_IN = \"cases.case.transferin\";\n public static final String CASES_CASE_TRANSFER_ROLLBACK = \"cases.case.transferrollback\";\n public static final String CASES_CASE_COMMENT = \"cases.case.comment\";\n public static final String CASES_CASE_ISSUE = \"cases.case.issues\";\n public static final String CASES_CASE_ISSUEFOLLOWUP = \"cases.case.issuefollowups\";\n public static final String CASES_CASE_PREVTREAT = \"cases.case.prevtreat\";\n public static final String CASES_CASE_CONTACT = \"cases.case.contact\";\n public static final String CASES_CASE_SIDEEFFECT = \"cases.case.sideeffect\";\n public static final String CASES_CASE_MED_EXAM = \"cases.case.medexam\";\n public static final String CASES_CASE_EXAM_MIC = \"cases.case.exammic\";\n public static final String CASES_CASE_EXAM_CUL = \"cases.case.examcul\";\n public static final String CASES_CASE_EXAM_XPERT = \"cases.case.examxpert\";\n public static final String CASES_CASE_EXAM_DST = \"cases.case.examdst\";\n public static final String CASES_CASE_EXAM_HIV = \"cases.case.examhiv\";\n public static final String CASES_CASE_EXAM_XRAY = \"cases.case.examxray\";\n\n public static final String CASES_TREAT_FOLLOWUP = \"cases.case.treatfollowup\";\n public static final String CASES_TREAT_INI = \"cases.case.treatini\";\n public static final String CASES_TREAT_UNDO = \"cases.case.treatundo\";\n public static final String CASES_TREAT_EDIT = \"cases.case.treatedit\";\n public static final String CASES_TREAT_ADDMED = \"cases.case.treat-addmed\";\n public static final String CASES_TREAT_PRESCEDT = \"cases.case.treat-prescedt\";\n public static final String CASES_TREAT_PRESCDEL = \"cases.case.treat-prescdel\";\n\n // user session commands\n public static final String SESSION_USER_SETTINGS = \"session.usersettings\";\n public static final String SESSION_CHANGE_PWD = \"session.changepwd\";\n\n // commands used in CRUD operations\n public static final String CMD_CREATE = \"create\";\n public static final String CMD_UPDATE = \"update\";\n public static final String CMD_DELETE = \"delete\";\n\n // commands used in file synchronization\n public static final String OFFLINE_SERVERINIT = \"offline.serverinit\";\n public static final String OFFLINE_SERVERSYNC = \"offline.serversync\";\n public static final String OFFLINE_CLIENTINIT = \"offline.clientinit\";\n public static final String OFFLINE_CLIENTSYNC = \"offline.clientsync\";\n\n // the root of all command types (commands are organized in a tree way)\n public static final RootCommandType ROOT = new RootCommandType();\n\n /**\n * Initialize the list of command types\n */\n static {\n // main groups\n ROOT.add(INIT);\n ROOT.add(PUBLIC);\n ROOT.add(CASES);\n ROOT.add(INVENTORY);\n ROOT.add(ADMIN);\n ROOT.add(SESSION);\n ROOT.add(OFFLINE);\n\n // initialization\n ROOT.add(INIT_REGWORKSPACE);\n\n // administration module\n ROOT.addCRUD(ADMIN_ADMINUNITS);\n ROOT.addCRUD(ADMIN_COUNTRYSTRUCTURES);\n ROOT.addCRUD(ADMIN_UNITS);\n ROOT.addCRUD(ADMIN_SOURCES);\n ROOT.addCRUD(ADMIN_PRODUCTS);\n ROOT.addCRUD(ADMIN_REGIMENS);\n ROOT.addCRUD(ADMIN_SUBSTANCES);\n ROOT.addCRUD(ADMIN_TAGS);\n ROOT.addCRUD(ADMIN_USERS);\n ROOT.add(ADMIN_USERS_CHANGE_PWD);\n ROOT.addCRUD(ADMIN_USERPROFILES);\n ROOT.addCRUD(ADMIN_WORKSPACES);\n ROOT.addCRUD(ADMIN_AGERANGES);\n ROOT.add(SYSTEM_SETUP);\n\n // cases module\n ROOT.addCRUD(CASES_CASE);\n ROOT.add(CASES_CASE_CLOSE);\n ROOT.add(CASES_CASE_REOPEN);\n ROOT.add(CASES_CASE_TAG);\n ROOT.add(CASES_CASE_VALIDATE);\n ROOT.add(CASES_CASE_TRANSFER_OUT);\n ROOT.add(CASES_CASE_TRANSFER_IN);\n ROOT.add(CASES_CASE_TRANSFER_ROLLBACK);\n ROOT.addCRUD(CASES_CASE_PREVTREAT);\n ROOT.addCRUD(CASES_CASE_CONTACT);\n ROOT.addCRUD(CASES_CASE_SIDEEFFECT);\n ROOT.addCRUD(CASES_CASE_COMMENT);\n ROOT.addCRUD(CASES_CASE_ISSUE);\n ROOT.addCRUD(CASES_CASE_ISSUEFOLLOWUP);\n ROOT.addCRUD(CASES_CASE_MED_EXAM);\n ROOT.addCRUD(CASES_CASE_EXAM_MIC);\n ROOT.addCRUD(CASES_CASE_EXAM_CUL);\n ROOT.addCRUD(CASES_CASE_EXAM_XPERT);\n ROOT.addCRUD(CASES_CASE_EXAM_DST);\n ROOT.addCRUD(CASES_CASE_EXAM_HIV);\n ROOT.addCRUD(CASES_CASE_EXAM_XRAY);\n ROOT.add(CASES_TREAT_FOLLOWUP);\n ROOT.add(CASES_TREAT_UNDO);\n ROOT.add(CASES_TREAT_INI);\n ROOT.add(CASES_TREAT_EDIT);\n ROOT.add(CASES_TREAT_ADDMED);\n ROOT.add(CASES_TREAT_PRESCEDT);\n ROOT.add(CASES_TREAT_PRESCDEL);\n\n // user sessions\n ROOT.add(SESSION_USER_SETTINGS);\n ROOT.add(SESSION_CHANGE_PWD, \"changepwd\");\n\n // offline mode\n ROOT.add(OFFLINE_SERVERINIT);\n ROOT.add(OFFLINE_SERVERSYNC);\n ROOT.add(OFFLINE_CLIENTINIT);\n ROOT.add(OFFLINE_CLIENTSYNC);\n }\n\n\n /**\n * Return the {@link CommandType} by its name\n * @param name the full name of the command (path)\n * @return The instance of {@link CommandType} or raise a {@link CommandException} if command type is not found\n */\n public static CommandType get(String name) {\n CommandType cmd = ROOT.find(name);\n if (cmd == null) {\n throw new CommandException(\"Invalid command type: \" + name);\n }\n return cmd;\n }\n}\n\nsrc/main/java/org/msh/etbm/db/enums/CaseClassification.java\npublic enum CaseClassification implements MessageKey {\n TB,\n DRTB,\n NTM;\n\n @Override\n public String getMessageKey() {\n return getClass().getSimpleName().concat(\".\" + name());\n }\n\n public String getKeySuspect() {\n return getClass().getSimpleName().concat(\".\" + name() + \".suspect\");\n }\n\n public String getKeyConfirmed() {\n return getClass().getSimpleName().concat(\".\" + name() + \".confirmed\");\n }\n}\n\nsrc/main/java/org/msh/etbm/commons/models/ModelDAOFactory.java\n@Service\npublic class ModelDAOFactory {\n\n @Autowired\n ModelManager modelManager;\n\n @Autowired\n UserRequestService userRequestService;\n\n @Autowired\n DataSource dataSource;\n\n @Autowired\n Messages messages;\n\n @Value(\"${development:false}\")\n boolean development;\n\n /**\n * Create a new model DAO from a model name\n * @param modelName the name of the model to search for\n * @return instance of {@link ModelDAO}\n */\n public ModelDAO create(String modelName) {\n CompiledModel compiledModel = modelManager.getCompiled(modelName);\n\n UUID wsId = userRequestService.getUserSession().getWorkspaceId();\n ModelResources resources = new ModelResources(dataSource, messages, wsId, development);\n\n return new ModelDAO(compiledModel, resources);\n }\n}\n\nsrc/main/java/org/msh/etbm/commons/forms/FormInitResponse.java\npublic class FormInitResponse {\n\n /**\n * The document to be edited\n */\n private Map doc;\n\n /**\n * The resources to initialize the controls\n */\n private Map resources;\n\n /**\n * The form schema, with list of controls, validators and defaultProperties\n */\n private String schema;\n\n public Map getDoc() {\n return doc;\n }\n\n public void setDoc(Map doc) {\n this.doc = doc;\n }\n\n public Map getResources() {\n return resources;\n }\n\n public void setResources(Map resources) {\n this.resources = resources;\n }\n\n public String getSchema() {\n return schema;\n }\n\n public void setSchema(String schema) {\n this.schema = schema;\n }\n}\n\nsrc/main/java/org/msh/etbm/commons/entities/EntityValidationException.java\npublic class EntityValidationException extends RuntimeException {\n\n private transient final Errors bindingResult;\n\n /**\n * Constructor when there is just one single validation error message\n *\n * @param field\n * @param message\n * @param code\n */\n public EntityValidationException(Object entity, String field, String message, String code) {\n super(message);\n\n this.bindingResult = new BeanPropertyBindingResult(entity, entity.getClass().getSimpleName());\n if (message != null) {\n this.bindingResult.reject(field, message);\n } else {\n this.bindingResult.rejectValue(field, code);\n }\n }\n\n /**\n * Constructor when there is just one single validation error message\n *\n * @param field\n * @param message\n * @param code\n */\n public EntityValidationException(Map entity, String field, String message, String code) {\n super(message);\n\n this.bindingResult = new MapBindingResult(entity, \"target\");\n if (message != null) {\n this.bindingResult.reject(field, message);\n } else {\n this.bindingResult.rejectValue(field, code);\n }\n }\n\n /**\n * Constructor when validation messages are already in the binding result object\n *\n * @param bindingResult instance of BindingResult object containing validation messages\n */\n public EntityValidationException(Errors bindingResult) {\n super();\n this.bindingResult = bindingResult;\n }\n\n public Errors getBindingResult() {\n return bindingResult;\n }\n\n @Override\n public String getMessage() {\n if (bindingResult == null) {\n return super.getMessage();\n }\n\n return bindingResult.toString();\n }\n}\n\nsrc/main/java/org/msh/etbm/db/entities/TbCase.java\n@Entity\n@Inheritance(strategy = InheritanceType.JOINED)\n@Table(name = \"tbcase\")\npublic class TbCase extends WorkspaceEntity {\n\n @PropertyLog(messageKey = \"CaseClassification\")\n private CaseClassification suspectClassification;\n\n /**\n * The code of the patient at the moment of registration (presumptive code)\n */\n @Column(length = 50)\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private String registrationNumber;\n\n private String caseNumber;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"PATIENT_ID\")\n @NotNull\n @PropertyLog(operations = {Operation.ALL})\n private Patient patient;\n\n private Integer age;\n\n /**\n * The date the patient was registered in the unit. If before the diagnosis date, this period\n * between this date and the diagnosis date is considered the period the patient was a suspect\n */\n @NotNull\n @Temporal(TemporalType.DATE)\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private Date registrationDate;\n\n @Temporal(TemporalType.DATE)\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private Date diagnosisDate;\n\n @Temporal(TemporalType.DATE)\n private Date outcomeDate;\n\n // Treatment information\n @Embedded\n @AttributeOverrides({\n @AttributeOverride(name = \"iniDate\", column = @Column(name = \"iniTreatmentDate\")),\n @AttributeOverride(name = \"endDate\", column = @Column(name = \"endTreatmentDate\"))\n })\n @PropertyLog(operations = {Operation.ALL}, addProperties = true)\n private Period treatmentPeriod = new Period();\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"REGIMEN_ID\")\n private Regimen regimen;\n\n private boolean movedToIndividualized;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"OWNER_UNIT_ID\")\n @NotNull\n private Tbunit ownerUnit;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"TRANSFER_OUT_UNIT_ID\")\n private Tbunit transferOutUnit;\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\")\n @PropertyLog(ignore = true)\n private List treatmentUnits = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\")\n @PropertyLog(ignore = true)\n private List prescriptions = new ArrayList<>();\n\n @NotNull\n private CaseState state;\n\n @NotNull\n private boolean validated;\n\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private String registrationGroup;\n\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private CaseDefinition caseDefinition;\n\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private DiagnosisType diagnosisType;\n\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE}, messageKey = \"DrugResistanceType\")\n private String drugResistanceType;\n\n @NotNull\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private CaseClassification classification;\n\n @PropertyLog(messageKey = \"InfectionSite\", operations = {Operation.NEW})\n private InfectionSite infectionSite;\n\n @Column(length = 50)\n private String pulmonaryType;\n\n @Column(length = 50)\n private String extrapulmonaryType;\n\n @Column(length = 50)\n private String extrapulmonaryType2;\n\n @Column(length = 100)\n private String registrationGroupOther;\n\n @Column(length = 50)\n @PropertyLog(messageKey = \"Nationality\")\n private String nationality;\n\n @Column(length = 50)\n private String outcome;\n\n /**\n * If true, case is being transferred to another unit\n */\n private boolean transferring;\n\n @Column(length = 100)\n private String otherOutcome;\n\n @Column(length = 50)\n @PropertyLog(messageKey = \"form.customId\")\n private String customId;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"NOTIFICATION_UNIT_ID\")\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private Tbunit notificationUnit;\n\n private boolean movedSecondLineTreatment;\n\n @Column(length = 100)\n private String patientContactName;\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List comments = new ArrayList<>();\n\n @Embedded\n @AttributeOverrides({\n @AttributeOverride(name = \"address\", column = @Column(name = \"NOTIF_ADDRESS\")),\n @AttributeOverride(name = \"complement\", column = @Column(name = \"NOTIF_COMPLEMENT\")),\n @AttributeOverride(name = \"zipCode\", column = @Column(name = \"NOTIF_ZIPCODE\")),\n })\n @AssociationOverrides({\n @AssociationOverride(name = \"adminUnit\", joinColumns = @JoinColumn(name = \"NOTIF_ADMINUNIT_ID\"))\n })\n @PropertyLog(messageKey = \"cases.details.addressnotif\", operations = {Operation.NEW})\n private Address notifAddress;\n\n @Embedded\n @AttributeOverrides({\n @AttributeOverride(name = \"address\", column = @Column(name = \"CURR_ADDRESS\")),\n @AttributeOverride(name = \"complement\", column = @Column(name = \"CURR_COMPLEMENT\")),\n @AttributeOverride(name = \"zipCode\", column = @Column(name = \"CURR_ZIPCODE\")),\n })\n @AssociationOverrides({\n @AssociationOverride(name = \"adminUnit\", joinColumns = @JoinColumn(name = \"CURR_ADMINUNIT_ID\"))\n })\n @PropertyLog(messageKey = \"cases.details.addresscurr\")\n private Address currentAddress;\n\n @Column(name = \"NOTIF_LOCALITYTYPE\")\n private LocalityType localityType;\n\n @Column(length = 50)\n private String phoneNumber;\n\n @Column(length = 50)\n @PropertyLog(messageKey = \"global.mobile\")\n private String mobileNumber;\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List sideEffects = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @OrderBy(\"date desc\")\n @PropertyLog(ignore = true)\n private List examinations = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List resXRay = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(messageKey = \"cases.contacts\")\n private List contacts = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List treatmentMonitoring = new ArrayList<>();\n\n /* EXAMS */\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List resHIV = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List examsCulture = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n @OrderBy(value = \"date\")\n private List examsMicroscopy = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List examsDST = new ArrayList<>();\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n @OrderBy(value = \"date\")\n private List examsXpert = new ArrayList<>();\n\n @PropertyLog(ignore = true)\n private SecDrugsReceived secDrugsReceived;\n\n @Temporal(TemporalType.DATE)\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private Date lastBmuDateTbRegister;\n\n @Column(length = 50)\n @PropertyLog(operations = {Operation.NEW, Operation.DELETE})\n private String lastBmuTbRegistNumber;\n\n @OneToMany(cascade = {CascadeType.ALL}, mappedBy = \"tbcase\", fetch = FetchType.LAZY)\n @PropertyLog(ignore = true)\n private List issues = new ArrayList<>();\n\n /**\n * Tags of this case\n */\n @ManyToMany(fetch = FetchType.LAZY)\n @JoinTable(name = \"tags_case\",\n joinColumns = {@JoinColumn(name = \"CASE_ID\")},\n inverseJoinColumns = {@JoinColumn(name = \"TAG_ID\")})\n @PropertyLog(ignore = true)\n private List tags = new ArrayList<>();\n\n @OneToOne(cascade = {CascadeType.REMOVE}, fetch = FetchType.EAGER, mappedBy = \"tbCase\")\n @PropertyLog(ignore = true)\n private CaseComorbidities comorbidities;\n\n /**\n * Return number of month of treatment based on the date\n *\n * @param date\n * @return\n */\n public int getMonthTreatment(Date date) {\n if ((treatmentPeriod == null) || (date == null)) {\n return -1;\n }\n\n Date dtTreat = getTreatmentPeriod().getIniDate();\n if ((dtTreat == null) || (date.before(dtTreat))) {\n return -1;\n }\n\n return DateUtils.monthsBetween(date, dtTreat) + 1;\n }\n\n\n /**\n * Returns if the case is validated or not\n *\n * @return true - if the case is validated, false - otherwise\n */\n public boolean isValidated() {\n return this.validated;\n }\n\n /**\n * Returns if the case is a pulmonary TB/MDRTB\n *\n * @return - true if it is pulmonary or pulmonary/extrapulmonary\n */\n public boolean isPulmonary() {\n return (getInfectionSite() != null) && ((infectionSite == InfectionSite.PULMONARY) || (infectionSite == InfectionSite.BOTH));\n }\n\n\n /**\n * Returns if the case is a extrapulmonary TB/MDRTB\n *\n * @return - true if it is extrapulmonary or pulmonary/extrapulmonary\n */\n public boolean isExtrapulmonary() {\n return (getInfectionSite() != null) && ((infectionSite == InfectionSite.EXTRAPULMONARY) || (infectionSite == InfectionSite.BOTH));\n }\n\n /**\n * Search for side effect data by the side effect\n *\n * @param sideEffect - FieldValue object representing the side effect\n * @return - CaseSideEffect instance containing side effect data of the case, or null if there is no side effect data\n */\n public CaseSideEffect findSideEffectData(String sideEffect) {\n for (CaseSideEffect se : getSideEffects()) {\n if (se.getSideEffect().equals(sideEffect)) {\n return se;\n }\n }\n return null;\n }\n\n\n /**\n * @return the sideEffects\n */\n public List getSideEffects() {\n return sideEffects;\n }\n\n\n /**\n * @param sideEffects the sideEffects to set\n */\n public void setSideEffects(List sideEffects) {\n this.sideEffects = sideEffects;\n }\n\n\n /**\n * Check if the case is open\n *\n * @return\n */\n public boolean isOpen() {\n return state != CaseState.CLOSED;\n }\n\n\n /**\n * Is case on treatment ?\n *\n * @return\n */\n public boolean isOnTreatment() {\n return state == CaseState.ONTREATMENT;\n }\n\n /**\n * Calculates the age based on birthDate and registrationDate\n * @return\n */\n public int getUpdatedAge() {\n Patient p = getPatient();\n if (p == null) {\n return 0;\n }\n\n Date dt = p.getBirthDate();\n Date dt2 = registrationDate;\n\n if (dt == null) {\n return 0;\n }\n\n if (dt2 == null) {\n dt2 = new Date();\n }\n\n return DateUtils.yearsBetween(dt, dt2);\n }\n\n public Patient getPatient() {\n return patient;\n }\n\n public void setPatient(Patient patient) {\n this.patient = patient;\n }\n\n public CaseState getState() {\n return state;\n }\n\n public void setState(CaseState state) {\n this.state = state;\n }\n\n public List getTreatmentUnits() {\n return treatmentUnits;\n }\n\n public void setTreatmentUnits(List treatmentUnits) {\n this.treatmentUnits = treatmentUnits;\n }\n\n public List getResHIV() {\n return resHIV;\n }\n\n\n public void setResHIV(List resHIV) {\n this.resHIV = resHIV;\n }\n\n\n public List getExaminations() {\n return examinations;\n }\n\n\n public void setExaminations(List examinations) {\n this.examinations = examinations;\n }\n\n\n public CaseClassification getClassification() {\n return classification;\n }\n\n\n public void setClassification(CaseClassification classification) {\n this.classification = classification;\n }\n\n\n public InfectionSite getInfectionSite() {\n return infectionSite;\n }\n\n\n public void setInfectionSite(InfectionSite infectionSite) {\n this.infectionSite = infectionSite;\n }\n\n public List getComments() {\n return comments;\n }\n\n public void setComments(List comments) {\n this.comments = comments;\n }\n\n public Address getNotifAddress() {\n if (notifAddress == null) {\n notifAddress = new Address();\n }\n\n return notifAddress;\n }\n\n\n public void setNotifAddress(Address notifAddress) {\n this.notifAddress = notifAddress;\n }\n\n\n public Address getCurrentAddress() {\n if (currentAddress == null) {\n currentAddress = new Address();\n }\n\n return currentAddress;\n }\n\n public void setCurrentAddress(Address currentAddress) {\n this.currentAddress = currentAddress;\n }\n\n public String getOutcome() {\n return outcome;\n }\n\n public void setOutcome(String outcome) {\n this.outcome = outcome;\n }\n\n public String getOtherOutcome() {\n return otherOutcome;\n }\n\n public void setOtherOutcome(String otherOutcome) {\n this.otherOutcome = otherOutcome;\n }\n\n public String getRegistrationGroup() {\n return registrationGroup;\n }\n\n public void setRegistrationGroup(String registrationGroup) {\n this.registrationGroup = registrationGroup;\n }\n\n public String getNationality() {\n return nationality;\n }\n\n\n public void setNationality(String nationality) {\n this.nationality = nationality;\n }\n\n\n public Tbunit getNotificationUnit() {\n return notificationUnit;\n }\n\n\n public void setNotificationUnit(Tbunit notificationUnit) {\n this.notificationUnit = notificationUnit;\n }\n\n\n public Date getDiagnosisDate() {\n return diagnosisDate;\n }\n\n\n public void setDiagnosisDate(Date diagnosisDate) {\n this.diagnosisDate = diagnosisDate;\n }\n\n\n public Date getOutcomeDate() {\n return outcomeDate;\n }\n\n\n public void setOutcomeDate(Date outcomeDate) {\n this.outcomeDate = outcomeDate;\n }\n\n public String getRegistrationGroupOther() {\n return registrationGroupOther;\n }\n\n public void setRegistrationGroupOther(String registrationGroupOther) {\n this.registrationGroupOther = registrationGroupOther;\n }\n\n /**\n * @return the resXRay\n */\n public List getResXRay() {\n return resXRay;\n }\n\n\n /**\n * @param resXRay the resXRay to set\n */\n public void setResXRay(List resXRay) {\n this.resXRay = resXRay;\n }\n\n\n /**\n * @return the age\n */\n public Integer getAge() {\n return age;\n }\n\n\n /**\n * @param age the age to set\n */\n public void setAge(Integer age) {\n this.age = age;\n }\n\n\n /**\n * @return the registrationDate\n */\n public Date getRegistrationDate() {\n return registrationDate;\n }\n\n /**\n * @param registrationDate the registrationDate to set\n */\n public void setRegistrationDate(Date registrationDate) {\n this.registrationDate = registrationDate;\n }\n\n\n /**\n * @param diagnosisType the diagnosisType to set\n */\n public void setDiagnosisType(DiagnosisType diagnosisType) {\n this.diagnosisType = diagnosisType;\n }\n\n\n /**\n * @return the diagnosisType\n */\n public DiagnosisType getDiagnosisType() {\n return diagnosisType;\n }\n\n\n /**\n * @return the registrationCode\n */\n public String getRegistrationNumber() {\n return registrationNumber;\n }\n\n\n /**\n * @param registrationCode the registrationCode to set\n */\n public void setRegistrationNumber(String registrationCode) {\n this.registrationNumber = registrationCode;\n }\n\n\n /**\n * @return the drugResistanceType\n */\n public String getDrugResistanceType() {\n return drugResistanceType;\n }\n\n\n /**\n * @param drugResistanceType the drugResistanceType to set\n */\n public void setDrugResistanceType(String drugResistanceType) {\n this.drugResistanceType = drugResistanceType;\n }\n\n /**\n * @return the patientContactName\n */\n public String getPatientContactName() {\n return patientContactName;\n }\n\n\n /**\n * @param patientContactName the patientContactName to set\n */\n public void setPatientContactName(String patientContactName) {\n this.patientContactName = patientContactName;\n }\n\n\n /**\n * @return the contacts\n */\n public List getContacts() {\n return contacts;\n }\n\n\n /**\n * @param contacts the contacts to set\n */\n public void setContacts(List contacts) {\n this.contacts = contacts;\n }\n\n\n /**\n * @return the pulmonaryType\n */\n public String getPulmonaryType() {\n return pulmonaryType;\n }\n\n\n /**\n * @param pulmonaryType the pulmonaryType to set\n */\n public void setPulmonaryType(String pulmonaryType) {\n this.pulmonaryType = pulmonaryType;\n }\n\n\n /**\n * @return the extrapulmonaryType\n */\n public String getExtrapulmonaryType() {\n return extrapulmonaryType;\n }\n\n\n /**\n * @param extrapulmonaryType the extrapulmonaryType to set\n */\n public void setExtrapulmonaryType(String extrapulmonaryType) {\n this.extrapulmonaryType = extrapulmonaryType;\n }\n\n\n /**\n * @return the extrapulmonaryType2\n */\n public String getExtrapulmonaryType2() {\n return extrapulmonaryType2;\n }\n\n\n /**\n * @param extrapulmonaryType2 the extrapulmonaryType2 to set\n */\n public void setExtrapulmonaryType2(String extrapulmonaryType2) {\n this.extrapulmonaryType2 = extrapulmonaryType2;\n }\n\n\n\n /**\n * @return the phoneNumber\n */\n public String getPhoneNumber() {\n return phoneNumber;\n }\n\n\n /**\n * @param phoneNumber the phoneNumber to set\n */\n public void setPhoneNumber(String phoneNumber) {\n this.phoneNumber = phoneNumber;\n }\n\n\n /**\n * @return the mobileNumber\n */\n public String getMobileNumber() {\n return mobileNumber;\n }\n\n\n /**\n * @param mobileNumber the mobileNumber to set\n */\n public void setMobileNumber(String mobileNumber) {\n this.mobileNumber = mobileNumber;\n }\n\n public void setValidated(boolean validated) {\n this.validated = validated;\n }\n\n public List getPrescriptions() {\n return prescriptions;\n }\n\n public void setPrescriptions(List prescriptions) {\n this.prescriptions = prescriptions;\n }\n\n public Period getTreatmentPeriod() {\n return treatmentPeriod;\n }\n\n\n public void setTreatmentPeriod(Period treatmentPeriod) {\n this.treatmentPeriod = treatmentPeriod;\n }\n\n\n\n public List getExamsCulture() {\n return examsCulture;\n }\n\n\n public void setExamsCulture(List examsCulture) {\n this.examsCulture = examsCulture;\n }\n\n\n public List getExamsMicroscopy() {\n return examsMicroscopy;\n }\n\n\n public void setExamsMicroscopy(List examsMicroscopy) {\n this.examsMicroscopy = examsMicroscopy;\n }\n\n\n public List getExamsDST() {\n return examsDST;\n }\n\n\n public void setExamsDST(List examsDST) {\n this.examsDST = examsDST;\n }\n\n\n /**\n * @return the regimen\n */\n public Regimen getRegimen() {\n return regimen;\n }\n\n\n /**\n * @param regimen the regimen to set\n */\n public void setRegimen(Regimen regimen) {\n this.regimen = regimen;\n }\n\n\n /**\n * @return the ownerUnit\n */\n public Tbunit getOwnerUnit() {\n return ownerUnit;\n }\n\n\n /**\n * @param ownerUnit the ownerUnit to set\n */\n public void setOwnerUnit(Tbunit ownerUnit) {\n this.ownerUnit = ownerUnit;\n }\n\n public Tbunit getTransferOutUnit() {\n return transferOutUnit;\n }\n\n public void setTransferOutUnit(Tbunit transferOutUnit) {\n this.transferOutUnit = transferOutUnit;\n }\n\n /**\n * @return the tags\n */\n public List getTags() {\n return tags;\n }\n\n\n /**\n * @param tags the tags to set\n */\n public void setTags(List tags) {\n this.tags = tags;\n }\n\n public List getIssues() {\n return issues;\n }\n\n public void setIssues(List issues) {\n this.issues = issues;\n }\n\n\n public String getCaseNumber() {\n return caseNumber;\n }\n\n public void setCaseNumber(String caseNumber) {\n this.caseNumber = caseNumber;\n }\n\n /**\n * @return the suspectClassification\n */\n public CaseClassification getSuspectClassification() {\n return suspectClassification;\n }\n\n\n /**\n * @param suspectClassification the suspectClassification to set\n */\n public void setSuspectClassification(CaseClassification suspectClassification) {\n this.suspectClassification = suspectClassification;\n }\n\n /**\n * @return the treatmentMonitoring\n */\n public List getTreatmentMonitoring() {\n return treatmentMonitoring;\n }\n\n /**\n * @param treatmentMonitoring the treatmentMonitoring to set\n */\n public void setTreatmentMonitoring(List treatmentMonitoring) {\n this.treatmentMonitoring = treatmentMonitoring;\n }\n\n public List getExamsXpert() {\n return examsXpert;\n }\n\n public void setExamsXpert(List examsXpert) {\n this.examsXpert = examsXpert;\n }\n\n public void setSecDrugsReceived(SecDrugsReceived secDrugsReceived) {\n this.secDrugsReceived = secDrugsReceived;\n }\n\n public SecDrugsReceived getSecDrugsReceived() {\n return this.secDrugsReceived;\n }\n\n public CaseDefinition getCaseDefinition() {\n return caseDefinition;\n }\n\n public void setCaseDefinition(CaseDefinition caseDefinition) {\n this.caseDefinition = caseDefinition;\n }\n\n public CaseComorbidities getComorbidities() {\n return comorbidities;\n }\n\n public void setComorbidities(CaseComorbidities comorbidities) {\n this.comorbidities = comorbidities;\n }\n\n public Date getLastBmuDateTbRegister() {\n return lastBmuDateTbRegister;\n }\n\n public void setLastBmuDateTbRegister(Date lastBmuDateTbRegister) {\n this.lastBmuDateTbRegister = lastBmuDateTbRegister;\n }\n\n public String getLastBmuTbRegistNumber() {\n return lastBmuTbRegistNumber;\n }\n\n public void setLastBmuTbRegistNumber(String lastBmuTbRegistNumber) {\n this.lastBmuTbRegistNumber = lastBmuTbRegistNumber;\n }\n\n public boolean isMovedSecondLineTreatment() {\n return movedSecondLineTreatment;\n }\n\n public void setMovedSecondLineTreatment(boolean movedSecondLineTreatment) {\n this.movedSecondLineTreatment = movedSecondLineTreatment;\n }\n\n public String getCustomId() {\n return customId;\n }\n\n public void setCustomId(String customId) {\n this.customId = customId;\n }\n\n public LocalityType getLocalityType() {\n return localityType;\n }\n\n public void setLocalityType(LocalityType localityType) {\n this.localityType = localityType;\n }\n\n @Override\n public String getDisplayString() {\n return \"(\" + classification + \") \" + patient.getDisplayString();\n }\n\n public boolean isMovedToIndividualized() {\n return movedToIndividualized;\n }\n\n public void setMovedToIndividualized(boolean movedToIndividualized) {\n this.movedToIndividualized = movedToIndividualized;\n }\n\n public boolean isTransferring() {\n return transferring;\n }\n\n public void setTransferring(boolean transferring) {\n this.transferring = transferring;\n }\n\n /**\n * Return list of treatment health units sorted by period\n * @return\n */\n public List getSortedTreatmentHealthUnits() {\n // sort the periods\n Collections.sort(treatmentUnits, new Comparator() {\n public int compare(TreatmentHealthUnit o1, TreatmentHealthUnit o2) {\n return o1.getPeriod().getIniDate().compareTo(o2.getPeriod().getIniDate());\n }\n });\n\n return treatmentUnits;\n }\n\n /**\n * Return move date during the transference\n * @return\n */\n public Date getMoveDate() {\n List sortedHU = getSortedTreatmentHealthUnits();\n\n if (!isTransferring() || sortedHU == null || sortedHU.size() < 1) {\n return null;\n }\n\n return sortedHU.get(sortedHU.size() - 1 ).getPeriod().getIniDate();\n }\n}", "answers": [" @PersistenceContext"], "length": 3609, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "993fb76c-bc15-4ef1-b015-0b1b4baa1b8a", "reasoning": "After the import statements, the service class will need to inject the JPA EntityManager. In this project services typically declare an EntityManager field annotated with @PersistenceContext. The very next line after the imports is therefore the annotation line that starts this field declaration.", "reasoning_model_answer": "@PersistenceContext", "assistant_with_reasoning": "\nAfter the import statements, the service class will need to inject the JPA EntityManager. In this project services typically declare an EntityManager field annotated with @PersistenceContext. The very next line after the imports is therefore the annotation line that starts this field declaration.\n\n@PersistenceContext", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.474, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37160, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "@PersistenceContext", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.extendedclip.deluxemenus.DeluxeMenus;\r\nimport com.extendedclip.deluxemenus.menu.Menu;\r\nimport com.extendedclip.deluxemenus.menu.MenuHolder;\r\nimport com.extendedclip.deluxemenus.utils.AdventureUtils;\r\nimport com.extendedclip.deluxemenus.utils.DebugLevel;\r\nimport com.extendedclip.deluxemenus.utils.ExpUtils;\r\nimport com.extendedclip.deluxemenus.utils.StringUtils;\r\nimport com.extendedclip.deluxemenus.utils.VersionHelper;\r\nimport java.util.logging.Level;\r\nimport me.clip.placeholderapi.PlaceholderAPI;\r\nimport net.kyori.adventure.Adventure;\r\nimport net.kyori.adventure.text.minimessage.MiniMessage;\r\nimport org.bukkit.Bukkit;\r\nimport org.bukkit.OfflinePlayer;\r\nimport org.bukkit.Sound;\r\nimport org.bukkit.entity.Player;\r\nimport org.bukkit.event.player.PlayerCommandPreprocessEvent;\r\nimport org.bukkit.scheduler.BukkitRunnable;\r\nimport org.jetbrains.annotations.NotNull;\r", "context": "src/main/java/com/extendedclip/deluxemenus/action/ClickActionTask.java\n final String executable = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, exec);\r\n final MenuHolder holder = Menu.getMenuHolder(player);\r\n\r\n switch (actionType) {\r\n case META:\r\n if (!VersionHelper.IS_PDC_VERSION || DeluxeMenus.getInstance().getPersistentMetaHandler() == null) {\r\n DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, \"Meta action not supported on this server version.\");\r\n break;\r\n }\r\n try {\r\n final boolean result = DeluxeMenus.getInstance().getPersistentMetaHandler().setMeta(player, executable);\r\n if (!result) {\r\n DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, \"Invalid meta action! Make sure you have the right syntax.\");\r\n break;\r\n }\r\n } catch (final NumberFormatException exception) {\r\n DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, \"Invalid integer value for meta action!\");\r\n }\r\n break;\r\n\r\n case PLAYER:\r\n player.chat(\"/\" + executable);\r\n break;\r\n\r\n case PLAYER_COMMAND_EVENT:\r\n Bukkit.getPluginManager().callEvent(new PlayerCommandPreprocessEvent(player, \"/\" + executable));\r\n break;\r\n\r\n case PLACEHOLDER:\r\n PlaceholderAPI.setPlaceholders(player, executable);\r\n break;\r\n\r\n case CHAT:\r\n player.chat(executable);\r\n break;\r\n\r\n case CONSOLE:\r\n Bukkit.dispatchCommand(Bukkit.getConsoleSender(), executable);\r\n break;\r\n\r\n case MINI_MESSAGE:\r\n plugin.adventure().player(player).sendMessage(MiniMessage.miniMessage().deserialize(executable));\r\n break;\r\n\r\n case MINI_BROADCAST:\r\n plugin.adventure().all().sendMessage(MiniMessage.miniMessage().deserialize(executable));\r\n break;\r\n\r\n case MESSAGE:\r\n player.sendMessage(StringUtils.color(executable));\r\n break;\r\n\r\n case BROADCAST:\r\n Bukkit.broadcastMessage(StringUtils.color(executable));\r\n break;\r\n\r\n case CLOSE:\r\n Menu.closeMenu(player, true, true);\r\n break;\r\n\r\n case OPEN_GUI_MENU:\r\n case OPEN_MENU:\r\n final Menu menuToOpen = Menu.getMenu(executable);\r\n if (menuToOpen == null) {\r\n DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, \"Could not find and open menu \" + executable);\r\n break;\r\n }\r\n\r\n if (holder == null) {\r\n menuToOpen.openMenu(player);\r\n break;\r\n }\r\n\r\n menuToOpen.openMenu(player, holder.getTypedArgs(), holder.getPlaceholderPlayer());\r\n break;\r\n\r\n case CONNECT:\r\n DeluxeMenus.getInstance().connect(player, executable);\r\n break;\r\n\r\n case JSON_MESSAGE:\r\n AdventureUtils.sendJson(player, executable);\r\n break;\r\n\r\n case JSON_BROADCAST:\r\n case BROADCAST_JSON:\r\n plugin.adventure().all().sendMessage(AdventureUtils.fromJson(executable));\r\n break;\r\n\r\n case REFRESH:\r\n if (holder == null) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n player.getName() + \" does not have menu open! Nothing to refresh!\"\r\n );\r\n break;\r\n }\r\n\r\n holder.refreshMenu();\r\n break;\r\n\r\n case TAKE_MONEY:\r\n if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {\r\n DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, \"Vault not hooked! Cannot take money!\");\r\n break;\r\n }\r\n\r\n try {\r\n DeluxeMenus.getInstance().getVault().takeMoney(player, Double.parseDouble(executable));\r\n } catch (final NumberFormatException exception) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Amount for take money action: \" + executable + \", is not a valid number!\"\r\n );\r\n }\r\n break;\r\n\r\n case GIVE_MONEY:\r\n\nsrc/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java\npublic class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMap(Enum::name, Function.identity()));\r\n private static DeluxeMenus instance;\r\n private static DebugLevel debugLevel = DebugLevel.LOWEST;\r\n private DeluxeMenusConfig menuConfig;\r\n private Map itemHooks;\r\n private VaultHook vaultHook;\r\n private boolean checkUpdates;\r\n private ItemStack head;\r\n private PersistentMetaHandler persistentMetaHandler;\r\n private MenuItemMarker menuItemMarker;\r\n private DupeFixer dupeFixer;\r\n private BukkitAudiences adventure;\r\n\r\n @Override\r\n public void onLoad() {\r\n instance = this;\r\n\r\n this.persistentMetaHandler = new PersistentMetaHandler();\r\n \r\n if (NbtProvider.isAvailable()) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"NMS hook has been setup successfully!\"\r\n );\r\n return;\r\n }\r\n\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Could not setup a NMS hook for your server version!\"\r\n );\r\n }\r\n\r\n @SuppressWarnings(\"deprecation\")\r\n @Override\r\n public void onEnable() {\r\n if (!hookPlaceholderAPI()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.SEVERE,\r\n \"Could not hook into PlaceholderAPI!\",\r\n \"DeluxeMenus will now disable!\"\r\n );\r\n Bukkit.getPluginManager().disablePlugin(this);\r\n return;\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"Successfully hooked into PlaceholderAPI!\"\r\n );\r\n }\r\n\r\n menuItemMarker = new MenuItemMarker(this);\r\n dupeFixer = new DupeFixer(this, menuItemMarker);\r\n\r\n this.adventure = BukkitAudiences.create(this);\r\n\r\n setupItemHooks();\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"Vault\")) {\r\n vaultHook = new VaultHook();\r\n\r\n if (vaultHook.hooked()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"Successfully hooked into Vault!\"\r\n );\r\n }\r\n }\r\n\r\n if (!VersionHelper.IS_ITEM_LEGACY) {\r\n head = new ItemStack(Material.PLAYER_HEAD, 1);\r\n } else {\r\n head = new ItemStack(Material.valueOf(\"SKULL_ITEM\"), 1, (short) 3);\r\n }\r\n\r\n menuConfig = new DeluxeMenusConfig(this);\r\n if (menuConfig.loadDefConfig()) {\r\n debugLevel(menuConfig.debugLevel());\r\n checkUpdates = getConfig().getBoolean(\"check_updates\");\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n menuConfig.loadGUIMenus() + \" GUI menus loaded!\"\r\n );\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Failed to load from config.yml. Use /dm reload after fixing your errors.\"\r\n );\r\n }\r\n\r\n new PlayerListener(this);\r\n new DeluxeMenusCommands(this);\r\n Bukkit.getMessenger().registerOutgoingPluginChannel(this, \"BungeeCord\");\r\n\r\n if (checkUpdates) {\r\n UpdateChecker updateChecker = new UpdateChecker(this);\r\n\r\n if (updateChecker.updateAvailable()) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"An update for DeluxeMenus (DeluxeMenus v\" + updateChecker.getLatestVersion() + \")\",\r\n \"is available at https://www.spigotmc.org/resources/deluxemenus.11734/\"\r\n );\r\n } else {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.INFO,\r\n \"You are running the latest version of DeluxeMenus!\"\r\n );\r\n }\r\n }\r\n\r\n startMetrics();\r\n\r\n new Expansion(this).register();\r\n }\r\n\r\n @Override\r\n public void onDisable() {\r\n Bukkit.getMessenger().unregisterOutgoingPluginChannel(this, \"BungeeCord\");\r\n\r\n Bukkit.getScheduler().cancelTasks(this);\r\n\r\n if (this.adventure != null) {\r\n this.adventure.close();\r\n this.adventure = null;\r\n }\r\n\r\n Menu.unloadForShutdown();\r\n\r\n itemHooks.clear();\r\n\r\n instance = null;\r\n }\r\n\r\n private void setupItemHooks() {\r\n itemHooks = new HashMap<>();\r\n\r\n if (PlaceholderAPIPlugin.getServerVersion().isSpigot()) {\r\n itemHooks.put(HeadType.NAMED.getHookName(), new NamedHeadHook(this));\r\n itemHooks.put(HeadType.BASE64.getHookName(), new BaseHeadHook());\r\n itemHooks.put(HeadType.TEXTURE.getHookName(), new TextureHeadHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"HeadDatabase\")) {\r\n try {\r\n Class.forName(\"me.arcaniax.hdb.api.HeadDatabaseAPI\");\r\n itemHooks.put(HeadType.HDB.getHookName(), new HeadDatabaseHook());\r\n } catch (ClassNotFoundException ignored) {}\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"ItemsAdder\")) {\r\n itemHooks.put(\"itemsadder\", new ItemsAdderHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"Oraxen\")) {\r\n itemHooks.put(\"oraxen\", new OraxenHook());\r\n }\r\n\r\n if (Bukkit.getPluginManager().isPluginEnabled(\"MMOItems\")) {\r\n itemHooks.put(\"mmoitems\", new MMOItemsHook());\r\n }\r\n }\r\n\r\n public Optional getItemHook(String id) {\r\n return Optional.ofNullable(itemHooks.get(id));\r\n }\r\n\r\n public Map getItemHooks() {\r\n return itemHooks;\r\n }\r\n\r\n public ItemStack getHead() {\r\n return head != null ? head : new ItemStack(Material.DIRT, 1);\r\n }\r\n\r\n public static DeluxeMenus getInstance() {\r\n return instance;\r\n }\r\n\r\n public static DebugLevel debugLevel() {\r\n return debugLevel;\r\n }\r\n\r\n public static void debugLevel(final DebugLevel level) {\r\n debugLevel = level;\r\n }\r\n\r\n public static DebugLevel printStacktraceLevel() {\r\n return DebugLevel.MEDIUM;\r\n }\r\n\r\n public static boolean shouldPrintStackTrace() {\r\n return debugLevel().getPriority() <= printStacktraceLevel().getPriority();\r\n }\r\n\r\n public static void printStacktrace(final String message, final Throwable throwable) {\r\n if (!shouldPrintStackTrace()) return;\r\n\r\n getInstance().getLogger().log(Level.SEVERE, message, throwable);\r\n }\r\n\r\n private void startMetrics() {\r\n Metrics metrics = new Metrics(this, 445);\r\n metrics.addCustomChart(new Metrics.SingleLineChart(\"menus\", Menu::getLoadedMenuSize));\r\n }\r\n\r\n public void connect(Player p, String server) {\r\n ByteArrayDataOutput out = ByteStreams.newDataOutput();\r\n\r\n try {\r\n out.writeUTF(\"Connect\");\r\n out.writeUTF(server);\r\n } catch (Exception e) {\r\n debug(\r\n DebugLevel.HIGHEST,\r\n Level.SEVERE,\r\n \"There was a problem attempting to send \" + p.getName() + \" to server \" + server + \"!\"\r\n );\r\n\r\n printStacktrace(\r\n \"There was a problem attempting to send \" + p.getName() + \" to server \" + server + \"!\",\r\n e\r\n );\r\n }\r\n\r\n p.sendPluginMessage(this, \"BungeeCord\", out.toByteArray());\r\n }\r\n\r\n public void sms(CommandSender s, Component msg) {\r\n adventure().sender(s).sendMessage(msg);\r\n }\r\n\r\n public void sms(CommandSender s, Messages msg) {\r\n adventure().sender(s).sendMessage(msg.message());\r\n }\r\n\r\n public static void debug(@NotNull final DebugLevel debugLevel, @NotNull final Level level, @NotNull final String... messages) {\r\n if (debugLevel().getPriority() > debugLevel.getPriority()) return;\r\n\r\n getInstance().getLogger().log(\r\n level,\r\n String.join(System.lineSeparator(), messages)\r\n );\r\n }\r\n\r\n private boolean hookPlaceholderAPI() {\r\n return Bukkit.getPluginManager().getPlugin(\"PlaceholderAPI\") != null;\r\n }\r\n\r\n public MenuItemMarker getMenuItemMarker() {\r\n return menuItemMarker;\r\n }\r\n\r\n public DeluxeMenusConfig getConfiguration() {\r\n return menuConfig;\r\n }\r\n\r\n public VaultHook getVault() {\r\n return vaultHook;\r\n }\r\n\r\n public PersistentMetaHandler getPersistentMetaHandler() {\r\n return persistentMetaHandler;\r\n }\r\n\r\n public BukkitAudiences adventure() {\r\n if (this.adventure == null) {\r\n throw new IllegalStateException(\"Tried to access Adventure when the plugin was disabled!\");\r\n }\r\n return this.adventure;\r\n }\r\n\r\n public void clearCaches() {\r\n itemHooks.values().stream()\r\n .filter(Objects::nonNull)\r\n .filter(hook -> hook instanceof SimpleCache)\r\n .map(hook -> (SimpleCache) hook)\r\n .forEach(SimpleCache::clearCache);\r\n }\r\n}\r\n\nsrc/main/java/com/extendedclip/deluxemenus/utils/StringUtils.java\npublic class StringUtils {\r\n\r\n private final static Pattern HEX_PATTERN = Pattern\r\n .compile(\"&(#[a-f0-9]{6})\", Pattern.CASE_INSENSITIVE);\r\n\r\n /**\r\n * Translates the ampersand color codes like '&7' to their section symbol counterparts like '§7'.\r\n *
\r\n * It also translates hex colors like '&#aaFF00' to their section symbol counterparts like '§x§a§a§F§F§0§0'.\r\n *\r\n * @param input The string in which to translate the color codes.\r\n * @return The string with the translated colors.\r\n */\r\n @NotNull\r\n public static String color(@NotNull String input) {\r\n //Hex Support for 1.16.1+\r\n Matcher m = HEX_PATTERN.matcher(input);\r\n if (VersionHelper.IS_HEX_VERSION) {\r\n while (m.find()) {\r\n input = input.replace(m.group(), ChatColor.of(m.group(1)).toString());\r\n }\r\n }\r\n\r\n return ChatColor.translateAlternateColorCodes('&', input);\r\n }\r\n\r\n}\r\n\nsrc/main/java/com/extendedclip/deluxemenus/menu/MenuHolder.java\npublic class MenuHolder implements InventoryHolder {\r\n\r\n private final Player viewer;\r\n private Player placeholderPlayer;\r\n private String menuName;\r\n private Set activeItems;\r\n private BukkitTask updateTask = null;\r\n private Inventory inventory;\r\n private boolean updating;\r\n private Map typedArgs;\r\n\r\n public MenuHolder(Player viewer) {\r\n this.viewer = viewer;\r\n }\r\n\r\n public MenuHolder(Player viewer, String menuName,\r\n Set activeItems, Inventory inventory) {\r\n this.viewer = viewer;\r\n this.menuName = menuName;\r\n this.activeItems = activeItems;\r\n this.inventory = inventory;\r\n }\r\n\r\n public String getViewerName() {\r\n return viewer.getName();\r\n }\r\n\r\n public BukkitTask getUpdateTask() {\r\n return updateTask;\r\n }\r\n\r\n public Player getViewer() {\r\n return viewer;\r\n }\r\n\r\n public String getMenuName() {\r\n return menuName;\r\n }\r\n\r\n public void setMenuName(String menuName) {\r\n this.menuName = menuName;\r\n }\r\n\r\n public Set getActiveItems() {\r\n return activeItems;\r\n }\r\n\r\n public void setActiveItems(Set items) {\r\n this.activeItems = items;\r\n }\r\n\r\n public MenuHolder getHolder() {\r\n return this;\r\n }\r\n\r\n public MenuItem getItem(int slot) {\r\n for (MenuItem item : activeItems) {\r\n if (item.options().slot() == slot) {\r\n return item;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n public Menu getMenu() {\r\n return Menu.getMenu(menuName);\r\n }\r\n\r\n public String setPlaceholders(String string) {\r\n // Set argument placeholders first\r\n if (this.typedArgs != null && !this.typedArgs.isEmpty()) {\r\n for (Entry entry : typedArgs.entrySet()) {\r\n string = string.replace(\"{\" + entry.getKey() + \"}\", entry.getValue());\r\n }\r\n }\r\n\r\n // Then set actual PAPI placeholders\r\n if (placeholderPlayer != null) {\r\n return PlaceholderAPI.setPlaceholders((OfflinePlayer) placeholderPlayer, string);\r\n } else {\r\n return this.getViewer() == null ? string\r\n : PlaceholderAPI.setPlaceholders((OfflinePlayer) this.getViewer(), string);\r\n }\r\n }\r\n\r\n public String setArguments(String string) {\r\n if (this.typedArgs == null || this.typedArgs.isEmpty()) {\r\n return string;\r\n }\r\n for (Entry entry : this.typedArgs.entrySet()) {\r\n string = string.replace(\"{\" + entry.getKey() + \"}\", entry.getValue());\r\n }\r\n return string;\r\n }\r\n\r\n public void refreshMenu() {\r\n\r\n Menu menu = getMenu();\r\n\r\n if (menu == null || menu.getMenuItems() == null || menu.getMenuItems().size() <= 0) {\r\n return;\r\n }\r\n\r\n setUpdating(true);\r\n\r\n stopPlaceholderUpdate();\r\n\r\n Bukkit.getScheduler().runTaskAsynchronously(DeluxeMenus.getInstance(), () -> {\r\n\r\n final Set active = new HashSet<>();\r\n\r\n for (int i = 0; i < getInventory().getSize(); i++) {\r\n TreeMap e = menu.getMenuItems().get(i);\r\n\r\n if (e == null) {\r\n getInventory().setItem(i, null);\r\n continue;\r\n }\r\n\r\n boolean m = false;\r\n for (MenuItem item : e.values()) {\r\n\r\n if (item.options().viewRequirements().isPresent()) {\r\n\r\n if (item.options().viewRequirements().get().evaluate(this)) {\r\n m = true;\r\n active.add(item);\r\n break;\r\n }\r\n } else {\r\n m = true;\r\n active.add(item);\r\n break;\r\n }\r\n }\r\n\r\n if (!m) {\r\n getInventory().setItem(i, null);\r\n }\r\n }\r\n\r\n if (active.isEmpty()) {\r\n Menu.closeMenu(getViewer(), true);\r\n }\r\n\r\n Bukkit.getScheduler().runTask(DeluxeMenus.getInstance(), () -> {\r\n\r\n boolean update = false;\r\n\r\n for (MenuItem item : active) {\r\n\r\n ItemStack iStack = item.getItemStack(this);\r\n\r\n int slot = item.options().slot();\r\n\r\n if (slot >= menu.getSize()) {\r\n continue;\r\n }\r\n\r\n if (item.options().updatePlaceholders()) {\r\n update = true;\r\n }\r\n\r\n getInventory().setItem(item.options().slot(), iStack);\r\n }\r\n\r\n setActiveItems(active);\r\n\r\n if (update) {\r\n startUpdatePlaceholdersTask();\r\n }\r\n\r\n setUpdating(false);\r\n });\r\n });\r\n }\r\n\r\n public void stopPlaceholderUpdate() {\r\n if (updateTask != null) {\r\n try {\r\n updateTask.cancel();\r\n } catch (Exception ignored) {\r\n }\r\n updateTask = null;\r\n }\r\n }\r\n\r\n public void startUpdatePlaceholdersTask() {\r\n\r\n if (updateTask != null) {\r\n stopPlaceholderUpdate();\r\n }\r\n\r\n updateTask = new BukkitRunnable() {\r\n\r\n @Override\r\n public void run() {\r\n\r\n if (updating) {\r\n return;\r\n }\r\n\r\n Set items = getActiveItems();\r\n\r\n if (items == null) {\r\n return;\r\n }\r\n\r\n for (MenuItem item : items) {\r\n\r\n if (item.options().updatePlaceholders()) {\r\n\r\n ItemStack i = inventory.getItem(item.options().slot());\r\n\r\n if (i == null) {\r\n continue;\r\n }\r\n\r\n int amt = i.getAmount();\r\n\r\n if (item.options().dynamicAmount().isPresent()) {\r\n try {\r\n amt = Integer.parseInt(setPlaceholders(item.options().dynamicAmount().get()));\r\n if (amt <= 0) {\r\n amt = 1;\r\n }\r\n } catch (Exception exception) {\r\n DeluxeMenus.printStacktrace(\r\n \"Something went wrong while updating item in slot \" + item.options().slot() +\r\n \". Invalid dynamic amount: \" + setPlaceholders(item.options().dynamicAmount().get()),\r\n exception\r\n );\r\n }\r\n }\r\n\r\n ItemMeta meta = i.getItemMeta();\r\n\r\n if (item.options().displayNameHasPlaceholders() && item.options().displayName().isPresent()) {\r\n meta.setDisplayName(StringUtils.color(setPlaceholders(item.options().displayName().get())));\r\n }\r\n\r\n if (item.options().loreHasPlaceholders()) {\r\n\r\n List updated = new ArrayList<>();\r\n\r\n for (String line : item.options().lore()) {\r\n updated.add(StringUtils\r\n .color(setPlaceholders(line)));\r\n }\r\n meta.setLore(updated);\r\n }\r\n\r\n i.setItemMeta(meta);\r\n i.setAmount(amt);\r\n }\r\n }\r\n }\r\n\r\n }.runTaskTimerAsynchronously(DeluxeMenus.getInstance(), 20L,\r\n 20L * Menu.getMenu(menuName).getUpdateInterval());\r\n }\r\n\r\n public boolean isUpdating() {\r\n return updating;\r\n }\r\n\r\n public void setUpdating(boolean updating) {\r\n this.updating = updating;\r\n }\r\n\r\n @Override\r\n public Inventory getInventory() {\r\n return this.inventory;\r\n }\r\n\r\n public void setInventory(Inventory i) {\r\n this.inventory = i;\r\n }\r\n\r\n public Map getTypedArgs() {\r\n return typedArgs;\r\n }\r\n\r\n public void setTypedArgs(Map typedArgs) {\r\n this.typedArgs = typedArgs;\r\n }\r\n\r\n public void setPlaceholderPlayer(Player placeholderPlayer) {\r\n this.placeholderPlayer = placeholderPlayer;\r\n }\r\n\r\n public Player getPlaceholderPlayer() {\r\n return placeholderPlayer;\r\n }\r\n}\r\n\nsrc/main/java/com/extendedclip/deluxemenus/utils/ExpUtils.java\npublic final class ExpUtils {\r\n private ExpUtils() {\r\n throw new AssertionError(\"Util classes should not be initialized\");\r\n }\r\n\r\n /**\r\n * Set the player's experience to the given value.\r\n * @param target The player to set the experience of.\r\n * @param stringAmount The amount of experience to set. Can end with an 'l' to set the experience levels.\r\n * @throws NumberFormatException If the stringAmount is not a valid number.\r\n */\r\n public static void setExp(\r\n @NotNull final Player target,\r\n @NotNull final String stringAmount\r\n ) throws NumberFormatException {\r\n long amount;\r\n final String lowerCase = stringAmount.toLowerCase(Locale.ENGLISH);\r\n\r\n if (stringAmount.contains(\"l\")) {\r\n final int neededLevel = Integer.parseInt(lowerCase.replaceAll(\"l\", \"\")) + target.getLevel();\r\n amount = getExpToLevel(neededLevel) + (getTotalExperience(target) - getExpToLevel(target.getLevel()));\r\n setTotalExperience(target, 0);\r\n }\r\n else {\r\n amount = Long.parseLong(lowerCase);\r\n }\r\n amount += getTotalExperience(target);\r\n if (amount > Integer.MAX_VALUE) {\r\n amount = Integer.MAX_VALUE;\r\n }\r\n if (amount < 0L) {\r\n amount = 0L;\r\n }\r\n setTotalExperience(target, (int) amount);\r\n }\r\n\r\n /**\r\n * Set the player's experience to the given value.\r\n *
\r\n * This method updates both the record total experience and displayed total experience.\r\n *\r\n * @param player The player to set the total experience for.\r\n * @param exp The amount of experience to set.\r\n * @throws IllegalArgumentException If the exp amount is less than 0.\r\n */\r\n public static void setTotalExperience(\r\n @NotNull final Player player,\r\n final int exp\r\n ) throws IllegalArgumentException {\r\n if (exp < 0) {\r\n throw new IllegalArgumentException(\"Experience is negative!\");\r\n }\r\n\r\n player.setExp(0);\r\n player.setLevel(0);\r\n player.setTotalExperience(0);\r\n\r\n int amount = exp;\r\n while (amount > 0) {\r\n final int expToLevel = getExpAtLevel(player);\r\n amount -= expToLevel;\r\n if (amount >= 0) {\r\n player.giveExp(expToLevel);\r\n } else {\r\n amount += expToLevel;\r\n player.giveExp(amount);\r\n amount = 0;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get the amount of experience required to reach the given level.\r\n * @param player The player to get the experience for.\r\n * @return The amount of experience required to reach the given level.\r\n */\r\n private static int getExpAtLevel(@NotNull final Player player) {\r\n return getExpAtLevel(player.getLevel());\r\n }\r\n\r\n /**\r\n * Get the amount of experience points required to reach the next level from the given level.\r\n * @param level The level to calculate the required experience points to level up for.\r\n * @return The amount of experience required to reach the next level from the given one.\r\n */\r\n public static int getExpAtLevel(final int level) {\r\n if (level <= 15) {\r\n return (2 * level) + 7;\r\n }\r\n if (level <= 30) {\r\n return (5 * level) - 38;\r\n }\r\n return (9 * level) - 158;\r\n }\r\n\r\n /**\r\n * Translates the given amount of levels to the amount of experience points required to get to this level from 0.\r\n * @param level The amount of levels to translate.\r\n * @return The amount of experience points required to reach the given level from 0.\r\n */\r\n public static int getExpToLevel(final int level) {\r\n int currentLevel = 0;\r\n int exp = 0;\r\n\r\n while (currentLevel < level) {\r\n exp += getExpAtLevel(currentLevel);\r\n currentLevel++;\r\n }\r\n if (exp < 0) {\r\n exp = Integer.MAX_VALUE;\r\n }\r\n return exp;\r\n }\r\n\r\n /**\r\n * Get the total amount of experience points that the given player has right now.\r\n * @param player The player to get the experience for.\r\n * @return The total amount of experience points that the given player has.\r\n */\r\n public static int getTotalExperience(@NotNull final Player player) {\r\n int exp = Math.round(getExpAtLevel(player) * player.getExp());\r\n int currentLevel = player.getLevel();\r\n\r\n while (currentLevel > 0) {\r\n currentLevel--;\r\n exp += getExpAtLevel(currentLevel);\r\n }\r\n if (exp < 0) {\r\n exp = Integer.MAX_VALUE;\r\n }\r\n return exp;\r\n }\r\n}\r\n\nsrc/main/java/com/extendedclip/deluxemenus/utils/AdventureUtils.java\npublic final class AdventureUtils {\r\n private final static GsonComponentSerializer gson = GsonComponentSerializer.gson();\r\n\r\n private AdventureUtils() {\r\n throw new AssertionError(\"Util classes should not be initialized\");\r\n }\r\n\r\n public static void sendJson(CommandSender sender, String json) {\r\n DeluxeMenus.getInstance().adventure().sender(sender).sendMessage(fromJson(json));\r\n }\r\n\r\n public static Component fromJson(String json) {\r\n return gson.deserialize(json);\r\n }\r\n}\n\nsrc/main/java/com/extendedclip/deluxemenus/utils/DebugLevel.java\npublic enum DebugLevel {\r\n LOWEST(0, \"LOWEST\"),\r\n LOW(1, \"LOW\"),\r\n MEDIUM(2, \"MEDIUM\"),\r\n HIGH(3, \"HIGH\"),\r\n HIGHEST(4, \"HIGHEST\");\r\n\r\n private final String[] names;\r\n private final int priority;\r\n\r\n private DebugLevel(final int priority, @NotNull final String... names) {\r\n this.priority = priority;\r\n this.names = names;\r\n }\r\n\r\n public int getPriority() {\r\n return priority;\r\n }\r\n\r\n private static final Map LEVELS = Arrays.stream(values())\r\n .flatMap(level -> Arrays.stream(level.names).map(name -> Map.entry(name.toLowerCase(Locale.ROOT), level)))\r\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\r\n\r\n public static @Nullable DebugLevel getByName(@NotNull final String name) {\r\n return LEVELS.get(name.toLowerCase(Locale.ROOT));\r\n }\r\n}\r\n\nsrc/main/java/com/extendedclip/deluxemenus/utils/VersionHelper.java\npublic final class VersionHelper {\r\n\r\n private static final String PACKAGE_NAME = Bukkit.getServer().getClass().getPackage().getName();\r\n public static final String NMS_VERSION = PACKAGE_NAME.substring(PACKAGE_NAME.lastIndexOf('.') + 1);\r\n\r\n // PlayerProfile API\r\n private static final int V1_18_1 = 1181;\r\n // Mojang obfuscation changes\r\n private static final int V1_17 = 1170;\r\n // Material and components on items change\r\n private static final int V1_13 = 1130;\r\n // PDC and customModelData\r\n private static final int V1_14 = 1140;\r\n // Hex colors\r\n private static final int V1_16 = 1160;\r\n // Paper adventure changes\r\n private static final int V1_16_5 = 1165;\r\n // SkullMeta#setOwningPlayer was added\r\n private static final int V1_12 = 1120;\r\n\r\n public static final int CURRENT_VERSION = getCurrentVersion();\r\n\r\n private static final boolean IS_PAPER = checkPaper();\r\n\r\n\r\n /**\r\n * Checks if current version includes the PlayerProfile API\r\n */\r\n public static final boolean HAS_PLAYER_PROFILES = CURRENT_VERSION >= V1_18_1;\r\n\r\n /**\r\n * Checks if the current version was a version without versioned packages.\r\n */\r\n public static final boolean HAS_OBFUSCATED_NAMES = CURRENT_VERSION >= V1_17;\r\n\r\n /**\r\n * Checks if the version supports Components or not\r\n * Paper versions above 1.16.5 would be true\r\n * Spigot always false\r\n */\r\n public static final boolean IS_COMPONENT = IS_PAPER && CURRENT_VERSION >= V1_16_5;\r\n\r\n /**\r\n * Checks if the version is lower than 1.13 due to the item changes\r\n */\r\n public static final boolean IS_ITEM_LEGACY = CURRENT_VERSION < V1_13;\r\n\r\n /**\r\n * Checks if the version supports {@link org.bukkit.persistence.PersistentDataContainer}\r\n */\r\n public static final boolean IS_PDC_VERSION = CURRENT_VERSION >= V1_14;\r\n\r\n /**\r\n * Checks if the version doesn't have {@link org.bukkit.inventory.meta.SkullMeta#setOwningPlayer(OfflinePlayer)} and\r\n * {@link org.bukkit.inventory.meta.SkullMeta#setOwner(String)} should be used instead\r\n */\r\n public static final boolean IS_SKULL_OWNER_LEGACY = CURRENT_VERSION <= V1_12;\r\n\r\n /**\r\n * Checks if the version has {@link org.bukkit.inventory.meta.ItemMeta#setCustomModelData(Integer)}\r\n */\r\n public static final boolean IS_CUSTOM_MODEL_DATA = CURRENT_VERSION >= V1_14;\r\n\r\n public static final boolean IS_HEX_VERSION = CURRENT_VERSION >= V1_16;\r\n\r\n private static List CHEST_INVENTORY_TYPES = null;\r\n\r\n private static List VALID_INVENTORY_TYPES = null;\r\n\r\n private static List getChestInventoryTypes() {\r\n if (CHEST_INVENTORY_TYPES != null) return CHEST_INVENTORY_TYPES;\r\n\r\n if (CURRENT_VERSION >= V1_14) {\r\n CHEST_INVENTORY_TYPES = List.of(\r\n InventoryType.BARREL,\r\n InventoryType.CHEST,\r\n InventoryType.CRAFTING,\r\n InventoryType.CREATIVE,\r\n InventoryType.ENDER_CHEST,\r\n InventoryType.LECTERN,\r\n InventoryType.MERCHANT,\r\n InventoryType.SHULKER_BOX\r\n );\r\n\r\n return CHEST_INVENTORY_TYPES;\r\n }\r\n\r\n CHEST_INVENTORY_TYPES = List.of(\r\n InventoryType.CHEST,\r\n InventoryType.CRAFTING,\r\n InventoryType.CREATIVE,\r\n InventoryType.ENDER_CHEST,\r\n InventoryType.MERCHANT,\r\n InventoryType.SHULKER_BOX\r\n );\r\n\r\n return CHEST_INVENTORY_TYPES;\r\n }\r\n\r\n public static List getValidInventoryTypes() {\r\n if (VALID_INVENTORY_TYPES != null) return VALID_INVENTORY_TYPES;\r\n\r\n final List chestInventoryTypes = getChestInventoryTypes();\r\n final List validInventoryTypes = new ArrayList<>();\r\n\r\n for (final InventoryType inventoryType : InventoryType.values()) {\r\n if (inventoryType != InventoryType.CHEST && chestInventoryTypes.contains(inventoryType)) continue;\r\n validInventoryTypes.add(inventoryType);\r\n }\r\n\r\n VALID_INVENTORY_TYPES = validInventoryTypes;\r\n return VALID_INVENTORY_TYPES;\r\n }\r\n\r\n /**\r\n * Check if the server has access to the Paper API\r\n * Taken from PaperLib\r\n *\r\n * @return True if on Paper server (or forks), false anything else\r\n */\r\n private static boolean checkPaper() {\r\n try {\r\n Class.forName(\"com.destroystokyo.paper.PaperConfig\");\r\n return true;\r\n } catch (ClassNotFoundException ignored) {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current server version\r\n *\r\n * @return A protocol like number representing the version, for example 1.16.5 - 1165\r\n */\r\n private static int getCurrentVersion() {\r\n // No need to cache since will only run once\r\n final Matcher matcher = Pattern.compile(\"(?\\\\d+\\\\.\\\\d+)(?\\\\.\\\\d+)?\").matcher(Bukkit.getBukkitVersion());\r\n\r\n final StringBuilder stringBuilder = new StringBuilder();\r\n if (matcher.find()) {\r\n stringBuilder.append(matcher.group(\"version\").replace(\".\", \"\"));\r\n final String patch = matcher.group(\"patch\");\r\n if (patch == null) stringBuilder.append(\"0\");\r\n else stringBuilder.append(patch.replace(\".\", \"\"));\r\n }\r\n\r\n //noinspection UnstableApiUsage\r\n final Integer version = Ints.tryParse(stringBuilder.toString());\r\n\r\n // Should never fail\r\n if (version == null) throw new RuntimeException(\"Could not retrieve server version!\");\r\n\r\n return version;\r\n }\r\n\r\n public static String getNmsVersion() {\r\n final String version = Bukkit.getServer().getClass().getPackage().getName();\r\n return version.substring(version.lastIndexOf('.') + 1);\r\n }\r\n\r\n /**\r\n * Gets the NMS class from class name.\r\n *\r\n * @return The NMS class.\r\n */\r\n public static Class getNMSClass(final String pkg, final String className) throws ClassNotFoundException {\r\n if (VersionHelper.HAS_OBFUSCATED_NAMES) {\r\n return Class.forName(\"net.minecraft.\" + pkg + \".\" + className);\r\n }\r\n return Class.forName(\"net.minecraft.server.\" + VersionHelper.NMS_VERSION + \".\" + className);\r\n }\r\n\r\n /**\r\n * Gets the craft class from class name.\r\n *\r\n * @return The craft class.\r\n */\r\n public static Class getCraftClass(@NotNull final String name) throws ClassNotFoundException {\r\n return Class.forName(\"org.bukkit.craftbukkit.\" + NMS_VERSION + \".\" + name);\r\n }\r\n\r\n}\r\n\nsrc/main/java/com/extendedclip/deluxemenus/menu/Menu.java\npublic class Menu extends Command {\r\n\r\n private static final Map menus = new HashMap<>();\r\n private static final Set holders = new HashSet<>();\r\n private static final Map lastMenus = new HashMap<>();\r\n private static CommandMap commandMap = null;\r\n private final String menuName;\r\n private final String menuTitle;\r\n private final int size;\r\n private final Map> items;\r\n private InventoryType type;\r\n private List menuCommands;\r\n private int updateInterval;\r\n private RequirementList openRequirements;\r\n private ClickHandler openHandler, closeHandler;\r\n private boolean registersCommand;\r\n // args\r\n private List args;\r\n private List argRequirements;\r\n private String argUsageMessage;\r\n\r\n public Menu(String menuName, String menuTitle, Map> items,\r\n int size, List menuCommands, boolean registerCommand, List args, List argRequirements) {\r\n super(menuCommands.get(0));\r\n this.menuName = menuName;\r\n this.menuTitle = StringUtils.color(menuTitle);\r\n this.items = items;\r\n this.size = size;\r\n this.menuCommands = menuCommands;\r\n this.registersCommand = registerCommand;\r\n this.args = args;\r\n this.argRequirements = argRequirements;\r\n if (registerCommand) {\r\n if (menuCommands.size() > 1) {\r\n this.setAliases(menuCommands.subList(1, menuCommands.size()));\r\n }\r\n addCommand();\r\n }\r\n menus.put(this.menuName, this);\r\n }\r\n\r\n public Menu(String menuName, String menuTitle, Map> items,\r\n int size) {\r\n super(menuName);\r\n this.menuName = menuName;\r\n this.menuTitle = StringUtils.color(menuTitle);\r\n this.items = items;\r\n this.size = size;\r\n menus.put(this.menuName, this);\r\n }\r\n\r\n public static void unload(String menu) {\r\n for (Player p : Bukkit.getOnlinePlayers()) {\r\n if (inMenu(p, menu)) {\r\n closeMenu(p, true);\r\n }\r\n }\r\n Menu m = Menu.getMenu(menu);\r\n if (m == null) {\r\n return;\r\n }\r\n\r\n m.removeCommand();\r\n menus.remove(menu);\r\n }\r\n\r\n public static void unload() {\r\n for (Player p : Bukkit.getOnlinePlayers()) {\r\n if (inMenu(p)) {\r\n closeMenu(p, true);\r\n }\r\n }\r\n if (Menu.getAllMenus() != null) {\r\n for (Menu menu : Menu.getAllMenus()) {\r\n menu.removeCommand();\r\n }\r\n }\r\n menus.clear();\r\n holders.clear();\r\n lastMenus.clear();\r\n }\r\n\r\n public static void unloadForShutdown() {\r\n for (Player player : Bukkit.getOnlinePlayers()) {\r\n if (inMenu(player)) {\r\n closeMenuForShutdown(player);\r\n }\r\n }\r\n menus.clear();\r\n }\r\n\r\n public static int getLoadedMenuSize() {\r\n return menus.size();\r\n }\r\n\r\n public static Menu getMenu(Player p) {\r\n return getOpenMenu(p);\r\n }\r\n\r\n public static Collection

getAllMenus() {\r\n return !menus.isEmpty() ? menus.values() : null;\r\n }\r\n\r\n public static Menu getMenu(String menuName) {\r\n for (Entry e : menus.entrySet()) {\r\n if (e.getKey().equalsIgnoreCase(menuName)) {\r\n return e.getValue();\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n public static Menu getMenuByCommand(String command) {\r\n for (Menu m : menus.values()) {\r\n if (m.getMenuCommandUsed(command) != null) {\r\n return m;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n public static boolean isMenuCommand(String command) {\r\n return getMenuByCommand(command) != null;\r\n }\r\n\r\n public static boolean inMenu(Player p) {\r\n return holders.stream().anyMatch(h -> h.getViewerName().equals(p.getName()));\r\n }\r\n\r\n public static boolean inMenu(Player p, String menu) {\r\n return holders.stream().anyMatch(h -> h.getMenuName().equals(menu) && h.getViewerName().equals(p.getName()));\r\n }\r\n\r\n public static MenuHolder getMenuHolder(Player p) {\r\n return holders.stream().filter(h -> h.getViewerName().equals(p.getName())).findFirst()\r\n .orElse(null);\r\n }\r\n\r\n public static Menu getOpenMenu(Player p) {\r\n MenuHolder h = getMenuHolder(p);\r\n return h == null ? null : h.getMenu();\r\n }\r\n public static Menu getLastMenu(Player p) {\r\n return lastMenus.get(p.getUniqueId());\r\n }\r\n\r\n public static void cleanInventory(Player player, @NotNull final MenuItemMarker marker) {\r\n if (player == null) {\r\n return;\r\n }\r\n for (final ItemStack itemStack : player.getInventory().getContents()) {\r\n if (itemStack == null) continue;\r\n if (!marker.isMarked(itemStack)) continue;\r\n\r\n DeluxeMenus.debug(\r\n DebugLevel.LOWEST,\r\n Level.INFO,\r\n \"Found a DeluxeMenus item in a player's inventory. Removing it.\"\r\n );\r\n player.getInventory().remove(itemStack);\r\n }\r\n player.updateInventory();\r\n }\r\n\r\n public static void closeMenu(final Player p, boolean close, boolean executeCloseActions) {\r\n\r\n MenuHolder holder = getMenuHolder(p);\r\n if (holder == null) {\r\n return;\r\n }\r\n\r\n holder.stopPlaceholderUpdate();\r\n\r\n if (executeCloseActions) {\r\n if (holder.getMenu().getCloseHandler() != null) {\r\n holder.getMenu().getCloseHandler().onClick(holder);\r\n }\r\n }\r\n\r\n if (close) {\r\n Bukkit.getScheduler().runTask(DeluxeMenus.getInstance(), () -> {\r\n p.closeInventory();\r\n cleanInventory(p, DeluxeMenus.getInstance().getMenuItemMarker());\r\n });\r\n }\r\n holders.remove(holder);\r\n lastMenus.put(p.getUniqueId(), holder.getMenu());\r\n }\r\n\r\n public static void closeMenuForShutdown(final Player p) {\r\n MenuHolder holder = getMenuHolder(p);\r\n if (holder == null) {\r\n return;\r\n }\r\n\r\n holder.stopPlaceholderUpdate();\r\n\r\n p.closeInventory();\r\n cleanInventory(p, DeluxeMenus.getInstance().getMenuItemMarker());\r\n }\r\n\r\n public static void closeMenu(final Player p, boolean close) {\r\n closeMenu(p, close, false);\r\n }\r\n\r\n private void addCommand() {\r\n if (commandMap == null) {\r\n try {\r\n final Field f = Bukkit.getServer().getClass().getDeclaredField(\"commandMap\");\r\n f.setAccessible(true);\r\n commandMap = (CommandMap) f.get(Bukkit.getServer());\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n return;\r\n }\r\n }\r\n boolean registered = commandMap.register(\"DeluxeMenus\", this);\r\n if (registered) {\r\n DeluxeMenus.debug(\r\n DebugLevel.LOW,\r\n Level.INFO,\r\n \"Registered command: \" + this.getName() + \" for menu: \" + this.getMenuName()\r\n );\r\n }\r\n }\r\n\r\n private void removeCommand() {\r\n if (commandMap != null && this.registersCommand()) {\r\n Field cMap;\r\n Field knownCommands;\r\n try {\r\n cMap = Bukkit.getServer().getClass().getDeclaredField(\"commandMap\");\r\n cMap.setAccessible(true);\r\n knownCommands = SimpleCommandMap.class.getDeclaredField(\"knownCommands\");\r\n knownCommands.setAccessible(true);\r\n ((Map) knownCommands.get((SimpleCommandMap) cMap.get(Bukkit.getServer())))\r\n .remove(this.getName());\r\n boolean unregistered = this.unregister((CommandMap) cMap.get(Bukkit.getServer()));\r\n this.unregister(commandMap);\r\n if (unregistered) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGH,\r\n Level.INFO,\r\n \"Successfully unregistered command: \" + this.getName()\r\n );\r\n } else {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Failed to unregister command: \" + this.getName()\r\n );\r\n }\r\n } catch (Exception ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public boolean execute(CommandSender sender, String commandLabel, String[] typedArgs) {\r\n if (!(sender instanceof Player)) {\r\n Msg.msg(sender, \"Menus can only be opened by players!\");\r\n return true;\r\n }\r\n\r\n Map argMap = null;\r\n\r\n if (!this.args.isEmpty()) {\r\n DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, \"has args\");\r\n if (typedArgs.length < this.args.size()) {\r\n if (this.argUsageMessage != null) {\r\n Msg.msg(sender, this.argUsageMessage);\r\n }\r\n return true;\r\n }\r\n argMap = new HashMap<>();\r\n int index = 0;\r\n for (String arg : this.args) {\r\n if (index + 1 == this.args.size()) {\r\n String last = String.join(\" \", Arrays.asList(typedArgs).subList(index, typedArgs.length));\r\n DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, \"arg: \" + arg + \" => \" + last);\r\n argMap.put(arg, last);\r\n } else {\r\n argMap.put(arg, typedArgs[index]);\r\n DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, \"arg: \" + arg + \" => \" + typedArgs[index]);\r\n }\r\n index++;\r\n }\r\n }\r\n\r\n Player player = (Player) sender;\r\n DeluxeMenus.debug(DebugLevel.LOWEST, Level.INFO, \"opening menu: \" + this.menuName);\r\n openMenu(player, argMap, null);\r\n return true;\r\n }\r\n\r\n private boolean hasOpenBypassPerm(Player viewer) {\r\n return viewer.hasPermission(\"deluxemenus.openrequirement.bypass.\" + menuName)\r\n || viewer.hasPermission(\"deluxemenus.openrequirement.bypass.*\");\r\n }\r\n\r\n private boolean handleOpenRequirements(MenuHolder holder) {\r\n if (openRequirements == null || openRequirements.getRequirements() == null) {\r\n return true;\r\n }\r\n\r\n if (holder.getViewer() != null && this.hasOpenBypassPerm(holder.getViewer())) {\r\n return true;\r\n }\r\n\r\n if (!openRequirements.evaluate(holder)) {\r\n if (openRequirements.getDenyHandler() != null) {\r\n openRequirements.getDenyHandler().onClick(holder);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n private boolean handleArgRequirements(MenuHolder holder) {\r\n if (argRequirements == null) {\r\n return true;\r\n }\r\n\r\n for (RequirementList rl : argRequirements) {\r\n if (rl.getRequirements() == null) {\r\n continue;\r\n }\r\n\r\n if (!rl.evaluate(holder)) {\r\n if (rl.getDenyHandler() != null) {\r\n rl.getDenyHandler().onClick(holder);\r\n }\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n public void openMenu(final Player viewer) {\r\n openMenu(viewer, null, null);\r\n }\r\n\r\n public void openMenu(final Player viewer, final Map args, final Player placeholderPlayer) {\r\n if (menuTitle == null || items == null || items.size() <= 0) {\r\n return;\r\n }\r\n\r\n final MenuHolder holder = new MenuHolder(viewer);\r\n if (placeholderPlayer != null) {\r\n holder.setPlaceholderPlayer(placeholderPlayer);\r\n }\r\n holder.setTypedArgs(args);\r\n\r\n if (!this.handleArgRequirements(holder)) {\r\n return;\r\n }\r\n\r\n if (!this.handleOpenRequirements(holder)) {\r\n return;\r\n }\r\n\r\n Bukkit.getScheduler().runTaskAsynchronously(DeluxeMenus.getInstance(), () -> {\r\n\r\n Set activeItems = new HashSet<>();\r\n\r\n for (Entry> entry : items.entrySet()) {\r\n\r\n for (MenuItem item : entry.getValue().values()) {\r\n\r\n int slot = item.options().slot();\r\n\r\n if (slot >= size) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Item set to slot \" + slot + \" for menu: \" + menuName + \" exceeds the inventory size!\",\r\n \"This item will not be added to the menu!\"\r\n );\r\n continue;\r\n }\r\n\r\n if (item.options().viewRequirements().isPresent()) {\r\n\r\n if (item.options().viewRequirements().get().evaluate(holder)) {\r\n\r\n activeItems.add(item);\r\n break;\r\n }\r\n } else {\r\n\r\n activeItems.add(item);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (activeItems.isEmpty()) {\r\n return;\r\n }\r\n\r\n holder.setMenuName(menuName);\r\n holder.setActiveItems(activeItems);\r\n\r\n if (this.openHandler != null) {\r\n this.openHandler.onClick(holder);\r\n }\r\n\r\n String title = StringUtils.color(holder.setPlaceholders(this.menuTitle));\r\n\r\n Inventory inventory;\r\n\r\n if (type != null) {\r\n inventory = Bukkit.createInventory(holder, type, title);\r\n } else {\r\n inventory = Bukkit.createInventory(holder, size, title);\r\n }\r\n\r\n holder.setInventory(inventory);\r\n\r\n boolean update = false;\r\n\r\n for (MenuItem item : activeItems) {\r\n\r\n ItemStack iStack = item.getItemStack(holder);\r\n\r\n if (iStack == null) {\r\n continue;\r\n }\r\n\r\n iStack = DeluxeMenus.getInstance().getMenuItemMarker().mark(iStack);\r\n\r\n int slot = item.options().slot();\r\n\r\n if (slot >= size) {\r\n DeluxeMenus.debug(\r\n DebugLevel.HIGHEST,\r\n Level.WARNING,\r\n \"Item set to slot \" + slot + \" for menu: \" + menuName + \" exceeds the inventory size!\",\r\n \"This item will not be added to the menu!\"\r\n );\r\n continue;\r\n }\r\n\r\n if (item.options().updatePlaceholders()) {\r\n update = true;\r\n }\r\n\r\n inventory.setItem(item.options().slot(), iStack);\r\n }\r\n\r\n final boolean updatePlaceholders = update;\r\n\r\n Bukkit.getScheduler().runTask(DeluxeMenus.getInstance(), () -> {\r\n if (inMenu(holder.getViewer())) {\r\n closeMenu(holder.getViewer(), false);\r\n }\r\n\r\n viewer.openInventory(inventory);\r\n holders.add(holder);\r\n\r\n if (updatePlaceholders) {\r\n holder.startUpdatePlaceholdersTask();\r\n }\r\n });\r\n });\r\n }\r\n\r\n public String getMenuTitle() {\r\n return menuTitle;\r\n }\r\n\r\n public String getMenuName() {\r\n return this.menuName;\r\n }\r\n\r\n public List getMenuCommands() {\r\n return this.menuCommands;\r\n }\r\n\r\n public Map> getMenuItems() {\r\n return this.items;\r\n }\r\n\r\n public int getSize() {\r\n return this.size;\r\n }\r\n\r\n public int getUpdateInterval() {\r\n return updateInterval >= 1 ? updateInterval : 10;\r\n }\r\n\r\n public void setUpdateInterval(int updateInterval) {\r\n this.updateInterval = updateInterval;\r\n }\r\n\r\n public String getMenuCommandUsed(String command) {\r\n if (getMenuCommands() == null) {\r\n return null;\r\n }\r\n for (String c : getMenuCommands()) {\r\n if (command.equalsIgnoreCase(c)) {\r\n return c;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n public RequirementList getOpenRequirements() {\r\n return openRequirements;\r\n }\r\n\r\n public void setOpenRequirements(RequirementList openRequirements) {\r\n this.openRequirements = openRequirements;\r\n }\r\n\r\n public InventoryType getInventoryType() {\r\n return type;\r\n }\r\n\r\n public void setInventoryType(InventoryType type) {\r\n this.type = type;\r\n }\r\n\r\n public ClickHandler getOpenHandler() {\r\n return openHandler;\r\n }\r\n\r\n public void setOpenHandler(ClickHandler openHandler) {\r\n this.openHandler = openHandler;\r\n }\r\n\r\n public ClickHandler getCloseHandler() {\r\n return closeHandler;\r\n }\r\n\r\n public void setCloseHandler(ClickHandler closeHandler) {\r\n this.closeHandler = closeHandler;\r\n }\r\n\r\n public boolean registersCommand() {\r\n return registersCommand;\r\n }\r\n\r\n public String getArgUsageMessage() {\r\n return argUsageMessage;\r\n }\r\n\r\n public void setArgUsageMessage(String argUsageMessage) {\r\n this.argUsageMessage = argUsageMessage;\r\n }\r\n}\r", "answers": [" if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {\r"], "length": 4417, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "0031db9f-c5bf-4634-8773-df513b617b53", "reasoning": "The switch case for GIVE_MONEY is analogous to the TAKE_MONEY case just above. The next line should start the vault availability check, matching the pattern used earlier. Therefore the next line is the if statement that verifies Vault is hooked before proceeding with the give money action.", "reasoning_model_answer": "if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {", "assistant_with_reasoning": "\nThe switch case for GIVE_MONEY is analogous to the TAKE_MONEY case just above. The next line should start the vault availability check, matching the pattern used earlier. Therefore the next line is the if statement that verifies Vault is hooked before proceeding with the give money action.\n\nif (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.544, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36907, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) {", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport threestudio\n import trimesh\nfrom dataclasses import dataclass, field\nfrom threestudio.models.geometry.base import (\n BaseExplicitGeometry,\n BaseGeometry,\n contract_to_unisphere,\n)\nfrom threestudio.models.geometry.implicit_sdf import ImplicitSDF\nfrom threestudio.models.geometry.implicit_volume import ImplicitVolume\nfrom threestudio.models.isosurface import MarchingTetrahedraHelper\nfrom threestudio.models.mesh import Mesh\nfrom threestudio.models.networks import get_encoding, get_mlp\nfrom threestudio.utils.misc import broadcast\nfrom threestudio.utils.ops import scale_tensor\nfrom threestudio.utils.typing import *\n from pysdf import SDF", "context": "threestudio/models/geometry/tetrahedra_sdf_grid.py\n\n\n\n\n@threestudio.register(\"tetrahedra-sdf-grid\")\nclass TetrahedraSDFGrid(BaseExplicitGeometry):\n @dataclass\n\n\nthreestudio/models/networks.py\ndef get_mlp(n_input_dims, n_output_dims, config) -> nn.Module:\n network: nn.Module\n if config.otype == \"VanillaMLP\":\n network = VanillaMLP(n_input_dims, n_output_dims, config_to_primitive(config))\n elif config.otype == \"SphereInitVanillaMLP\":\n network = SphereInitVanillaMLP(\n n_input_dims, n_output_dims, config_to_primitive(config)\n )\n else:\n assert (\n config.get(\"sphere_init\", False) is False\n ), \"sphere_init=True only supported by VanillaMLP\"\n network = TCNNNetwork(n_input_dims, n_output_dims, config_to_primitive(config))\n return network\n\nthreestudio/utils/misc.py\ndef broadcast(tensor, src=0):\n if not _distributed_available():\n return tensor\n else:\n torch.distributed.broadcast(tensor, src=src)\n return tensor\n\nthreestudio/models/geometry/base.py\nclass BaseGeometry(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n @staticmethod\n def create_from(\n other: \"BaseGeometry\", cfg: Optional[Union[dict, DictConfig]] = None, **kwargs\n ) -> \"BaseGeometry\":\n raise TypeError(\n f\"Cannot create {BaseGeometry.__name__} from {other.__class__.__name__}\"\n )\n\n def export(self, *args, **kwargs) -> Dict[str, Any]:\n return {}\n\nthreestudio/models/mesh.py\nclass Mesh:\n def __init__(\n self, v_pos: Float[Tensor, \"Nv 3\"], t_pos_idx: Integer[Tensor, \"Nf 3\"], **kwargs\n ) -> None:\n self.v_pos: Float[Tensor, \"Nv 3\"] = v_pos\n self.t_pos_idx: Integer[Tensor, \"Nf 3\"] = t_pos_idx\n self._v_nrm: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tng: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tex: Optional[Float[Tensor, \"Nt 3\"]] = None\n self._t_tex_idx: Optional[Float[Tensor, \"Nf 3\"]] = None\n self._v_rgb: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n self.extras: Dict[str, Any] = {}\n for k, v in kwargs.items():\n self.add_extra(k, v)\n\n def add_extra(self, k, v) -> None:\n self.extras[k] = v\n\n def remove_outlier(self, outlier_n_faces_threshold: Union[int, float]) -> Mesh:\n if self.requires_grad:\n threestudio.debug(\"Mesh is differentiable, not removing outliers\")\n return self\n\n # use trimesh to first split the mesh into connected components\n # then remove the components with less than n_face_threshold faces\n import trimesh\n\n # construct a trimesh object\n mesh = trimesh.Trimesh(\n vertices=self.v_pos.detach().cpu().numpy(),\n faces=self.t_pos_idx.detach().cpu().numpy(),\n )\n\n # split the mesh into connected components\n components = mesh.split(only_watertight=False)\n # log the number of faces in each component\n threestudio.debug(\n \"Mesh has {} components, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n\n n_faces_threshold: int\n if isinstance(outlier_n_faces_threshold, float):\n # set the threshold to the number of faces in the largest component multiplied by outlier_n_faces_threshold\n n_faces_threshold = int(\n max([c.faces.shape[0] for c in components]) * outlier_n_faces_threshold\n )\n else:\n # set the threshold directly to outlier_n_faces_threshold\n n_faces_threshold = outlier_n_faces_threshold\n\n # log the threshold\n threestudio.debug(\n \"Removing components with less than {} faces\".format(n_faces_threshold)\n )\n\n # remove the components with less than n_face_threshold faces\n components = [c for c in components if c.faces.shape[0] >= n_faces_threshold]\n\n # log the number of faces in each component after removing outliers\n threestudio.debug(\n \"Mesh has {} components after removing outliers, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n # merge the components\n mesh = trimesh.util.concatenate(components)\n\n # convert back to our mesh format\n v_pos = torch.from_numpy(mesh.vertices).to(self.v_pos)\n t_pos_idx = torch.from_numpy(mesh.faces).to(self.t_pos_idx)\n\n clean_mesh = Mesh(v_pos, t_pos_idx)\n # keep the extras unchanged\n\n if len(self.extras) > 0:\n clean_mesh.extras = self.extras\n threestudio.debug(\n f\"The following extra attributes are inherited from the original mesh unchanged: {list(self.extras.keys())}\"\n )\n return clean_mesh\n\n @property\n def requires_grad(self):\n return self.v_pos.requires_grad\n\n @property\n def v_nrm(self):\n if self._v_nrm is None:\n self._v_nrm = self._compute_vertex_normal()\n return self._v_nrm\n\n @property\n def v_tng(self):\n if self._v_tng is None:\n self._v_tng = self._compute_vertex_tangent()\n return self._v_tng\n\n @property\n def v_tex(self):\n if self._v_tex is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._v_tex\n\n @property\n def t_tex_idx(self):\n if self._t_tex_idx is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._t_tex_idx\n\n @property\n def v_rgb(self):\n return self._v_rgb\n\n @property\n def edges(self):\n if self._edges is None:\n self._edges = self._compute_edges()\n return self._edges\n\n def _compute_vertex_normal(self):\n i0 = self.t_pos_idx[:, 0]\n i1 = self.t_pos_idx[:, 1]\n i2 = self.t_pos_idx[:, 2]\n\n v0 = self.v_pos[i0, :]\n v1 = self.v_pos[i1, :]\n v2 = self.v_pos[i2, :]\n\n face_normals = torch.cross(v1 - v0, v2 - v0)\n\n # Splat face normals to vertices\n v_nrm = torch.zeros_like(self.v_pos)\n v_nrm.scatter_add_(0, i0[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i1[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i2[:, None].repeat(1, 3), face_normals)\n\n # Normalize, replace zero (degenerated) normals with some default value\n v_nrm = torch.where(\n dot(v_nrm, v_nrm) > 1e-20, v_nrm, torch.as_tensor([0.0, 0.0, 1.0]).to(v_nrm)\n )\n v_nrm = F.normalize(v_nrm, dim=1)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(v_nrm))\n\n return v_nrm\n\n def _compute_vertex_tangent(self):\n vn_idx = [None] * 3\n pos = [None] * 3\n tex = [None] * 3\n for i in range(0, 3):\n pos[i] = self.v_pos[self.t_pos_idx[:, i]]\n tex[i] = self.v_tex[self.t_tex_idx[:, i]]\n # t_nrm_idx is always the same as t_pos_idx\n vn_idx[i] = self.t_pos_idx[:, i]\n\n tangents = torch.zeros_like(self.v_nrm)\n tansum = torch.zeros_like(self.v_nrm)\n\n # Compute tangent space for each triangle\n uve1 = tex[1] - tex[0]\n uve2 = tex[2] - tex[0]\n pe1 = pos[1] - pos[0]\n pe2 = pos[2] - pos[0]\n\n nom = pe1 * uve2[..., 1:2] - pe2 * uve1[..., 1:2]\n denom = uve1[..., 0:1] * uve2[..., 1:2] - uve1[..., 1:2] * uve2[..., 0:1]\n\n # Avoid division by zero for degenerated texture coordinates\n tang = nom / torch.where(\n denom > 0.0, torch.clamp(denom, min=1e-6), torch.clamp(denom, max=-1e-6)\n )\n\n # Update all 3 vertices\n for i in range(0, 3):\n idx = vn_idx[i][:, None].repeat(1, 3)\n tangents.scatter_add_(0, idx, tang) # tangents[n_i] = tangents[n_i] + tang\n tansum.scatter_add_(\n 0, idx, torch.ones_like(tang)\n ) # tansum[n_i] = tansum[n_i] + 1\n tangents = tangents / tansum\n\n # Normalize and make sure tangent is perpendicular to normal\n tangents = F.normalize(tangents, dim=1)\n tangents = F.normalize(tangents - dot(tangents, self.v_nrm) * self.v_nrm)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(tangents))\n\n return tangents\n\n def _unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n threestudio.info(\"Using xatlas to perform UV unwrapping, may take a while ...\")\n\n import xatlas\n\n atlas = xatlas.Atlas()\n atlas.add_mesh(\n self.v_pos.detach().cpu().numpy(),\n self.t_pos_idx.cpu().numpy(),\n )\n co = xatlas.ChartOptions()\n po = xatlas.PackOptions()\n for k, v in xatlas_chart_options.items():\n setattr(co, k, v)\n for k, v in xatlas_pack_options.items():\n setattr(po, k, v)\n atlas.generate(co, po)\n vmapping, indices, uvs = atlas.get_mesh(0)\n vmapping = (\n torch.from_numpy(\n vmapping.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n uvs = torch.from_numpy(uvs).to(self.v_pos.device).float()\n indices = (\n torch.from_numpy(\n indices.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n return uvs, indices\n\n def unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n self._v_tex, self._t_tex_idx = self._unwrap_uv(\n xatlas_chart_options, xatlas_pack_options\n )\n\n def set_vertex_color(self, v_rgb):\n assert v_rgb.shape[0] == self.v_pos.shape[0]\n self._v_rgb = v_rgb\n\n def _compute_edges(self):\n # Compute edges\n edges = torch.cat(\n [\n self.t_pos_idx[:, [0, 1]],\n self.t_pos_idx[:, [1, 2]],\n self.t_pos_idx[:, [2, 0]],\n ],\n dim=0,\n )\n edges = edges.sort()[0]\n edges = torch.unique(edges, dim=0)\n return edges\n\n def normal_consistency(self) -> Float[Tensor, \"\"]:\n edge_nrm: Float[Tensor, \"Ne 2 3\"] = self.v_nrm[self.edges]\n nc = (\n 1.0 - torch.cosine_similarity(edge_nrm[:, 0], edge_nrm[:, 1], dim=-1)\n ).mean()\n return nc\n\n def _laplacian_uniform(self):\n # from stable-dreamfusion\n # https://github.com/ashawkey/stable-dreamfusion/blob/8fb3613e9e4cd1ded1066b46e80ca801dfb9fd06/nerf/renderer.py#L224\n verts, faces = self.v_pos, self.t_pos_idx\n\n V = verts.shape[0]\n F = faces.shape[0]\n\n # Neighbor indices\n ii = faces[:, [1, 2, 0]].flatten()\n jj = faces[:, [2, 0, 1]].flatten()\n adj = torch.stack([torch.cat([ii, jj]), torch.cat([jj, ii])], dim=0).unique(\n dim=1\n )\n adj_values = torch.ones(adj.shape[1]).to(verts)\n\n # Diagonal indices\n diag_idx = adj[0]\n\n # Build the sparse matrix\n idx = torch.cat((adj, torch.stack((diag_idx, diag_idx), dim=0)), dim=1)\n values = torch.cat((-adj_values, adj_values))\n\n # The coalesce operation sums the duplicate indices, resulting in the\n # correct diagonal\n return torch.sparse_coo_tensor(idx, values, (V, V)).coalesce()\n\n def laplacian(self) -> Float[Tensor, \"\"]:\n with torch.no_grad():\n L = self._laplacian_uniform()\n loss = L.mm(self.v_pos)\n loss = loss.norm(dim=1)\n loss = loss.mean()\n return loss\n\nthreestudio/models/geometry/implicit_sdf.py\nclass ImplicitSDF(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: Union[\n float, str\n ] = 0.01 # in [float, \"progressive\"]\n shape_init: Optional[str] = None\n shape_init_params: Optional[Any] = None\n shape_init_mesh_up: str = \"+z\"\n shape_init_mesh_front: str = \"+x\"\n force_shape_init: bool = False\n sdf_bias: Union[float, str] = 0.0\n sdf_bias_params: Optional[Any] = None\n\n # no need to removal outlier for SDF\n isosurface_remove_outliers: bool = False\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.sdf_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n if self.cfg.isosurface_deformable_grid:\n assert (\n self.cfg.isosurface_method == \"mt\"\n ), \"isosurface_deformable_grid only works with mt\"\n self.deformation_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n self.finite_difference_normal_eps: Optional[float] = None\n\n def initialize_shape(self) -> None:\n if self.cfg.shape_init is None and not self.cfg.force_shape_init:\n return\n\n # do not initialize shape if weights are provided\n if self.cfg.weights is not None and not self.cfg.force_shape_init:\n return\n\n if self.cfg.sdf_bias != 0.0:\n threestudio.warn(\n \"shape_init and sdf_bias are both specified, which may lead to unexpected results.\"\n )\n\n get_gt_sdf: Callable[[Float[Tensor, \"N 3\"]], Float[Tensor, \"N 1\"]]\n assert isinstance(self.cfg.shape_init, str)\n if self.cfg.shape_init == \"ellipsoid\":\n assert (\n isinstance(self.cfg.shape_init_params, Sized)\n and len(self.cfg.shape_init_params) == 3\n )\n size = torch.as_tensor(self.cfg.shape_init_params).to(self.device)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return ((points_rand / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n\n get_gt_sdf = func\n elif self.cfg.shape_init == \"sphere\":\n assert isinstance(self.cfg.shape_init_params, float)\n radius = self.cfg.shape_init_params\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius\n\n get_gt_sdf = func\n elif self.cfg.shape_init.startswith(\"mesh:\"):\n assert isinstance(self.cfg.shape_init_params, float)\n mesh_path = self.cfg.shape_init[5:]\n if not os.path.exists(mesh_path):\n raise ValueError(f\"Mesh file {mesh_path} does not exist.\")\n\n import trimesh\n\n scene = trimesh.load(mesh_path)\n if isinstance(scene, trimesh.Trimesh):\n mesh = scene\n elif isinstance(scene, trimesh.scene.Scene):\n mesh = trimesh.Trimesh()\n for obj in scene.geometry.values():\n mesh = trimesh.util.concatenate([mesh, obj])\n else:\n raise ValueError(f\"Unknown mesh type at {mesh_path}.\")\n\n # move to center\n centroid = mesh.vertices.mean(0)\n mesh.vertices = mesh.vertices - centroid\n\n # align to up-z and front-x\n dirs = [\"+x\", \"+y\", \"+z\", \"-x\", \"-y\", \"-z\"]\n dir2vec = {\n \"+x\": np.array([1, 0, 0]),\n \"+y\": np.array([0, 1, 0]),\n \"+z\": np.array([0, 0, 1]),\n \"-x\": np.array([-1, 0, 0]),\n \"-y\": np.array([0, -1, 0]),\n \"-z\": np.array([0, 0, -1]),\n }\n if (\n self.cfg.shape_init_mesh_up not in dirs\n or self.cfg.shape_init_mesh_front not in dirs\n ):\n raise ValueError(\n f\"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}.\"\n )\n if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]:\n raise ValueError(\n \"shape_init_mesh_up and shape_init_mesh_front must be orthogonal.\"\n )\n z_, x_ = (\n dir2vec[self.cfg.shape_init_mesh_up],\n dir2vec[self.cfg.shape_init_mesh_front],\n )\n y_ = np.cross(z_, x_)\n std2mesh = np.stack([x_, y_, z_], axis=0).T\n mesh2std = np.linalg.inv(std2mesh)\n\n # scaling\n scale = np.abs(mesh.vertices).max()\n mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params\n mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T\n\n from pysdf import SDF\n\n sdf = SDF(mesh.vertices, mesh.faces)\n\n def func(points_rand: Float[Tensor, \"N 3\"]) -> Float[Tensor, \"N 1\"]:\n # add a negative signed here\n # as in pysdf the inside of the shape has positive signed distance\n return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to(\n points_rand\n )[..., None]\n\n get_gt_sdf = func\n\n else:\n raise ValueError(\n f\"Unknown shape initialization type: {self.cfg.shape_init}\"\n )\n\n # Initialize SDF to a given shape when no weights are provided or force_shape_init is True\n optim = torch.optim.Adam(self.parameters(), lr=1e-3)\n from tqdm import tqdm\n\n for _ in tqdm(\n range(1000),\n desc=f\"Initializing SDF to a(n) {self.cfg.shape_init}:\",\n disable=get_rank() != 0,\n ):\n points_rand = (\n torch.rand((10000, 3), dtype=torch.float32).to(self.device) * 2.0 - 1.0\n )\n sdf_gt = get_gt_sdf(points_rand)\n sdf_pred = self.forward_sdf(points_rand)\n loss = F.mse_loss(sdf_pred, sdf_gt)\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n # explicit broadcast to ensure param consistency across ranks\n for param in self.parameters():\n broadcast(param, src=0)\n\n def get_shifted_sdf(\n self, points: Float[Tensor, \"*N Di\"], sdf: Float[Tensor, \"*N 1\"]\n ) -> Float[Tensor, \"*N 1\"]:\n sdf_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.sdf_bias == \"ellipsoid\":\n assert (\n isinstance(self.cfg.sdf_bias_params, Sized)\n and len(self.cfg.sdf_bias_params) == 3\n )\n size = torch.as_tensor(self.cfg.sdf_bias_params).to(points)\n sdf_bias = ((points / size) ** 2).sum(\n dim=-1, keepdim=True\n ).sqrt() - 1.0 # pseudo signed distance of an ellipsoid\n elif self.cfg.sdf_bias == \"sphere\":\n assert isinstance(self.cfg.sdf_bias_params, float)\n radius = self.cfg.sdf_bias_params\n sdf_bias = (points**2).sum(dim=-1, keepdim=True).sqrt() - radius\n elif isinstance(self.cfg.sdf_bias, float):\n sdf_bias = self.cfg.sdf_bias\n else:\n raise ValueError(f\"Unknown sdf bias {self.cfg.sdf_bias}\")\n return sdf + sdf_bias\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).view(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n output = {\"sdf\": sdf}\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n assert self.finite_difference_normal_eps is not None\n eps: float = self.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 6 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (\n 0.5\n * (sdf_offset[..., 0::2, 0] - sdf_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n sdf_offset: Float[Tensor, \"... 3 1\"] = self.forward_sdf(\n points_offset\n )\n sdf_grad = (sdf_offset[..., 0::1, 0] - sdf) / eps\n normal = F.normalize(sdf_grad, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n sdf_grad = normal\n elif self.cfg.normal_type == \"analytic\":\n sdf_grad = -torch.autograd.grad(\n sdf,\n points_unscaled,\n grad_outputs=torch.ones_like(sdf),\n create_graph=True,\n )[0]\n normal = F.normalize(sdf_grad, dim=-1)\n if not grad_enabled:\n sdf_grad = sdf_grad.detach()\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update(\n {\"normal\": normal, \"shading_normal\": normal, \"sdf_grad\": sdf_grad}\n )\n return output\n\n def forward_sdf(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n sdf = self.sdf_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n return sdf\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n sdf = self.sdf_network(enc).reshape(*points.shape[:-1], 1)\n sdf = self.get_shifted_sdf(points_unscaled, sdf)\n deformation: Optional[Float[Tensor, \"*N 3\"]] = None\n if self.cfg.isosurface_deformable_grid:\n deformation = self.deformation_network(enc).reshape(*points.shape[:-1], 3)\n return sdf, deformation\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return field - threshold\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n if isinstance(self.cfg.finite_difference_normal_eps, float):\n self.finite_difference_normal_eps = (\n self.cfg.finite_difference_normal_eps\n )\n elif self.cfg.finite_difference_normal_eps == \"progressive\":\n # progressive finite difference eps from Neuralangelo\n # https://arxiv.org/abs/2306.03092\n hg_conf: Any = self.cfg.pos_encoding_config\n assert (\n hg_conf.otype == \"ProgressiveBandHashGrid\"\n ), \"finite_difference_normal_eps=progressive only works with ProgressiveBandHashGrid\"\n current_level = min(\n hg_conf.start_level\n + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps,\n hg_conf.n_levels,\n )\n grid_res = hg_conf.base_resolution * hg_conf.per_level_scale ** (\n current_level - 1\n )\n grid_size = 2 * self.cfg.radius / grid_res\n if grid_size != self.finite_difference_normal_eps:\n threestudio.info(\n f\"Update finite_difference_normal_eps to {grid_size}\"\n )\n self.finite_difference_normal_eps = grid_size\n else:\n raise ValueError(\n f\"Unknown finite_difference_normal_eps={self.cfg.finite_difference_normal_eps}\"\n )\n\nthreestudio/utils/ops.py\ndef scale_tensor(\n dat: Num[Tensor, \"... D\"], inp_scale: ValidScale, tgt_scale: ValidScale\n):\n if inp_scale is None:\n inp_scale = (0, 1)\n if tgt_scale is None:\n tgt_scale = (0, 1)\n if isinstance(tgt_scale, Tensor):\n assert dat.shape[-1] == tgt_scale.shape[-1]\n dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0])\n dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0]\n return dat\n\nthreestudio/models/geometry/base.py\ndef contract_to_unisphere(\n x: Float[Tensor, \"... 3\"], bbox: Float[Tensor, \"2 3\"], unbounded: bool = False\n) -> Float[Tensor, \"... 3\"]:\n if unbounded:\n x = scale_tensor(x, bbox, (0, 1))\n x = x * 2 - 1 # aabb is at [-1, 1]\n mag = x.norm(dim=-1, keepdim=True)\n mask = mag.squeeze(-1) > 1\n x[mask] = (2 - 1 / mag[mask]) * (x[mask] / mag[mask])\n x = x / 4 + 0.5 # [-inf, inf] is at [0, 1]\n else:\n x = scale_tensor(x, bbox, (0, 1))\n return x\n\nthreestudio/models/geometry/implicit_volume.py\nclass ImplicitVolume(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n density_activation: Optional[str] = \"softplus\"\n density_bias: Union[float, str] = \"blob_magic3d\"\n density_blob_scale: float = 10.0\n density_blob_std: float = 0.5\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: Union[\n float, str\n ] = 0.01 # in [float, \"progressive\"]\n\n # automatically determine the threshold\n isosurface_threshold: Union[float, str] = 25.0\n\n # 4D Gaussian Annealing\n anneal_density_blob_std_config: Optional[dict] = None\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.density_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n self.finite_difference_normal_eps: Optional[float] = None\n\n def get_activated_density(\n self, points: Float[Tensor, \"*N Di\"], density: Float[Tensor, \"*N 1\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Float[Tensor, \"*N 1\"]]:\n density_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.density_bias == \"blob_dreamfusion\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * torch.exp(\n -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2\n )[..., None]\n )\n elif self.cfg.density_bias == \"blob_magic3d\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * (\n 1\n - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std\n )[..., None]\n )\n elif isinstance(self.cfg.density_bias, float):\n density_bias = self.cfg.density_bias\n else:\n raise ValueError(f\"Unknown density bias {self.cfg.density_bias}\")\n raw_density: Float[Tensor, \"*N 1\"] = density + density_bias\n density = get_activation(self.cfg.density_activation)(raw_density)\n return raw_density, density\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n density = self.density_network(enc).view(*points.shape[:-1], 1)\n raw_density, density = self.get_activated_density(points_unscaled, density)\n\n output = {\n \"density\": density,\n }\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n # TODO: use raw density\n assert self.finite_difference_normal_eps is not None\n eps: float = self.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 6 1\"] = self.forward_density(\n points_offset\n )\n normal = (\n -0.5\n * (density_offset[..., 0::2, 0] - density_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 3 1\"] = self.forward_density(\n points_offset\n )\n normal = -(density_offset[..., 0::1, 0] - density) / eps\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"analytic\":\n normal = -torch.autograd.grad(\n density,\n points_unscaled,\n grad_outputs=torch.ones_like(density),\n create_graph=True,\n )[0]\n normal = F.normalize(normal, dim=-1)\n if not grad_enabled:\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update({\"normal\": normal, \"shading_normal\": normal})\n\n torch.set_grad_enabled(grad_enabled)\n return output\n\n def forward_density(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n density = self.density_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n\n _, density = self.get_activated_density(points_unscaled, density)\n return density\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n if self.cfg.isosurface_deformable_grid:\n threestudio.warn(\n f\"{self.__class__.__name__} does not support isosurface_deformable_grid. Ignoring.\"\n )\n density = self.forward_density(points)\n return density, None\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return -(field - threshold)\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n @staticmethod\n @torch.no_grad()\n def create_from(\n other: BaseGeometry,\n cfg: Optional[Union[dict, DictConfig]] = None,\n copy_net: bool = True,\n **kwargs,\n ) -> \"ImplicitVolume\":\n if isinstance(other, ImplicitVolume):\n instance = ImplicitVolume(cfg, **kwargs)\n instance.encoding.load_state_dict(other.encoding.state_dict())\n instance.density_network.load_state_dict(other.density_network.state_dict())\n if copy_net:\n if (\n instance.cfg.n_feature_dims > 0\n and other.cfg.n_feature_dims == instance.cfg.n_feature_dims\n ):\n instance.feature_network.load_state_dict(\n other.feature_network.state_dict()\n )\n if (\n instance.cfg.normal_type == \"pred\"\n and other.cfg.normal_type == \"pred\"\n ):\n instance.normal_network.load_state_dict(\n other.normal_network.state_dict()\n )\n return instance\n else:\n raise TypeError(\n f\"Cannot create {ImplicitVolume.__name__} from {other.__class__.__name__}\"\n )\n\n # FIXME: use progressive normal eps\n def update_step(\n self, epoch: int, global_step: int, on_load_weights: bool = False\n ) -> None:\n if self.cfg.anneal_density_blob_std_config is not None:\n min_step = self.cfg.anneal_density_blob_std_config.min_anneal_step\n max_step = self.cfg.anneal_density_blob_std_config.max_anneal_step\n if global_step >= min_step and global_step <= max_step:\n end_val = self.cfg.anneal_density_blob_std_config.end_val\n start_val = self.cfg.anneal_density_blob_std_config.start_val\n self.density_blob_std = start_val + (global_step - min_step) * (\n end_val - start_val\n ) / (max_step - min_step)\n\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n if isinstance(self.cfg.finite_difference_normal_eps, float):\n self.finite_difference_normal_eps = (\n self.cfg.finite_difference_normal_eps\n )\n elif self.cfg.finite_difference_normal_eps == \"progressive\":\n # progressive finite difference eps from Neuralangelo\n # https://arxiv.org/abs/2306.03092\n hg_conf: Any = self.cfg.pos_encoding_config\n assert (\n hg_conf.otype == \"ProgressiveBandHashGrid\"\n ), \"finite_difference_normal_eps=progressive only works with ProgressiveBandHashGrid\"\n current_level = min(\n hg_conf.start_level\n + max(global_step - hg_conf.start_step, 0) // hg_conf.update_steps,\n hg_conf.n_levels,\n )\n grid_res = hg_conf.base_resolution * hg_conf.per_level_scale ** (\n current_level - 1\n )\n grid_size = 2 * self.cfg.radius / grid_res\n if grid_size != self.finite_difference_normal_eps:\n threestudio.info(\n f\"Update finite_difference_normal_eps to {grid_size}\"\n )\n self.finite_difference_normal_eps = grid_size\n else:\n raise ValueError(\n f\"Unknown finite_difference_normal_eps={self.cfg.finite_difference_normal_eps}\"\n )\n\nthreestudio/models/isosurface.py\nclass MarchingTetrahedraHelper(IsosurfaceHelper):\n def __init__(self, resolution: int, tets_path: str):\n super().__init__()\n self.resolution = resolution\n self.tets_path = tets_path\n\n self.triangle_table: Float[Tensor, \"...\"]\n self.register_buffer(\n \"triangle_table\",\n torch.as_tensor(\n [\n [-1, -1, -1, -1, -1, -1],\n [1, 0, 2, -1, -1, -1],\n [4, 0, 3, -1, -1, -1],\n [1, 4, 2, 1, 3, 4],\n [3, 1, 5, -1, -1, -1],\n [2, 3, 0, 2, 5, 3],\n [1, 4, 0, 1, 5, 4],\n [4, 2, 5, -1, -1, -1],\n [4, 5, 2, -1, -1, -1],\n [4, 1, 0, 4, 5, 1],\n [3, 2, 0, 3, 5, 2],\n [1, 3, 5, -1, -1, -1],\n [4, 1, 2, 4, 3, 1],\n [3, 0, 4, -1, -1, -1],\n [2, 0, 1, -1, -1, -1],\n [-1, -1, -1, -1, -1, -1],\n ],\n dtype=torch.long,\n ),\n persistent=False,\n )\n self.num_triangles_table: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"num_triangles_table\",\n torch.as_tensor(\n [0, 1, 1, 2, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 0], dtype=torch.long\n ),\n persistent=False,\n )\n self.base_tet_edges: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"base_tet_edges\",\n torch.as_tensor([0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3], dtype=torch.long),\n persistent=False,\n )\n\n tets = np.load(self.tets_path)\n self._grid_vertices: Float[Tensor, \"...\"]\n self.register_buffer(\n \"_grid_vertices\",\n torch.from_numpy(tets[\"vertices\"]).float(),\n persistent=False,\n )\n self.indices: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"indices\", torch.from_numpy(tets[\"indices\"]).long(), persistent=False\n )\n\n self._all_edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n\n def normalize_grid_deformation(\n self, grid_vertex_offsets: Float[Tensor, \"Nv 3\"]\n ) -> Float[Tensor, \"Nv 3\"]:\n return (\n (self.points_range[1] - self.points_range[0])\n / (self.resolution) # half tet size is approximately 1 / self.resolution\n * torch.tanh(grid_vertex_offsets)\n ) # FIXME: hard-coded activation\n\n @property\n def grid_vertices(self) -> Float[Tensor, \"Nv 3\"]:\n return self._grid_vertices\n\n @property\n def all_edges(self) -> Integer[Tensor, \"Ne 2\"]:\n if self._all_edges is None:\n # compute edges on GPU, or it would be VERY SLOW (basically due to the unique operation)\n edges = torch.tensor(\n [0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],\n dtype=torch.long,\n device=self.indices.device,\n )\n _all_edges = self.indices[:, edges].reshape(-1, 2)\n _all_edges_sorted = torch.sort(_all_edges, dim=1)[0]\n _all_edges = torch.unique(_all_edges_sorted, dim=0)\n self._all_edges = _all_edges\n return self._all_edges\n\n def sort_edges(self, edges_ex2):\n with torch.no_grad():\n order = (edges_ex2[:, 0] > edges_ex2[:, 1]).long()\n order = order.unsqueeze(dim=1)\n\n a = torch.gather(input=edges_ex2, index=order, dim=1)\n b = torch.gather(input=edges_ex2, index=1 - order, dim=1)\n\n return torch.stack([a, b], -1)\n\n def _forward(self, pos_nx3, sdf_n, tet_fx4):\n with torch.no_grad():\n occ_n = sdf_n > 0\n occ_fx4 = occ_n[tet_fx4.reshape(-1)].reshape(-1, 4)\n occ_sum = torch.sum(occ_fx4, -1)\n valid_tets = (occ_sum > 0) & (occ_sum < 4)\n occ_sum = occ_sum[valid_tets]\n\n # find all vertices\n all_edges = tet_fx4[valid_tets][:, self.base_tet_edges].reshape(-1, 2)\n all_edges = self.sort_edges(all_edges)\n unique_edges, idx_map = torch.unique(all_edges, dim=0, return_inverse=True)\n\n unique_edges = unique_edges.long()\n mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1\n mapping = (\n torch.ones(\n (unique_edges.shape[0]), dtype=torch.long, device=pos_nx3.device\n )\n * -1\n )\n mapping[mask_edges] = torch.arange(\n mask_edges.sum(), dtype=torch.long, device=pos_nx3.device\n )\n idx_map = mapping[idx_map] # map edges to verts\n\n interp_v = unique_edges[mask_edges]\n edges_to_interp = pos_nx3[interp_v.reshape(-1)].reshape(-1, 2, 3)\n edges_to_interp_sdf = sdf_n[interp_v.reshape(-1)].reshape(-1, 2, 1)\n edges_to_interp_sdf[:, -1] *= -1\n\n denominator = edges_to_interp_sdf.sum(1, keepdim=True)\n\n edges_to_interp_sdf = torch.flip(edges_to_interp_sdf, [1]) / denominator\n verts = (edges_to_interp * edges_to_interp_sdf).sum(1)\n\n idx_map = idx_map.reshape(-1, 6)\n\n v_id = torch.pow(2, torch.arange(4, dtype=torch.long, device=pos_nx3.device))\n tetindex = (occ_fx4[valid_tets] * v_id.unsqueeze(0)).sum(-1)\n num_triangles = self.num_triangles_table[tetindex]\n\n # Generate triangle indices\n faces = torch.cat(\n (\n torch.gather(\n input=idx_map[num_triangles == 1],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 1]][:, :3],\n ).reshape(-1, 3),\n torch.gather(\n input=idx_map[num_triangles == 2],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 2]][:, :6],\n ).reshape(-1, 3),\n ),\n dim=0,\n )\n\n return verts, faces\n\n def forward(\n self,\n level: Float[Tensor, \"N3 1\"],\n deformation: Optional[Float[Tensor, \"N3 3\"]] = None,\n ) -> Mesh:\n if deformation is not None:\n grid_vertices = self.grid_vertices + self.normalize_grid_deformation(\n deformation\n )\n else:\n grid_vertices = self.grid_vertices\n\n v_pos, t_pos_idx = self._forward(grid_vertices, level, self.indices)\n\n mesh = Mesh(\n v_pos=v_pos,\n t_pos_idx=t_pos_idx,\n # extras\n grid_vertices=grid_vertices,\n tet_edges=self.all_edges,\n grid_level=level,\n grid_deformation=deformation,\n )\n\n return mesh", "answers": [" class Config(BaseExplicitGeometry.Config):"], "length": 3950, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "660f400b-df95-40fb-ab86-0460b0e60225", "reasoning": "Inside the TetrahedraSDFGrid class we see the @dataclass decorator, which in other geometry classes is used to define an inner Config dataclass inheriting from the base geometry's Config. After the imports, the next logical line is the declaration of this inner Config class.", "reasoning_model_answer": "class Config(BaseExplicitGeometry.Config):", "assistant_with_reasoning": "\nInside the TetrahedraSDFGrid class we see the @dataclass decorator, which in other geometry classes is used to define an inner Config dataclass inheriting from the base geometry's Config. After the imports, the next logical line is the declaration of this inner Config class.\n\nclass Config(BaseExplicitGeometry.Config):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.547, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36800, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "class Config(BaseExplicitGeometry.Config):", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.buschmais.backend.users.User;\nimport com.buschmais.frontend.MainLayout;\nimport com.buschmais.frontend.views.ADRExplorer.ADRExplorerView;\nimport com.buschmais.frontend.views.adrCreate.ADRRichCreateView;\nimport com.buschmais.frontend.views.adrVote.ADRVoteView;\nimport com.buschmais.frontend.views.kanban.KanbanView;\nimport com.buschmais.frontend.views.login.LoginView;\nimport com.buschmais.frontend.views.logout.LogoutView;\nimport com.buschmais.frontend.views.notifications.NotiView;\nimport com.buschmais.frontend.views.user.UserView;\nimport com.buschmais.frontend.views.usercontrol.GroupsInformationView;\nimport com.buschmais.frontend.views.usercontrol.UserControlView;\nimport com.buschmais.frontend.views.welcome.WelcomeView;\nimport com.vaadin.flow.component.Component;\nimport com.vaadin.flow.router.RouterLayout;\nimport lombok.Getter;\nimport lombok.NonNull;", "context": "src/main/java/com/buschmais/frontend/vars/OtherConstantsFrontend.java\npackage com.buschmais.frontend.vars;\n\n\npublic class OtherConstantsFrontend {\n\n\tpublic static final User DEFAULT_DELETED_USER = new User(StringConstantsFrontend.DEFAULT_DELETED_USER_NAME, Double.toString(Math.random()*1000000000000d));\n\n\tpublic static class MenuItemInfo {\n\n\t\tprivate String text;\n\t\tprivate String iconClass;\n\t\tprivate Class view;\n\n\t\tpublic MenuItemInfo(String text, String iconClass, Class view) {\n\t\t\tthis.text = text;\n\t\t\tthis.iconClass = iconClass;\n\t\t\tthis.view = view;\n\t\t}\n\n\t\tpublic String getText() {\n\t\t\treturn text;\n\t\t}\n\n\t\tpublic String getIconClass() {\n\t\t\treturn iconClass;\n\t\t}\n\n\t\tpublic Class getView() {\n\t\t\treturn view;\n\t\t}\n\t}\n\tpublic static final MenuItemInfo[] MENU_ITEM_INFOS = new MenuItemInfo[]{\n\t\t\tnew MenuItemInfo(StringConstantsFrontend.MENU_TITLE_LOGIN, \"la la-user\", LoginView.class),\n\n\t\t\tnew MenuItemInfo(StringConstantsFrontend.MENU_TITLE_OVERVIEW, \"la la-clipboard\", KanbanView.class),\n\n\t\t\tnew MenuItemInfo(StringConstantsFrontend.MENU_TITLE_EXPLORER, \"la la-archive\", ADRExplorerView.class),\n\n\t\t\tnew MenuItemInfo(StringConstantsFrontend.MENU_TITLE_CREATE_ADR, \"la la-pencil\", ADRRichCreateView.class),\n\n\t\t\tnew MenuItemInfo(StringConstantsFrontend.MENU_TITLE_USER, \"la la-user\", UserView.class),\n\n\t\t\tnew MenuItemInfo(StringConstantsFrontend.MENU_TITLE_USER_CONTROL, \"la la-users\", UserControlView.class),\n\n\n\n\t\t\t//new MenuItemInfo(\"ADRDetails\", \"la la-info-circle\", ADRDetailsView.class),\n\n\n\n\t};\n\n\n\tpublic static class Route {\n\n\t\t@NonNull\n\t\t@Getter\n\t\tprivate String path;\n\n\t\t@NonNull\n\t\t@Getter\n\t\tprivate Class view;\n\n\t\t@NonNull\n\t\t@Getter\n\t\tprivate Class parentView;\n\n\t\tpublic Route(@NonNull String path, @NonNull Class view) {\n\t\t\tthis.path = path;\n\t\t\tthis.view = view;\n\t\t\tthis.parentView = MainLayout.class;\n\t\t}\n\n\t\tpublic Route(@NonNull String path, @NonNull Class view, @NonNull Class parentView) {\n\t\t\tthis.path = path;\n\t\t\tthis.view = view;\n\t\t\tthis.parentView = parentView;\n\t\t}\n\t}\n\tpublic static final Route[] ALWAYS_ACCESSIBLE_ROUTES = new Route[] {\n\t\t\tnew Route(StringConstantsFrontend.LANDING_PAGE_PATH, WelcomeView.class),\n\t\t\tnew Route(StringConstantsFrontend.LANDING_PAGE_PATH_ALIAS, WelcomeView.class)\n\t};\n\tpublic static final Route[] LOGGED_OUT_ACCESSIBLE_ROUTES = new Route[] {\n\t\t\tnew Route(StringConstantsFrontend.LOGIN_PATH, LoginView.class)\n/*\t\t\tnew Route(StringConstantsFrontend.ADR_CREATE_PATH, ADRCreateView.class),\n\t\t\tnew Route(StringConstantsFrontend.ADR_CREATE_PATH, ADRCreateView.class),\n\t\t\tnew Route(StringConstantsFrontend.ADR_CREATE_PATH, ADRCreateView.class)\n*/\t};\n\tpublic static final Route[] LOGGED_IN_ACCESSIBLE_ROUTES = new Route[] {\n\t\t\tnew Route(StringConstantsFrontend.ADR_CREATE_PATH, ADRRichCreateView.class),\n\t\t\tnew Route(StringConstantsFrontend.OVERVIEW_PATH, KanbanView.class),\n\t\t\tnew Route(StringConstantsFrontend.ADR_DETAILS_PATH, ADRVoteView.class),\n\t\t\tnew Route(StringConstantsFrontend.USER_PATH, UserView.class),\n\t\t\tnew Route(StringConstantsFrontend.LOGOUT_PATH, LogoutView.class),\n\t\t\tnew Route(StringConstantsFrontend.NOTI_PATH, NotiView.class),\n\t\t\tnew Route(StringConstantsFrontend.EXPL_PATH, ADRExplorerView.class),\n\n//\t\t\tnew Route(StringConstantsFrontend.ADR_CREATE_PATH, ADRCreateView.class)\n\t};\n\tpublic static final Route[] ADMIN_ACCESSIBLE_ROUTES = new Route[] {\n\nsrc/main/java/com/buschmais/frontend/views/welcome/WelcomeView.java\n@PageTitle(\"Willkommen\")\n//@Route(value = StringConstantsFrontend.LANDING_PAGE_PATH, layout = MainLayout.class)\n//@RouteAlias(value = \"\", layout = MainLayout.class)\n@CssImport(value = \"./themes/adr-workbench/welcome/welcome.css\")\n@Tag(\"hello-world-view\")\n//@WebServlet(value = \"/*\", asyncSupported = true)\npublic class WelcomeView extends VerticalLayout {\n\n\tprivate UserDao userDao;\n\n\tprivate Label welcomeLabel;\n\tprivate Label motivationLabel;\n\tprivate Label joinLabel;\n\tprivate Label loginLabel;\n\n\tprivate Html motivationSpan;\n\tprivate Html loginSpan;\n\tprivate Html registerSpan;\n\tprivate Html blankLineP;\n\n\tprivate Div welcomeDiv;\n\tprivate Div motivationDiv;\n\tprivate Div joinDiv;\n\n\tprivate Button loginButton;\n\n\tpublic WelcomeView(@Autowired UserDao userDao) {\n\t\tthis.userDao = userDao;\n\n\t\tsetupComponents();\n\t\taddComponentsToLayouts();\n\t}\n\n\tprivate void setupComponents() {\n\n\t\t// define\n\t\t{\n\t\t\tthis.welcomeLabel = new Label(\"Willkommen bei ADR-Workbench\");\n\t\t\tthis.motivationLabel = new Label(\"Motivation\");\n\t\t\tthis.joinLabel = new Label(\"Projektbeteiligung\");\n\t\t\tthis.loginLabel = new Label(\"Login\");\n\n\t\t\tthis.motivationSpan = new Html(\"

Die Dokumentation während der Entwicklung eines Softwareprojekte ist kein besonders beliebtes Thema. \" +\n\t\t\t\t\t\"Dennoch ist Dokumentation das nahezu wichtigste, um den Überblick über ein Projekt zu behalten und um dieses schlussendlich erfolgreich fertigstellen zu können.\" +\n\t\t\t\t\t\"Um diese Arbeit zu erleichtern wird das Tool ADR-Workbench entworfen. \" +\n\t\t\t\t\t\"Hiermit soll es möglich sein, sogenannte Architecture Decision Records (kurz ADRs) kollaborativ zu entwerfen. \" +\n\t\t\t\t\t\"Ein ADR stellt dabei eine beliebige Architekturentscheidung (z.B. es wird nur noch Logger X genutzt) dar, die von allen Mitarbeitern akzeptiert, kommentiert und abgelehnt werden kann.\" +\n\t\t\t\t\t\"So ist es möglich die Entscheidungen einheitlich zu speichern und immer geordnet abrufen zu können. \" +\n\t\t\t\t\t\"Die grafische Oberfläche (Web-Applikation) soll dabei eine einfache Bedienbarkeit bereitstellen, um ein möglichst effizientes Arbeiten zu ermöglichen.

\");\n\n\t\t\tthis.loginSpan = new Html(\"

Du bist bereits am Projekt beteiligt? Dann kommst du hier zum Login:

\");\n\t\t\tthis.registerSpan = new Html(\"

Du hast noch keine Zugangsdaten? Kein Problem, frag einfach deinen Projektleiter nach einem Zugang!

\");\n\t\t\tthis.blankLineP = new Html(\"

\");\n\n\n\t\t\tthis.welcomeDiv = new Div();\n\t\t\tthis.motivationDiv = new Div();\n\t\t\tthis.joinDiv = new Div();\n\n\t\t\tthis.loginButton = new Button(\"Login\");\n\t\t}\n\n\t\t// set properties\n\t\t{\n\n\t\t\tthis.welcomeDiv.addClassName(\"welcome-div\");\n\t\t\tthis.motivationDiv.addClassName(\"motivation-div\");\n\t\t\tthis.joinDiv.addClassName(\"join-div\");\n\n\t\t\tthis.welcomeLabel.addClassName(\"heading\");\n\t\t\tthis.motivationLabel.addClassName(\"sub-heading\");\n\t\t\tthis.joinLabel.addClassName(\"sub-heading\");\n\n\t\t\tthis.loginButton.addClassName(\"login-button\");\n\t\t\tthis.registerSpan.getElement().getStyle().set(\"padding-top\", \"20px\");\n\t\t}\n\n\t\t// listener\n\t\taddButtonListener();\n\n\t}\n\n\tprivate void addComponents() {\n\t\tthis.welcomeDiv.add(this.welcomeLabel);\n\n\t\tthis.motivationDiv.add(this.motivationLabel);\n\t\tthis.motivationDiv.add(this.motivationSpan);\n\n\t\tif(userDao.getCurrentUser() == null) {\n\t\t\tthis.joinDiv.add(this.joinLabel);\n\t\t\tthis.joinDiv.add(this.loginSpan);\n\t\t\tthis.joinDiv.add(this.loginButton);\n\t\t\tthis.joinDiv.add(this.blankLineP);\n\t\t\tthis.joinDiv.add(this.registerSpan);\n\t\t}\n\t}\n\n\tprivate void addComponentsToLayouts() {\n\t\taddComponents();\n\n\t\tadd(this.welcomeDiv);\n\t\tadd(this.motivationDiv);\n\t\tadd(this.joinDiv);\n\t}\n\n\tprivate void addButtonListener(){\n\t\tthis.loginButton.addClickListener(event -> {\n\t\t\tif(this.getUI().isPresent()) this.getUI().get().navigate(\"login\");\n\t\t});\n\t}\n}\n\nsrc/main/java/com/buschmais/frontend/views/usercontrol/GroupsInformationView.java\n@PageTitle(\"Group Information\")\n@CssImport(value = \"./themes/adr-workbench/UserControl/GroupComponent.css\")\npublic class GroupsInformationView extends VerticalLayout implements HasUrlParameter, BroadcastListener, BeforeLeaveObserver {\n\n\tprivate final ADRAccessDao adrAccessDao;\n\tprivate final UserDao userDao;\n\n\tprivate String groupId;\n\n\tprivate HorizontalLayout groupsHeadLayout;\n\tprivate HorizontalLayout grouprightsLayout;\n\tprivate HorizontalLayout membersmanagementLayout;\n\n\tprivate Span readableYes;\n\tprivate Span readableNo;\n\tprivate Span writableYes;\n\tprivate Span writableNo;\n\tprivate Span votableYes;\n\tprivate Span votableNo;\n\n\tprivate Button deleteGroupButton;\n\tprivate Button manageUsers;\n\tprivate Button readable;\n\tprivate Button unreadable;\n\tprivate Button writable;\n\tprivate Button unwritable;\n\tprivate Button votable;\n\tprivate Button unvotable;\n\n\tprivate Dialog deleteConfirmDialog;\n\n\tpublic GroupsInformationView(@Autowired ADRAccessDao accessDao, @Autowired UserDao userDao){\n\t\tthis.adrAccessDao = accessDao;\n\t\tthis.userDao = userDao;\n\n\t\tBroadcaster.registerListener(this);\n\t}\n\n\t@Override\n\tpublic void setParameter(BeforeEvent beforeEvent, String groupname) {\n\t\tsynchronized (adrAccessDao){\n\t\t\tOptional group1 = adrAccessDao.findByName(groupname);\n\t\t\tgroup1.ifPresent((group) -> {\n\t\t\t\tthis.groupId = group.getId();\n\n\t\t\t\tCollection members = group.getUsers();\n\n\t\t\t\tgroupsHeadLayout = new HorizontalLayout();\n\n\t\t\t\tLabel groupsname = new Label(group.getName());\n\t\t\t\tgroupsname.getElement().getThemeList().add(\"badge primary\");\n\t\t\t\tButton back = new Button(new Icon(VaadinIcon.ANGLE_DOUBLE_LEFT));\n\t\t\t\tback.addClickListener(event -> {\n\t\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(UserControlView.class);\n\t\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t\t});\n\t\t\t\tdeleteGroupButton = new Button(StringConstantsFrontend.GROUP_DELETE);\n\t\t\t\tdeleteGroupButton.addThemeVariants(ButtonVariant.LUMO_ERROR, ButtonVariant.LUMO_PRIMARY);\n\t\t\t\tdeleteGroupButton.addClickListener(event -> {\n\t\t\t\t\tdeleteConfirmDialog = new ConfirmDialog(\"Group löschen\", \"Die Gruppe \\\"\" + group.getName() + \"\\\" wirklich löschen?\", \"löschen\", confirmClickEvent -> {\n\t\t\t\t\t\tsynchronized (adrAccessDao){\n\t\t\t\t\t\t\tadrAccessDao.findByName(group.getName()).ifPresent(adrAccessDao::delete);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.deleteConfirmDialog.close();\n\t\t\t\t\t\tnew SuccessNotification(\"Die Gruppe wurde erfolgreich gelöscht!\");\n\t\t\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(UserControlView.class);\n\t\t\t\t\t\tthis.removeAll();\n\t\t\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t\t\t\tBroadcaster.broadcastMessage(Event.GROUP_CHANGED, groupId, this);\n\t\t\t\t\t}, StringConstantsFrontend.GENERAL_DIALOG_BUTTON_CANCEL, cancelEvent -> {\n\t\t\t\t\t\tthis.deleteConfirmDialog.close();\n\t\t\t\t\t\tnew ErrorNotification(\"Es gab einen Fehler beim Löschen der Gruppe!\").open();\n\t\t\t\t\t});\n\t\t\t\t\tthis.deleteConfirmDialog.open();\n\t\t\t\t});\n\n\t\t\t\tmanageUsers = new Button(\"Nutzer verwalten\");\n\t\t\t\tmanageUsers.addClickListener(e -> {\n\t\t\t\t\tChangeGroupUsersDialog dialog = new ChangeGroupUsersDialog(this.userDao, this.adrAccessDao, this.groupId);\n\n\t\t\t\t\tdialog.addDetachListener(event -> {\n\t\t\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\t\t\tthis.removeAll();\n\t\t\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t\t\t});\n\t\t\t\t\tdialog.open();\n\t\t\t\t});\n\n\t\t\t\tgroupsHeadLayout.add(back,groupsname,manageUsers, deleteGroupButton);\n\t\t\t\tmembersmanagementLayout = new HorizontalLayout();\n\t\t\t\t//addUserConfigure(group);\n\t\t\t\t//removeUserConfigure(group);\n\n\t\t\t\tthis.setSizeFull();\n\n\t\t\t\tthis.add(groupsHeadLayout);\n\t\t\t\tgroupRightsConfigure(group);\n\t\t\t\tbuttonsListenerConfigure(group);\n\t\t\t\tmembersListConfigure(members);\n\t\t\t\tthis.add(membersmanagementLayout);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate void groupRightsConfigure(AccessGroup group){\n\n\t\treadableYes = new Span(new Icon(VaadinIcon.CHECK), new Span(StringConstantsFrontend.GROUP_READABLE));\n\t\treadableNo = new Span(new Icon(VaadinIcon.CLOSE), new Span(StringConstantsFrontend.GROUP_READABLE));\n\t\twritableYes = new Span(new Icon(VaadinIcon.CHECK), new Span(StringConstantsFrontend.GROUP_WRITABLE));\n\t\twritableNo = new Span(new Icon(VaadinIcon.CLOSE), new Span(StringConstantsFrontend.GROUP_WRITABLE));\n\t\tvotableYes = new Span(new Icon(VaadinIcon.CHECK), new Span(StringConstantsFrontend.GROUP_VOTABLE));\n\t\tvotableNo = new Span(new Icon(VaadinIcon.CLOSE), new Span(StringConstantsFrontend.GROUP_VOTABLE));\n\n\t\treadable = new Button(StringConstantsFrontend.GROUP_READABLE);\n\t\tunreadable = new Button(StringConstantsFrontend.GROUP_UNREADABLE);\n\t\twritable = new Button(StringConstantsFrontend.GROUP_WRITABLE);\n\t\tunwritable = new Button(StringConstantsFrontend.GROUP_UNWRITABLE);\n\t\tvotable = new Button(StringConstantsFrontend.GROUP_VOTABLE);\n\t\tunvotable = new Button(StringConstantsFrontend.GROUP_UNVOTABLE);\n\n\t\treadableYes.addClassName(\"readable-yes-span\");\n\t\treadableNo.addClassName(\"readable-no-span\");\n\t\twritableYes.addClassName(\"writable-yes-span\");\n\t\twritableNo.addClassName(\"writable-no-span\");\n\t\tvotableYes.addClassName(\"votable-yes-span\");\n\t\tvotableNo.addClassName(\"votable-no-span\");\n\t\treadable.addClassName(\"readable-button\");\n\t\tunreadable.addClassName(\"unreadable-button\");\n\t\twritable.addClassName(\"writable-button\");\n\t\tunwritable.addClassName(\"unwritable-button\");\n\t\tvotable.addClassName(\"votable-button\");\n\t\tunvotable.addClassName(\"unvotable-button\");\n\n\t\treadableYes.getElement().getThemeList().add(\"badge\");\n\t\treadableNo.getElement().getThemeList().add(\"badge\");\n\t\twritableYes.getElement().getThemeList().add(\"badge\");\n\t\twritableNo.getElement().getThemeList().add(\"badge\");\n\t\tvotableYes.getElement().getThemeList().add(\"badge\");\n\t\tvotableNo.getElement().getThemeList().add(\"badge\");\n\n\t\treadable.addThemeVariants(ButtonVariant.LUMO_SMALL);\n\t\tunreadable.addThemeVariants(ButtonVariant.LUMO_SMALL);\n\t\twritable.addThemeVariants(ButtonVariant.LUMO_SMALL);\n\t\tunwritable.addThemeVariants(ButtonVariant.LUMO_SMALL);\n\t\tvotable.addThemeVariants(ButtonVariant.LUMO_SMALL);\n\t\tunvotable.addThemeVariants(ButtonVariant.LUMO_SMALL);\n\n\t\tgrouprightsLayout = new HorizontalLayout();\n\n\t\tif(group.getRights().isReadable()){\n\t\t\tgrouprightsLayout.add(readableYes);\n\t\t\tgrouprightsLayout.add(unreadable);\n\t\t}else{\n\t\t\tgrouprightsLayout.add(readableNo);\n\t\t\tgrouprightsLayout.add(readable);\n\t\t}\n\t\tif(group.getRights().isWritable()){\n\t\t\tgrouprightsLayout.add(writableYes);\n\t\t\tgrouprightsLayout.add(unwritable);\n\t\t}else{\n\t\t\tgrouprightsLayout.add(writableNo);\n\t\t\tgrouprightsLayout.add(writable);\n\t\t}\n\t\tif(group.getRights().isVotable()){\n\t\t\tgrouprightsLayout.add(votableYes);\n\t\t\tgrouprightsLayout.add(unvotable);\n\t\t}else{\n\t\t\tgrouprightsLayout.add(votableNo);\n\t\t\tgrouprightsLayout.add(votable);\n\t\t}\n\n\t\tthis.add(grouprightsLayout);\n\n\t}\n\n\tprivate void membersListConfigure(Collection members){\n\t\tGrid userGrid = new Grid<>(User.class,false);\n\n\t\tuserGrid.addColumn(User::getUserName).setHeader(StringConstantsFrontend.GROUP_NAME);\n\t\tuserGrid.setItems(members);\n\t\tuserGrid.addClassName(\"user-grid\");\n\t\tuserGrid.getColumns().forEach(col -> col.setAutoWidth(true));\n\t\tthis.add(userGrid);\n\t}\n\n\tprivate void buttonsListenerConfigure(AccessGroup group){\n\t\treadable.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tgroup.getRights().setReadable(true);\n\t\t\t\tadrAccessDao.save(group);\n\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\tthis.removeAll();\n\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t}\n\t\t});\n\t\tunreadable.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tgroup.getRights().setReadable(false);\n\t\t\t\tadrAccessDao.save(group);\n\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\tthis.removeAll();\n\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t}\n\t\t});\n\t\twritable.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tgroup.getRights().setWritable(true);\n\t\t\t\tadrAccessDao.save(group);\n\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\tthis.removeAll();\n\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t}\n\t\t});\n\t\tunwritable.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tgroup.getRights().setWritable(false);\n\t\t\t\tadrAccessDao.save(group);\n\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\tthis.removeAll();\n\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t}\n\t\t});\n\t\tvotable.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tgroup.getRights().setVotable(true);\n\t\t\t\tadrAccessDao.save(group);\n\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\tthis.removeAll();\n\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t}\n\t\t});\n\t\tunvotable.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tgroup.getRights().setVotable(false);\n\t\t\t\tadrAccessDao.save(group);\n\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\tthis.removeAll();\n\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic void receiveBroadcast(BroadcastListener.Event event, String message) {\n\t\tif(event == Event.GROUP_CHANGED && groupId.equals(message)) {\n\t\t\tgetUI().ifPresent(ui -> ui.access(() -> {\n\t\t\t\tnew ErrorNotification(StringConstantsFrontend.GROUP_GOT_DELETED);\n\t\t\t\tui.getPage().setLocation(StringConstantsFrontend.USER_CONTROL_PATH);\n\t\t\t}));\n\t\t}\n/*\t\t\tcase ADR_CHANGED -> updateDescribingLabels();\n\t\t\tcase ADR_REVIEW_STS_CHANGED -> {\n\t\t\t\tif (adrId != null && adrId.equals(message)) {\n\t\t\t\t\tgetUI().ifPresent(ui -> ui.access(this::setVariableVotingSectionElements));\n\t\t\t\t}\n\t\t\t}\n*/\t}\n\n\t/*\n\tprivate void addUserConfigure(AccessGroup group){\n\t\tComboBox addUser = new ComboBox<>(\"add member\");\n\t\taddUser.setPlaceholder(\"select user\");\n\t\taddUser.setAllowCustomValue(false);\n\t\tComboBox.ItemFilter filter = (user, filterString) -> user.getUserName().toLowerCase().startsWith(filterString.toLowerCase());\n\t\taddUser.setItems(filter, userDao.findAll());\n\t\taddUser.setItemLabelGenerator(user -> {\n\t\t\treturn user.getUserName();\n\t\t});\n\t\tButton add = new Button(StringConstantsFrontend.GROUP_ADD);\n\t\tadd.addThemeVariants(ButtonVariant.LUMO_SMALL, ButtonVariant.LUMO_SUCCESS);\n\t\tadd.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tif(!addUser.isEmpty()){\n\t\t\t\t\tUser u= addUser.getValue();\n\t\t\t\t\tif(!group.containsUser(u)){\n\t\t\t\t\t\tgroup.addUser(u);\n\t\t\t\t\t\tadrAccessDao.save(group);\n\t\t\t\t\t\tfor (AccessGroup accessGroup : adrAccessDao.findAll()) {\n\t\t\t\t\t\t\tif (accessGroup.containsUser(u)) {\n\t\t\t\t\t\t\t\tif(accessGroup.hashCode() != group.hashCode()){\n\t\t\t\t\t\t\t\t\taccessGroup.removeUser(u);\n\t\t\t\t\t\t\t\t\tadrAccessDao.save(accessGroup);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\t\t\tthis.removeAll();\n\t\t\t\t\t\tthis.getUI().ifPresent(page -> {\n\t\t\t\t\t\t\tpage.navigate(route);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmembersmanagementLayout.add(addUser,add);\n\t}\n\tprivate void removeUserConfigure(AccessGroup group){\n\t\tComboBox removeUser = new ComboBox<>(\"remove member\");\n\t\tremoveUser.setPlaceholder(\"select user\");\n\t\tremoveUser.setAllowCustomValue(false);\n\t\tComboBox.ItemFilter filter = (user, filterString) -> user.getUserName().toLowerCase().startsWith(filterString.toLowerCase());\n\t\tremoveUser.setItems(filter, group.getUsers());\n\t\tremoveUser.setItemLabelGenerator(user -> {\n\t\t\treturn user.getUserName();\n\t\t});\n\t\tButton remove = new Button(StringConstantsFrontend.MEMBERCOMPONENT_REMOVE);\n\t\tremove.addThemeVariants(ButtonVariant.LUMO_SMALL, ButtonVariant.LUMO_ERROR);\n\t\tremove.addClickListener(event -> {\n\t\t\tsynchronized (adrAccessDao) {\n\t\t\t\tif(!removeUser.isEmpty()){\n\t\t\t\t\tUser u= removeUser.getValue();\n\t\t\t\t\tgroup.removeUser(u);\n\t\t\t\t\tadrAccessDao.save(group);\n\t\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(GroupsInformationView.class, group.getName());\n\t\t\t\t\tthis.removeAll();\n\t\t\t\t\tthis.getUI().ifPresent(page -> {\n\t\t\t\t\t\tpage.navigate(route);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tmembersmanagementLayout.add(removeUser,remove);\n\t}\n\t */\n\n\t@Override\n\tpublic void beforeLeave(BeforeLeaveEvent beforeLeaveEvent) {\n\t\tBroadcaster.unregisterListener(this);\n\t}\n}\n\nsrc/main/java/com/buschmais/frontend/views/adrVote/ADRVoteView.java\n@CssImport(value = \"./themes/adr-workbench/adrVoting/label.css\")\n@CssImport(value = \"./themes/adr-workbench/adrVoting/comment-section.css\")\n@CssImport(value = \"./themes/adr-workbench/vaadin-components/buttons.css\")\n@CssImport(value = \"./themes/adr-workbench/adrVoting/adr-information.css\")\n@PageTitle(\"ADR Details\")\npublic class ADRVoteView extends HorizontalLayout implements HasUrlParameter, BroadcastListener, BeforeEnterObserver, BeforeLeaveObserver {\n\n\t/* ADR */\n\tprivate String adrId;\n\tprivate final ADRDao adrDao;\n\tprivate final ADRAccessDao accessGroupService;\n\tprivate final UserDao userDao;\n\tprivate final ImageDao imageService;\n\n\t/* Components */\n\tprivate ErrorNotification invalidIdNotification;\n\tprivate VoteResultBar voteResultBar;\n\n\t// overall layouts\n\tprivate VerticalLayout leftLayout;\n\tprivate VerticalLayout rightLayout;\n\n\tprivate HorizontalLayout adrInformationLayout;\n\tprivate HorizontalLayout adrInformationAuthorStatusLayout;\n\tprivate HorizontalLayout adrActionButtonsLayout;\n\n\t// information about adr (left side)\n\tprivate VerticalLayout adrTopInformationLayout;\n\tprivate VerticalLayout titleLayout;\n\tprivate VerticalLayout authorLayout;\n\tprivate VerticalLayout contextLayout;\n\tprivate VerticalLayout decisionLayout;\n\tprivate VerticalLayout consequencesLayout;\n\tprivate VerticalLayout supersedesLayout;\n\n\t// buttons layout\n\tprivate VerticalLayout adrButtonsLayout;\n\tprivate HorizontalLayout actionButtonsLayout;\n\n\t// voting and comments (right side)\n\tprivate VerticalLayout voteLayout;\n\tprivate HorizontalLayout voteTitleLayout;\n\tprivate VerticalLayout commentLayout;\n\tprivate VerticalLayout commentMessagesLayout;\n\tprivate HorizontalLayout sendCommentButtonLayout;\n\n\tprivate HorizontalLayout voteIconLayout;\n\n\t// Label\n\tprivate Label statusLabel;\n\tprivate Label titleLabel;\n\tprivate Label authorLabel;\n\tprivate RichTextEditor contextLabel;\n\tprivate RichTextEditor decisionLabel;\n\tprivate RichTextEditor consequencesLabel;\n\tprivate RichTextEditor supersedesLabel;\n\n\tprivate Label separatorAuthorStatus;\n\n\tprivate Label adrInformationLabel;\n\tprivate Label titleStringLabel;\n\tprivate Label authorStringLabel;\n\tprivate Label contextStringLabel;\n\tprivate Label decisionStringLabel;\n\tprivate Label consequencesStringLabel;\n\tprivate Label supersedesStringLabel;\n\n\tprivate Label voteLabel;\n\tprivate Label voteNotStartedYet;\n\tprivate Label votingSeparatorLabel;\n\tprivate Label votingProLabel;\n\tprivate Label votingContraLabel;\n\tprivate Label votingNotYetVotedLabel;\n\tprivate Label votingNotAllowedToVote;\n\n\tprivate Label commentLabel;\n\n\t// buttons\n\tprivate Button editButton;\n\tprivate Button accessGroupsButton;\n\tprivate Button sendButton;\n\tprivate Button startVoteButton;\n\tprivate Button endVoteButton;\n\tprivate Button inviteVoterButton;\n\tprivate Button proposeDirectlyButton;\n\n\t// text areas\n\tprivate TextArea sendMessageArea;\n\n\t// icons\n\tprivate Icon thumbsUpIcon;\n\tprivate Icon thumbsDownIcon;\n\n\t// divs\n\tprivate Div titleDiv;\n\tprivate Div authorDiv;\n\tprivate Div contextDiv;\n\tprivate Div decisionDiv;\n\tprivate Div consequencesDiv;\n\tprivate Div supersedesDiv;\n\n\t// collaboration\n\tprivate CollaborationMessageList collabMessageList;\n\tprivate CollaborationMessageInput collabMessageInput;\n\tprivate final CollaborationMessagePersister collaborationMessagePersister;\n\tprivate UserInfo userInfo;\n\n\tfinal String htmlRegEx = \"<[^>]*>\";\n\n\tpublic ADRVoteView(@Autowired ADRDao adrService, @Autowired ADRAccessDao accessGroupService, @Autowired UserDao userService, @Autowired ImageDao imageService, @Autowired CollaborationMessagePersister collaborationMessagePersister) {\n\t\tthis.adrDao = adrService;\n\t\tthis.accessGroupService = accessGroupService;\n\t\tthis.userDao = userService;\n\t\tthis.imageService = imageService;\n\t\tthis.collaborationMessagePersister = collaborationMessagePersister;\n\t\tBroadcaster.registerListener(this);\n\t\taddDetachListener((DetachEvent e) -> Broadcaster.unregisterListener(this));\n\n\t}\n\n\tprivate void setupComponents(ADR adr) {\n\n\t\tUser u = this.userDao.getCurrentUser();\n\t\tthis.userInfo = new UserInfo(u.getId(), u.getUserName());\n\n\t\t// define components\n\t\t{\n\t\t\t// layouts\n\t\t\tthis.leftLayout = new VerticalLayout();\n\t\t\tthis.rightLayout = new VerticalLayout();\n\n\t\t\tthis.adrTopInformationLayout = new VerticalLayout();\n\t\t\tthis.adrInformationLayout = new HorizontalLayout();\n\t\t\tthis.adrInformationAuthorStatusLayout = new HorizontalLayout();\n\t\t\tthis.adrActionButtonsLayout = new HorizontalLayout();\n\n\t\t\tthis.titleLayout = new VerticalLayout();\n\t\t\tthis.authorLayout = new VerticalLayout();\n\t\t\tthis.contextLayout = new VerticalLayout();\n\t\t\tthis.decisionLayout = new VerticalLayout();\n\t\t\tthis.consequencesLayout = new VerticalLayout();\n\t\t\tthis.supersedesLayout = new VerticalLayout();\n\n\t\t\tthis.adrButtonsLayout = new VerticalLayout();\n\t\t\tthis.actionButtonsLayout = new HorizontalLayout();\n\n\t\t\tthis.voteLayout = new VerticalLayout();\n\t\t\tthis.voteTitleLayout = new HorizontalLayout();\n\t\t\tthis.commentLayout = new VerticalLayout();\n\t\t\tthis.commentMessagesLayout = new VerticalLayout();\n\t\t\tthis.sendCommentButtonLayout = new HorizontalLayout();\n\n\t\t\tthis.voteIconLayout = new HorizontalLayout();\n\n\t\t\t//this.adrInformationLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_ADR_INFORMATION);\n\t\t\tthis.adrInformationLabel = new Label(adr.getTitle());\n\n\t\t\tthis.separatorAuthorStatus = new Label(\"\\u2012\");\n\n\t\t\tthis.titleStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_TITEL_STRING);\n\t\t\tthis.authorStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_AUTHOR_STRING);\n\t\t\tthis.contextStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_CONTEXT_STRING);\n\t\t\tthis.decisionStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_DECISION_STRING);\n\t\t\tthis.consequencesStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_CONSEQUENCES_STRING);\n\t\t\tthis.supersedesStringLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_SUPERSEDES_STRING);\n\t\t\tthis.commentLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_COMMENTS_STRING);\n\n\t\t\tthis.voteLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_VOTE_STRING);\n\t\t\tthis.voteNotStartedYet = new Label(StringConstantsFrontend.ADRVOTEVIEW_VOTING_HAS_NOT_STARTED_YET);\n\t\t\tthis.votingSeparatorLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_VOTING_SEPARATOR_STRING);\n\t\t\tthis.votingProLabel = new Label();\n\t\t\tthis.votingContraLabel = new Label();\n\t\t\tthis.votingNotYetVotedLabel = new Label(StringConstantsFrontend.ADRVOTEVIEW_LABEL_NOT_YET_VOTED);\n\t\t\tthis.votingNotAllowedToVote = new Label(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE);\n\n\t\t\t// buttons\n\t\t\tthis.sendButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_BUTTON_SEND_COMMENT);\n\t\t\tthis.accessGroupsButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_BUTTON_EDIT_ACCESS_GROUPS_BUTTON);\n\t\t\tthis.editButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_EDIT_STRING);\n\t\t\tthis.startVoteButton = new Button(\n\t\t\t\t\tadr.getStatus().getType().equals(ADRStatusType.CREATED)\n\t\t\t\t\t\t\t? StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_START_INTERNAL_VOTING\n\t\t\t\t\t\t\t: StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_START_VOTING);\n\n\t\t\tthis.proposeDirectlyButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_PROPOSE_DIRECTLY);\n\n\t\t\tthis.endVoteButton = new Button(\n\t\t\t\t\tadr.getStatus().getType().equals(ADRStatusType.INTERNALLY_PROPOSED)\n\t\t\t\t\t\t\t? StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_END_INTERNAL_VOTING\n\t\t\t\t\t\t\t: StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_END_VOTING);\n\n\t\t\tthis.inviteVoterButton = new Button(StringConstantsFrontend.ADRVOTEVIEW_LABEL_BUTTON_INVITE_VOTER);\n\n\t\t\t// text areas\n\t\t\tthis.sendMessageArea = new TextArea();\n\t\t\tthis.sendMessageArea.setPlaceholder(StringConstantsFrontend.ADRVOTEVIEW_TEXTAREA_COMMENT_PLACEHOLDER);\n\n\t\t\t// icons\n\t\t\tthis.thumbsUpIcon = new Icon(VaadinIcon.THUMBS_UP_O);\n\t\t\tthis.thumbsDownIcon = new Icon(VaadinIcon.THUMBS_DOWN_O);\n\n\t\t\t// divs\n\t\t\tthis.titleDiv = new Div();\n\t\t\tthis.authorDiv = new Div();\n\t\t\tthis.contextDiv = new Div();\n\t\t\tthis.decisionDiv = new Div();\n\t\t\tthis.consequencesDiv = new Div();\n\t\t\tthis.supersedesDiv = new Div();\n\n\t\t\t// comments\n\t\t\tthis.collabMessageList = new CollaborationMessageList(this.userInfo, \"adr|\" + this.adrId, this.collaborationMessagePersister);\n\t\t\tthis.collabMessageInput = new CollaborationMessageInput(this.collabMessageList);\n\t\t}\n\n\t\t// methods\n\t\taddDescribingLabels();\n\t\t//this.updateDescribingLabels();\n\t\tsetupStatusAndAuthorLabel(adr);\n\n\t\t// setup properties\n\t\t{\n\t\t\tthis.leftLayout.setSpacing(false);\n\n\t\t\tthis.leftLayout.addClassName(\"adr-vote-sub-main-layout\");\n\t\t\tthis.rightLayout.addClassName(\"adr-vote-sub-main-layout\");\n\n\t\t\tthis.adrInformationAuthorStatusLayout.addClassName(\"adr-information-layout-author-status\");\n\n\t\t\tthis.titleLayout.addClassName(\"adr-vote-information-layout\");\n\t\t\tthis.authorLayout.addClassName(\"adr-vote-information-layout\");\n\t\t\tthis.contextLayout.addClassName(\"adr-vote-information-layout\");\n\t\t\tthis.decisionLayout.addClassName(\"adr-vote-information-layout\");\n\t\t\tthis.consequencesLayout.addClassName(\"adr-vote-information-layout\");\n\t\t\tthis.supersedesLayout.addClassName(\"adr-vote-information-layout-superseded\");\n\n\t\t\tthis.separatorAuthorStatus.addClassName(\"adr-vote-separator-author-status\");\n\n\t\t\tthis.titleStringLabel.addClassName(\"adr-vote-small-heading\");\n\t\t\tthis.authorStringLabel.addClassName(\"adr-vote-small-heading\");\n\t\t\tthis.contextStringLabel.addClassName(\"adr-vote-small-heading\");\n\t\t\tthis.decisionStringLabel.addClassName(\"adr-vote-small-heading\");\n\t\t\tthis.consequencesStringLabel.addClassName(\"adr-vote-small-heading\");\n\t\t\tthis.supersedesStringLabel.addClassName(\"adr-vote-small-heading\");\n\n\t\t\tthis.titleDiv.addClassName(\"adr-information-div\");\n\t\t\tthis.authorDiv.addClassName(\"adr-information-div\");\n\t\t\tthis.contextDiv.addClassName(\"adr-information-div\");\n\t\t\tthis.decisionDiv.addClassName(\"adr-information-div\");\n\t\t\tthis.consequencesDiv.addClassName(\"adr-information-div\");\n\t\t\tthis.supersedesDiv.addClassName(\"adr-information-div-superseded\");\n\t\t\tthis.adrInformationLabel.addClassName(\"adr-vote-heading\");\n\t\t\tthis.voteLabel.addClassName(\"adr-vote-heading\");\n\t\t\tthis.voteLabel.getStyle().set(\"margin-bottom\", \"15px\");\n\n\t\t\tthis.commentLabel.addClassName(\"adr-vote-heading\");\n\n\t\t\tthis.thumbsUpIcon.setSize(\"35px\");\n\t\t\tthis.thumbsDownIcon.setSize(\"35px\");\n\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR);\n\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR);\n\t\t\tif (!adr.getStatus().isVotable()) {\n\t\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED);\n\t\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED);\n\t\t\t}\n\n\t\t\tthis.votingNotYetVotedLabel.getStyle().set(\"font-weight\", \"bold\");\n\t\t\tthis.votingNotYetVotedLabel.getStyle().set(\"padding\", \"10px\");\n\n\t\t\tthis.votingProLabel.addClassName(\"adr-vote-pro-label\");\n\t\t\tthis.votingContraLabel.addClassName(\"adr-vote-contra-label\");\n\t\t\tthis.votingSeparatorLabel.addClassName(\"adr-vote-separator-label\");\n\n\t\t\tthis.sendButton.addClassName(\"confirm-button\");\n\t\t\tthis.sendMessageArea.addClassName(\"adr-vote-message-text-area\");\n\n\t\t\tthis.commentMessagesLayout.addClassName(\"adr-vote-message-layout\");\n\n\t\t\tthis.sendCommentButtonLayout.addClassName(\"adr-vote-send-message-layout\");\n\n\t\t\tthis.editButton.addClassName(\"confirm-button\");\n\t\t\tthis.accessGroupsButton.addClassName(\"confirm-button\");\n\t\t\tthis.startVoteButton.addClassName(\"confirm-button\");\n\t\t\tthis.proposeDirectlyButton.addClassName(\"confirm-button\");\n\t\t\tthis.endVoteButton.addClassName(\"confirm-button\");\n\n\t\t\tthis.inviteVoterButton.addClassName(\"confirm-button\");\n\t\t}\n\n\t\t// listener\n\t\t//addSendButtonListener();\n\t\tsetMessageInputSubmitter();\n\t\taddSendButtonShortcut();\n\t\taddEditButtonListener();\n\t\taddEditAccessGroupsButtonListener();\n\t\taddInviteVoterButtonListener();\n\t\taddVoteIconsListener();\n\t\taddStartVoteButtonListener();\n\t\taddEndVoteButtonListener();\n\n\t}\n\n\tprivate void setupStatusAndAuthorLabel(ADR adr) {\n\t\tthis.statusLabel = new Label(adr.getStatus().getType().getName());\n\t\tthis.statusLabel.setClassName(\"adr-vote-status-label-\" + adr.getStatus().getType().getName().toLowerCase().replaceAll(\" \", \"-\"));\n\t\tthis.authorLabel.addClassName(\"adr-vote-information-author-label\");\n\t}\n\n\tprivate void addDescribingLabels() {\n\t\tadrDao.findById(adrId).ifPresent(adr -> {\n\t\t\tthis.titleDiv.add(this.titleLabel = new Label(adr.getTitle()));\n\t\t\tthis.authorDiv.add(this.authorLabel = new Label(adr.getAuthor().isPresent() ? adr.getAuthor().get().getUserName() : StringConstantsFrontend.GENERAL_UNKNOWN_AUTHOR));\n\t\t\tthis.contextDiv.add(this.contextLabel = new RichTextEditor(adr.getContext()));\n\t\t\tthis.decisionDiv.add(this.decisionLabel = new RichTextEditor(adr.getDecision()));\n\t\t\tthis.consequencesDiv.add(this.consequencesLabel = new RichTextEditor(adr.getConsequences()));\n\n\t\t\tList supersededADRs = new LinkedList<>();\n\t\t\tadr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add));\n\t\t\tsupersededADRs.forEach(supersededAdr -> {\n\t\t\t\tSpan tagSpan = new Span(supersededAdr.getTitle());\n\t\t\t\ttagSpan.addClassName(\"adr-vote-information-layout-superseded-adr-span\");\n\t\t\t\tthis.supersedesDiv.add(tagSpan);\n\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate void updateDescribingLabels() {\n\t\tadrDao.findById(adrId).ifPresent(adr -> getUI().ifPresent(ui -> ui.access(() -> {\n\t\t\tthis.titleDiv.remove(this.titleLabel);\n\t\t\tthis.adrInformationAuthorStatusLayout.remove(this.statusLabel);\n\t\t\tthis.adrInformationAuthorStatusLayout.remove(this.authorLabel);\n\t\t\tthis.contextDiv.remove(this.contextLabel);\n\t\t\tthis.decisionDiv.remove(this.decisionLabel);\n\t\t\tthis.consequencesDiv.remove(this.consequencesLabel);\n\t\t\tthis.supersedesLayout.remove(this.supersedesDiv);\n\n\t\t\tthis.titleLabel.setText(adr.getTitle());\n\t\t\tthis.statusLabel.setText(adr.getStatus().getType().getName());\n\t\t\tthis.authorLabel.setText(adr.getAuthor().isPresent() ? adr.getAuthor().get().getUserName() : StringConstantsFrontend.GENERAL_UNKNOWN_AUTHOR);\n\t\t\tthis.contextLabel = new RichTextEditor(adr.getContext());\n\t\t\tthis.decisionLabel = new RichTextEditor(adr.getDecision());\n\t\t\tthis.consequencesLabel = new RichTextEditor(adr.getConsequences());\n\t\t\tthis.supersedesDiv = new Div();\n\n\t\t\tList supersededADRs = new LinkedList<>();\n\t\t\tadr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add));\n\t\t\tsupersededADRs.forEach(supersededAdr -> {\n\t\t\t\tSpan tagSpan = new Span(supersededAdr.getTitle());\n\t\t\t\ttagSpan.addClassName(\"adr-vote-information-layout-superseded-adr-span\");\n\t\t\t\tthis.supersedesDiv.add(tagSpan);\n\t\t\t});\n\n\t\t\tthis.titleDiv.add(this.titleLabel);\n\t\t\tthis.adrInformationAuthorStatusLayout.add(this.statusLabel);\n\t\t\tthis.adrInformationAuthorStatusLayout.addComponentAsFirst(this.authorLabel);\n\t\t\tthis.contextDiv.add(this.contextLabel);\n\t\t\tthis.decisionDiv.add(this.decisionLabel);\n\t\t\tthis.consequencesDiv.add(this.consequencesLabel);\n\t\t\tthis.supersedesLayout.add(this.supersedesDiv);\n\t\t})));\n\t}\n\n\tprivate void setMessageInputSubmitter() {\n\t\tthis.collabMessageList.setSubmitter(activationContext -> {\n\t\t\tRegistration registration = this.sendButton.addClickListener(event -> {\n\t\t\t\tString tempValue = this.sendMessageArea.getValue().trim();\n\t\t\t\tif (!tempValue.isEmpty()) {\n\t\t\t\t\tactivationContext.appendMessage(tempValue);\n\t\t\t\t\tthis.sendMessageArea.clear();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn () -> {\n\t\t\t\tregistration.remove();\n\t\t\t\tthis.sendButton.setEnabled(false);\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate synchronized void addComponentsToLayouts(@NonNull final ADR adr) {\n\t\t// setup\n\t\tsetupComponents(adr);\n\t\t// add titles to main right and left side layout\n\n\t\tthis.adrTopInformationLayout.add(this.adrInformationLayout, this.adrInformationAuthorStatusLayout, this.adrActionButtonsLayout);\n\n\t\tthis.adrInformationLayout.add(this.adrInformationLabel);\n\n/*\t\tif (adr.canWrite(this.userDao.getCurrentUser())) {\n\t\t\tthis.adrActionButtonsLayout.add(this.editButton);\n\t\t}\n\n\t\tif(adr.canEditAccessGroups(this.userDao.getCurrentUser())){\n\t\t\tthis.adrActionButtonsLayout.add(this.accessGroupsButton);\n\t\t}\n*/\n\t\tthis.leftLayout.add(this.adrTopInformationLayout);\n\n\t\t/* Left side (ADR Information) */\n\t\t// adding components to vertical adr information layouts\n\t\tthis.titleLayout.add(this.titleStringLabel, this.titleDiv);\n\t\tthis.authorLayout.add(this.authorStringLabel, this.authorDiv);\n\t\tthis.contextLayout.add(this.contextStringLabel, this.contextDiv);\n\t\tthis.decisionLayout.add(this.decisionStringLabel, this.decisionDiv);\n\t\tthis.consequencesLayout.add(this.consequencesStringLabel, this.consequencesDiv);\n\n\t\t// add only if not empty\n\t\tif (!adr.getSupersededIds().isEmpty()) {\n\t\t\tthis.supersedesLayout.add(this.supersedesStringLabel, this.supersedesDiv);\n\t\t}\n\n\t\t// add vertical adr information layouts to main left layout - leftLayout\n\t\t//this.leftLayout.add(this.titleLayout, this.authorLayout, this.contextLayout, this.decisionLayout, this.consequencesLayout, this.supersedesLayout, this.adrButtonsLayout);\n\t\tthis.leftLayout.add(this.contextLayout, this.decisionLayout, this.consequencesLayout, this.supersedesLayout, this.adrButtonsLayout);\n\n\t\tthis.adrButtonsLayout.add(this.actionButtonsLayout);\n\n\t\t/* Right side (voting and comments) */\n\t\tthis.voteTitleLayout.add(this.voteLabel);\n\n\t\tthis.voteLayout.add(this.voteTitleLayout);\n\n\t\tthis.commentLayout.add(this.commentLabel);\n\n\t\tthis.voteLayout.add(this.voteIconLayout);\n\n\t\tthis.voteResultBar = new VoteResultBar();\n\t\tthis.voteLayout.add(this.voteResultBar);\n\n\t\tthis.setVariableVotingSectionElements();\n\n\t\tthis.commentMessagesLayout.add(this.collabMessageList);\n\t\tthis.commentLayout.add(this.commentMessagesLayout);\n\n\t\tthis.sendCommentButtonLayout.add(this.sendMessageArea, this.sendButton);\n\n\t\tthis.commentLayout.add(this.sendCommentButtonLayout);\n\n\t\tthis.rightLayout.add(this.voteLayout);\n\t\tthis.rightLayout.add(this.commentLayout);\n\n\t\t// adding main side layouts to overall main layout\n\t\tthis.add(this.leftLayout);\n\t\tthis.add(this.rightLayout);\n\t}\n\n\tprivate void addSendButtonShortcut() {\n\t\tthis.sendButton.addClickShortcut(Key.ENTER);\n\t}\n\n\tprivate void addEditButtonListener() {\n\t\tthis.editButton.addClickListener(event -> {\n\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(ADRRichCreateView.class, adrId);\n\t\t\tthis.getUI().ifPresent((ui) -> ui.getPage().setLocation(route));\n\t\t});\n\t}\n\n\tprivate void addEditAccessGroupsButtonListener() {\n\t\tthis.accessGroupsButton.addClickListener(event -> {\n\t\t\tAccessGroupDialog dialog = new AccessGroupDialog(this.accessGroupService, this.adrDao, this.adrId);\n\t\t\t//dialog.addDetachListener(event2 -> Broadcaster.broadcastMessage(Event.ADR_ACCESS_GROUPS_CHANGED, adrId, this));\n\t\t\tdialog.open();\n\t\t});\n\t}\n\n\tprivate void addInviteVoterButtonListener() {\n\t\tthis.inviteVoterButton.addClickListener(event -> adrDao.findById(adrId).ifPresent(adr -> adr.getStatus().adrReviewAsOpt().ifElse(review -> {\n\t\t\t\t\tInviteVoterDialog dialog = new InviteVoterDialog(this.userDao, this.adrDao, adr);\n\t\t\t\t\tdialog.addDetachListener(event2 -> {\n\t\t\t\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this);\n\t\t\t\t\t\tsetVariableVotingSectionElements();\n\t\t\t\t\t});\n\t\t\t\t\tdialog.open();\n\t\t\t\t},\n\t\t\t\t() -> new ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_USERS_CURRENTLY_NOT_INVITABLE).open())));\n\t}\n\n\tprivate void addStartVoteButtonListener() {\n\t\tthis.startVoteButton.addClickListener(event -> {\n\t\t\tsynchronized (adrDao) {\n\t\t\t\tadrDao.findById(adrId).ifPresent((adr) -> {\n\t\t\t\t\tif (!adr.canStartVoting(userDao.getCurrentUser())) return;\n\t\t\t\t\tadr.propose();\n\t\t\t\t\tthis.adrDao.save(adr);\n\t\t\t\t\tadr.getStatus().adrReviewAsOpt().ifPresent(review ->\n\t\t\t\t\t\t\tuserDao\n\t\t\t\t\t\t\t\t\t.getCurrentUser()\n\t\t\t\t\t\t\t\t\t.pushNotification(new VotingPendingNotification(review, LocalDateTime.now())));\n\t\t\t\t});\n\t\t\t\t//this.getUI().ifPresent((ui) -> ui.getPage().reload());\n\t\t\t}\n\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this);\n\t\t\tthis.setVariableVotingSectionElements();\n\t\t});\n\t\tthis.proposeDirectlyButton.addClickListener(event -> {\n\t\t\tsynchronized (adrDao) {\n\t\t\t\tadrDao.findById(adrId).ifPresent((adr) -> {\n\t\t\t\t\tif (!adr.canPropose(userDao.getCurrentUser())) return;\n\t\t\t\t\tadr.propose();\n\t\t\t\t\tif (adr.canPropose(userDao.getCurrentUser())) adr.propose();\n\t\t\t\t\tthis.adrDao.save(adr);\n\t\t\t\t\tadr.getStatus().adrReviewAsOpt().ifPresent(review ->\n\t\t\t\t\t\t\tuserDao\n\t\t\t\t\t\t\t\t\t.getCurrentUser()\n\t\t\t\t\t\t\t\t\t.pushNotification(new VotingPendingNotification(review, LocalDateTime.now())));\n\t\t\t\t});\n\t\t\t\tthis.getUI().ifPresent((ui) -> ui.getPage().reload());\n\t\t\t}\n\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this);\n\t\t\t//this.setVariableVotingSectionElements();\n\t\t});\n\t}\n\n\tprivate void addEndVoteButtonListener() {\n\t\tthis.endVoteButton.addClickListener(event -> {\n\t\t\tsynchronized (adrDao) {\n\t\t\t\tadrDao.findById(adrId).ifPresent((adr) -> {\n\t\t\t\t\tADR.VoteResult res = adr.endVoting(adrDao);\n\t\t\t\t\tif (res.equals(ADR.VoteResult.INTERNALLY_APPROVED)) {\n\t\t\t\t\t\tadr.getStatus().adrReviewAsOpt().ifPresent(review ->\n\t\t\t\t\t\t\t\tuserDao\n\t\t\t\t\t\t\t\t\t\t.getCurrentUser()\n\t\t\t\t\t\t\t\t\t\t.pushNotification(new VotingPendingNotification(review, LocalDateTime.now())));\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.adrDao.save(adr);\n\t\t\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_STS_CHANGED, adrId, this);\n\t\t\t\t\tthis.setVariableVotingSectionElements();\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\tstatic private final class VoteSts {\n\t\tstatic final int ADR_NOT_PROPOSED = -2, USER_NOT_PERMITTED_TO_VOTE = -1, VOTE_WITHDRAWN = 0, VOTE_GIVEN = 1;\n\t}\n\n\tprivate void addVoteIconsListener() {\n\t\tthis.thumbsUpIcon.addClickListener(event -> {\n\t\t\tAtomicInteger voteSuccess = new AtomicInteger(VoteSts.ADR_NOT_PROPOSED);\n\t\t\tsynchronized (adrDao) {\n\t\t\t\tadrDao.findById(adrId).ifPresent((adr) -> adr.getStatus().adrReviewAsOpt().ifPresent(adrReview -> {\n\t\t\t\t\tif (adrReview.getUserVote(this.userDao.getCurrentUser()).isEmpty() || !adrReview.getUserVote(this.userDao.getCurrentUser()).get().equals(VoteType.FOR)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (adr.getStatus().isVotable()) {\n\t\t\t\t\t\t\t\tadrReview.putVote(this.userDao.getCurrentUser(), VoteType.FOR);\n\t\t\t\t\t\t\t\tthis.adrDao.save(adr);\n\t\t\t\t\t\t\t\tvoteSuccess.set(VoteSts.VOTE_GIVEN);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (UserIsNotInvitedException e) {\n\t\t\t\t\t\t\tvoteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (adr.getStatus().isVotable()) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadrReview.removeVote(this.userDao.getCurrentUser());\n\t\t\t\t\t\t\tthis.adrDao.save(adr);\n\t\t\t\t\t\t\tvoteSuccess.set(VoteSts.VOTE_WITHDRAWN);\n\t\t\t\t\t\t} catch (UserIsNotInvitedException e) {\n\t\t\t\t\t\t\tvoteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t}\n\t\t\tswitch (voteSuccess.get()) {\n\t\t\t\tcase VoteSts.VOTE_GIVEN:\n\t\t\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this);\n\t\t\t\t\tnew SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_SUCCESSFULLY_VOTED).open();\n\t\t\t\t\tsetVariableVotingSectionElements();\n\t\t\t\t\tbreak;\n\t\t\t\tcase VoteSts.VOTE_WITHDRAWN:\n\t\t\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this);\n\t\t\t\t\tnew SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_VOTE_REFUSED).open();\n\t\t\t\t\tsetVariableVotingSectionElements();\n\t\t\t\t\tbreak;\n\t\t\t\tcase VoteSts.USER_NOT_PERMITTED_TO_VOTE:\n\t\t\t\t\tnew ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE).open();\n\t\t\t\tdefault:\n\t\t\t\t\tnew ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NO_LONGER_PROPOSED).open();\n\t\t\t}\n\t\t});\n\n\t\tthis.thumbsDownIcon.addClickListener(event -> {\n\n\t\t\tAtomicInteger voteSuccess = new AtomicInteger(VoteSts.ADR_NOT_PROPOSED); //-2 = ADR not proposed; -1 = user not permitted to vote; 0 = vote successfully withdrawn; 1 = vote successfully given\n\t\t\tsynchronized (adrDao) {\n\t\t\t\tadrDao.findById(adrId).ifPresent((adr) ->\n\t\t\t\t\t\tadr.getStatus().adrReviewAsOpt().ifPresent(adrReview -> {\n\t\t\t\t\t\t\tif (adrReview.getUserVote(this.userDao.getCurrentUser()).isEmpty() ||\n\t\t\t\t\t\t\t\t\t!adrReview.getUserVote(this.userDao.getCurrentUser()).get().equals(VoteType.AGAINST)) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tif (adr.getStatus().isVotable()) {\n\t\t\t\t\t\t\t\t\t\tadrReview.putVote(this.userDao.getCurrentUser(), VoteType.AGAINST);\n\t\t\t\t\t\t\t\t\t\tthis.adrDao.save(adr);\n\t\t\t\t\t\t\t\t\t\tvoteSuccess.set(VoteSts.VOTE_GIVEN);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} catch (UserIsNotInvitedException e) {\n\t\t\t\t\t\t\t\t\tvoteSuccess.set(-1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// voted\n\t\t\t\t\t\t\telse if (adr.getStatus().isVotable()) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tadrReview.removeVote(this.userDao.getCurrentUser());\n\t\t\t\t\t\t\t\t\tthis.adrDao.save(adr);\n\t\t\t\t\t\t\t\t\tvoteSuccess.set(VoteSts.VOTE_WITHDRAWN);\n\t\t\t\t\t\t\t\t} catch (UserIsNotInvitedException e) {\n\t\t\t\t\t\t\t\t\tvoteSuccess.set(VoteSts.USER_NOT_PERMITTED_TO_VOTE);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\tswitch (voteSuccess.get()) {\n\t\t\t\tcase VoteSts.VOTE_GIVEN:\n\t\t\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this);\n\t\t\t\t\tnew SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_SUCCESSFULLY_VOTED).open();\n\t\t\t\t\tsetVariableVotingSectionElements();\n\t\t\t\t\tbreak;\n\t\t\t\tcase VoteSts.VOTE_WITHDRAWN:\n\t\t\t\t\tBroadcaster.broadcastMessage(Event.ADR_REVIEW_VOTE_CNT_CHANGED, adrId, this);\n\t\t\t\t\tnew SuccessNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_VOTE_REFUSED).open();\n\t\t\t\t\tsetVariableVotingSectionElements();\n\t\t\t\t\tbreak;\n\t\t\t\tcase VoteSts.USER_NOT_PERMITTED_TO_VOTE:\n\t\t\t\t\tnew ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NOT_ALLOWED_TO_VOTE).open();\n\t\t\t\tdefault:\n\t\t\t\t\tnew ErrorNotification(StringConstantsFrontend.ADRVOTEVIEW_ADR_NO_LONGER_PROPOSED).open();\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate void updateVotingResults() {\n\t\tVoteResultBar newBar = new VoteResultBar();\n\t\tthis.voteLayout.replace(this.voteResultBar, newBar);\n\t\tthis.voteResultBar = newBar;\n\t}\n\n\tprivate void updateVotingResults(ADRReview adrReview) {\n\t\tVoteResultBar newBar = new VoteResultBar(adrReview.getVoteResult().get(VoteType.FOR), adrReview.getVoteResult().get(VoteType.AGAINST), adrReview.getInvitedVoters().size());\n\t\tthis.voteLayout.replace(this.voteResultBar, newBar);\n\t\tthis.voteResultBar = newBar;\n\t}\n\n\tprivate void setVoteSection(int votedFor, boolean activeVoting) {\n\t\tthis.voteIconLayout.removeAll();\n\n\t\tif (votedFor == 1) {\n\t\t\tif (activeVoting) {\n\t\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_UP_COLOR_VALUE);\n\t\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR);\n\t\t\t} else {\n\t\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_UP_COLOR_VALUE_DISABLED);\n\t\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED);\n\t\t\t}\n\t\t} else if (votedFor == -1) {\n\t\t\tif (activeVoting) {\n\t\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DOWN_COLOR_VALUE);\n\t\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR);\n\t\t\t} else {\n\t\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DOWN_COLOR_VALUE_DISABLED);\n\t\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED);\n\t\t\t}\n\t\t} else {\n\t\t\tif (activeVoting) {\n\t\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR);\n\t\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR);\n\t\t\t} else {\n\t\t\t\tthis.thumbsUpIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED);\n\t\t\t\tthis.thumbsDownIcon.setColor(StringConstantsFrontend.ADRVOTEVIEW_ICON_THUMBS_DEFAULT_COLOR_DISABLED);\n\t\t\t}\n\t\t}\n\n\t\tthis.voteIconLayout.add(this.thumbsUpIcon);\n\t\tthis.voteIconLayout.add(this.votingSeparatorLabel);\n\t\tthis.voteIconLayout.add(this.thumbsDownIcon);\n\t}\n\n\tprivate void setVariableVotingSectionElements() {\n\t\tUser user = userDao.getCurrentUser();\n\t\tif (user == null) return;\n\n\t\tthis.adrDao.findById(adrId).ifPresent(adr -> {\n\t\t\tthis.adrInformationAuthorStatusLayout.removeAll();\n\t\t\tthis.setupStatusAndAuthorLabel(adr);\n\t\t\tthis.adrInformationAuthorStatusLayout.add(this.authorLabel, this.separatorAuthorStatus, this.statusLabel);\n\n\t\t\tif (adr.canInviteVoters(this.userDao.getCurrentUser())) {\n\t\t\t\tthis.voteTitleLayout.addComponentAsFirst(this.inviteVoterButton);\n\t\t\t\tthis.voteTitleLayout.remove(this.voteLabel);\n\t\t\t\tthis.voteTitleLayout.addComponentAsFirst(this.voteLabel);\n\t\t\t} else {\n\t\t\t\tthis.voteTitleLayout.remove(this.inviteVoterButton);\n\t\t\t}\n\n\t\t\tif (adr.canEndVoting(this.userDao.getCurrentUser())) {\n\t\t\t\tthis.voteTitleLayout.add(this.endVoteButton);\n\t\t\t} else {\n\t\t\t\tthis.voteTitleLayout.remove(this.endVoteButton);\n\t\t\t}\n\n\t\t\tif (adr.canStartVoting(this.userDao.getCurrentUser())) {\n\t\t\t\tthis.voteTitleLayout.add(this.startVoteButton);\n\t\t\t} else {\n\t\t\t\tthis.voteTitleLayout.remove(this.startVoteButton);\n\t\t\t\tif (adr.getStatus().isVotingStartable()) {\n\t\t\t\t\tthis.voteIconLayout.add(this.voteNotStartedYet);\n\t\t\t\t} else {\n\t\t\t\t\tthis.voteIconLayout.remove(this.voteNotStartedYet);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (adr.canWrite(user)) {\n\t\t\t\tthis.adrActionButtonsLayout.add(this.editButton);\n\t\t\t} else {\n\t\t\t\tthis.adrActionButtonsLayout.remove(this.editButton);\n\t\t\t}\n\n\t\t\tif (adr.canEditAccessGroups(user)) {\n\t\t\t\tthis.adrActionButtonsLayout.add(this.accessGroupsButton);\n\t\t\t} else {\n\t\t\t\tthis.adrActionButtonsLayout.remove(this.accessGroupsButton);\n\t\t\t}\n\n\t\t\tif (adr.canPropose(this.userDao.getCurrentUser())) {\n\t\t\t\tthis.voteTitleLayout.add(this.proposeDirectlyButton);\n\t\t\t} else {\n\t\t\t\tthis.voteTitleLayout.remove(this.proposeDirectlyButton);\n\t\t\t}\n\n\t\t\tif (adr.getStatus().getType() != ADRStatusType.CREATED) {\n\t\t\t\tadr.getStatus().adrReviewAsOpt().ifPresent(review -> {\n\t\t\t\t\tif (review.userHasVoted(user).isPresent()) {\n\t\t\t\t\t\tif (review.userHasVoted(user).get() && review.getUserVote(user).isPresent()) {\n\t\t\t\t\t\t\tsetVoteSection(review.getUserVote(user).get() == VoteType.FOR ? 1 : -1, adr.getStatus().isVotable());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsetVoteSection(0, adr.getStatus().isVotable());\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.voteIconLayout.removeAll();\n\t\t\t\t\t}\n\t\t\t\t\tupdateVotingResults(review);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tupdateVotingResults();\n\t\t\t\tthis.voteIconLayout.removeAll();\n\t\t\t}\n\t\t});\n\t}\n\n\t/* Overrides */\n\t@Override\n\tpublic void setParameter(BeforeEvent beforeEvent, String adrId) {\n\t\tthis.adrId = adrId;\n\t\tOptional foundADR = this.adrDao.findById(adrId);\n\t\tif (foundADR.isEmpty()) {\n\n\t\t\t/* Error Message ADR not found */\n\t\t\tthis.invalidIdNotification = new ErrorNotification();\n\t\t\tthis.invalidIdNotification.setDuration(0);\n\t\t\tthis.invalidIdNotification.open();\n\n\t\t\tLabel msg = new Label(StringConstantsFrontend.ADRCREATE_ERROR_ID_NOT_FOUND);\n\n\t\t\tButton confirm = new Button(StringConstantsFrontend.GENERAL_BUTTON_CONFIRM);\n\t\t\tconfirm.getStyle().set(\"margin-left\", \"auto\");\n\t\t\tconfirm.addClickShortcut(Key.ENTER);\n\n\t\t\tVerticalLayout layout = new VerticalLayout(msg, confirm);\n\n\t\t\tthis.invalidIdNotification.add(layout);\n\n\t\t\t// confirm button click-listener\n\t\t\tconfirm.addClickListener(event -> this.invalidIdNotification.close());\n\n\t\t\t// redirect user to kanban view\n\t\t\tthis.invalidIdNotification.addOpenedChangeListener(event ->\n\t\t\t\t\tthis.getUI().ifPresent(page ->\n\t\t\t\t\t\t\tpage.getPage().setLocation(StringConstantsFrontend.OVERVIEW_PATH)));\n\t\t} else {\n\t\t\t/* constructor */\n\n\t\t\taddComponentsToLayouts(foundADR.get());\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void receiveBroadcast(Event event, String message) {\n\t\tswitch (event) {\n\t\t\tcase ADR_REVIEW_VOTE_CNT_CHANGED -> {\n\t\t\t\tif (adrId != null && adrId.equals(message))\n\t\t\t\t\tgetUI().ifPresent(ui -> ui.access(() -> {\n\t\t\t\t\t\tsynchronized (adrDao) {\n\t\t\t\t\t\t\tadrDao.findById(adrId)\n\t\t\t\t\t\t\t\t\t.flatMap(adr -> adr.getStatus().adrReviewAsOpt().stdOpt())\n\t\t\t\t\t\t\t\t\t.ifPresent(this::updateVotingResults);\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t}\n\t\t\tcase ADR_CHANGED -> updateDescribingLabels();\n\t\t\tcase ADR_REVIEW_STS_CHANGED -> {\n\t\t\t\tif (adrId != null && adrId.equals(message)) {\n\t\t\t\t\tgetUI().ifPresent(ui -> ui.access(this::setVariableVotingSectionElements));\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase ADR_ACCESS_GROUPS_CHANGED -> {\n\t\t\t\tif (adrId != null && adrId.equals(message)) {\n\t\t\t\t\tgetUI().ifPresent(ui -> ui.access(() -> {\n\t\t\t\t\t\tsynchronized (adrDao) {\n\t\t\t\t\t\t\tadrDao.findById(adrId).ifPresent(adr -> {\n\t\t\t\t\t\t\t\tthis.actionButtonsLayout.remove(editButton);\n\t\t\t\t\t\t\t\tif(adr.canWrite(userDao.getCurrentUser())){\n\t\t\t\t\t\t\t\t\tthis.actionButtonsLayout.addComponentAsFirst(editButton);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void beforeEnter(BeforeEnterEvent beforeEnterEvent) {\n\t\tadrDao.findById(adrId).ifPresentOrElse(adr -> {\n\t\t\tif (adr.canRead(userDao.getCurrentUser())) beforeEnterEvent.rerouteTo(StringConstantsFrontend.LANDING_PAGE_PATH);\n\t\t}, () -> beforeEnterEvent.rerouteTo(StringConstantsFrontend.LANDING_PAGE_PATH));\n\t}\n\n\t@Override\n\tpublic void beforeLeave(BeforeLeaveEvent beforeLeaveEvent) {\n\t\tBroadcaster.unregisterListener(this);\n\t}\n}\n\nsrc/main/java/com/buschmais/frontend/views/adrCreate/ADRRichCreateView.java\n@CssImport(value = \"./themes/adr-workbench/vaadin-components/buttons.css\")\n@PageTitle(StringConstantsFrontend.ADRCREATE_EDITADR)\npublic class ADRRichCreateView extends VerticalLayout implements HasUrlParameter, BeforeEnterObserver {\n\n\t//name of new ADR\n\tprivate final TextField name = new TextField(StringConstantsFrontend.ADRCREATE_NAME);\n\t//title of new ADR\n\tprivate final TextField title = new TextField(StringConstantsFrontend.ADRCREATE_TITLE);\n\t//context, decision and consequences of new ADR\n\n\tprivate final Label contextLabel = new Label(StringConstantsFrontend.ADRCREATE_CONTEXT);\n\tprivate final RichTextEditor context = new RichTextEditor();\n\tprivate final Label decisionLabel = new Label(StringConstantsFrontend.ADRCREATE_DECISION);\n\tprivate final RichTextEditor decision = new RichTextEditor();\n\tprivate final Label consequencesLabel = new Label(StringConstantsFrontend.ADRCREATE_CONSEQUENCES);\n\tprivate final RichTextEditor consequences = new RichTextEditor();\n\tprivate final TextField id = new TextField();\n\n\tprivate ErrorNotification errNot;\n\tprivate SuccessNotification succNot;\n\n\t//Scroller so that we can fit everything\n\tprivate Scroller scroller;\n\n\t//Contents of the Scroller\n\tprivate final VerticalLayout mainContent = new VerticalLayout();\n\t//Title of the Scroller\n\tH2 editADR = new H2();\n\tprivate final Header header = new Header();\n\n\tprivate TagSelect tagSelect;\n\n\tprivate StringSelect supersededSelect;\n\n\tprivate final ADRDao adrDao;\n\tprivate final UserDao userDao;\n\n\tprivate ADR adr;\n\n\tprivate boolean newadr = true;\n\n\n\tBinder binder = new Binder<>(ADR.class);\n\n\tpublic ADRRichCreateView(@Autowired ADRDao adrDao, @Autowired UserDao userDao) {\n\t\tthis.userDao = userDao;\n\t\tthis.adrDao = adrDao;\n\t\tsetSizeFull();\n\n\t\t//setClassNames();\n\n\t\tcontext.setWidthFull();\n\t\tcontext.setHeight(\"300px\");\n\n\t\t//context.setValueChangeMode(ValueChangeMode.EAGER);\n\t\t//context.addValueChangeListener(e -> e.getSource().setHelperText(e.getValue().length() + \"/\" + 100));\n\n\t\tdecision.setWidthFull();\n\t\tdecision.setHeight(\"300px\");\n\t\t//decision.setValueChangeMode(ValueChangeMode.EAGER);\n\t\t//decision.addValueChangeListener(e -> e.getSource().setHelperText(e.getValue().length() + \"/\" + 50));\n\n\t\tconsequences.setWidthFull();\n\t\tconsequences.setHeight(\"300px\");\n\t\t//consequences.setValueChangeMode(ValueChangeMode.EAGER);\n\t\t//consequences.addValueChangeListener(e -> e.getSource().setHelperText(e.getValue().length() + \"/\" + 80));\n\n\n\t\t//create the Scroller with the Content of the Editor\n\t\tscroller = new Scroller(mainContentCreate());\n\t\tscroller.setSizeFull();\n\t\tscroller.setScrollDirection(Scroller.ScrollDirection.VERTICAL);\n\n\t\t//add the Title of the Page to the Header\n\t\theader.add(editADR);\n\n\t\tadd(header, scroller);\n\n\t\tconfigureBinder();\n\n\t}\n\n\t//buttonsview to create\n\tprivate HorizontalLayout buttonCreate() {\n\n\t\tButton save = new Button(StringConstantsFrontend.GENERAL_DIALOG_BUTTON_SAVE);\n\t\tsave.addClassName(\"confirm-button\");\n\t\tButton cancel = new Button(StringConstantsFrontend.GENERAL_DIALOG_BUTTON_CANCEL);\n\t\tcancel.addClassName(\"cancel-button\");\n\t\tButton create = new Button(StringConstantsFrontend.ADRCREATE_CREATE);\n\t\tcreate.addClassName(\"blue-button\");\n\t\tButton load = new Button(StringConstantsFrontend.ADRCREATE_LOAD);\n\t\tload.addClassName(\"blue-button\");\n\n\t\tsave.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SUCCESS);\n\n\t\tsave.addClickListener((event -> {\n\t\t\tboolean success = false;\n\t\t\tif (newadr) {\n\t\t\t\tadr = new ADR(\n\t\t\t\t\t\tApplication.root,\n\t\t\t\t\t\tname.getValue(),\n\t\t\t\t\t\ttitle.getValue(),\n\t\t\t\t\t\tuserDao.getCurrentUser(),\n\t\t\t\t\t\tcontext.getValue(), consequences.getValue(), decision.getValue());\n\t\t\t\tadr.setStatus(new ADRStatusCreated());\n\n\t\t\t\tadr.getTags().clear();\n\t\t\t\ttagSelect.getValue().forEach(tag -> adr.addTag(tag));\n\n\t\t\t\tsynchronized (adrDao) {\n\t\t\t\t\tList supersededTitles = supersededSelect.getSelected();\n\t\t\t\t\tSet supersededIds = new HashSet<>();\n\t\t\t\t\tfor (String name : supersededTitles) {\n\t\t\t\t\t\tsupersededIds.addAll(adrDao.findAllByTitle(name).stream().map(ADR::getId).collect(Collectors.toSet()));\n\t\t\t\t\t}\n\t\t\t\t\tadr.setSupersededIds(supersededIds);\n\n\t\t\t\t\tadr = adrDao.save(adr);\n\t\t\t\t}\n\n\t\t\t\tsuccess = true;\n\t\t\t} else {\n\t\t\t\tsynchronized (adrDao) {\n\t\t\t\t\tadr = adrDao.findById(adr.getId()).orElse(null);\n\t\t\t\t\tif (adr != null) {\n\t\t\t\t\t\tadr.setTitle(title.getValue());\n\t\t\t\t\t\tadr.setName(name.getValue());\n\t\t\t\t\t\tadr.setContext(context.getValue());\n\t\t\t\t\t\tadr.setConsequences(consequences.getValue());\n\t\t\t\t\t\tadr.setDecision(decision.getValue());\n\n\t\t\t\t\t\tadr.getTags().clear();\n\t\t\t\t\t\ttagSelect.getValue().forEach(tag -> adr.addTag(tag));\n\n\t\t\t\t\t\tList supersededTitles = supersededSelect.getSelected();\n\t\t\t\t\t\tSet supersededIds = new HashSet<>();\n\t\t\t\t\t\tfor (String name : supersededTitles) {\n\t\t\t\t\t\t\tsupersededIds.addAll(adrDao.findAllByTitle(name).stream().map(ADR::getId).collect(Collectors.toSet()));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tadr.setSupersededIds(supersededIds);\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tadrDao.save(adr);\n\t\t\t\t\t\t\tsuccess = true;\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\tSystem.out.println(Arrays.toString(e.getStackTrace()));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (success) {\n\t\t\t\tsuccNot = new SuccessNotification(StringConstantsFrontend.ADRCREATE_SUCC);\n\t\t\t\tsuccNot.open();\n\t\t\t\tBroadcaster.broadcastMessage(BroadcastListener.Event.ADR_CHANGED, adr.getId(), this);\n\t\t\t\t//Change URL to include adrId\n\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(ADRVoteView.class, this.adr.getId()); //TODO: Eric hier ^^\n\t\t\t\tthis.getUI().ifPresent(ui -> ui.navigate(route));\n\t\t\t} else {\n\t\t\t\terrNot = new ErrorNotification(StringConstantsFrontend.ADRCREATE_ERROR_GENERAL);\n\t\t\t\terrNot.open();\n\t\t\t}\n\t\t}));\n\n\t\tcancel.addThemeVariants(ButtonVariant.LUMO_ERROR);\n\t\tcancel.addClickListener((event -> {\n\t\t}));\n\n\n\t\tcreate.addClickListener((event -> {\n\t\t\tnewadr = true;\n\t\t\tloadVals(\"\", \"\", new LinkedList<>(), Stream.empty(), \"\", \"\", \"\");\n\n\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(ADRRichCreateView.class, \"\");\n\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\t\t}));\n\n\n\t\tload.addClickListener((event -> {\n\n\t\t\tNotification not = new Notification();\n\t\t\tTextField txt = new TextField();\n\t\t\tDiv diag = new Div(new Text(\"Id to Load (Temp):\"));\n\t\t\tButton conf = new Button(StringConstantsFrontend.ADRCREATE_LOAD);\n\t\t\tconf.addClickListener((event1 -> {\n\t\t\t\tADR adr1 = adrDao.findById(txt.getValue()).orElse(null);\n\t\t\t\tif (adr1 != null) {\n\n\t\t\t\t\tloadADR(adr1);\n\n\t\t\t\t\tString route = RouteConfiguration.forSessionScope().getUrl(ADRRichCreateView.class, this.adr.getId());\n\t\t\t\t\tthis.getUI().ifPresent(page -> page.navigate(route));\n\n\t\t\t\t} else {\n\t\t\t\t\terrNot = new ErrorNotification(StringConstantsFrontend.ADRCREATE_ERROR_ID_NOT_FOUND);\n\t\t\t\t\terrNot.open();\n\t\t\t\t\t//Notification errnot = Notification.show(\"ID not Found\");\n\t\t\t\t}\n\t\t\t\tnot.close();\n\t\t\t}));\n\t\t\ttxt.setWidth(\"300px\");\n\n\t\t\tHorizontalLayout layout = new HorizontalLayout(diag, txt, conf);\n\t\t\tlayout.setAlignItems(Alignment.CENTER);\n\n\n\t\t\tnot.add(layout);\n\t\t\tnot.setPosition(Notification.Position.BOTTOM_CENTER);\n\t\t\tnot.open();\n\n\t\t}));\n\t\tHorizontalLayout buttons = new HorizontalLayout();\n\t\tbuttons.add(save, cancel, create);\n\t\treturn buttons;\n\n\n\t}\n\n\tprivate VerticalLayout mainContentCreate() {\n\t\tsynchronized (adrDao) {\n\t\t\ttagSelect = new TagSelect(StringConstantsFrontend.ADR_TAGS, adrDao.findAllTagsMatchRegex(\".*\"));\n\t\t\tsupersededSelect = new StringSelect(StringConstantsFrontend.ADRCREATE_SUPERSEEDES_FOLLOWING_ADRS);\n\n\t\t\tList supersededADRs = new LinkedList<>();\n\t\t\tif (adr != null) adr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add));\n\t\t\tsupersededSelect.load(adrDao.findAll().stream()\n\t\t\t\t\t\t\t.filter(adr -> !adr.isSuperseded())\n\t\t\t\t\t\t\t.map(ADR::getTitle)\n\t\t\t\t\t\t\t.filter(n -> this.adr == null || !n.equals(this.adr.getTitle())),\n\t\t\t\t\tsupersededADRs.stream().map(ADR::getTitle));\n\t\t}\n\t\tmainContent.add(name, title, tagSelect, supersededSelect, contextLabel, context, decisionLabel, decision, consequencesLabel, consequences, buttonCreate());\n\t\tmainContent.setSizeUndefined();\n\t\treturn mainContent;\n\t}\n\n\n\tpublic void loadVals(String name,\n\t\t\t\t\t\t String title,\n\t\t\t\t\t\t List Tags,\n\t\t\t\t\t\t Stream superseded,\n\t\t\t\t\t\t String context,\n\t\t\t\t\t\t String decision,\n\t\t\t\t\t\t String consequences) {\n\t\tthis.name.setValue(name);\n\t\tthis.title.setValue(title);\n\t\tthis.tagSelect.setValue(Tags);\n\t\tthis.context.load(context);\n\t\tthis.decision.load(decision);\n\t\tthis.consequences.load(consequences);\n\t\tthis.supersededSelect.load(adrDao.findAll().stream()\n\t\t\t\t\t\t.filter(adr -> !adr.isSuperseded())\n\t\t\t\t\t\t.map(ADR::getTitle)\n\t\t\t\t\t\t.filter(n -> !n.equals(name)),\n\t\t\t\tsuperseded);\n\t}\n\n\tpublic void loadADR(ADR adr) {\n\t\tnewadr = false;\n\t\tthis.adr = adr;\n\t\tList supersededADRs = new LinkedList<>();\n\t\tif (adr != null) adr.getSupersededIds().forEach(id -> adrDao.findById(id).ifPresent(supersededADRs::add));\n\t\tloadVals(adr.getName(), adr.getTitle(), adr.getTags(), supersededADRs.stream().map(ADR::getTitle), adr.getContext(), adr.getDecision(), adr.getConsequences());\n\n\t}\n\n\tprivate void configureBinder() {\n\t\tbinder.forField(name)\n\t\t\t\t.withValidator(\n\t\t\t\t\t\tname -> !name.isEmpty(),\n\t\t\t\t\t\tStringConstantsFrontend.ADRCREATE_NAME + StringConstantsFrontend.ADRCREATE_ERROR_FIELD_EMPTY)\n\t\t\t\t.bind(ADR::getName, ADR::setName);\n\t\tbinder.bind(title, ADR::getTitle, ADR::setTitle);\n\t\tbinder.bind(context, ADR::getContext, ADR::setContext);\n\t\tbinder.bind(decision, ADR::getDecision, ADR::setDecision);\n\t\tbinder.bind(consequences, ADR::getConsequences, ADR::setConsequences);\n\n\t}\n\n\t@Override\n\tpublic void setParameter(BeforeEvent event, @OptionalParameter String parameter) {\n\t\tADR adr1 = null;\n\t\tif (parameter != null) {\n\t\t\tthis.editADR.setText(StringConstantsFrontend.ADRCREATE_EDITADR);\n\t\t\tadr1 = adrDao.findById(parameter).orElse(null);\n\t\t}else{\n\t\t\tthis.editADR.setText(StringConstantsFrontend.ADRCREATE_CREATEADR);\n\t\t}\n\n\t\tif (adr1 != null) {\n\t\t\tloadADR(adr1);\n\t\t}//else{\n\t\t//Notification errnot = Notification.show(StringConstantsFrontend.ADRCREATE_ERROR_ID_NOT_FOUND);\n\t\t//}\n\t}\n\n\n\t@Override\n\tpublic void beforeEnter(BeforeEnterEvent beforeEnterEvent) {\n\t\tif (adr == null || adr.getId() == null) return;\n\t\tadrDao.findById(this.adr.getId()).ifPresentOrElse(adr -> {\n\t\t\tif (!adr.canWrite(userDao.getCurrentUser()))\n\t\t\t\tbeforeEnterEvent.rerouteTo(StringConstantsFrontend.LANDING_PAGE_PATH);\n\t\t}, () -> beforeEnterEvent.rerouteTo(StringConstantsFrontend.LANDING_PAGE_PATH));\n\t}\n\n}", "answers": ["\t\t\tnew Route(StringConstantsFrontend.USER_CONTROL_PATH, UserControlView.class),"], "length": 3933, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "2f8e934f-4c29-4860-9b15-1cdf34727e6f", "reasoning": "The file defines several arrays of Route objects. After the opening brace of ADMIN_ACCESSIBLE_ROUTES, the first element should be a Route for the admin‑only user‑control view, which is referenced elsewhere (e.g., in GroupsInformationView). Therefore the next line is the Route construction for the user‑control path.", "reasoning_model_answer": "new Route(StringConstantsFrontend.USER_CONTROL_PATH, UserControlView.class),", "assistant_with_reasoning": "\nThe file defines several arrays of Route objects. After the opening brace of ADMIN_ACCESSIBLE_ROUTES, the first element should be a Route for the admin‑only user‑control view, which is referenced elsewhere (e.g., in GroupsInformationView). Therefore the next line is the Route construction for the user‑control path.\n\nnew Route(StringConstantsFrontend.USER_CONTROL_PATH, UserControlView.class),", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.565, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36896, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "new Route(StringConstantsFrontend.USER_CONTROL_PATH, UserControlView.class),", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport javax.validation.Validator;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\nimport org.springframework.util.CollectionUtils;\nimport com.ruoyi.common.constant.UserConstants;\nimport com.ruoyi.common.exception.ServiceException;\nimport com.ruoyi.common.utils.StringUtils;\nimport com.ruoyi.common.utils.bean.BeanValidators;\nimport com.ruoyi.common.utils.security.ShiroUtils;\nimport com.ruoyi.common.utils.spring.SpringUtils;\nimport com.ruoyi.common.utils.text.Convert;\nimport com.ruoyi.framework.aspectj.lang.annotation.DataScope;\nimport com.ruoyi.framework.shiro.service.PasswordService;\nimport com.ruoyi.project.system.config.service.IConfigService;\nimport com.ruoyi.project.system.post.domain.Post;\nimport com.ruoyi.project.system.post.mapper.PostMapper;\nimport com.ruoyi.project.system.role.domain.Role;\nimport com.ruoyi.project.system.role.mapper.RoleMapper;\nimport com.ruoyi.project.system.user.domain.User;\nimport com.ruoyi.project.system.user.domain.UserPost;\nimport com.ruoyi.project.system.user.domain.UserRole;\nimport com.ruoyi.project.system.user.mapper.UserMapper;\nimport com.ruoyi.project.system.user.mapper.UserPostMapper;\nimport com.ruoyi.project.system.user.mapper.UserRoleMapper;", "context": "src/main/java/com/ruoyi/project/system/user/service/UserServiceImpl.java\npackage com.ruoyi.project.system.user.service;\n\n\n/**\n * 用户 业务层处理\n * \n * @author ruoyi\n */\n@Service\npublic class UserServiceImpl implements IUserService\n{\n private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);\n\n @Autowired\n private UserMapper userMapper;\n\n @Autowired\n private RoleMapper roleMapper;\n\n @Autowired\n private PostMapper postMapper;\n\n @Autowired\n private UserPostMapper userPostMapper;\n\n @Autowired\n private UserRoleMapper userRoleMapper;\n\n @Autowired\n private IConfigService configService;\n\n @Autowired\n private PasswordService passwordService;\n\n @Autowired\n protected Validator validator;\n\n /**\n * 根据条件分页查询用户列表\n * \n * @param user 用户信息\n * @return 用户信息集合信息\n */\n @Override\n @DataScope(deptAlias = \"d\", userAlias = \"u\")\n public List selectUserList(User user)\n {\n // 生成数据权限过滤条件\n return userMapper.selectUserList(user);\n }\n\n /**\n * 根据条件分页查询已分配用户角色列表\n * \n * @param user 用户信息\n * @return 用户信息集合信息\n */\n @Override\n @DataScope(deptAlias = \"d\", userAlias = \"u\")\n public List selectAllocatedList(User user)\n {\n return userMapper.selectAllocatedList(user);\n }\n\n /**\n * 根据条件分页查询未分配用户角色列表\n * \n * @param user 用户信息\n * @return 用户信息集合信息\n */\n @Override\n @DataScope(deptAlias = \"d\", userAlias = \"u\")\n public List selectUnallocatedList(User user)\n {\n return userMapper.selectUnallocatedList(user);\n }\n\n /**\n * 通过用户名查询用户\n * \n * @param userName 用户名\n * @return 用户对象信息\n */\n @Override\n public User selectUserByLoginName(String userName)\n {\n return userMapper.selectUserByLoginName(userName);\n }\n\n /**\n * 通过手机号码查询用户\n * \n * @param phoneNumber 手机号码\n * @return 用户对象信息\n */\n @Override\n public User selectUserByPhoneNumber(String phoneNumber)\n {\n return userMapper.selectUserByPhoneNumber(phoneNumber);\n }\n\n /**\n * 通过邮箱查询用户\n * \n * @param email 邮箱\n * @return 用户对象信息\n */\n @Override\n public User selectUserByEmail(String email)\n {\n return userMapper.selectUserByEmail(email);\n }\n\n /**\n * 通过用户ID查询用户\n * \n * @param userId 用户ID\n * @return 用户对象信息\n */\n @Override\n public User selectUserById(Long userId)\n {\n return userMapper.selectUserById(userId);\n }\n\n /**\n * 通过用户ID查询用户和角色关联\n * \n * @param userId 用户ID\n * @return 用户和角色关联列表\n */\n @Override\n\nsrc/main/java/com/ruoyi/project/system/user/mapper/UserRoleMapper.java\npublic interface UserRoleMapper\n{\n /**\n * 通过用户ID查询用户和角色关联\n * \n * @param userId 用户ID\n * @return 用户和角色关联列表\n */\n public List selectUserRoleByUserId(Long userId);\n\n /**\n * 通过用户ID删除用户和角色关联\n * \n * @param userId 用户ID\n * @return 结果\n */\n public int deleteUserRoleByUserId(Long userId);\n\n /**\n * 批量删除用户和角色关联\n * \n * @param ids 需要删除的数据ID\n * @return 结果\n */\n public int deleteUserRole(Long[] ids);\n\n /**\n * 通过角色ID查询角色使用数量\n * \n * @param roleId 角色ID\n * @return 结果\n */\n public int countUserRoleByRoleId(Long roleId);\n\n /**\n * 批量新增用户角色信息\n * \n * @param userRoleList 用户角色列表\n * @return 结果\n */\n public int batchUserRole(List userRoleList);\n\n /**\n * 删除用户和角色关联信息\n * \n * @param userRole 用户和角色关联信息\n * @return 结果\n */\n public int deleteUserRoleInfo(UserRole userRole);\n\n /**\n * 批量取消授权用户角色\n * \n * @param roleId 角色ID\n * @param userIds 需要删除的用户数据ID\n * @return 结果\n */\n public int deleteUserRoleInfos(@Param(\"roleId\") Long roleId, @Param(\"userIds\") Long[] userIds);\n}\n\nsrc/main/java/com/ruoyi/project/system/post/mapper/PostMapper.java\npublic interface PostMapper\n{\n /**\n * 查询岗位数据集合\n * \n * @param post 岗位信息\n * @return 岗位数据集合\n */\n public List selectPostList(Post post);\n\n /**\n * 查询所有岗位\n * \n * @return 岗位列表\n */\n public List selectPostAll();\n\n /**\n * 根据用户ID查询岗位\n * \n * @param userId 用户ID\n * @return 岗位列表\n */\n public List selectPostsByUserId(Long userId);\n\n /**\n * 通过岗位ID查询岗位信息\n * \n * @param postId 岗位ID\n * @return 角色对象信息\n */\n public Post selectPostById(Long postId);\n\n /**\n * 批量删除岗位信息\n * \n * @param ids 需要删除的数据ID\n * @return 结果\n */\n public int deletePostByIds(Long[] ids);\n\n /**\n * 修改岗位信息\n * \n * @param post 岗位信息\n * @return 结果\n */\n public int updatePost(Post post);\n\n /**\n * 新增岗位信息\n * \n * @param post 岗位信息\n * @return 结果\n */\n public int insertPost(Post post);\n\n /**\n * 校验岗位名称\n * \n * @param postName 岗位名称\n * @return 结果\n */\n public Post checkPostNameUnique(String postName);\n\n /**\n * 校验岗位编码\n * \n * @param postCode 岗位编码\n * @return 结果\n */\n public Post checkPostCodeUnique(String postCode);\n}\n\nsrc/main/java/com/ruoyi/common/constant/UserConstants.java\npublic class UserConstants\n{\n /** 正常状态 */\n public static final String NORMAL = \"0\";\n\n /** 异常状态 */\n public static final String EXCEPTION = \"1\";\n\n /** 用户封禁状态 */\n public static final String USER_DISABLE = \"1\";\n\n /** 角色封禁状态 */\n public static final String ROLE_DISABLE = \"1\";\n\n /** 部门正常状态 */\n public static final String DEPT_NORMAL = \"0\";\n\n /** 部门停用状态 */\n public static final String DEPT_DISABLE = \"1\";\n\n /** 字典正常状态 */\n public static final String DICT_NORMAL = \"0\";\n\n /** 是否为系统默认(是) */\n public static final String YES = \"Y\";\n\n /**\n * 用户名长度限制\n */\n public static final int USERNAME_MIN_LENGTH = 2;\n public static final int USERNAME_MAX_LENGTH = 20;\n\n /** 登录名称是否唯一的返回结果码 */\n public final static String USER_NAME_UNIQUE = \"0\";\n public final static String USER_NAME_NOT_UNIQUE = \"1\";\n\n /** 手机号码是否唯一的返回结果 */\n public final static String USER_PHONE_UNIQUE = \"0\";\n public final static String USER_PHONE_NOT_UNIQUE = \"1\";\n\n /** e-mail 是否唯一的返回结果 */\n public final static String USER_EMAIL_UNIQUE = \"0\";\n public final static String USER_EMAIL_NOT_UNIQUE = \"1\";\n\n /** 部门名称是否唯一的返回结果码 */\n public final static String DEPT_NAME_UNIQUE = \"0\";\n public final static String DEPT_NAME_NOT_UNIQUE = \"1\";\n\n /** 角色名称是否唯一的返回结果码 */\n public final static String ROLE_NAME_UNIQUE = \"0\";\n public final static String ROLE_NAME_NOT_UNIQUE = \"1\";\n\n /** 岗位名称是否唯一的返回结果码 */\n public final static String POST_NAME_UNIQUE = \"0\";\n public final static String POST_NAME_NOT_UNIQUE = \"1\";\n\n /** 角色权限是否唯一的返回结果码 */\n public final static String ROLE_KEY_UNIQUE = \"0\";\n public final static String ROLE_KEY_NOT_UNIQUE = \"1\";\n\n /** 岗位编码是否唯一的返回结果码 */\n public final static String POST_CODE_UNIQUE = \"0\";\n public final static String POST_CODE_NOT_UNIQUE = \"1\";\n\n /** 菜单名称是否唯一的返回结果码 */\n public final static String MENU_NAME_UNIQUE = \"0\";\n public final static String MENU_NAME_NOT_UNIQUE = \"1\";\n\n /** 字典类型是否唯一的返回结果码 */\n public final static String DICT_TYPE_UNIQUE = \"0\";\n public final static String DICT_TYPE_NOT_UNIQUE = \"1\";\n\n /** 参数键名是否唯一的返回结果码 */\n public final static String CONFIG_KEY_UNIQUE = \"0\";\n public final static String CONFIG_KEY_NOT_UNIQUE = \"1\";\n\n /**\n * 密码长度限制\n */\n public static final int PASSWORD_MIN_LENGTH = 5;\n public static final int PASSWORD_MAX_LENGTH = 20;\n\n /**\n * 用户类型\n */\n public static final String SYSTEM_USER_TYPE = \"00\";\n public static final String REGISTER_USER_TYPE = \"01\";\n\n /**\n * 手机号码格式限制\n */\n public static final String MOBILE_PHONE_NUMBER_PATTERN = \"^0{0,1}(13[0-9]|15[0-9]|14[0-9]|18[0-9])[0-9]{8}$\";\n\n /**\n * 邮箱格式限制\n */\n public static final String EMAIL_PATTERN = \"^((([a-z]|\\\\d|[!#\\\\$%&'\\\\*\\\\+\\\\-\\\\/=\\\\?\\\\^_`{\\\\|}~]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])+(\\\\.([a-z]|\\\\d|[!#\\\\$%&'\\\\*\\\\+\\\\-\\\\/=\\\\?\\\\^_`{\\\\|}~]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])+)*)|((\\\\x22)((((\\\\x20|\\\\x09)*(\\\\x0d\\\\x0a))?(\\\\x20|\\\\x09)+)?(([\\\\x01-\\\\x08\\\\x0b\\\\x0c\\\\x0e-\\\\x1f\\\\x7f]|\\\\x21|[\\\\x23-\\\\x5b]|[\\\\x5d-\\\\x7e]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(\\\\\\\\([\\\\x01-\\\\x09\\\\x0b\\\\x0c\\\\x0d-\\\\x7f]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF]))))*(((\\\\x20|\\\\x09)*(\\\\x0d\\\\x0a))?(\\\\x20|\\\\x09)+)?(\\\\x22)))@((([a-z]|\\\\d|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(([a-z]|\\\\d|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])*([a-z]|\\\\d|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])))\\\\.)+(([a-z]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(([a-z]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])*([a-z]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])))\\\\.?\";\n}\n\nsrc/main/java/com/ruoyi/project/system/role/domain/Role.java\npublic class Role extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 角色ID */\n @Excel(name = \"角色序号\", cellType = ColumnType.NUMERIC)\n private Long roleId;\n\n /** 角色名称 */\n @Excel(name = \"角色名称\")\n private String roleName;\n\n /** 角色权限 */\n @Excel(name = \"角色权限\")\n private String roleKey;\n\n /** 角色排序 */\n @Excel(name = \"角色排序\")\n private String roleSort;\n\n /** 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限;5:仅本人数据权限) */\n @Excel(name = \"数据范围\", readConverterExp = \"1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限\")\n private String dataScope;\n\n /** 角色状态(0正常 1停用) */\n @Excel(name = \"角色状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 用户是否存在此角色标识 默认不存在 */\n private boolean flag = false;\n\n /** 菜单组 */\n private Long[] menuIds;\n\n /** 部门组(数据权限) */\n private Long[] deptIds;\n\n public Role()\n {\n\n }\n\n public Role(Long roleId)\n {\n this.roleId = roleId;\n }\n\n public Long getRoleId()\n {\n return roleId;\n }\n\n public void setRoleId(Long roleId)\n {\n this.roleId = roleId;\n }\n\n public boolean isAdmin()\n {\n return isAdmin(this.roleId);\n }\n\n public static boolean isAdmin(Long roleId)\n {\n return roleId != null && 1L == roleId;\n }\n\n public String getDataScope()\n {\n return dataScope;\n }\n\n public void setDataScope(String dataScope)\n {\n this.dataScope = dataScope;\n }\n\n @NotBlank(message = \"角色名称不能为空\")\n @Size(min = 0, max = 30, message = \"角色名称长度不能超过30个字符\")\n public String getRoleName()\n {\n return roleName;\n }\n\n public void setRoleName(String roleName)\n {\n this.roleName = roleName;\n }\n\n @NotBlank(message = \"权限字符不能为空\")\n @Size(min = 0, max = 100, message = \"权限字符长度不能超过100个字符\")\n public String getRoleKey()\n {\n return roleKey;\n }\n\n public void setRoleKey(String roleKey)\n {\n this.roleKey = roleKey;\n }\n\n @NotBlank(message = \"显示顺序不能为空\")\n public String getRoleSort()\n {\n return roleSort;\n }\n\n public void setRoleSort(String roleSort)\n {\n this.roleSort = roleSort;\n }\n\n public String getStatus()\n {\n return status;\n }\n\n public String getDelFlag()\n {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag)\n {\n this.delFlag = delFlag;\n }\n\n public void setStatus(String status)\n {\n this.status = status;\n }\n\n public boolean isFlag()\n {\n return flag;\n }\n\n public void setFlag(boolean flag)\n {\n this.flag = flag;\n }\n\n public Long[] getMenuIds()\n {\n return menuIds;\n }\n\n public void setMenuIds(Long[] menuIds)\n {\n this.menuIds = menuIds;\n }\n\n public Long[] getDeptIds()\n {\n return deptIds;\n }\n\n public void setDeptIds(Long[] deptIds)\n {\n this.deptIds = deptIds;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"roleId\", getRoleId())\n .append(\"roleName\", getRoleName())\n .append(\"roleKey\", getRoleKey())\n .append(\"roleSort\", getRoleSort())\n .append(\"dataScope\", getDataScope())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .toString();\n }\n}\n\nsrc/main/java/com/ruoyi/project/system/config/service/IConfigService.java\npublic interface IConfigService\n{\n /**\n * 查询参数配置信息\n * \n * @param configId 参数配置ID\n * @return 参数配置信息\n */\n public Config selectConfigById(Long configId);\n\n /**\n * 根据键名查询参数配置信息\n * \n * @param configKey 参数键名\n * @return 参数键值\n */\n public String selectConfigByKey(String configKey);\n\n /**\n * 查询参数配置列表\n * \n * @param config 参数配置信息\n * @return 参数配置集合\n */\n public List selectConfigList(Config config);\n\n /**\n * 新增参数配置\n * \n * @param config 参数配置信息\n * @return 结果\n */\n public int insertConfig(Config config);\n\n /**\n * 修改参数配置\n * \n * @param config 参数配置信息\n * @return 结果\n */\n public int updateConfig(Config config);\n\n /**\n * 批量删除参数配置信息\n * \n * @param ids 需要删除的数据ID\n */\n public void deleteConfigByIds(String ids);\n\n /**\n * 加载参数缓存数据\n */\n public void loadingConfigCache();\n\n /**\n * 清空参数缓存数据\n */\n public void clearConfigCache();\n\n /**\n * 重置参数缓存数据\n */\n public void resetConfigCache();\n\n /**\n * 校验参数键名是否唯一\n * \n * @param config 参数信息\n * @return 结果\n */\n public String checkConfigKeyUnique(Config config);\n}\n\nsrc/main/java/com/ruoyi/project/system/user/domain/User.java\npublic class User extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, prompt = \"用户编号\")\n private Long userId;\n\n /** 部门ID */\n @Excel(name = \"部门编号\", type = Type.IMPORT)\n private Long deptId;\n\n /** 部门父ID */\n private Long parentId;\n\n /** 角色ID */\n private Long roleId;\n\n /** 登录名称 */\n @Excel(name = \"登录名称\")\n private String loginName;\n\n /** 用户名称 */\n @Excel(name = \"用户名称\")\n private String userName;\n\n /** 用户类型 */\n private String userType;\n\n /** 用户邮箱 */\n @Excel(name = \"用户邮箱\")\n private String email;\n\n /** 手机号码 */\n @Excel(name = \"手机号码\")\n private String phonenumber;\n\n /** 用户性别 */\n @Excel(name = \"用户性别\", readConverterExp = \"0=男,1=女,2=未知\")\n private String sex;\n\n /** 用户头像 */\n private String avatar;\n\n /** 密码 */\n private String password;\n\n /** 盐加密 */\n private String salt;\n\n /** 帐号状态(0正常 1停用) */\n @Excel(name = \"帐号状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 最后登录IP */\n @Excel(name = \"最后登录IP\", type = Type.EXPORT)\n private String loginIp;\n\n /** 最后登录时间 */\n @Excel(name = \"最后登录时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\", type = Type.EXPORT)\n private Date loginDate;\n\n /** 密码最后更新时间 */\n private Date pwdUpdateDate;\n\n /** 部门对象 */\n @Excels({\n @Excel(name = \"部门名称\", targetAttr = \"deptName\", type = Type.EXPORT),\n @Excel(name = \"部门负责人\", targetAttr = \"leader\", type = Type.EXPORT)\n })\n private Dept dept;\n\n private List roles;\n\n /** 角色组 */\n private Long[] roleIds;\n\n /** 岗位组 */\n private Long[] postIds;\n\n public User()\n {\n\n }\n\n public User(Long userId)\n {\n this.userId = userId;\n }\n\n public Long getUserId()\n {\n return userId;\n }\n\n public void setUserId(Long userId)\n {\n this.userId = userId;\n }\n\n public boolean isAdmin()\n {\n return isAdmin(this.userId);\n }\n\n public static boolean isAdmin(Long userId)\n {\n return userId != null && 1L == userId;\n }\n\n public Long getDeptId()\n {\n return deptId;\n }\n\n public void setDeptId(Long deptId)\n {\n this.deptId = deptId;\n }\n\n public Long getParentId()\n {\n return parentId;\n }\n\n public void setParentId(Long parentId)\n {\n this.parentId = parentId;\n }\n\n public Long getRoleId()\n {\n return roleId;\n }\n\n public void setRoleId(Long roleId)\n {\n this.roleId = roleId;\n }\n\n @Xss(message = \"登录账号不能包含脚本字符\")\n @NotBlank(message = \"登录账号不能为空\")\n @Size(min = 0, max = 30, message = \"登录账号长度不能超过30个字符\")\n public String getLoginName()\n {\n return loginName;\n }\n\n public void setLoginName(String loginName)\n {\n this.loginName = loginName;\n }\n\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @Size(min = 0, max = 30, message = \"用户昵称长度不能超过30个字符\")\n public String getUserName()\n {\n return userName;\n }\n\n public void setUserName(String userName)\n {\n this.userName = userName;\n }\n\n public String getUserType()\n {\n return userType;\n }\n\n public void setUserType(String userType)\n {\n this.userType = userType;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail()\n {\n return email;\n }\n\n public void setEmail(String email)\n {\n this.email = email;\n }\n\n @Size(min = 0, max = 11, message = \"手机号码长度不能超过11个字符\")\n public String getPhonenumber()\n {\n return phonenumber;\n }\n\n public void setPhonenumber(String phonenumber)\n {\n this.phonenumber = phonenumber;\n }\n\n public String getSex()\n {\n return sex;\n }\n\n public void setSex(String sex)\n {\n this.sex = sex;\n }\n\n public String getAvatar()\n {\n return avatar;\n }\n\n public void setAvatar(String avatar)\n {\n this.avatar = avatar;\n }\n\n @JsonIgnore\n public String getPassword()\n {\n return password;\n }\n\n public void setPassword(String password)\n {\n this.password = password;\n }\n\n public String getSalt()\n {\n return salt;\n }\n\n public void setSalt(String salt)\n {\n this.salt = salt;\n }\n\n /**\n * 生成随机盐\n */\n public void randomSalt()\n {\n // 一个Byte占两个字节,此处生成的3字节,字符串长度为6\n SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();\n String hex = secureRandom.nextBytes(3).toHex();\n setSalt(hex);\n }\n\n public String getStatus()\n {\n return status;\n }\n\n public void setStatus(String status)\n {\n this.status = status;\n }\n\n public String getDelFlag()\n {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag)\n {\n this.delFlag = delFlag;\n }\n\n public String getLoginIp()\n {\n return loginIp;\n }\n\n public void setLoginIp(String loginIp)\n {\n this.loginIp = loginIp;\n }\n\n public Date getLoginDate()\n {\n return loginDate;\n }\n\n public void setLoginDate(Date loginDate)\n {\n this.loginDate = loginDate;\n }\n\n public Date getPwdUpdateDate()\n {\n return pwdUpdateDate;\n }\n\n public void setPwdUpdateDate(Date pwdUpdateDate)\n {\n this.pwdUpdateDate = pwdUpdateDate;\n }\n\n public Dept getDept()\n {\n if (dept == null)\n {\n dept = new Dept();\n }\n return dept;\n }\n\n public void setDept(Dept dept)\n {\n this.dept = dept;\n }\n\n public List getRoles()\n {\n return roles;\n }\n\n public void setRoles(List roles)\n {\n this.roles = roles;\n }\n\n public Long[] getRoleIds()\n {\n return roleIds;\n }\n\n public void setRoleIds(Long[] roleIds)\n {\n this.roleIds = roleIds;\n }\n\n public Long[] getPostIds()\n {\n return postIds;\n }\n\n public void setPostIds(Long[] postIds)\n {\n this.postIds = postIds;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"userId\", getUserId())\n .append(\"deptId\", getDeptId())\n .append(\"loginName\", getLoginName())\n .append(\"userName\", getUserName())\n .append(\"userType\", getUserType())\n .append(\"email\", getEmail())\n .append(\"phonenumber\", getPhonenumber())\n .append(\"sex\", getSex())\n .append(\"avatar\", getAvatar())\n .append(\"password\", getPassword())\n .append(\"salt\", getSalt())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"loginIp\", getLoginIp())\n .append(\"loginDate\", getLoginDate())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .append(\"dept\", getDept())\n .append(\"roles\", getRoles())\n .toString();\n }\n}\n\nsrc/main/java/com/ruoyi/common/utils/text/Convert.java\npublic class Convert\n{\n /**\n * 转换为字符串
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static String toStr(Object value, String defaultValue)\n {\n if (null == value)\n {\n return defaultValue;\n }\n if (value instanceof String)\n {\n return (String) value;\n }\n return value.toString();\n }\n\n /**\n * 转换为字符串
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static String toStr(Object value)\n {\n return toStr(value, null);\n }\n\n /**\n * 转换为字符
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Character toChar(Object value, Character defaultValue)\n {\n if (null == value)\n {\n return defaultValue;\n }\n if (value instanceof Character)\n {\n return (Character) value;\n }\n\n final String valueStr = toStr(value, null);\n return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);\n }\n\n /**\n * 转换为字符
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Character toChar(Object value)\n {\n return toChar(value, null);\n }\n\n /**\n * 转换为byte
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Byte toByte(Object value, Byte defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Byte)\n {\n return (Byte) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).byteValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Byte.parseByte(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为byte
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Byte toByte(Object value)\n {\n return toByte(value, null);\n }\n\n /**\n * 转换为Short
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Short toShort(Object value, Short defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Short)\n {\n return (Short) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).shortValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Short.parseShort(valueStr.trim());\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Short
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Short toShort(Object value)\n {\n return toShort(value, null);\n }\n\n /**\n * 转换为Number
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Number toNumber(Object value, Number defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Number)\n {\n return (Number) value;\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return NumberFormat.getInstance().parse(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Number
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Number toNumber(Object value)\n {\n return toNumber(value, null);\n }\n\n /**\n * 转换为int
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Integer toInt(Object value, Integer defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Integer)\n {\n return (Integer) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).intValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Integer.parseInt(valueStr.trim());\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为int
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Integer toInt(Object value)\n {\n return toInt(value, null);\n }\n\n /**\n * 转换为Integer数组
\n * \n * @param str 被转换的值\n * @return 结果\n */\n public static Integer[] toIntArray(String str)\n {\n return toIntArray(\",\", str);\n }\n\n /**\n * 转换为Long数组
\n * \n * @param str 被转换的值\n * @return 结果\n */\n public static Long[] toLongArray(String str)\n {\n return toLongArray(\",\", str);\n }\n\n /**\n * 转换为Integer数组
\n * \n * @param split 分隔符\n * @param split 被转换的值\n * @return 结果\n */\n public static Integer[] toIntArray(String split, String str)\n {\n if (StringUtils.isEmpty(str))\n {\n return new Integer[] {};\n }\n String[] arr = str.split(split);\n final Integer[] ints = new Integer[arr.length];\n for (int i = 0; i < arr.length; i++)\n {\n final Integer v = toInt(arr[i], 0);\n ints[i] = v;\n }\n return ints;\n }\n\n /**\n * 转换为Long数组
\n * \n * @param split 分隔符\n * @param str 被转换的值\n * @return 结果\n */\n public static Long[] toLongArray(String split, String str)\n {\n if (StringUtils.isEmpty(str))\n {\n return new Long[] {};\n }\n String[] arr = str.split(split);\n final Long[] longs = new Long[arr.length];\n for (int i = 0; i < arr.length; i++)\n {\n final Long v = toLong(arr[i], null);\n longs[i] = v;\n }\n return longs;\n }\n\n /**\n * 转换为String数组
\n * \n * @param str 被转换的值\n * @return 结果\n */\n public static String[] toStrArray(String str)\n {\n return toStrArray(\",\", str);\n }\n\n /**\n * 转换为String数组
\n * \n * @param split 分隔符\n * @param split 被转换的值\n * @return 结果\n */\n public static String[] toStrArray(String split, String str)\n {\n return str.split(split);\n }\n\n /**\n * 转换为long
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Long toLong(Object value, Long defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Long)\n {\n return (Long) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).longValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n // 支持科学计数法\n return new BigDecimal(valueStr.trim()).longValue();\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为long
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Long toLong(Object value)\n {\n return toLong(value, null);\n }\n\n /**\n * 转换为double
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Double toDouble(Object value, Double defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Double)\n {\n return (Double) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).doubleValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n // 支持科学计数法\n return new BigDecimal(valueStr.trim()).doubleValue();\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为double
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Double toDouble(Object value)\n {\n return toDouble(value, null);\n }\n\n /**\n * 转换为Float
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Float toFloat(Object value, Float defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Float)\n {\n return (Float) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).floatValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Float.parseFloat(valueStr.trim());\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Float
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Float toFloat(Object value)\n {\n return toFloat(value, null);\n }\n\n /**\n * 转换为boolean
\n * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Boolean toBool(Object value, Boolean defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Boolean)\n {\n return (Boolean) value;\n }\n String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n valueStr = valueStr.trim().toLowerCase();\n switch (valueStr)\n {\n case \"true\":\n return true;\n case \"false\":\n return false;\n case \"yes\":\n return true;\n case \"ok\":\n return true;\n case \"no\":\n return false;\n case \"1\":\n return true;\n case \"0\":\n return false;\n default:\n return defaultValue;\n }\n }\n\n /**\n * 转换为boolean
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Boolean toBool(Object value)\n {\n return toBool(value, null);\n }\n\n /**\n * 转换为Enum对象
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * \n * @param clazz Enum的Class\n * @param value 值\n * @param defaultValue 默认值\n * @return Enum\n */\n public static > E toEnum(Class clazz, Object value, E defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (clazz.isAssignableFrom(value.getClass()))\n {\n @SuppressWarnings(\"unchecked\")\n E myE = (E) value;\n return myE;\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Enum.valueOf(clazz, valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Enum对象
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * \n * @param clazz Enum的Class\n * @param value 值\n * @return Enum\n */\n public static > E toEnum(Class clazz, Object value)\n {\n return toEnum(clazz, value, null);\n }\n\n /**\n * 转换为BigInteger
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static BigInteger toBigInteger(Object value, BigInteger defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof BigInteger)\n {\n return (BigInteger) value;\n }\n if (value instanceof Long)\n {\n return BigInteger.valueOf((Long) value);\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return new BigInteger(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为BigInteger
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static BigInteger toBigInteger(Object value)\n {\n return toBigInteger(value, null);\n }\n\n /**\n * 转换为BigDecimal
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof BigDecimal)\n {\n return (BigDecimal) value;\n }\n if (value instanceof Long)\n {\n return new BigDecimal((Long) value);\n }\n if (value instanceof Double)\n {\n return new BigDecimal((Double) value);\n }\n if (value instanceof Integer)\n {\n return new BigDecimal((Integer) value);\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return new BigDecimal(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为BigDecimal
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static BigDecimal toBigDecimal(Object value)\n {\n return toBigDecimal(value, null);\n }\n\n /**\n * 将对象转为字符串
\n * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法\n * \n * @param obj 对象\n * @return 字符串\n */\n public static String utf8Str(Object obj)\n {\n return str(obj, CharsetKit.CHARSET_UTF_8);\n }\n\n /**\n * 将对象转为字符串
\n * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法\n * \n * @param obj 对象\n * @param charsetName 字符集\n * @return 字符串\n */\n public static String str(Object obj, String charsetName)\n {\n return str(obj, Charset.forName(charsetName));\n }\n\n /**\n * 将对象转为字符串
\n * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法\n * \n * @param obj 对象\n * @param charset 字符集\n * @return 字符串\n */\n public static String str(Object obj, Charset charset)\n {\n if (null == obj)\n {\n return null;\n }\n\n if (obj instanceof String)\n {\n return (String) obj;\n }\n else if (obj instanceof byte[])\n {\n return str((byte[]) obj, charset);\n }\n else if (obj instanceof Byte[])\n {\n byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj);\n return str(bytes, charset);\n }\n else if (obj instanceof ByteBuffer)\n {\n return str((ByteBuffer) obj, charset);\n }\n return obj.toString();\n }\n\n /**\n * 将byte数组转为字符串\n * \n * @param bytes byte数组\n * @param charset 字符集\n * @return 字符串\n */\n public static String str(byte[] bytes, String charset)\n {\n return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));\n }\n\n /**\n * 解码字节码\n * \n * @param data 字符串\n * @param charset 字符集,如果此字段为空,则解码的结果取决于平台\n * @return 解码后的字符串\n */\n public static String str(byte[] data, Charset charset)\n {\n if (data == null)\n {\n return null;\n }\n\n if (null == charset)\n {\n return new String(data);\n }\n return new String(data, charset);\n }\n\n /**\n * 将编码的byteBuffer数据转换为字符串\n * \n * @param data 数据\n * @param charset 字符集,如果为空使用当前系统字符集\n * @return 字符串\n */\n public static String str(ByteBuffer data, String charset)\n {\n if (data == null)\n {\n return null;\n }\n\n return str(data, Charset.forName(charset));\n }\n\n /**\n * 将编码的byteBuffer数据转换为字符串\n * \n * @param data 数据\n * @param charset 字符集,如果为空使用当前系统字符集\n * @return 字符串\n */\n public static String str(ByteBuffer data, Charset charset)\n {\n if (null == charset)\n {\n charset = Charset.defaultCharset();\n }\n return charset.decode(data).toString();\n }\n\n // ----------------------------------------------------------------------- 全角半角转换\n /**\n * 半角转全角\n * \n * @param input String.\n * @return 全角字符串.\n */\n public static String toSBC(String input)\n {\n return toSBC(input, null);\n }\n\n /**\n * 半角转全角\n * \n * @param input String\n * @param notConvertSet 不替换的字符集合\n * @return 全角字符串.\n */\n public static String toSBC(String input, Set notConvertSet)\n {\n char c[] = input.toCharArray();\n for (int i = 0; i < c.length; i++)\n {\n if (null != notConvertSet && notConvertSet.contains(c[i]))\n {\n // 跳过不替换的字符\n continue;\n }\n\n if (c[i] == ' ')\n {\n c[i] = '\\u3000';\n }\n else if (c[i] < '\\177')\n {\n c[i] = (char) (c[i] + 65248);\n\n }\n }\n return new String(c);\n }\n\n /**\n * 全角转半角\n * \n * @param input String.\n * @return 半角字符串\n */\n public static String toDBC(String input)\n {\n return toDBC(input, null);\n }\n\n /**\n * 替换全角为半角\n * \n * @param text 文本\n * @param notConvertSet 不替换的字符集合\n * @return 替换后的字符\n */\n public static String toDBC(String text, Set notConvertSet)\n {\n char c[] = text.toCharArray();\n for (int i = 0; i < c.length; i++)\n {\n if (null != notConvertSet && notConvertSet.contains(c[i]))\n {\n // 跳过不替换的字符\n continue;\n }\n\n if (c[i] == '\\u3000')\n {\n c[i] = ' ';\n }\n else if (c[i] > '\\uFF00' && c[i] < '\\uFF5F')\n {\n c[i] = (char) (c[i] - 65248);\n }\n }\n String returnString = new String(c);\n\n return returnString;\n }\n\n /**\n * 数字金额大写转换 先写个完整的然后将如零拾替换成零\n * \n * @param n 数字\n * @return 中文大写数字\n */\n public static String digitUppercase(double n)\n {\n String[] fraction = { \"角\", \"分\" };\n String[] digit = { \"零\", \"壹\", \"贰\", \"叁\", \"肆\", \"伍\", \"陆\", \"柒\", \"捌\", \"玖\" };\n String[][] unit = { { \"元\", \"万\", \"亿\" }, { \"\", \"拾\", \"佰\", \"仟\" } };\n\n String head = n < 0 ? \"负\" : \"\";\n n = Math.abs(n);\n\n String s = \"\";\n for (int i = 0; i < fraction.length; i++)\n {\n s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll(\"(零.)+\", \"\");\n }\n if (s.length() < 1)\n {\n s = \"整\";\n }\n int integerPart = (int) Math.floor(n);\n\n for (int i = 0; i < unit[0].length && integerPart > 0; i++)\n {\n String p = \"\";\n for (int j = 0; j < unit[1].length && n > 0; j++)\n {\n p = digit[integerPart % 10] + unit[1][j] + p;\n integerPart = integerPart / 10;\n }\n s = p.replaceAll(\"(零.)*零$\", \"\").replaceAll(\"^$\", \"零\") + unit[0][i] + s;\n }\n return head + s.replaceAll(\"(零.)*零元\", \"元\").replaceFirst(\"(零.)+\", \"\").replaceAll(\"(零.)+\", \"零\").replaceAll(\"^整$\", \"零元整\");\n }\n}", "answers": [" public List selectUserRoleByUserId(Long userId)"], "length": 4432, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "27adc274-f092-49bc-a8ea-591bff2a4aaa", "reasoning": "The file ends right after an @Override annotation for the method that retrieves user-role associations by user ID. Following the pattern of earlier methods, the next line should be the method signature that returns a List and takes a Long userId parameter.", "reasoning_model_answer": "public List selectUserRoleByUserId(Long userId)", "assistant_with_reasoning": "\nThe file ends right after an @Override annotation for the method that retrieves user-role associations by user ID. Following the pattern of earlier methods, the next line should be the method signature that returns a List and takes a Long userId parameter.\n\npublic List selectUserRoleByUserId(Long userId)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.826, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37497, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public List selectUserRoleByUserId(Long userId)", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.badlogic.gdx.graphics.g2d.TextureAtlas;\nimport com.badlogic.gdx.math.Vector2;\nimport com.csse3200.game.areas.TestGameArea;\nimport com.csse3200.game.areas.terrain.GameMap;\nimport com.csse3200.game.areas.terrain.TerrainComponent;\nimport com.csse3200.game.areas.terrain.TerrainFactory;\nimport com.csse3200.game.components.CameraComponent;\nimport com.csse3200.game.components.combat.CombatStatsComponent;\nimport com.csse3200.game.entities.Entity;\nimport com.csse3200.game.entities.factories.PlayerFactory;\nimport com.csse3200.game.extensions.GameExtension;\nimport com.csse3200.game.physics.PhysicsService;\nimport com.csse3200.game.physics.components.PhysicsComponent;\nimport com.csse3200.game.rendering.AnimationRenderComponent;\nimport com.csse3200.game.rendering.RenderService;\nimport com.csse3200.game.services.ResourceService;\nimport com.csse3200.game.services.ServiceLocator;\nimport com.csse3200.game.utils.math.Vector2Utils;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeAll;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.Arguments;\nimport org.junit.jupiter.params.provider.MethodSource;\nimport java.util.stream.Stream;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Named.named;\nimport static org.junit.jupiter.params.provider.Arguments.arguments;\nimport static org.mockito.Mockito.doReturn;\nimport static org.mockito.Mockito.mock;", "context": "source/core/src/test/com/csse3200/game/components/player/PlayerMovementIntegrationTest.java\npackage com.csse3200.game.components.player;\n\n\n\n\n\n@ExtendWith(GameExtension.class)\nclass PlayerMovementIntegrationTest {\n\tprivate Entity player;\n\t//TestGameArea to register so GameMap can be accessed through the ServiceLocator\n\tprivate static final TestGameArea gameArea = new TestGameArea();\n\n\t@BeforeAll\n\tstatic void setupGameAreaAndMap() {\n\t\t//necessary for allowing the Terrain factory to properly generate the map with correct tile dimensions\n\t\tResourceService resourceService = new ResourceService();\n\t\tresourceService.loadTextures(TerrainFactory.getMapTextures());\n\t\tresourceService.loadAll();\n\t\tServiceLocator.registerResourceService(resourceService);\n\n\t\t//Loads the test terrain into the GameMap\n\t\tTerrainComponent terrainComponent = mock(TerrainComponent.class);\n\t\tdoReturn(TerrainFactory.WORLD_TILE_SIZE).when(terrainComponent).getTileSize();\n\t\tGameMap gameMap = new GameMap(new TerrainFactory(new CameraComponent()));\n\t\tgameMap.setTerrainComponent(terrainComponent);\n\t\tgameMap.loadTestTerrain(\"configs/TestMaps/exampleTestMap.txt\");\n\n\t\t//Sets the GameMap in the TestGameArea\n\t\tgameArea.setGameMap(gameMap);\n\n\t\t//Only needed the assets for the map loading, can be unloaded\n\t\tresourceService.unloadAssets(TerrainFactory.getMapTextures());\n\t\tresourceService.dispose();\n\t}\n\n\t@BeforeEach\n\tvoid initialiseTest() {\n\t\tServiceLocator.registerPhysicsService(new PhysicsService());\n\t\tServiceLocator.registerRenderService(new RenderService());\n\t\tServiceLocator.registerGameArea(gameArea);\n\n\t\tResourceService resourceService = new ResourceService();\n\t\tresourceService.loadTextureAtlases(new String[]{\"images/player.atlas\"});\n\t\tresourceService.loadTextures(new String[]{\"images/heart.png\"});\n\t\tresourceService.loadAll();\n\t\tServiceLocator.registerResourceService(resourceService);\n\t\tAnimationRenderComponent animator =\n\t\t\t\tnew AnimationRenderComponent(\n\t\t\t\t\t\tServiceLocator.getResourceService().getAsset(\"images/player.atlas\", TextureAtlas.class)\n\t\t\t\t);\n\n\t\tPlayerFactory.setupPlayerAnimator(animator);\n\n\t\tplayer = new Entity()\n\nsource/core/src/main/com/csse3200/game/physics/PhysicsService.java\npublic class PhysicsService {\n\tprivate final PhysicsEngine engine;\n\n\tpublic PhysicsService() {\n\t\tthis(new PhysicsEngine());\n\t}\n\n\tpublic PhysicsService(PhysicsEngine engine) {\n\t\tthis.engine = engine;\n\t}\n\n\tpublic PhysicsEngine getPhysics() {\n\t\treturn engine;\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/entities/factories/PlayerFactory.java\npublic class PlayerFactory {\n\tprivate static final PlayerConfig stats =\n\t\t\tFileLoader.readClass(PlayerConfig.class, \"configs/player.json\");\n\n\t/**\n\t * Create a player entity.\n\t *\n\t * @return entity\n\t */\n\tpublic static Entity createPlayer() {\n\t\tInputComponent inputComponent =\n\t\t\t\tServiceLocator.getInputService().getInputFactory().createForPlayer();\n\n\t\tAnimationRenderComponent animator =\n\t\t\t\tnew AnimationRenderComponent(\n\t\t\t\t\t\tServiceLocator.getResourceService().getAsset(\"images/player.atlas\", TextureAtlas.class),\n\t\t\t\t\t\t16f\n\t\t\t\t);\n\n\t\tsetupPlayerAnimator(animator);\n\n\t\tEntity player =\n\t\t\t\tnew Entity(EntityType.PLAYER)\n\t\t\t\t\t\t.addComponent(new PhysicsComponent())\n\t\t\t\t\t\t.addComponent(new ColliderComponent())\n\t\t\t\t\t\t.addComponent(new HitboxComponent().setLayer(PhysicsLayer.PLAYER))\n\t\t\t\t\t\t.addComponent(new PlayerActions())\n\t\t\t\t\t\t.addComponent(new CombatStatsComponent(stats.PLAYER_HEALTH, stats.BASE_ATTACK))\n\t\t\t\t\t\t.addComponent(new InventoryComponent())\n\t\t\t\t\t\t.addComponent(new HungerComponent(30))\n\t\t\t\t\t\t.addComponent(inputComponent)\n\t\t\t\t\t\t.addComponent(animator)\n\t\t\t\t\t\t.addComponent(new OpenPauseComponent())\n\t\t\t\t\t\t.addComponent(new PlayerAnimationController())\n\t\t\t\t\t\t.addComponent(new ItemPickupComponent())\n\t\t\t\t\t\t.addComponent(new InteractionDetector(2f, new ArrayList<>(Arrays.asList(EntityType.QUESTGIVER, EntityType.GATE, EntityType.CHEST, EntityType.CHICKEN,\n\t\t\t\t\t\t\t\tEntityType.COW, EntityType.ASTROLOTL, EntityType.OXYGEN_EATER, EntityType.SHIP_DEBRIS, EntityType.SHIP, EntityType.GOLDEN_STATUE))))\n\t\t\t\t\t\t.addComponent(new ToolbarDisplay())\n\t\t\t\t\t\t.addComponent(new AuraLightComponent(6f))\n\t\t\t\t\t\t.addComponent(new ParticleEffectComponent())\n\t\t\t\t\t\t.addComponent(new InventoryDisplay(\"updateInventory\", \"toggleInventory\", 30, 10, true))\n\t\t\t\t\t\t.addComponent(new BlinkComponent())\n\t\t\t\t\t\t.addComponent(new StunComponent())\n\t\t\t\t\t\t.addComponent(new DimComponent())\n\t\t\t\t\t\t.addComponent(new PauseMenuActions());\n\n\t\tplayer.getComponent(ColliderComponent.class).setDensity(1.5f);\n\t\tplayer.getComponent(ColliderComponent.class).setAsBox(new Vector2(0.9f, 0.9f), new Vector2(1.5f, 1f));\n\t\tplayer.getComponent(HitboxComponent.class).setAsBox(new Vector2(1f, 2f), new Vector2(1.5f, 1.5f));\n\t\tplayer.getComponent(AnimationRenderComponent.class).scaleEntity();\n\t\tplayer.getComponent(KeyboardPlayerInputComponent.class).setActions(player.getComponent(PlayerActions.class));\n\n\t\tplayer.getComponent(PlayerAnimationController.class).addFishingRodAnimatorEntity(createFishingRodAnimatorEntity());\n\n\t\treturn player;\n\t}\n\n\t/**\n\t * Registers player animations to the AnimationRenderComponent.\n\t */\n\tpublic static void setupPlayerAnimator(AnimationRenderComponent animator) {\n\t\tanimator.addAnimation(\"walk_left\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"walk_right\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"walk_down\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"walk_up\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"run_left\", 0.05f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"run_right\", 0.05f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"run_down\", 0.05f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"run_up\", 0.05f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"blink_down\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"yawn_down\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"snooze_down\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"blink_left\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"yawn_left\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"snooze_left\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"blink_up\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"yawn_up\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"snooze_up\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"blink_right\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"yawn_right\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"snooze_right\", 0.5f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"default\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"interact_down\", 0.13f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"interact_up\", 0.13f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"interact_right\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"interact_left\", 0.1f, Animation.PlayMode.NORMAL);\n\n\t\tanimator.addAnimation(\"hoe_up\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"hoe_left\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"hoe_right\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"hoe_down\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"shovel_up\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"shovel_left\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"shovel_right\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"shovel_down\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"watering_can_up\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"watering_can_left\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"watering_can_right\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"watering_can_down\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"scythe_up\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"scythe_left\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"scythe_right\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"scythe_down\", 0.1f, Animation.PlayMode.NORMAL);\n\n\t\tanimator.addAnimation(\"sword_up\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"sword_left\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"sword_right\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"sword_down\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"gun_up\", 0.3f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"gun_left\", 0.3f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"gun_right\", 0.3f, Animation.PlayMode.NORMAL);\n\t\tanimator.addAnimation(\"gun_down\", 0.3f, Animation.PlayMode.NORMAL);\n\n\t\tanimator.addAnimation(\"fishing_left\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"fishing_right\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"fishing_up\", 0.1f, Animation.PlayMode.LOOP);\n\t\tanimator.addAnimation(\"fishing_down\", 0.1f, Animation.PlayMode.LOOP);\n\n\t\tanimator.addAnimation(\"bye_bye\", 0.1f, Animation.PlayMode.NORMAL);\n\t}\n\n\tpublic static Entity createFishingRodAnimatorEntity() {\n\t\tAnimationRenderComponent playerFishingRodAnimator = new AnimationRenderComponent(\n\t\t\t\tServiceLocator.getResourceService().getAsset(\"images/player_fishing.atlas\", TextureAtlas.class),\n\t\t\t\t16f\n\t\t);\n\n\t\tplayerFishingRodAnimator.addAnimation(\"cast_left\", 0.1f, Animation.PlayMode.LOOP);\n\t\tplayerFishingRodAnimator.addAnimation(\"cast_right\", 0.1f, Animation.PlayMode.LOOP);\n\t\tplayerFishingRodAnimator.addAnimation(\"cast_up\", 0.1f, Animation.PlayMode.LOOP);\n\t\tplayerFishingRodAnimator.addAnimation(\"cast_down\", 0.1f, Animation.PlayMode.LOOP);\n\t\tplayerFishingRodAnimator.addAnimation(\"fishing_left\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tplayerFishingRodAnimator.addAnimation(\"fishing_right\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tplayerFishingRodAnimator.addAnimation(\"fishing_up\", 0.1f, Animation.PlayMode.NORMAL);\n\t\tplayerFishingRodAnimator.addAnimation(\"fishing_down\", 0.1f, Animation.PlayMode.NORMAL);\n\n\t\treturn new Entity(EntityType.DUMMY)\n\t\t\t\t.addComponent(playerFishingRodAnimator);\n\t}\n\n\tprivate PlayerFactory() {\n\t\tthrow new IllegalStateException(\"Instantiating static util class\");\n\t}\n\n}\n\nsource/core/src/main/com/csse3200/game/areas/terrain/GameMap.java\npublic class GameMap {\n\t/**\n\t * The terrainFactory used for creating the game map\n\t */\n\tprivate final TerrainFactory terrainFactory;\n\t/**\n\t * The TiledMap that stores the created map and its TerrainTile instances\n\t */\n\tprivate final TiledMap tiledMap;\n\t/**\n\t * The TerrainComponent used to render the terrain of the map\n\t */\n\tprivate TerrainComponent terrainComponent;\n\t/**\n\t * The logger used to log information for debugging and info\n\t */\n\tprivate static final Logger logger = LoggerFactory.getLogger(GameMap.class);\n\n\t/**\n\t * Creates a new GameMap instance, setting the terrainFactory and instantiating a new TiledMap instance.\n\t *\n\t * @param terrainFactory the terrainFactory passed to the SpaceGameArea from the MainGameScreen class.\n\t */\n\tpublic GameMap(TerrainFactory terrainFactory) {\n\t\tthis.terrainFactory = terrainFactory;\n\t\tthis.tiledMap = new TiledMap();\n\t}\n\n\t/**\n\t * Creates the TerrainComponent instance used to render the SpaceGameArea map and stores it in the GameMap class.\n\t * Additionally, updates the TiledMap instance so that getter and setter methods for accessing TerrainTile instances\n\t * can function correctly.\n\t */\n\tpublic void createTerrainComponent() {\n\t\tterrainComponent = terrainFactory.createSpaceGameTerrain(tiledMap);\n\t}\n\n\t/**\n\t * Creates the TerrainComponent instance used to render a test game map. Additionally, updates the TiledMap instance\n\t * so that the getter and setter methods for accessing TerrainTile instances can function correctly. This method is\n\t * intended to allow for play testing of different game maps. Trying to generate a TerrainComponent through JUnit\n\t * tests can be difficult, so an alternate loadTestTerrain() method has been provided to only set the TiledMap\n\t * instance needed for interacting with terrain.\n\t *\n\t * @param testMapFilePath the file path of the test map file to load.\n\t */\n\tpublic void createTestTerrainComponent(String testMapFilePath) {\n\t\tterrainComponent = terrainFactory.createTestTerrain(tiledMap, testMapFilePath);\n\t}\n\n\t/**\n\t * Instantiates the GameMap with a test file map to be used in JUnit testing. This updates the TiledMap instance so\n\t * that the getter and setter methods for accessing TerrainTile instances can function correctly in JUnit tests that\n\t * require them. This method does not create a TerrainComponent, which means it cannot be used to render an actual\n\t * game map.\n\t *\n\t * @param testMapFilePath the file path of the test map file to load.\n\t */\n\tpublic void loadTestTerrain(String testMapFilePath) {\n\t\tterrainFactory.loadTiledMap(tiledMap, testMapFilePath);\n\t}\n\n\t/**\n\t * Returns the TerrainFactory instance stored in the GameMap class.\n\t *\n\t * @return the terrainFactory variable.\n\t */\n\tpublic TerrainFactory getTerrainFactory() {\n\t\treturn terrainFactory;\n\t}\n\n\t/**\n\t * Returns the TiledMap instance stored in the GameMap class.\n\t *\n\t * @return the tiledMap variable.\n\t */\n\tpublic TiledMap getTiledMap() {\n\t\treturn tiledMap;\n\t}\n\n\t/**\n\t * Returns the TerrainComponent instance stored in the GameMap class.\n\t *\n\t * @return the terrainComponent variable.\n\t */\n\tpublic TerrainComponent getTerrainComponent() {\n\t\tif (this.terrainComponent != null) {\n\t\t\treturn this.terrainComponent;\n\t\t} else {\n\t\t\tlogger.info(\"getTerrainComponent called before terrainComponent was set\");\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Sets the TerrainComponent.\n\t *\n\t * @param terrainComponent the terrainComponent to be set.\n\t */\n\tpublic void setTerrainComponent(TerrainComponent terrainComponent) {\n\t\tthis.terrainComponent = terrainComponent;\n\t}\n\n\t/**\n\t * Returns a GridPoint2 instance that contains the size of the map.\n\t *\n\t * @return a copy of the GridPoint2 instance which contains the dimensions of the map.\n\t */\n\tpublic GridPoint2 getMapSize() {\n\t\treturn terrainFactory.getMapSize().cpy();\n\t}\n\n\t/**\n\t * Gets the TerrainTile at the specified GridPoint2 position. The x and y values in the GridPoint2 class directly\n\t * correspond to the tile's position in the map layer. (0, 0) is the bottom left of the map.\n\t *\n\t * @param gridPoint The GridPoint2 instance representing the target TerrainTile's position.\n\t * @return TerrainTile instance at the specified position IF the gridpoint is within the bounds of the map, null\n\t * otherwise\n\t */\n\tpublic TerrainTile getTile(GridPoint2 gridPoint) {\n\t\tTiledMapTileLayer.Cell cell = getCell(gridPoint.x, gridPoint.y);\n\n\t\tif (cell != null) {\n\t\t\treturn (TerrainTile) cell.getTile();\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Gets the TerrainTile at the specified Vector2 position. The x and y float values in the Vector2 class are\n\t * transformed so that they correspond to the integer positions of the TerrainTile in the map layer. (0, 0) is the\n\t * bottom left of the map.\n\t *

\n\t * If using the Vector2 position variable from the Entity class, it is important to remember that the vector points\n\t * to the bottom left of the entity , not the centre of the entity (This is important to know if the entity uses\n\t * animations since the entity size may be larger than the actual sprite). The Entity class provides the\n\t * getPosition() and getCentredPosition() methods to help retrieve an appropriate Vector2 instance to use.\n\t *\n\t * @param vector The Vector2 instance representing the target TerrainTile's position.\n\t * @return TerrainTile instance at the specified position IF the vector is within the bounds of the map, null\n\t * otherwise\n\t */\n\tpublic TerrainTile getTile(Vector2 vector) {\n\t\treturn getTile(vectorToTileCoordinates(vector));\n\t}\n\n\t/**\n\t * Converts a GridPoint2 instance into a Vector2 instance representing the same TerrainTile position on the map\n\t * layer. The integer values in the GridPoint2 class which directly correspond to the TerrainTile coordinates\n\t * are transformed for the new Vector2 instance.\n\t *\n\t * @param gridPoint2 The GridPoint2 instance being used to create a corresponding Vector2 instance.\n\t * @return the new Vector2 instance.\n\t */\n\tpublic Vector2 tileCoordinatesToVector(GridPoint2 gridPoint2) {\n\t\tfloat tileSize = this.terrainComponent.getTileSize();\n\t\tfloat x = (gridPoint2.x * tileSize);\n\t\tfloat y = (gridPoint2.y * tileSize);\n\t\treturn new Vector2(x, y);\n\t}\n\n\t/**\n\t * Converts a Vector2 instance into a GridPoint2 instance representing the same TerrainTile position on the map\n\t * layer. The float values in the Vector2 instance are transformed to integer x and y values for the GridPoint2\n\t * instance.\n\t *\n\t * @param vector The Vector2 instance being used to create a corresponding GridPoint2 instance.\n\t * @return the new GridPoint2 instance.\n\t */\n\tpublic GridPoint2 vectorToTileCoordinates(Vector2 vector) {\n\t\tfloat tileSize = this.terrainComponent.getTileSize();\n\t\tint x = (int) Math.floor(vector.x / tileSize);\n\t\tint y = (int) Math.floor(vector.y / tileSize);\n\t\treturn new GridPoint2(x, y);\n\t}\n\n\t/**\n\t * Returns the Cell object in the TiledMap corresponding to the provided coordinates. Used as a helper function to\n\t * reduce the complexity of other methods involved with coordinates and vectors.\n\t *\n\t * @param x x coordinate (0 -> MAP_SIZE.x -1)\n\t * @param y y coordinate (0 -> MAP_SIZE.y -1)\n\t * @return the Cell at the specified position IF the coordinates are within the bounds of the map, null otherwise\n\t * (an error message will be logged when coordinates outside the map are passed to the function).\n\t */\n\tprivate TiledMapTileLayer.Cell getCell(int x, int y) {\n\t\tGridPoint2 mapBounds = this.getMapSize();\n\t\tint xMin = 0;\n\t\tint xMax = mapBounds.x;\n\t\tint yMin = 0;\n\t\tint yMax = mapBounds.y;\n\n\t\tif (x < xMin || x >= xMax || y < yMin || y >= yMax) {\n\t\t\tString log = String.format(\"The provided coordinates (%d , %d) do not fall within the map bounds of x: %d - %d and y: %d - %d\", x, y, xMin, xMax, yMin, yMax);\n\t\t\tlogger.info(log);\n\t\t\treturn null;\n\t\t}\n\t\treturn ((TiledMapTileLayer) this.tiledMap.getLayers().get(0)).getCell(x, y);\n\t}\n\n\t/**\n\t * Retrieves a list of grid coordinates representing traversable tiles on the map.\n\t *\n\t * @return An ArrayList of GridPoint2 objects containing the coordinates of traversable tiles.\n\t */\n\tpublic List getTraversableTileCoordinates() {\n\t\treturn traversableTileCoordinatesHelper(true);\n\t}\n\n\t/**\n\t * Retrieves a list of grid coordinates representing non-traversable tiles on the map.\n\t *\n\t * @return An ArrayList of GridPoint2 objects containing the coordinates of non-traversable tiles.\n\t */\n\tpublic List getNonTraversableTileCoordinates() {\n\t\treturn traversableTileCoordinatesHelper(false);\n\t}\n\n\t/**\n\t * Helper function to retrieve a list of grid coordinates based on traversability.\n\t *\n\t * @param isTraversable A Boolean flag indicating whether to retrieve traversable (true) or non-traversable (false)\n\t * tiles.\n\t * @return An ArrayList of GridPoint2 objects containing the coordinates of tiles based on the specified\n\t * traversability.\n\t */\n\tprivate List traversableTileCoordinatesHelper(boolean isTraversable) {\n\t\tGridPoint2 mapBounds = this.getMapSize();\n\t\tint xMax = mapBounds.x;\n\t\tint yMax = mapBounds.y;\n\n\t\tArrayList tileCoordinatesList = new ArrayList<>();\n\n\t\tfor (int x = 0; x < xMax; x++) {\n\t\t\tfor (int y = 0; y < yMax; y++) {\n\t\t\t\tGridPoint2 tileGridPoint = new GridPoint2(x, y);\n\t\t\t\tif (getTile(tileGridPoint).isTraversable() == isTraversable) {\n\t\t\t\t\ttileCoordinatesList.add(tileGridPoint);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn tileCoordinatesList;\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/utils/math/Vector2Utils.java\npublic class Vector2Utils {\n\tpublic static final Vector2 LEFT = new Vector2(-1f, 0f);\n\tpublic static final Vector2 RIGHT = new Vector2(1f, 0f);\n\tpublic static final Vector2 UP = new Vector2(0f, 1f);\n\tpublic static final Vector2 DOWN = new Vector2(0f, -1f);\n\n\tpublic static final Vector2 ONE = new Vector2(1f, 1f);\n\tpublic static final Vector2 MAX = new Vector2(Float.MAX_VALUE, Float.MAX_VALUE);\n\tpublic static final Vector2 MIN = new Vector2(Float.MIN_VALUE, Float.MIN_VALUE);\n\n\t/**\n\t * Calculate the angle in degrees of a vector.\n\t *\n\t * @param vector The vector relative to the origin\n\t * @return Angle in degrees from -180 to 180\n\t */\n\tpublic static double angleTo(Vector2 vector) {\n\t\treturn Math.toDegrees(Math.atan2(vector.y, vector.x));\n\t}\n\n\t/**\n\t * Calculate the angle in degrees between two vectors\n\t *\n\t * @param from The vector from which angle is measured\n\t * @param to The vector to which angle is measured\n\t * @return Angle in degrees from -180 to 180\n\t */\n\tpublic static double angleFromTo(Vector2 from, Vector2 to) {\n\t\treturn Math.toDegrees(Math.atan2(to.y - from.y, to.x - from.x));\n\t}\n\n\tprivate Vector2Utils() {\n\t\tthrow new IllegalStateException(\"Instantiating static util class\");\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/entities/Entity.java\npublic class Entity implements Json.Serializable {\n\tprivate static final Logger logger = LoggerFactory.getLogger(Entity.class);\n\tprivate static int nextId = 0;\n\tprivate static final String EVT_NAME_POS = \"setPosition\";\n\tprivate static final String COMPONENTS_STRING = \"components\";\n\tprivate final int id;\n\tprivate EntityType type;\n\tprivate final IntMap components;\n\tprivate final EventHandler eventHandler;\n\tprivate boolean enabled = true;\n\tprivate boolean created = false;\n\tprivate Vector2 position = Vector2.Zero.cpy();\n\tprivate Vector2 scale = new Vector2(1, 1);\n\tprivate Array createdComponents;\n\n\tpublic Entity() {\n\t\tthis.type = EntityType.DUMMY;\n\t\tid = nextId;\n\t\tnextId++;\n\n\t\tcomponents = new IntMap<>(4);\n\t\teventHandler = new EventHandler();\n\t}\n\n\tpublic Entity(EntityType type) {\n\t\tthis.type = type;\n\t\tid = nextId;\n\t\tnextId++;\n\n\t\tcomponents = new IntMap<>(4);\n\t\teventHandler = new EventHandler();\n\t}\n\n\t/**\n\t * Enable or disable an entity. Disabled entities do not run update() or\n\t * earlyUpdate() on their\n\t * components, but can still be disposed.\n\t *\n\t * @param enabled true for enable, false for disable.\n\t */\n\tpublic void setEnabled(boolean enabled) {\n\t\tlogger.debug(\"Setting enabled={} on entity {}\", enabled, this);\n\t\tthis.enabled = enabled;\n\t}\n\n\t/**\n\t * Get the entity's game position.\n\t *\n\t * @return position\n\t */\n\tpublic Vector2 getPosition() {\n\t\treturn position.cpy(); // Cpy gives us pass-by-value to prevent bugs\n\t}\n\n\t/**\n\t * Set the entity's game position.\n\t *\n\t * @param position new position.\n\t */\n\tpublic void setPosition(Vector2 position) {\n\t\tthis.position = position.cpy();\n\t\tgetEvents().trigger(EVT_NAME_POS, position.cpy());\n\t}\n\n\tpublic void setCenterPosition(Vector2 position) {\n\t\tthis.position = position.cpy().mulAdd(getScale(), -0.5f);\n\t}\n\n\t/**\n\t * Set the entity's game position.\n\t *\n\t * @param x new x position\n\t * @param y new y position\n\t */\n\tpublic void setPosition(float x, float y) {\n\t\tthis.position.x = x;\n\t\tthis.position.y = y;\n\t\tgetEvents().trigger(EVT_NAME_POS, position.cpy());\n\t}\n\n\t/**\n\t * Set the entity's game position and optionally notifies listeners.\n\t *\n\t * @param position new position.\n\t * @param notify true to notify (default), false otherwise\n\t */\n\tpublic void setPosition(Vector2 position, boolean notify) {\n\t\tthis.position = position;\n\t\tif (notify) {\n\t\t\tgetEvents().trigger(EVT_NAME_POS, position);\n\t\t}\n\t}\n\n\t/**\n\t * Get the entity's scale. Used for rendering and physics bounding box\n\t * calculations.\n\t *\n\t * @return Scale in x and y directions. 1 = 1 metre.\n\t */\n\tpublic Vector2 getScale() {\n\t\treturn scale.cpy(); // Cpy gives us pass-by-value to prevent bugs\n\t}\n\n\t/**\n\t * Set the entity's scale.\n\t *\n\t * @param scale new scale in metres\n\t */\n\tpublic void setScale(Vector2 scale) {\n\t\tthis.scale = scale.cpy();\n\t}\n\n\t/**\n\t * Set the entity's scale.\n\t *\n\t * @param x width in metres\n\t * @param y height in metres\n\t */\n\tpublic void setScale(float x, float y) {\n\t\tthis.scale.x = x;\n\t\tthis.scale.y = y;\n\t}\n\n\t/**\n\t * Set the entity's width and scale the height to maintain aspect ratio.\n\t *\n\t * @param x width in metres\n\t */\n\tpublic void scaleWidth(float x) {\n\t\tthis.scale.y = this.scale.y / this.scale.x * x;\n\t\tthis.scale.x = x;\n\t}\n\n\t/**\n\t * Set the entity's height and scale the width to maintain aspect ratio.\n\t *\n\t * @param y height in metres\n\t */\n\tpublic void scaleHeight(float y) {\n\t\tthis.scale.x = this.scale.x / this.scale.y * y;\n\t\tthis.scale.y = y;\n\t}\n\n\t/**\n\t * Get the entity's center position\n\t *\n\t * @return center position\n\t */\n\tpublic Vector2 getCenterPosition() {\n\t\treturn getPosition().mulAdd(getScale(), 0.5f);\n\t}\n\n\t/**\n\t * Get a component of type T on the entity.\n\t *\n\t * @param type The component class, e.g. RenderComponent.class\n\t * @param The component type, e.g. RenderComponent\n\t * @return The entity component, or null if nonexistent.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic T getComponent(Class type) {\n\t\tComponentType componentType = ComponentType.getFrom(type);\n\t\treturn (T) components.get(componentType.getId());\n\t}\n\n\t/**\n\t * Add a component to the entity. Can only be called before the entity is\n\t * registered in the world.\n\t *\n\t * @param component The component to add. Only one component of a type can be\n\t * added to an entity.\n\t * @return Itself\n\t */\n\tpublic Entity addComponent(Component component) {\n\t\tif (created) {\n\t\t\tlogger.error(\n\t\t\t\t\t\"Adding {} to {} after creation is not supported and will be ignored\", component, this);\n\t\t\treturn this;\n\t\t}\n\t\tComponentType componentType = ComponentType.getFrom(component.getClass());\n\t\tif (components.containsKey(componentType.getId())) {\n\t\t\tlogger.error(\n\t\t\t\t\t\"Attempted to add multiple components of class {} to {}. Only one component of a class \"\n\t\t\t\t\t\t\t+ \"can be added to an entity, this will be ignored.\",\n\t\t\t\t\tcomponent,\n\t\t\t\t\tthis);\n\t\t\treturn this;\n\t\t}\n\t\tcomponents.put(componentType.getId(), component);\n\t\tcomponent.setEntity(this);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Dispose of the entity. This will dispose of all components on this entity.\n\t */\n\tpublic void dispose() {\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.dispose();\n\t\t}\n\t\tServiceLocator.getEntityService().unregister(this);\n\t}\n\n\t/**\n\t * Create the entity and start running. This is called when the entity is\n\t * registered in the world,\n\t * and should not be called manually.\n\t */\n\tpublic void create() {\n\t\tif (created) {\n\t\t\tlogger.error(\n\t\t\t\t\t\"{} was created twice. Entity should only be registered with the entity service once.\",\n\t\t\t\t\tthis);\n\t\t\treturn;\n\t\t}\n\t\tcreatedComponents = components.values().toArray();\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.create();\n\t\t}\n\t\tcreated = true;\n\t}\n\n\t/**\n\t * Perform an early update on all components. This is called by the entity\n\t * service and should not\n\t * be called manually.\n\t */\n\tpublic void earlyUpdate() {\n\t\tif (!enabled) {\n\t\t\treturn;\n\t\t}\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.triggerEarlyUpdate();\n\t\t}\n\t}\n\n\t/**\n\t * Perform an update on all components. This is called by the entity service and\n\t * should not be\n\t * called manually.\n\t */\n\tpublic void update() {\n\t\tif (!enabled) {\n\t\t\treturn;\n\t\t}\n\t\tgetEvents().update();\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.triggerUpdate();\n\t\t}\n\t}\n\n\tpublic void togglePauseAnimations(boolean pausePlayer) {\n\t\tif (!pausePlayer) {\n\t\t\tfor (Component component : createdComponents) {\n\t\t\t\tif (component instanceof KeyboardPlayerInputComponent ||\n\t\t\t\t\t\tcomponent instanceof PlayerAnimationController ||\n\t\t\t\t\t\tcomponent instanceof AnimalAnimationController ||\n\t\t\t\t\t\tcomponent instanceof GhostAnimationController ||\n\t\t\t\t\t\tcomponent instanceof TamableComponent ||\n\t\t\t\t\t\tcomponent instanceof ItemPickupComponent) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (Component component : createdComponents) {\n\t\t\tif (component instanceof PlayerAnimationController) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tfor (Component component : createdComponents) {\n\t\t\tif (component instanceof AnimationRenderComponent animationRenderComponent) {\n\t\t\t\tanimationRenderComponent.togglePauseAnimation();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * This entity's unique ID. Used for equality checks\n\t *\n\t * @return unique ID\n\t */\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Get the event handler attached to this entity. Can be used to trigger events\n\t * from an attached\n\t * component, or listen to events from a component.\n\t *\n\t * @return entity's event handler\n\t */\n\tpublic EventHandler getEvents() {\n\t\treturn eventHandler;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn (obj instanceof Entity entity) && entity.getId() == this.getId();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn super.hashCode();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Entity{id=%d} {type=%s}\", id, type == null ? \"none\" : type.toString());\n\t}\n\n\t/**\n\t * Writes to the json info about entities.\n\t * Writes the entities x,y coordinates\n\t * ALso loops through the entities associated components and writes information\n\t * to the json about\n\t * the component.\n\t * note each component should have a override write function\n\t *\n\t * @param json which is a valid Json that is written to\n\t */\n\tpublic void write(Json json) {\n\t\t// Should be gone but incase double check\n\t\tif (getType() == EntityType.ITEM || getType() == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tjson.writeValue(\"Entity\", getType());\n\t\tfloat posX = position.x;\n\t\tfloat posY = position.y;\n\t\tjson.writeValue(\"x\", posX);\n\t\tjson.writeValue(\"y\", posY);\n\t\tjson.writeObjectStart(COMPONENTS_STRING);\n\t\tif (createdComponents == null) {\n\t\t\tjson.writeObjectEnd();\n\t\t\treturn;\n\t\t}\n\t\tfor (Component c : createdComponents) {\n\t\t\tc.write(json);\n\t\t}\n\t\tjson.writeObjectEnd();\n\t}\n\n\t/**\n\t * Writes the item to the json file\n\t *\n\t * @param json which is a valid Json that is written to\n\t */\n\tpublic void writeItem(Json json) {\n\t\tjson.writeValue(\"name\", this.getComponent(ItemComponent.class).getItemName());\n\t\tif (createdComponents != null) {\n\t\t\tjson.writeObjectStart(COMPONENTS_STRING);\n\t\t\tfor (Component c : createdComponents) {\n\t\t\t\tc.write(json);\n\t\t\t}\n\t\t\tjson.writeObjectEnd();\n\t\t}\n\t}\n\n\t/**\n\t * Reads the item entity from the json file\n\t *\n\t * @param json which is a valid Json that is read from\n\t * @param jsonMap which is a valid JsonValue that is read from\n\t */\n\tpublic void readItem(Json json, JsonValue jsonMap) {\n\t\tif (createdComponents != null) {\n\t\t\tfor (Component c : createdComponents) {\n\t\t\t\tc.read(json, jsonMap);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reads the json file and creates the entities based on the information in the\n\t * json file\n\t *\n\t * @param json which is a valid Json that is read from\n\t * @param jsonMap which is a valid JsonValue that is read from\n\t */\n\tpublic void read(Json json, JsonValue jsonMap) {\n\t\t// This method creates an Entity but will not use that Entity for anything that\n\t\t// is being remade as\n\t\t// it makes the code duplication extremely high as it is a whole factory here\n\n\t\t// Saves the position\n\t\tposition = new Vector2(jsonMap.getFloat(\"x\"), jsonMap.getFloat(\"y\"));\n\n\t\t// Gets the type of Entity\n\t\tString value = jsonMap.getString(\"Entity\");\n\t\ttry {\n\t\t\ttype = EntityType.valueOf(value);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\ttype = null;\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (type) {\n\t\t\tcase TRACTOR:\n\t\t\t\treadTractor(jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase TILE:\n\t\t\t\treadTile(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase SHIP_PART_TILE:\n\t\t\t\treadShipPartTile(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase SHIP_DEBRIS:\n\t\t\t\treadShipDebris();\n\t\t\t\tbreak;\n\t\t\tcase SHIP:\n\t\t\t\treadShip(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase PLAYER:\n\t\t\t\treadPlayer(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (FactoryService.getNpcFactories().containsKey(type)) {\n\t\t\t\t\t// Makes a new NPC\n\t\t\t\t\tEntity npc = FactoryService.getNpcFactories().get(type).get();\n\t\t\t\t\tif (npc.getComponent(TamableComponent.class) != null) {\n\t\t\t\t\t\tnpc.getComponent(TamableComponent.class).read(json, jsonMap.get(COMPONENTS_STRING));\n\t\t\t\t\t}\n\t\t\t\t\tif (npc.getComponent(CombatStatsComponent.class) != null) {\n\t\t\t\t\t\tnpc.getComponent(CombatStatsComponent.class).read(json, jsonMap.get(COMPONENTS_STRING));\n\t\t\t\t\t}\n\t\t\t\t\tServiceLocator.getGameArea().spawnEntity(npc);\n\t\t\t\t\tnpc.setPosition(position);\n\t\t\t\t} else if (FactoryService.getPlaceableFactories().containsKey(type.toString())) {\n\t\t\t\t\t// Makes a new Placeable\n\t\t\t\t\tEntity placeable = FactoryService.getPlaceableFactories().get(type.toString()).get();\n\t\t\t\t\tplaceable.setPosition(position);\n\t\t\t\t\tif (placeable.getType() == EntityType.CHEST) {\n\t\t\t\t\t\tplaceable.getComponent(InventoryComponent.class).read(json, jsonMap.get(COMPONENTS_STRING));\n\t\t\t\t\t}\n\t\t\t\t\tServiceLocator.getGameArea().getMap().getTile(position).setOccupant(placeable);\n\t\t\t\t\tServiceLocator.getGameArea().spawnEntity(placeable);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate void readPlayer(Json json, JsonValue jsonMap) {\n\t\t// Does not make a new player, instead just updates the current one\n\t\tInventoryComponent inventoryComponent = new InventoryComponent();\n\t\tJsonValue playerComponents = jsonMap.get(COMPONENTS_STRING);\n\t\tinventoryComponent.read(json, playerComponents);\n\t\tthis.addComponent(inventoryComponent);\n\n\t\tCombatStatsComponent combatStats = new CombatStatsComponent(0, 0);\n\t\tcombatStats.read(json, playerComponents);\n\t\tthis.addComponent(combatStats);\n\n\t\tHungerComponent hungerComponent = new HungerComponent(0);\n\t\thungerComponent.read(json, playerComponents);\n\t\tthis.addComponent(hungerComponent);\n\t}\n\n\tprivate void readShip(Json json, JsonValue jsonMap) {\n\t\tEntity ship = ShipFactory.createShip();\n\n\t\tServiceLocator.getGameArea().spawnEntity(ship);\n\n\t\tShipAnimationController shipAnimationController = ship.getComponent(ShipAnimationController.class);\n\t\tshipAnimationController.read(json, jsonMap.get(COMPONENTS_STRING).get(ShipAnimationController.class.getSimpleName()));\n\n\t\tShipProgressComponent progressComponent = ship.getComponent(ShipProgressComponent.class);\n\t\tprogressComponent.read(json, jsonMap.get(COMPONENTS_STRING).get(ShipProgressComponent.class.getSimpleName()));\n\n\t\tShipTimeSkipComponent shipTimeSkipComponent = ship.getComponent(ShipTimeSkipComponent.class);\n\t\tJsonValue shipTimeSkipComponentJson = jsonMap.get(COMPONENTS_STRING).get(ShipTimeSkipComponent.class.getSimpleName());\n\t\tshipTimeSkipComponent.read(json, shipTimeSkipComponentJson);\n\n\t\tShipLightComponent shipLightComponent = ship.getComponent(ShipLightComponent.class);\n\t\tJsonValue shipLightComponentJson = jsonMap.get(COMPONENTS_STRING)\n\t\t\t\t.get(ShipLightComponent.class.getSimpleName());\n\t\tshipLightComponent.read(json, shipLightComponentJson);\n\n\t\tShipDisplay shipDisplay = ship.getComponent(ShipDisplay.class);\n\t\tJsonValue shipDisplayJson = jsonMap.get(COMPONENTS_STRING)\n\t\t\t\t.get(ShipDisplay.class.getSimpleName());\n\t\tshipDisplay.read(json, shipDisplayJson);\n\n\t\tship.setPosition(position);\n\t}\n\n\tprivate void readShipDebris() {\n\t\tEntity shipDebris = ShipDebrisFactory.createShipDebris();\n\t\tServiceLocator.getGameArea().spawnEntity(shipDebris);\n\t\tshipDebris.setPosition(position);\n\n\t\tTerrainTile debrisTerrainTile = ServiceLocator.getGameArea().getMap().getTile(position);\n\t\tdebrisTerrainTile.setOccupant(shipDebris);\n\t\tdebrisTerrainTile.setOccupied();\n\t}\n\n\tprivate void readShipPartTile(Json json, JsonValue jsonMap) {\n\t\tEntity partTile = ShipPartTileFactory.createShipPartTile(position);\n\t\tServiceLocator.getGameArea().spawnEntity(partTile);\n\t\tpartTile.setPosition(position);\n\n\t\tTerrainTile partTerrainTile = ServiceLocator.getGameArea().getMap().getTile(position);\n\t\tif (partTerrainTile.isOccupied() && partTerrainTile.getOccupant().getType() == EntityType.SHIP_DEBRIS) {\n\t\t\t// remove the ship debris that is occupying the terrain tile, since it will\n\t\t\t// be recreated by the ShipPartTileComponent\n\t\t\tEntity unneededShipDebris = partTerrainTile.getOccupant();\n\t\t\tunneededShipDebris.dispose();\n\t\t\tpartTerrainTile.removeOccupant();\n\n\t\t\tpartTile.getComponent(ShipPartTileComponent.class).read(json, jsonMap);\n\n\t\t\tpartTerrainTile.setOccupant(partTile);\n\t\t\tpartTerrainTile.setOccupied();\n\t\t}\n\t}\n\n\tprivate void readTile(Json json, JsonValue jsonMap) {\n\t\tEntity tile = TerrainCropTileFactory.createTerrainEntity(position);\n\t\ttile.getComponent(CropTileComponent.class).read(json, jsonMap);\n\t\tServiceLocator.getGameArea().spawnEntity(tile);\n\t\ttile.setPosition(position);\n\t\tTerrainTile terrainTile = ServiceLocator.getGameArea().getMap().getTile(tile.getPosition());\n\t\tterrainTile.setOccupant(tile);\n\t}\n\n\t/**\n\t * Gets the type of entity\n\t *\n\t * @return the type of entity from EntityType enum\n\t */\n\tpublic EntityType getType() {\n\t\treturn type;\n\t}\n\n\tpublic void readTractor(JsonValue jsonMap) {\n\t\t// Make a new tractor\n\t\tEntity tractor = TractorFactory.createTractor();\n\t\tJsonValue tractorActions = jsonMap.get(COMPONENTS_STRING).get(\"TractorActions\");\n\t\ttractor.getComponent(TractorActions.class).setMuted(tractorActions.getBoolean(\"isMuted\"));\n\t\tJsonValue lightJsonMap = jsonMap.get(COMPONENTS_STRING).get(\"ConeLightComponent\");\n\t\tif (lightJsonMap.getBoolean(\"isActive\")) {\n\t\t\ttractor.getComponent(ConeLightComponent.class).toggleLight();\n\t\t}\n\t\tServiceLocator.getGameArea().setTractor(tractor);\n\t\ttractor.setPosition(position);\n\t\tServiceLocator.getGameArea().spawnEntity(tractor);\n\t}\n}", "answers": ["\t\t\t\t.addComponent(new PhysicsComponent())"], "length": 3813, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "da0e48fa-3700-4fdd-96d9-368ace903ae9", "reasoning": "In the test setup, after creating a new Entity instance, the code will start chaining component additions to build the player entity. The first component needed for movement is the PhysicsComponent, which is imported. Therefore the next line continues the chain with .addComponent(new PhysicsComponent()).", "reasoning_model_answer": ".addComponent(new PhysicsComponent())", "assistant_with_reasoning": "\nIn the test setup, after creating a new Entity instance, the code will start chaining component additions to build the player entity. The first component needed for movement is the PhysicsComponent, which is imported. Therefore the next line continues the chain with .addComponent(new PhysicsComponent()).\n\n.addComponent(new PhysicsComponent())", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.772, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37588, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": ".addComponent(new PhysicsComponent())", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.bluewind.base.common.config.auth.constant.AuthConstant;\nimport com.bluewind.base.common.util.redis.RedisUtils;\nimport com.bluewind.base.common.util.spring.SpringContextUtil;\nimport com.bluewind.base.common.util.web.CookieUtils;\nimport com.bluewind.base.common.util.web.ServletUtils;\nimport com.bluewind.base.module.system.auth.entity.UserInfo;\nimport com.bluewind.base.module.system.auth.service.AuthService;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.shiro.SecurityUtils;\nimport org.apache.shiro.subject.Subject;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport javax.servlet.http.HttpServletRequest;\nimport java.util.Objects;", "context": "src/main/java/com/bluewind/base/common/config/auth/util/UserInfoUtil.java\npackage com.bluewind.base.common.config.auth.util;\n\n\n\n/**\n * @author liuxingyu01\n * @date 2022-08-27 13:42\n * @description 用户会话工具类\n **/\npublic class UserInfoUtil {\n private static final Logger logger = LoggerFactory.getLogger(UserInfoUtil.class);\n\n\n private static RedisUtils redisUtils;\n\n private static RedisUtils getRedisUtils() {\n if (redisUtils == null) {\n Object bean = SpringContextUtil.getBean(\"redisUtils\");\n if (bean == null) {\n logger.error(\"redisUtils bean is null!\");\n }\n redisUtils = (RedisUtils) bean;\n }\n return redisUtils;\n }\n\n\n private static AuthService authService;\n\n private static AuthService getAuthService() {\n if (authService == null) {\n AuthService bean = SpringContextUtil.getBean(AuthService.class);\n if (bean == null) {\n logger.error(\"FinanceConvertUtilsService bean is null\");\n }\n authService = bean;\n return authService;\n }\n return authService;\n }\n\n\n /**\n * 获取当前登录用户的token会话串\n *\n * @return String\n */\n public static String getToken() {\n HttpServletRequest httpServletRequest = ServletUtils.getRequest();\n if (Objects.isNull(httpServletRequest)) {\n return null;\n }\n String token = httpServletRequest.getHeader(AuthConstant.BLUEWIND_TOKEN_KEY);\n if (StringUtils.isBlank(token)) {\n token = CookieUtils.getCookie(httpServletRequest, AuthConstant.BLUEWIND_COOKIE_KEY);\n }\n return token;\n }\n\n\n /**\n * 获取指定HttpServletRequest的token会话串\n *\n * @return String\n */\n public static String getToken(HttpServletRequest httpServletRequest) {\n if (Objects.isNull(httpServletRequest)) {\n return null;\n }\n String token = httpServletRequest.getHeader(AuthConstant.BLUEWIND_TOKEN_KEY);\n if (StringUtils.isBlank(token)) {\n\nsrc/main/java/com/bluewind/base/common/util/spring/SpringContextUtil.java\n@Component\n@Deprecated\npublic class SpringContextUtil implements ApplicationContextAware {\n private static ApplicationContext applicationContext = null;\n\n private SpringContextUtil() {\n super();\n }\n\n @Override\n public void setApplicationContext(ApplicationContext arg0) throws BeansException {\n if (applicationContext == null) {\n applicationContext = arg0;\n }\n }\n\n public static ApplicationContext getApplicationContext() {\n return applicationContext;\n }\n\n\n public static void setAppCtx(ApplicationContext webAppCtx) {\n if (webAppCtx != null) {\n applicationContext = webAppCtx;\n }\n }\n\n /**\n * 通过class获取Bean\n *\n * @param clazz\n * @param \n * @return\n */\n public static T getBean(Class clazz) {\n return getApplicationContext().getBean(clazz);\n }\n\n\n public static T getBean(String name, Class clazz) throws ClassNotFoundException {\n return getApplicationContext().getBean(name, clazz);\n }\n\n /**\n * 通过beanName获取Bean\n *\n * @param beanName\n * @return\n */\n public static Object getBean(String beanName) {\n return getApplicationContext().getBean(beanName);\n }\n\n\n public static Object getBean(String beanName, String className) throws ClassNotFoundException {\n Class clz = Class.forName(className);\n return getApplicationContext().getBean(beanName, clz.getClass());\n }\n\n\n public static boolean containsBean(String name) {\n return getApplicationContext().containsBean(name);\n }\n\n\n public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {\n return getApplicationContext().isSingleton(name);\n }\n\n\n public static Class getType(String name) throws NoSuchBeanDefinitionException {\n return getApplicationContext().getType(name);\n }\n\n\n public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {\n return getApplicationContext().getAliases(name);\n }\n\n}\n\nsrc/main/java/com/bluewind/base/module/system/auth/entity/UserInfo.java\npublic class UserInfo implements Serializable {\n private static final long serialVersionUID = 6460626203515194126L;\n\n private Long userId;\n\n private Long deptId;\n\n private String username;\n\n private String password;\n\n private String nickname;\n\n private String mobile;\n\n private String email;\n\n private String avatar;\n\n private Integer avatarStatus;\n\n private Integer sex;\n\n private Integer status;\n\n private Long createdBy;\n\n private Long updatedBy;\n\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private String createdAt;\n\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private String updatedAt;\n\n private String remark;\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getNickname() {\n return nickname;\n }\n\n public void setNickname(String nickname) {\n this.nickname = nickname;\n }\n\n public String getMobile() {\n return mobile;\n }\n\n public void setMobile(String mobile) {\n this.mobile = mobile;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public Integer getAvatarStatus() {\n return avatarStatus;\n }\n\n public void setAvatarStatus(Integer avatarStatus) {\n this.avatarStatus = avatarStatus;\n }\n\n public Integer getSex() {\n return sex;\n }\n\n public void setSex(Integer sex) {\n this.sex = sex;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Long getCreatedBy() {\n return createdBy;\n }\n\n public void setCreatedBy(Long createdBy) {\n this.createdBy = createdBy;\n }\n\n public Long getUpdatedBy() {\n return updatedBy;\n }\n\n public void setUpdatedBy(Long updatedBy) {\n this.updatedBy = updatedBy;\n }\n\n public String getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(String createdAt) {\n this.createdAt = createdAt;\n }\n\n public String getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(String updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public String getRemark() {\n return remark;\n }\n\n public void setRemark(String remark) {\n this.remark = remark;\n }\n\n @Override\n public String toString() {\n return \"UserInfo{\" +\n \"userId=\" + userId +\n \", deptId=\" + deptId +\n \", username='\" + username + '\\'' +\n \", password='\" + password + '\\'' +\n \", nickname='\" + nickname + '\\'' +\n \", mobile='\" + mobile + '\\'' +\n \", email='\" + email + '\\'' +\n \", avatar='\" + avatar + '\\'' +\n \", avatarStatus=\" + avatarStatus +\n \", sex=\" + sex +\n \", status=\" + status +\n \", createdBy=\" + createdBy +\n \", updatedBy=\" + updatedBy +\n \", createdAt='\" + createdAt + '\\'' +\n \", updatedAt='\" + updatedAt + '\\'' +\n \", remark='\" + remark + '\\'' +\n '}';\n }\n}\n\nsrc/main/java/com/bluewind/base/common/util/redis/RedisUtils.java\n@Component\npublic class RedisUtils {\n final static Logger log = LoggerFactory.getLogger(RedisUtils.class);\n\n @Autowired\n private RedisTemplate redisTemplate;\n\n public RedisUtils(RedisTemplate redisTemplate) {\n this.redisTemplate = redisTemplate;\n }\n\n\n\n /*============================Common Start=============================*/\n /**\n * 指定缓存失效时间\n *\n * @param key 键\n * @param time 时间(秒)\n * @return\n */\n public boolean expire(final String key, final long time) {\n if (StringUtils.isEmpty(key)) {\n return false;\n }\n try {\n if (time > 0) {\n redisTemplate.expire(key, time, TimeUnit.SECONDS);\n }\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - expire - 设置缓存时间失败,Exception:{e}\", e);\n return false;\n }\n }\n\n\n /**\n * 指定缓存失效时间\n *\n * @param key 键\n * @param time 时间\n * @param unit 时间类型\n * @return\n */\n public boolean expire(final String key, final long time, final TimeUnit unit) {\n if (StringUtils.isEmpty(key)) {\n return false;\n }\n try {\n if (time > 0) {\n redisTemplate.expire(key, time, unit);\n }\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - expire - 设置缓存时间失败,Exception:{e}\", e);\n return false;\n }\n }\n\n\n /**\n * 根据key 获取过期时间\n *\n * @param key 键 不能为null\n * @return 时间(秒) 返回0代表为永久有效\n */\n public long getExpire(final String key) {\n try {\n return redisTemplate.getExpire(key, TimeUnit.SECONDS);\n } catch (Exception e) {\n log.error(\"RedisUtil - getExpire - 获取过期时间失败,Exception:{e}\", e);\n return 0;\n }\n }\n\n\n /**\n * 判断key是否存在\n *\n * @param key 键\n * @return true 存在 false不存在\n */\n public boolean hasKey(final String key) {\n try {\n return redisTemplate.hasKey(key);\n } catch (Exception e) {\n log.error(\"RedisUtil - hasKey - 判断key是否存在失败,Exception:{e}\", e);\n return false;\n }\n }\n\n\n /**\n * 修改 key 的名称\n *\n * @param oldKey 旧名字\n * @param newKey 新名字\n */\n public void rename(final String oldKey, final String newKey) {\n redisTemplate.rename(oldKey, newKey);\n }\n\n\n /**\n * 删除缓存\n *\n * @param key 可以传一个值 或多个\n */\n @SuppressWarnings(\"unchecked\")\n public void del(String... key) {\n if (key != null && key.length > 0) {\n if (key.length == 1) {\n redisTemplate.delete(key[0]);\n } else {\n redisTemplate.delete(CollectionUtils.arrayToList(key));\n }\n }\n }\n\n\n /**\n * 模糊查询获取key值\n *\n * @param pattern 传入\"\"查询所有key, 传入\"shiro:test:\" 查询所有这个开头的key\n * @return\n */\n public Set keys(final String pattern) {\n return redisTemplate.keys(pattern.concat(\"*\"));\n }\n /*============================Common End=============================*/\n\n\n /*============================String Start=============================*/\n /**\n * 普通缓存获取\n *\n * @param key 键\n * @return 值\n */\n public Object get(final String key) {\n return key == null ? null : redisTemplate.opsForValue().get(key);\n }\n\n\n /**\n * 普通缓存获取(直接转字符串)\n *\n * @param key 键\n * @return 值,返回String\n */\n public String getStr(String key) {\n if (key == null) {\n return null;\n }\n Object obj = redisTemplate.opsForValue().get(key);\n return obj == null ? null : obj.toString();\n }\n\n\n /**\n * 批量获取缓存\n * @param keys Collection\n * @return List\n */\n public List multiGet(Collection keys) {\n if (CollectionUtils.isEmpty(keys)) {\n return null;\n } else {\n List result = redisTemplate.opsForValue().multiGet(keys);\n return result;\n }\n }\n\n\n /**\n * 普通缓存放入(永不失效)\n *\n * @param key 键\n * @param value 值\n * @return true成功 false失败\n */\n public boolean set(final String key, final Object value) {\n try {\n redisTemplate.opsForValue().set(key, value);\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - set - 存入redis失败,Exception:{e}\", e);\n return false;\n }\n }\n\n\n /**\n * 普通缓存放入并设置失效时间\n *\n * @param key 键\n * @param value 值\n * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期\n * @return true成功 false 失败\n */\n public boolean set(String key, Object value, long time) {\n try {\n if (time > 0) {\n redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);\n } else {\n set(key, value);\n }\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - set - 存入redis失败,Exception:{e}\", e);\n return false;\n }\n }\n\n\n /**\n * 普通缓存放入并设置时间\n *\n * @param key 键\n * @param value 值\n * @param time 时间 time要大于0 如果time小于等于0 将为无限期\n * @param timeUnit 时间单位TimeUnit\n * TimeUnit.DAYS 天\n * TimeUnit.HOURS 小时\n * TimeUnit.MINUTES 分钟\n * TimeUnit.SECONDS 秒\n * TimeUnit.MILLISECONDS 毫秒\n * @return true成功 false 失败\n */\n public boolean set(String key, Object value, long time, TimeUnit timeUnit) {\n try {\n if (time > 0) {\n redisTemplate.opsForValue().set(key, value, time, timeUnit);\n } else {\n set(key, value);\n }\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - set - 存入redis失败,Exception:{e}\", e);\n return false;\n }\n }\n\n /**\n * 批量写入数据\n * @param map\n * @return true成功 false 失败\n */\n public boolean multiSet(Map map) {\n if (CollectionUtils.isEmpty(map)) {\n return false;\n }\n try {\n redisTemplate.opsForValue().multiSet(map);\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - multiSet - 批量存入redis失败,Exception:{e}\", e);\n }\n return false;\n }\n\n\n /**\n * 根据key更新数据\n * @param key\n * @param value\n * @return true成功 false 失败\n */\n public boolean update(final String key, Object value) {\n if (StringUtils.isEmpty(key)) {\n return false;\n }\n try {\n redisTemplate.opsForValue().getAndSet(key, value);\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - update - 更新redis失败,Exception:{e}\", e);\n }\n return false;\n }\n\n\n /**\n * 递增(将key所储存的值加上增量 increment;如果key不存在,那么key的值会先被初始化为0)\n *\n * @param key 键\n * @param delta 要增加几(大于0)\n * @return\n */\n public long incr(String key, long delta) {\n if (delta < 0) {\n throw new RuntimeException(\"递增因子必须大于0\");\n }\n return redisTemplate.opsForValue().increment(key, delta);\n }\n\n\n /**\n * 递减\n *\n * @param key 键\n * @param delta 要减少几(小于0)\n * @return\n */\n public long decr(String key, long delta) {\n if (delta < 0) {\n throw new RuntimeException(\"递减因子必须大于0\");\n }\n return redisTemplate.opsForValue().increment(key, -delta);\n }\n /*============================String end=============================*/\n\n\n /*================================Map==============================*/\n\n /**\n * HashGet\n *\n * @param key 键 不能为null\n * @param item 项 不能为null\n * @return 值\n */\n public Object hget(String key, String item) {\n return redisTemplate.opsForHash().get(key, item);\n }\n\n /**\n * 获取hashKey对应的所有键值\n *\n * @param key 键\n * @return 对应的多个键值\n */\n public Map hmget(String key) {\n return redisTemplate.opsForHash().entries(key);\n }\n\n /**\n * HashSet\n *\n * @param key 键\n * @param map 对应多个键值\n * @return true 成功 false 失败\n */\n public boolean hmset(String key, Map map) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * HashSet 并设置时间\n *\n * @param key 键\n * @param map 对应多个键值\n * @param time 时间(秒)\n * @return true成功 false失败\n */\n public boolean hmset(String key, Map map, long time) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param item 项\n * @param value 值\n * @return true 成功 false失败\n */\n public boolean hset(String key, String item, Object value) {\n try {\n redisTemplate.opsForHash().put(key, item, value);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param item 项\n * @param value 值\n * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间\n * @return true 成功 false失败\n */\n public boolean hset(String key, String item, Object value, long time) {\n try {\n redisTemplate.opsForHash().put(key, item, value);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 删除hash表中的值\n *\n * @param key 键 不能为null\n * @param item 项 可以使多个 不能为null\n */\n public void hdel(String key, Object... item) {\n redisTemplate.opsForHash().delete(key, item);\n }\n\n /**\n * 判断hash表中是否有该项的值\n *\n * @param key 键 不能为null\n * @param item 项 不能为null\n * @return true 存在 false不存在\n */\n public boolean hHasKey(String key, String item) {\n return redisTemplate.opsForHash().hasKey(key, item);\n }\n\n /**\n * hash递增 如果不存在,就会创建一个 并把新增后的值返回\n *\n * @param key 键\n * @param item 项\n * @param by 要增加几(大于0)\n * @return\n */\n public double hincr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, by);\n }\n\n /**\n * hash递减\n *\n * @param key 键\n * @param item 项\n * @param by 要减少记(小于0)\n * @return\n */\n public double hdecr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, -by);\n }\n /*================================Map end====================*/\n\n\n /*============================set=============================*/\n /**\n * 根据key获取Set中的所有值\n *\n * @param key 键\n * @return\n */\n public Set sGet(String key) {\n try {\n return redisTemplate.opsForSet().members(key);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * 根据value从一个set中查询,是否存在\n *\n * @param key 键\n * @param value 值\n * @return true 存在 false不存在\n */\n public boolean sHasKey(String key, Object value) {\n try {\n return redisTemplate.opsForSet().isMember(key, value);\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 将数据放入set缓存\n *\n * @param key 键\n * @param values 值 可以是多个\n * @return 成功个数\n */\n public long sSet(String key, Object... values) {\n try {\n return redisTemplate.opsForSet().add(key, values);\n } catch (Exception e) {\n e.printStackTrace();\n return 0;\n }\n }\n\n /**\n * 将set数据放入缓存\n *\n * @param key 键\n * @param time 时间(秒)\n * @param values 值 可以是多个\n * @return 成功个数\n */\n public long sSetAndTime(String key, long time, Object... values) {\n try {\n Long count = redisTemplate.opsForSet().add(key, values);\n if (time > 0) {\n expire(key, time);\n }\n return count;\n } catch (Exception e) {\n e.printStackTrace();\n return 0;\n }\n }\n\n /**\n * 获取set缓存的长度\n *\n * @param key 键\n * @return\n */\n public long sGetSetSize(String key) {\n try {\n return redisTemplate.opsForSet().size(key);\n } catch (Exception e) {\n e.printStackTrace();\n return 0;\n }\n }\n\n /**\n * 移除值为value的\n *\n * @param key 键\n * @param values 值 可以是多个\n * @return 移除的个数\n */\n public long setRemove(String key, Object... values) {\n try {\n Long count = redisTemplate.opsForSet().remove(key, values);\n return count;\n } catch (Exception e) {\n e.printStackTrace();\n return 0;\n }\n }\n /*============================set end=============================*/\n\n\n /*===============================list=============================*/\n /**\n * 获取list缓存的内容\n *\n * @param key 键\n * @param start 开始\n * @param end 结束 0 到 -1代表所有值\n * @return\n */\n public List lGet(String key, long start, long end) {\n try {\n return redisTemplate.opsForList().range(key, start, end);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * 获取list缓存的长度\n *\n * @param key 键\n * @return\n */\n public long lGetListSize(String key) {\n try {\n return redisTemplate.opsForList().size(key);\n } catch (Exception e) {\n e.printStackTrace();\n return 0;\n }\n }\n\n /**\n * 通过索引 获取list中的值\n *\n * @param key 键\n * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推\n * @return\n */\n public Object lGetIndex(String key, long index) {\n try {\n return redisTemplate.opsForList().index(key, index);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n\n /**\n * 根据索引修改list中的某条数据\n *\n * @param key 键\n * @param index 索引\n * @param value 值\n * @return\n */\n public boolean lUpdateIndex(String key, long index, Object value) {\n try {\n redisTemplate.opsForList().set(key, index, value);\n return true;\n } catch (Exception e) {\n log.error(\"RedisUtil - lUpdateIndex - Exception:{e}\", e);\n return false;\n }\n }\n\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @return\n */\n public boolean lRightPush(String key, Object value) {\n try {\n redisTemplate.opsForList().rightPush(key, value);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @param time 时间(秒)\n * @return\n */\n public boolean lRightPush(String key, Object value, long time) {\n try {\n redisTemplate.opsForList().rightPush(key, value);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @return\n */\n public boolean lRightPushAll(String key, List value) {\n try {\n redisTemplate.opsForList().rightPushAll(key, value);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @param time 时间(秒)\n * @return\n */\n public boolean lRightPushAll(String key, List value, long time) {\n try {\n redisTemplate.opsForList().rightPushAll(key, value);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n\n /**\n * 将指定的值插入存储在键的列表的头部。\n * 如果键不存在,则在执行推送操作之前将其创建为空列表。(从左边插入)\n * @param key 键\n * @param value 值\n * @return Long 返回的结果为推送操作后的列表的长度\n */\n public Long lLeftPush(String key, Object value) {\n try {\n return redisTemplate.opsForList().leftPush(key, value);\n } catch (Exception e) {\n log.error(\"RedisUtil - lLeftPush - Exception:{e}\", e);\n return 0L;\n }\n }\n\n /**\n * 将指定的值插入存储在键的列表的头部。\n * 如果键不存在,则在执行推送操作之前将其创建为空列表。(从左边插入)\n * @param key 键\n * @param value 值\n * @param time 过期时间(秒)\n * @return Long 返回的结果为推送操作后的列表的长度\n */\n public Long lLeftPush(String key, Object value, long time) {\n try {\n Long num = redisTemplate.opsForList().leftPush(key, value);\n if (time > 0) {\n expire(key, time);\n }\n return num;\n } catch (Exception e) {\n log.error(\"RedisUtil - lLeftPush - Exception:{e}\", e);\n return 0L;\n }\n }\n\n\n /**\n * 将所有指定的值插入存储在键的列表的头部。\n * 如果键不存在,则在执行推送操作之前将其创建为空列表。(从左边插入)\n * @param key 键\n * @param value 值\n * @return Long 返回的结果为推送操作后的列表的长度\n */\n public Long lLeftPushAll(String key, List value) {\n try {\n return redisTemplate.opsForList().leftPushAll(key, value);\n } catch (Exception e) {\n log.error(\"RedisUtil - lLeftPushAll - Exception:{e}\", e);\n return 0L;\n }\n }\n\n /**\n * 将所有指定的值插入存储在键的列表的头部。\n * 如果键不存在,则在执行推送操作之前将其创建为空列表。(从左边插入)\n * @param key 键\n * @param value 值\n * @param time 过期时间(秒)\n * @return Long 返回的结果为推送操作后的列表的长度\n */\n public Long lLeftPushAll(String key, List value, long time) {\n try {\n Long num = redisTemplate.opsForList().leftPushAll(key, value);\n if (time > 0) {\n expire(key, time);\n }\n return num;\n } catch (Exception e) {\n log.error(\"RedisUtil - lLeftPushAll - Exception:{e}\", e);\n return 0L;\n }\n }\n\n\n /**\n * 移除N个值为value\n *\n * @param key 键\n * @param count 移除多少个\n * @param value 值\n * @return 移除的个数\n */\n public long lRemove(String key, long count, Object value) {\n try {\n Long remove = redisTemplate.opsForList().remove(key, count, value);\n return remove;\n } catch (Exception e) {\n e.printStackTrace();\n return 0;\n }\n }\n\n /**\n * 弹出最左边的元素并返回,弹出之后该值在列表中将不复存在\n *\n * @param key 键\n * @return Object 弹出的元素\n */\n public Object lLeftPop(String key) {\n try {\n return redisTemplate.opsForList().leftPop(key);\n } catch (Exception e) {\n log.error(\"RedisUtils - lLeftPop - Exception:{e}\", e);\n return null;\n }\n }\n\n /**\n * 弹出最右边的元素并返回,弹出之后该值在列表中将不复存在\n *\n * @param key 键\n * @return Object 弹出的元素\n */\n public Object lRightPop(String key) {\n try {\n return redisTemplate.opsForList().rightPop(key);\n } catch (Exception e) {\n log.error(\"RedisUtils - lRightPop - Exception:{e}\", e);\n return null;\n }\n }\n\n /*===============================list end=============================*/\n\n\n /**\n * 使用Redis的消息队列\n *\n * @param channel\n * @param message 消息内容\n */\n public void convertAndSend(String channel, Object message) {\n redisTemplate.convertAndSend(channel, message);\n }\n\n\n //=========BoundListOperations 用法 start============\n\n /**\n * 将数据添加到Redis的list中(从右边添加)\n *\n * @param listKey\n * @param time 过期时间\n * @param timeUnit 时间单位\n * @param values 待添加的数据\n */\n public void addToListRight(String listKey, Long time, TimeUnit timeUnit, Object... values) {\n //绑定操作\n BoundListOperations boundValueOperations = redisTemplate.boundListOps(listKey);\n //插入数据\n boundValueOperations.rightPushAll(values);\n //设置过期时间\n boundValueOperations.expire(time, timeUnit);\n }\n\n /**\n * 根据起始结束序号遍历Redis中的list\n *\n * @param listKey\n * @param start 起始序号\n * @param end 结束序号\n * @return\n */\n public List rangeList(String listKey, long start, long end) {\n //绑定操作\n BoundListOperations boundValueOperations = redisTemplate.boundListOps(listKey);\n //查询数据\n return boundValueOperations.range(start, end);\n }\n\n /**\n * 弹出右边的值 --- 并且移除这个值\n *\n * @param listKey\n */\n public Object rifhtPop(String listKey) {\n //绑定操作\n BoundListOperations boundValueOperations = redisTemplate.boundListOps(listKey);\n return boundValueOperations.rightPop();\n }\n\n //=========BoundListOperations 用法 End============\n\n\n}\n\nsrc/main/java/com/bluewind/base/common/config/auth/constant/AuthConstant.java\npublic class AuthConstant {\n\n // 登录用户token-key\n public static final String BLUEWIND_TOKEN_KEY = \"token\";\n\n\n // 用户会话redis的key\n public final static String BLUEWIND_TOKEN_CACHE = \"bluewind:token:cache\";\n\n // 用户会话key\n public final static String BLUEWIND_COOKIE_KEY = \"bluewind-session-key\";\n\n // 密码的盐\n public final static String SALT = \"ymp8R3Vg7Kv5$y5fM3*xl&ins7SZcTEY\";\n\n // session编码\n public final static String BLUEWIND_SSO_SHIRO_SESSION_ID = \"bluewind-sso-shiro-session-id\";\n\n // 用户会话key(LAMBO_SSO_COOKIE_KEY)的redis的key\n public final static String BLUEWIND_SSO_CODE = \"bluewind-sso-code\";\n\n // session编码集合\n public final static String BLUEWIND_SSO_SESSION_IDS = \"bluewind-sso-session-ids\";\n\n // 登陆会话数\n public final static String BLUEWIND_USER_SESSION_NUMS = \"bluewind:user-session-nums\";\n\n // 尝试登陆次数\n public final static String BLUEWIND_LOGIN_ATTEMPT_TIMES = \"bluewind:login-attempt-times\";\n\n // 缓存用户会话信息\n public final static String BLUEWIND_USERINFO_CACHE = \"bluewind:userinfo:cache\";\n\n // 缓存权限信息\n public final static String BLUEWIND_PERMISSIONS_CACHE = \"bluewind:permissions:cache\";\n\n // 缓存角色信息\n public final static String BLUEWIND_ROLES_CACHE = \"bluewind:roles:cache\";\n\n}\n\nsrc/main/java/com/bluewind/base/common/util/web/ServletUtils.java\npublic class ServletUtils {\n public static final String DEFAULT_PARAMS_PARAM = \"params\"; // 登录扩展参数(JSON字符串)优先级高于扩展参数前缀\n public static final String DEFAULT_PARAM_PREFIX_PARAM = \"param_\"; // 扩展参数前缀\n\n // 定义静态文件后缀;静态文件排除URI地址\n private static String[] staticFiles;\n private static String[] staticFileExcludeUri;\n\n /**\n * 获取当前请求对象\n *\n */\n public static HttpServletRequest getRequest() {\n HttpServletRequest request = null;\n try {\n request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();\n return request;\n } catch (Exception e) {\n return null;\n }\n }\n\n /**\n * 获取当前响应对象\n *\n */\n public static HttpServletResponse getResponse() {\n HttpServletResponse response = null;\n try {\n response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();\n return response;\n } catch (Exception e) {\n return null;\n }\n }\n\n\n /**\n * 获取session\n *\n */\n public static HttpSession getSession() {\n return getRequest().getSession();\n }\n\n\n /**\n * 是否是Ajax异步请求\n *\n * @param request\n */\n public static boolean isAjaxRequest(HttpServletRequest request) {\n String accept = request.getHeader(\"accept\");\n if (accept != null && accept.indexOf(\"application/json\") != -1) {\n return true;\n }\n\n String xRequestedWith = request.getHeader(\"X-Requested-With\");\n if (xRequestedWith != null && xRequestedWith.indexOf(\"XMLHttpRequest\") != -1) {\n return true;\n }\n\n String uri = request.getRequestURI();\n if (inStringIgnoreCase(uri, \".json\", \".xml\")) {\n return true;\n }\n\n String ajax = request.getParameter(\"__ajax\");\n if (inStringIgnoreCase(ajax, \"json\", \"xml\")) {\n return true;\n }\n\n return false;\n }\n\n\n /**\n * 返回结果JSON字符串(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @return JSON字符串:{result:'true',message:''}\n */\n public static String renderResult(String result, String message) {\n return renderResult(result, message, null);\n }\n\n\n /**\n * 返回结果JSON字符串(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @param data 消息数据\n * @return JSON字符串:{result:'true',message:'', if map then key:value,key2:value2... else data:{} }\n */\n @SuppressWarnings(\"unchecked\")\n public static String renderResult(String result, String message, Object data) {\n Map resultMap = new HashMap<>();\n resultMap.put(\"result\", result);\n resultMap.put(\"message\", message);\n if (data != null) {\n if (data instanceof Map) {\n resultMap.putAll((Map) data);\n } else {\n resultMap.put(\"data\", data);\n }\n }\n HttpServletRequest request = ServletUtils.getRequest();\n String uri = request.getRequestURI();\n String functionName = request.getParameter(\"__callback\");\n ObjectMapper objectMapper = new ObjectMapper();\n String returnStr = \"\";\n try {\n if (StringUtils.isNotBlank(functionName)) {\n returnStr = objectMapper.writeValueAsString(new JSONPObject(functionName, resultMap));\n } else {\n returnStr = objectMapper.writeValueAsString(resultMap);\n }\n } catch (IOException var3) {\n\n }\n\n return returnStr;\n }\n\n\n /**\n * 直接将结果JSON字符串渲染到客户端(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param response 渲染对象:{result:'true',message:'',data:{}}\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @return null\n */\n public static String renderResult(HttpServletResponse response, String result, String message) {\n return renderString(response, renderResult(result, message), null);\n }\n\n\n /**\n * 直接将结果JSON字符串渲染到客户端(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param response 渲染对象:{result:'true',message:'',data:{}}\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @param data 消息数据\n * @return null\n */\n public static String renderResult(HttpServletResponse response, String result, String message, Object data) {\n return renderString(response, renderResult(result, message, data), null);\n }\n\n /**\n * 将对象转换为JSON字符串渲染到客户端(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param response 渲染对象\n * @param object 待转换JSON并渲染的对象\n * @return null\n */\n public static String renderObject(HttpServletResponse response, Object object) {\n HttpServletRequest request = ServletUtils.getRequest();\n String uri = request.getRequestURI();\n String functionName = request.getParameter(\"__callback\");\n\n ObjectMapper objectMapper = new ObjectMapper();\n String returnStr = \"\";\n\n try {\n if (StringUtils.isNotBlank(functionName)) {\n returnStr = objectMapper.writeValueAsString(new JSONPObject(functionName, object));\n } else {\n returnStr = objectMapper.writeValueAsString(object);\n }\n } catch (IOException var3) {\n\n }\n return returnStr;\n }\n\n\n /**\n * 将字符串渲染到客户端\n *\n * @param response 渲染对象\n * @param string 待渲染的字符串\n * @return null\n */\n public static String renderString(HttpServletResponse response, String string) {\n return renderString(response, string, null);\n }\n\n\n /**\n * 将字符串渲染到客户端\n *\n * @param response 渲染对象\n * @param string 待渲染的字符串\n * @return null\n */\n public static String renderString(HttpServletResponse response, String string, String type) {\n try {\n//\t\t\tresponse.reset(); // 先注释掉,否则以前设置的Header会被清理掉,如ajax登录设置记住我Cookie\n response.setContentType(type == null ? \"application/json\" : type);\n response.setCharacterEncoding(\"utf-8\");\n response.getWriter().print(string);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * 获得请求参数值\n */\n public static String getParameter(String name) {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return null;\n }\n return request.getParameter(name);\n }\n\n /**\n * 获得请求参数Map\n */\n public static Map getParameters() {\n return getParameters(getRequest());\n }\n\n /**\n * 获得请求参数Map\n */\n public static Map getParameters(ServletRequest request) {\n if (request == null) {\n return new HashMap();\n }\n return getParametersStartingWith(request, \"\");\n }\n\n /**\n * 取得带相同前缀的Request Parameters, copy from spring WebUtils.\n * 返回的结果的Parameter名已去除前缀.\n */\n @SuppressWarnings(\"rawtypes\")\n public static Map getParametersStartingWith(ServletRequest request, String prefix) {\n Validate.notNull(request, \"Request must not be null\");\n Enumeration paramNames = request.getParameterNames();\n Map params = new TreeMap();\n String pre = prefix;\n if (pre == null) {\n pre = \"\";\n }\n while (paramNames != null && paramNames.hasMoreElements()) {\n String paramName = (String) paramNames.nextElement();\n if (\"\".equals(pre) || paramName.startsWith(pre)) {\n String unprefixed = paramName.substring(pre.length());\n String[] values = request.getParameterValues(paramName);\n if (values == null || values.length == 0) {\n values = new String[]{};\n // Do nothing, no values found at all.\n } else if (values.length > 1) {\n params.put(unprefixed, values);\n } else {\n params.put(unprefixed, values[0]);\n }\n }\n }\n return params;\n }\n\n\n /**\n * 组合Parameters生成Query String的Parameter部分,并在paramter name上加上prefix.\n */\n public static String encodeParameterStringWithPrefix(Map params, String prefix) {\n StringBuilder queryStringBuilder = new StringBuilder();\n String pre = prefix;\n if (pre == null) {\n pre = \"\";\n }\n Iterator> it = params.entrySet().iterator();\n while (it.hasNext()) {\n Entry entry = it.next();\n queryStringBuilder.append(pre).append(entry.getKey()).append(\"=\").append(entry.getValue());\n if (it.hasNext()) {\n queryStringBuilder.append(\"&\");\n }\n }\n return queryStringBuilder.toString();\n }\n\n\n /**\n * 从请求对象中扩展参数数据,格式:JSON 或 param_ 开头的参数\n *\n * @param request 请求对象\n * @return 返回Map对象\n */\n public static Map getExtParams(ServletRequest request) {\n Map paramMap = null;\n String params = StringUtils.trim(request.getParameter(DEFAULT_PARAMS_PARAM));\n if (StringUtils.isNotBlank(params) && StringUtils.startsWith(params, \"{\")) {\n ObjectMapper mapper = new ObjectMapper();\n try {\n paramMap = mapper.readValue(params, Map.class);\n } catch (Exception e) {\n paramMap = new HashMap<>();\n }\n\n } else {\n paramMap = getParametersStartingWith(ServletUtils.getRequest(), DEFAULT_PARAM_PREFIX_PARAM);\n }\n return paramMap;\n }\n\n\n /**\n * 设置客户端缓存过期时间 的Header.\n */\n public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {\n // Http 1.0 header, set a fix expires date.\n response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000);\n // Http 1.1 header, set a time after now.\n response.setHeader(HttpHeaders.CACHE_CONTROL, \"private, max-age=\" + expiresSeconds);\n }\n\n\n /**\n * 设置禁止客户端缓存的Header.\n */\n public static void setNoCacheHeader(HttpServletResponse response) {\n // Http 1.0 header\n response.setDateHeader(HttpHeaders.EXPIRES, 1L);\n response.addHeader(HttpHeaders.PRAGMA, \"no-cache\");\n // Http 1.1 header\n response.setHeader(HttpHeaders.CACHE_CONTROL, \"no-cache, no-store, max-age=0\");\n }\n\n\n /**\n * 设置LastModified Header.\n */\n public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {\n response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedDate);\n }\n\n /**\n * 设置Etag Header.\n */\n public static void setEtag(HttpServletResponse response, String etag) {\n response.setHeader(HttpHeaders.ETAG, etag);\n }\n\n /**\n * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.\n * 如果无修改, checkIfModify返回false ,设置304 not modify status.\n *\n * @param lastModified 内容的最后修改时间.\n */\n public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,\n long lastModified) {\n long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);\n if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {\n response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);\n return false;\n }\n return true;\n }\n\n\n /**\n * 根据浏览器 If-None-Match Header, 计算Etag是否已无效.\n * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.\n *\n * @param etag 内容的ETag.\n */\n public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {\n String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);\n if (headerValue != null) {\n boolean conditionSatisfied = false;\n if (!\"*\".equals(headerValue)) {\n StringTokenizer commaTokenizer = new StringTokenizer(headerValue, \",\");\n\n while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {\n String currentToken = commaTokenizer.nextToken();\n if (currentToken.trim().equals(etag)) {\n conditionSatisfied = true;\n }\n }\n } else {\n conditionSatisfied = true;\n }\n\n if (conditionSatisfied) {\n response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);\n response.setHeader(HttpHeaders.ETAG, etag);\n return false;\n }\n }\n return true;\n }\n\n\n /**\n * 是否包含字符串\n *\n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs) {\n if (str != null && strs != null) {\n for (String s : strs) {\n if (str.equalsIgnoreCase(StringUtils.trim(s))) {\n return true;\n }\n }\n }\n return false;\n }\n}", "answers": [" token = CookieUtils.getCookie(httpServletRequest, AuthConstant.BLUEWIND_COOKIE_KEY);"], "length": 4342, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "4eda4b58-f53d-4ce4-9adc-f0b5ad134967", "reasoning": "The method getToken(HttpServletRequest) mirrors getToken() without request argument. After retrieving the token from the header, it checks if the token is blank. The next logical line is to retrieve the token from the cookie using CookieUtils, matching the pattern used earlier in getToken().", "reasoning_model_answer": "token = CookieUtils.getCookie(httpServletRequest, AuthConstant.BLUEWIND_COOKIE_KEY);", "assistant_with_reasoning": "\nThe method getToken(HttpServletRequest) mirrors getToken() without request argument. After retrieving the token from the header, it checks if the token is blank. The next logical line is to retrieve the token from the cookie using CookieUtils, matching the pattern used earlier in getToken().\n\ntoken = CookieUtils.getCookie(httpServletRequest, AuthConstant.BLUEWIND_COOKIE_KEY);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.68, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36700, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "token = CookieUtils.getCookie(httpServletRequest, AuthConstant.BLUEWIND_COOKIE_KEY);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "import net.minecraft.block.BlockShulkerBox;\nimport net.minecraft.tileentity.TileEntityShulkerBox;\nimport org.bukkit.DyeColor;\nimport org.bukkit.Material;\nimport org.bukkit.block.Block;\nimport org.bukkit.block.ShulkerBox;\nimport org.bukkit.craftbukkit.v1_12_R1.util.CraftMagicNumbers;\nimport org.bukkit.craftbukkit.v1_12_R1.inventory.CraftInventory;\nimport org.bukkit.inventory.Inventory;", "context": "src/main/java/org/bukkit/craftbukkit/v1_12_R1/block/CraftShulkerBox.java\npackage org.bukkit.craftbukkit.v1_12_R1.block;\n\n\npublic class CraftShulkerBox extends CraftLootable implements ShulkerBox {\n\n public CraftShulkerBox(final Block block) {\n super(block, TileEntityShulkerBox.class);\n }\n\n public CraftShulkerBox(final Material material, final TileEntityShulkerBox te) {\n super(material, te);\n }\n\n @Override\n public Inventory getSnapshotInventory() {\n return new CraftInventory(this.getSnapshot());\n }\n\n @Override\n public Inventory getInventory() {\n if (!this.isPlaced()) {\n return this.getSnapshotInventory();\n }\n\n return new CraftInventory(this.getTileEntity());\n }\n\n @Override\n public DyeColor getColor() {\n net.minecraft.block.Block block = CraftMagicNumbers.getBlock(this.getType());\n\n\nsrc/main/java/org/bukkit/block/ShulkerBox.java\npublic interface ShulkerBox extends Container, Nameable {\n\n /**\n * Get the {@link DyeColor} corresponding to this ShulkerBox\n *\n * @return the {@link DyeColor} of this ShulkerBox\n */\n public DyeColor getColor();\n}\n\nsrc/main/java/org/bukkit/block/Block.java\npublic interface Block extends Metadatable {\n\n /**\n * Gets the metadata for this block\n *\n * @return block specific metadata\n * @deprecated Magic value\n */\n @Deprecated\n byte getData();\n\n /**\n * Gets the block at the given offsets\n *\n * @param modX X-coordinate offset\n * @param modY Y-coordinate offset\n * @param modZ Z-coordinate offset\n * @return Block at the given offsets\n */\n Block getRelative(int modX, int modY, int modZ);\n\n /**\n * Gets the block at the given face\n *

\n * This method is equal to getRelative(face, 1)\n *\n * @param face Face of this block to return\n * @return Block at the given face\n * @see #getRelative(BlockFace, int)\n */\n Block getRelative(BlockFace face);\n\n /**\n * Gets the block at the given distance of the given face\n *

\n * For example, the following method places water at 100,102,100; two\n * blocks above 100,100,100.\n *\n *

\n     * Block block = world.getBlockAt(100, 100, 100);\n     * Block shower = block.getRelative(BlockFace.UP, 2);\n     * shower.setType(Material.WATER);\n     * 
\n *\n * @param face Face of this block to return\n * @param distance Distance to get the block at\n * @return Block at the given face\n */\n Block getRelative(BlockFace face, int distance);\n\n /**\n * Gets the type of this block\n *\n * @return block type\n */\n Material getType();\n\n /**\n * Gets the type-id of this block\n *\n * @return block type-id\n * @deprecated Magic value\n */\n @Deprecated\n int getTypeId();\n\n /**\n * Gets the light level between 0-15\n *\n * @return light level\n */\n byte getLightLevel();\n\n /**\n * Get the amount of light at this block from the sky.\n *

\n * Any light given from other sources (such as blocks like torches) will\n * be ignored.\n *\n * @return Sky light level\n */\n byte getLightFromSky();\n\n /**\n * Get the amount of light at this block from nearby blocks.\n *

\n * Any light given from other sources (such as the sun) will be ignored.\n *\n * @return Block light level\n */\n byte getLightFromBlocks();\n\n /**\n * Gets the world which contains this Block\n *\n * @return World containing this block\n */\n World getWorld();\n\n /**\n * Gets the x-coordinate of this block\n *\n * @return x-coordinate\n */\n int getX();\n\n /**\n * Gets the y-coordinate of this block\n *\n * @return y-coordinate\n */\n int getY();\n\n /**\n * Gets the z-coordinate of this block\n *\n * @return z-coordinate\n */\n int getZ();\n\n /**\n * Gets the Location of the block\n *\n * @return Location of block\n */\n Location getLocation();\n\n /**\n * Stores the location of the block in the provided Location object.\n *

\n * If the provided Location is null this method does nothing and returns\n * null.\n *\n * @param loc the location to copy into\n * @return The Location object provided or null\n */\n Location getLocation(Location loc);\n\n /**\n * Gets the chunk which contains this block\n *\n * @return Containing Chunk\n */\n Chunk getChunk();\n\n /**\n * Sets the metadata for this block\n *\n * @param data New block specific metadata\n * @deprecated Magic value\n */\n @Deprecated\n void setData(byte data);\n\n /**\n * Sets the metadata for this block\n *\n * @param data New block specific metadata\n * @param applyPhysics False to cancel physics from the changed block.\n * @deprecated Magic value\n */\n @Deprecated\n void setData(byte data, boolean applyPhysics);\n\n /**\n * Sets the type of this block\n *\n * @param type Material to change this block to\n */\n void setType(Material type);\n\n /**\n * Sets the type of this block\n *\n * @param type Material to change this block to\n * @param applyPhysics False to cancel physics on the changed block.\n */\n void setType(Material type, boolean applyPhysics);\n\n /**\n * Sets the type-id of this block\n *\n * @param type Type-Id to change this block to\n * @return whether the block was changed\n * @deprecated Magic value\n */\n @Deprecated\n boolean setTypeId(int type);\n\n /**\n * Sets the type-id of this block\n *\n * @param type Type-Id to change this block to\n * @param applyPhysics False to cancel physics on the changed block.\n * @return whether the block was changed\n * @deprecated Magic value\n */\n @Deprecated\n boolean setTypeId(int type, boolean applyPhysics);\n\n /**\n * Sets the type-id of this block\n *\n * @param type Type-Id to change this block to\n * @param data The data value to change this block to\n * @param applyPhysics False to cancel physics on the changed block\n * @return whether the block was changed\n * @deprecated Magic value\n */\n @Deprecated\n boolean setTypeIdAndData(int type, byte data, boolean applyPhysics);\n\n /**\n * Gets the face relation of this block compared to the given block.\n *

\n * For example: \n *

{@code\n     * Block current = world.getBlockAt(100, 100, 100);\n     * Block target = world.getBlockAt(100, 101, 100);\n     *\n     * current.getFace(target) == BlockFace.Up;\n     * }
\n *
\n * If the given block is not connected to this block, null may be returned\n *\n * @param block Block to compare against this block\n * @return BlockFace of this block which has the requested block, or null\n */\n BlockFace getFace(Block block);\n\n /**\n * Captures the current state of this block. You may then cast that state\n * into any accepted type, such as Furnace or Sign.\n *

\n * The returned object will never be updated, and you are not guaranteed\n * that (for example) a sign is still a sign after you capture its state.\n *\n * @return BlockState with the current state of this block.\n */\n BlockState getState();\n\n /**\n * Returns the biome that this block resides in\n *\n * @return Biome type containing this block\n */\n Biome getBiome();\n\n /**\n * Sets the biome that this block resides in\n *\n * @param bio new Biome type for this block\n */\n void setBiome(Biome bio);\n\n /**\n * Returns true if the block is being powered by Redstone.\n *\n * @return True if the block is powered.\n */\n boolean isBlockPowered();\n\n /**\n * Returns true if the block is being indirectly powered by Redstone.\n *\n * @return True if the block is indirectly powered.\n */\n boolean isBlockIndirectlyPowered();\n\n /**\n * Returns true if the block face is being powered by Redstone.\n *\n * @param face The block face\n * @return True if the block face is powered.\n */\n boolean isBlockFacePowered(BlockFace face);\n\n /**\n * Returns true if the block face is being indirectly powered by Redstone.\n *\n * @param face The block face\n * @return True if the block face is indirectly powered.\n */\n boolean isBlockFaceIndirectlyPowered(BlockFace face);\n\n /**\n * Returns the redstone power being provided to this block face\n *\n * @param face the face of the block to query or BlockFace.SELF for the\n * block itself\n * @return The power level.\n */\n int getBlockPower(BlockFace face);\n\n /**\n * Returns the redstone power being provided to this block\n *\n * @return The power level.\n */\n int getBlockPower();\n\n /**\n * Checks if this block is empty.\n *

\n * A block is considered empty when {@link #getType()} returns {@link\n * Material#AIR}.\n *\n * @return true if this block is empty\n */\n boolean isEmpty();\n\n /**\n * Checks if this block is liquid.\n *

\n * A block is considered liquid when {@link #getType()} returns {@link\n * Material#WATER}, {@link Material#STATIONARY_WATER}, {@link\n * Material#LAVA} or {@link Material#STATIONARY_LAVA}.\n *\n * @return true if this block is liquid\n */\n boolean isLiquid();\n\n /**\n * Gets the temperature of the biome of this block\n *\n * @return Temperature of this block\n */\n double getTemperature();\n\n /**\n * Gets the humidity of the biome of this block\n *\n * @return Humidity of this block\n */\n double getHumidity();\n\n /**\n * Returns the reaction of the block when moved by a piston\n *\n * @return reaction\n */\n PistonMoveReaction getPistonMoveReaction();\n\n /**\n * Breaks the block and spawns items as if a player had digged it\n *\n * @return true if the block was destroyed\n */\n boolean breakNaturally();\n\n /**\n * Breaks the block and spawns items as if a player had digged it with a\n * specific tool\n *\n * @param tool The tool or item in hand used for digging\n * @return true if the block was destroyed\n */\n boolean breakNaturally(ItemStack tool);\n\n /**\n * Returns a list of items which would drop by destroying this block\n *\n * @return a list of dropped items for this type of block\n */\n Collection getDrops();\n\n /**\n * Returns a list of items which would drop by destroying this block with\n * a specific tool\n *\n * @param tool The tool or item in hand used for digging\n * @return a list of dropped items for this type of block\n */\n Collection getDrops(ItemStack tool);\n\n}\n\nsrc/main/java/org/bukkit/DyeColor.java\npublic enum DyeColor {\n\n /**\n * Represents white dye.\n */\n WHITE(0x0, 0xF, Color.fromRGB(0xF9FFFE), Color.fromRGB(0xF0F0F0)),\n /**\n * Represents orange dye.\n */\n ORANGE(0x1, 0xE, Color.fromRGB(0xF9801D), Color.fromRGB(0xEB8844)),\n /**\n * Represents magenta dye.\n */\n MAGENTA(0x2, 0xD, Color.fromRGB(0xC74EBD), Color.fromRGB(0xC354CD)),\n /**\n * Represents light blue dye.\n */\n LIGHT_BLUE(0x3, 0xC, Color.fromRGB(0x3AB3DA), Color.fromRGB(0x6689D3)),\n /**\n * Represents yellow dye.\n */\n YELLOW(0x4, 0xB, Color.fromRGB(0xFED83D), Color.fromRGB(0xDECF2A)),\n /**\n * Represents lime dye.\n */\n LIME(0x5, 0xA, Color.fromRGB(0x80C71F), Color.fromRGB(0x41CD34)),\n /**\n * Represents pink dye.\n */\n PINK(0x6, 0x9, Color.fromRGB(0xF38BAA), Color.fromRGB(0xD88198)),\n /**\n * Represents gray dye.\n */\n GRAY(0x7, 0x8, Color.fromRGB(0x474F52), Color.fromRGB(0x434343)),\n /**\n * Represents silver dye.\n */\n SILVER(0x8, 0x7, Color.fromRGB(0x9D9D97), Color.fromRGB(0xABABAB)),\n /**\n * Represents cyan dye.\n */\n CYAN(0x9, 0x6, Color.fromRGB(0x169C9C), Color.fromRGB(0x287697)),\n /**\n * Represents purple dye.\n */\n PURPLE(0xA, 0x5, Color.fromRGB(0x8932B8), Color.fromRGB(0x7B2FBE)),\n /**\n * Represents blue dye.\n */\n BLUE(0xB, 0x4, Color.fromRGB(0x3C44AA), Color.fromRGB(0x253192)),\n /**\n * Represents brown dye.\n */\n BROWN(0xC, 0x3, Color.fromRGB(0x835432), Color.fromRGB(0x51301A)),\n /**\n * Represents green dye.\n */\n GREEN(0xD, 0x2, Color.fromRGB(0x5E7C16), Color.fromRGB(0x3B511A)),\n /**\n * Represents red dye.\n */\n RED(0xE, 0x1, Color.fromRGB(0xB02E26), Color.fromRGB(0xB3312C)),\n /**\n * Represents black dye.\n */\n BLACK(0xF, 0x0, Color.fromRGB(0x1D1D21), Color.fromRGB(0x1E1B1B));\n\n private final byte woolData;\n private final byte dyeData;\n private final Color color;\n private final Color firework;\n private final static DyeColor[] BY_WOOL_DATA;\n private final static DyeColor[] BY_DYE_DATA;\n private final static Map BY_COLOR;\n private final static Map BY_FIREWORK;\n\n private DyeColor(final int woolData, final int dyeData, Color color, Color firework) {\n this.woolData = (byte) woolData;\n this.dyeData = (byte) dyeData;\n this.color = color;\n this.firework = firework;\n }\n\n /**\n * Gets the associated wool data value representing this color.\n *\n * @return A byte containing the wool data value of this color\n * @see #getDyeData()\n * @deprecated Magic value\n */\n @Deprecated\n public byte getWoolData() {\n return woolData;\n }\n\n /**\n * Gets the associated dye data value representing this color.\n *\n * @return A byte containing the dye data value of this color\n * @see #getWoolData()\n * @deprecated Magic value\n */\n @Deprecated\n public byte getDyeData() {\n return dyeData;\n }\n\n /**\n * Gets the color that this dye represents.\n *\n * @return The {@link Color} that this dye represents\n */\n public Color getColor() {\n return color;\n }\n\n /**\n * Gets the firework color that this dye represents.\n *\n * @return The {@link Color} that this dye represents\n */\n public Color getFireworkColor() {\n return firework;\n }\n\n /**\n * Gets the DyeColor with the given wool data value.\n *\n * @param data Wool data value to fetch\n * @return The {@link DyeColor} representing the given value, or null if\n * it doesn't exist\n * @see #getByDyeData(byte)\n * @deprecated Magic value\n */\n @Deprecated\n public static DyeColor getByWoolData(final byte data) {\n int i = 0xff & data;\n if (i >= BY_WOOL_DATA.length) {\n return null;\n }\n return BY_WOOL_DATA[i];\n }\n\n /**\n * Gets the DyeColor with the given dye data value.\n *\n * @param data Dye data value to fetch\n * @return The {@link DyeColor} representing the given value, or null if\n * it doesn't exist\n * @see #getByWoolData(byte)\n * @deprecated Magic value\n */\n @Deprecated\n public static DyeColor getByDyeData(final byte data) {\n int i = 0xff & data;\n if (i >= BY_DYE_DATA.length) {\n return null;\n }\n return BY_DYE_DATA[i];\n }\n\n /**\n * Gets the DyeColor with the given color value.\n *\n * @param color Color value to get the dye by\n * @return The {@link DyeColor} representing the given value, or null if\n * it doesn't exist\n */\n public static DyeColor getByColor(final Color color) {\n return BY_COLOR.get(color);\n }\n\n /**\n * Gets the DyeColor with the given firework color value.\n *\n * @param color Color value to get dye by\n * @return The {@link DyeColor} representing the given value, or null if\n * it doesn't exist\n */\n public static DyeColor getByFireworkColor(final Color color) {\n return BY_FIREWORK.get(color);\n }\n\n static {\n BY_WOOL_DATA = values();\n BY_DYE_DATA = values();\n ImmutableMap.Builder byColor = ImmutableMap.builder();\n ImmutableMap.Builder byFirework = ImmutableMap.builder();\n\n for (DyeColor color : values()) {\n BY_WOOL_DATA[color.woolData & 0xff] = color;\n BY_DYE_DATA[color.dyeData & 0xff] = color;\n byColor.put(color.getColor(), color);\n byFirework.put(color.getFireworkColor(), color);\n }\n\n BY_COLOR = byColor.build();\n BY_FIREWORK = byFirework.build();\n }\n}\n\nsrc/main/java/org/bukkit/inventory/Inventory.java\npublic interface Inventory extends Iterable {\n\n /**\n * Returns the size of the inventory\n *\n * @return The size of the inventory\n */\n public int getSize();\n\n /**\n * Returns the maximum stack size for an ItemStack in this inventory.\n *\n * @return The maximum size for an ItemStack in this inventory.\n */\n public int getMaxStackSize();\n\n /**\n * This method allows you to change the maximum stack size for an\n * inventory.\n *

\n * Caveats:\n *

    \n *
  • Not all inventories respect this value.\n *
  • Stacks larger than 127 may be clipped when the world is saved.\n *
  • This value is not guaranteed to be preserved; be sure to set it\n * before every time you want to set a slot over the max stack size.\n *
  • Stacks larger than the default max size for this type of inventory\n * may not display correctly in the client.\n *
\n *\n * @param size The new maximum stack size for items in this inventory.\n */\n public void setMaxStackSize(int size);\n\n /**\n * Returns the name of the inventory\n *\n * @return The String with the name of the inventory\n */\n public String getName();\n\n /**\n * Returns the ItemStack found in the slot at the given index\n *\n * @param index The index of the Slot's ItemStack to return\n * @return The ItemStack in the slot\n */\n public ItemStack getItem(int index);\n\n /**\n * Stores the ItemStack at the given index of the inventory.\n *\n * @param index The index where to put the ItemStack\n * @param item The ItemStack to set\n */\n public void setItem(int index, ItemStack item);\n\n /**\n * Stores the given ItemStacks in the inventory. This will try to fill\n * existing stacks and empty slots as well as it can.\n *

\n * The returned HashMap contains what it couldn't store, where the key is\n * the index of the parameter, and the value is the ItemStack at that\n * index of the varargs parameter. If all items are stored, it will return\n * an empty HashMap.\n *

\n * If you pass in ItemStacks which exceed the maximum stack size for the\n * Material, first they will be added to partial stacks where\n * Material.getMaxStackSize() is not exceeded, up to\n * Material.getMaxStackSize(). When there are no partial stacks left\n * stacks will be split on Inventory.getMaxStackSize() allowing you to\n * exceed the maximum stack size for that material.\n *

\n * It is known that in some implementations this method will also set\n * the inputted argument amount to the number of that item not placed in\n * slots.\n *\n * @param items The ItemStacks to add\n * @return A HashMap containing items that didn't fit.\n * @throws IllegalArgumentException if items or any element in it is null\n */\n public HashMap addItem(ItemStack... items) throws IllegalArgumentException;\n\n /**\n * Removes the given ItemStacks from the inventory.\n *

\n * It will try to remove 'as much as possible' from the types and amounts\n * you give as arguments.\n *

\n * The returned HashMap contains what it couldn't remove, where the key is\n * the index of the parameter, and the value is the ItemStack at that\n * index of the varargs parameter. If all the given ItemStacks are\n * removed, it will return an empty HashMap.\n *

\n * It is known that in some implementations this method will also set the\n * inputted argument amount to the number of that item not removed from\n * slots.\n *\n * @param items The ItemStacks to remove\n * @return A HashMap containing items that couldn't be removed.\n * @throws IllegalArgumentException if items is null\n */\n public HashMap removeItem(ItemStack... items) throws IllegalArgumentException;\n\n /**\n * Returns all ItemStacks from the inventory\n *\n * @return An array of ItemStacks from the inventory.\n */\n public ItemStack[] getContents();\n\n /**\n * Completely replaces the inventory's contents. Removes all existing\n * contents and replaces it with the ItemStacks given in the array.\n *\n * @param items A complete replacement for the contents; the length must\n * be less than or equal to {@link #getSize()}.\n * @throws IllegalArgumentException If the array has more items than the\n * inventory.\n */\n public void setContents(ItemStack[] items) throws IllegalArgumentException;\n\n /**\n * Return the contents from the section of the inventory where items can\n * reasonably be expected to be stored. In most cases this will represent\n * the entire inventory, but in some cases it may exclude armor or result\n * slots.\n *
\n * It is these contents which will be used for add / contains / remove\n * methods which look for a specific stack.\n *\n * @return inventory storage contents\n */\n public ItemStack[] getStorageContents();\n\n /**\n * Put the given ItemStacks into the storage slots\n *\n * @param items The ItemStacks to use as storage contents\n * @throws IllegalArgumentException If the array has more items than the\n * inventory.\n */\n public void setStorageContents(ItemStack[] items) throws IllegalArgumentException;\n\n /**\n * Checks if the inventory contains any ItemStacks with the given\n * materialId\n *\n * @param materialId The materialId to check for\n * @return true if an ItemStack in this inventory contains the materialId\n * @deprecated Magic value\n */\n @Deprecated\n public boolean contains(int materialId);\n\n /**\n * Checks if the inventory contains any ItemStacks with the given\n * material.\n *\n * @param material The material to check for\n * @return true if an ItemStack is found with the given Material\n * @throws IllegalArgumentException if material is null\n */\n public boolean contains(Material material) throws IllegalArgumentException;\n\n /**\n * Checks if the inventory contains any ItemStacks matching the given\n * ItemStack.\n *

\n * This will only return true if both the type and the amount of the stack\n * match.\n *\n * @param item The ItemStack to match against\n * @return false if item is null, true if any exactly matching ItemStacks\n * were found\n */\n public boolean contains(ItemStack item);\n\n /**\n * Checks if the inventory contains any ItemStacks with the given\n * materialId, adding to at least the minimum amount specified.\n *\n * @param materialId The materialId to check for\n * @param amount The minimum amount to look for\n * @return true if this contains any matching ItemStack with the given\n * materialId and amount\n * @deprecated Magic value\n */\n @Deprecated\n public boolean contains(int materialId, int amount);\n\n /**\n * Checks if the inventory contains any ItemStacks with the given\n * material, adding to at least the minimum amount specified.\n *\n * @param material The material to check for\n * @param amount The minimum amount\n * @return true if amount is less than 1, true if enough ItemStacks were\n * found to add to the given amount\n * @throws IllegalArgumentException if material is null\n */\n public boolean contains(Material material, int amount) throws IllegalArgumentException;\n\n /**\n * Checks if the inventory contains at least the minimum amount specified\n * of exactly matching ItemStacks.\n *

\n * An ItemStack only counts if both the type and the amount of the stack\n * match.\n *\n * @param item the ItemStack to match against\n * @param amount how many identical stacks to check for\n * @return false if item is null, true if amount less than 1, true if\n * amount of exactly matching ItemStacks were found\n * @see #containsAtLeast(ItemStack, int)\n */\n public boolean contains(ItemStack item, int amount);\n\n /**\n * Checks if the inventory contains ItemStacks matching the given\n * ItemStack whose amounts sum to at least the minimum amount specified.\n *\n * @param item the ItemStack to match against\n * @param amount the minimum amount\n * @return false if item is null, true if amount less than 1, true if\n * enough ItemStacks were found to add to the given amount\n */\n public boolean containsAtLeast(ItemStack item, int amount);\n\n /**\n * Returns a HashMap with all slots and ItemStacks in the inventory with\n * given materialId.\n *

\n * The HashMap contains entries where, the key is the slot index, and the\n * value is the ItemStack in that slot. If no matching ItemStack with the\n * given materialId is found, an empty map is returned.\n *\n * @param materialId The materialId to look for\n * @return A HashMap containing the slot index, ItemStack pairs\n * @deprecated Magic value\n */\n @Deprecated\n public HashMap all(int materialId);\n\n /**\n * Returns a HashMap with all slots and ItemStacks in the inventory with\n * the given Material.\n *

\n * The HashMap contains entries where, the key is the slot index, and the\n * value is the ItemStack in that slot. If no matching ItemStack with the\n * given Material is found, an empty map is returned.\n *\n * @param material The material to look for\n * @return A HashMap containing the slot index, ItemStack pairs\n * @throws IllegalArgumentException if material is null\n */\n public HashMap all(Material material) throws IllegalArgumentException;\n\n /**\n * Finds all slots in the inventory containing any ItemStacks with the\n * given ItemStack. This will only match slots if both the type and the\n * amount of the stack match\n *

\n * The HashMap contains entries where, the key is the slot index, and the\n * value is the ItemStack in that slot. If no matching ItemStack with the\n * given Material is found, an empty map is returned.\n *\n * @param item The ItemStack to match against\n * @return A map from slot indexes to item at index\n */\n public HashMap all(ItemStack item);\n\n /**\n * Finds the first slot in the inventory containing an ItemStack with the\n * given materialId.\n *\n * @param materialId The materialId to look for\n * @return The slot index of the given materialId or -1 if not found\n * @deprecated Magic value\n */\n @Deprecated\n public int first(int materialId);\n\n /**\n * Finds the first slot in the inventory containing an ItemStack with the\n * given material\n *\n * @param material The material to look for\n * @return The slot index of the given Material or -1 if not found\n * @throws IllegalArgumentException if material is null\n */\n public int first(Material material) throws IllegalArgumentException;\n\n /**\n * Returns the first slot in the inventory containing an ItemStack with\n * the given stack. This will only match a slot if both the type and the\n * amount of the stack match\n *\n * @param item The ItemStack to match against\n * @return The slot index of the given ItemStack or -1 if not found\n */\n public int first(ItemStack item);\n\n /**\n * Returns the first empty Slot.\n *\n * @return The first empty Slot found, or -1 if no empty slots.\n */\n public int firstEmpty();\n\n /**\n * Removes all stacks in the inventory matching the given materialId.\n *\n * @param materialId The material to remove\n * @deprecated Magic value\n */\n @Deprecated\n public void remove(int materialId);\n\n /**\n * Removes all stacks in the inventory matching the given material.\n *\n * @param material The material to remove\n * @throws IllegalArgumentException if material is null\n */\n public void remove(Material material) throws IllegalArgumentException;\n\n /**\n * Removes all stacks in the inventory matching the given stack.\n *

\n * This will only match a slot if both the type and the amount of the\n * stack match\n *\n * @param item The ItemStack to match against\n */\n public void remove(ItemStack item);\n\n /**\n * Clears out a particular slot in the index.\n *\n * @param index The index to empty.\n */\n public void clear(int index);\n\n /**\n * Clears out the whole Inventory.\n */\n public void clear();\n\n /**\n * Gets a list of players viewing the inventory. Note that a player is\n * considered to be viewing their own inventory and internal crafting\n * screen even when said inventory is not open. They will normally be\n * considered to be viewing their inventory even when they have a\n * different inventory screen open, but it's possible for customized\n * inventory screens to exclude the viewer's inventory, so this should\n * never be assumed to be non-empty.\n *\n * @return A list of HumanEntities who are viewing this Inventory.\n */\n public List getViewers();\n\n /**\n * Returns the title of this inventory.\n *\n * @return A String with the title.\n */\n public String getTitle();\n\n /**\n * Returns what type of inventory this is.\n *\n * @return The InventoryType representing the type of inventory.\n */\n public InventoryType getType();\n\n /**\n * Gets the block or entity belonging to the open inventory\n *\n * @return The holder of the inventory; null if it has no holder.\n */\n public InventoryHolder getHolder();\n\n @Override\n public ListIterator iterator();\n\n /**\n * Returns an iterator starting at the given index. If the index is\n * positive, then the first call to next() will return the item at that\n * index; if it is negative, the first call to previous will return the\n * item at index (getSize() + index).\n *\n * @param index The index.\n * @return An iterator.\n */\n public ListIterator iterator(int index);\n\n /**\n * Get the location of the block or entity which corresponds to this inventory. May return null if this container\n * was custom created or is a virtual / subcontainer.\n *\n * @return location or null if not applicable.\n */\n public Location getLocation();\n}", "answers": [" return DyeColor.getByWoolData((byte) ((BlockShulkerBox) block).color.getMetadata());"], "length": 4349, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "36d76178-7284-45cf-88a8-a290e5b6e499", "reasoning": "The method getColor() should convert the underlying Minecraft block's color to the Bukkit DyeColor enum. After retrieving the net.minecraft.block.Block instance, the code needs to cast it to BlockShulkerBox, call getColor() to get the EnumDyeColor, obtain its metadata, and map it to Bukkit's DyeColor via DyeColor.getByWoolData. Therefore the next line returns that mapped DyeColor.", "reasoning_model_answer": "return DyeColor.getByWoolData((byte) ((BlockShulkerBox) block).getColor().getMetadata());", "assistant_with_reasoning": "\nThe method getColor() should convert the underlying Minecraft block's color to the Bukkit DyeColor enum. After retrieving the net.minecraft.block.Block instance, the code needs to cast it to BlockShulkerBox, call getColor() to get the EnumDyeColor, obtain its metadata, and map it to Bukkit's DyeColor via DyeColor.getByWoolData. Therefore the next line returns that mapped DyeColor.\n\nreturn DyeColor.getByWoolData((byte) ((BlockShulkerBox) block).getColor().getMetadata());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.801, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 31784, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return DyeColor.getByWoolData((byte) ((BlockShulkerBox) block).getColor().getMetadata());", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import os\r\nimport math\r\nimport json\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch\r\nimport random\r\nimport csv\r\nfrom collections import defaultdict\r\nfrom transformers import BartTokenizer, T5Tokenizer\r\nfrom transformers import AdamW, get_linear_schedule_with_warmup\r\nfrom utils import *\r\nfrom scoring.fluency_scorer import FluencyScorer\r\nfrom scoring.saliency_scorer import SaliencyBERTScore\r\nfrom scoring.simplicity_scorer import SimplicityTextScore\r\nfrom scoring.guardrails import *\r\nfrom scoring.aggregate_scorer import ScorerWrapper\r\nfrom GAP.data_relations_as_nodes import GAPDataloader, EventDataset, WebNLGDataset\r\nfrom GAP.data_relations_as_nodes import evaluate_bleu, get_t_emb_dim\r\nfrom tqdm import tqdm, trange\r\nfrom rake_nltk import Rake\r\nfrom evaluate import load\r\nfrom sentence_similarity import sentence_similarity\r\nfrom GAP.modeling_gap_type import GAPBartForConditionalGeneration as GAP_Type_model\r\nfrom GAP.modeling_gap import GAPBartForConditionalGeneration as GAP_model\r\nfrom T5.modeling_t5 import T5ForConditionalGeneration as T5\r", "context": "simplify_batched.py\n\r\n\r\n\r\n\r\n\r\n# import yake\r\n#T5\r\n\r\nbertscore = load(\"bertscore\")\r\n## sentence model for merge\r\nphrase_model = sentence_similarity(model_name='distilbert-base-uncased',embedding_type='cls_token_embedding')\r\n\r\n## for sentence checking\r\nner_check = NERInaccuracyPenalty()\r\n\r\ndef run(args, logger):\r\n #load in model for graph-to-text and tokenizer\r\n checkpoint = args.model_path\r\n tokenizer_path = args.tokenizer_path\r\n if 't5' in tokenizer_path:\r\n tokenizer = T5Tokenizer.from_pretrained(tokenizer_path)\r\n else:\r\n tokenizer = BartTokenizer.from_pretrained(tokenizer_path)\r\n \r\n n_gpu = torch.cuda.device_count()\r\n if n_gpu > 0:\r\n torch.cuda.manual_seed_all(args.seed)\r\n \r\n if args.type_encoding:\r\n t_emb_dim = get_t_emb_dim(args)\r\n model = GAP_Type_model.from_pretrained(checkpoint,t_emb_dim=t_emb_dim)\r\n else:\r\n if 't5' in args.model_path:\r\n\n\nGAP/data_relations_as_nodes.py\nclass WebNLGDataset(Dataset):\n def __init__(self, logger, args, data_path, tokenizer, mode):\n self.data_path = data_path\n self.tokenizer = tokenizer\n self.topology = {\"entity-entity\": args.entity_entity, \n \"entity-relation\": args.entity_relation,\n \"relation-entity\": args.relation_entity,\n \"relation-relation\": args.relation_relation\n } \n \n with open(self.data_path + '.json', 'r') as f:\n self.data = json.load(f)\n\n print(\"Total samples = {}\".format(len(self.data)))\n\n assert type(self.data) == list\n assert all([\"id\" in d for d in self.data]), self.data[0].keys()\n if type(self.data[0][\"id\"]) == int:\n for i in range(len(self.data)):\n self.data[i][\"id\"] = str(self.data[i][\"id\"])\n\n self.args = args\n self.data_type = mode\n self.metric = \"BLEU\"\n\n self.head_ids, self.rel_ids, self.tail_ids = self.tokenizer.encode(' [head]', add_special_tokens=False), \\\n self.tokenizer.encode(' [relation]', add_special_tokens=False), \\\n self.tokenizer.encode(' [tail]', add_special_tokens=False)\n\n self.graph_ids, self.text_ids = self.tokenizer.encode(' [graph]', add_special_tokens=False), \\\n self.tokenizer.encode(' [text]', add_special_tokens=False)\n\n if self.args.model_name == \"bart\":\n self.mask_token = self.tokenizer.mask_token\n self.mask_token_id = self.tokenizer.mask_token_id\n else:\n self.mask_token = self.tokenizer.additional_special_tokens[0]\n self.mask_token_id = self.tokenizer.convert_tokens_to_ids(self.tokenizer.additional_special_tokens[0])\n\n if self.args.model_name == \"bart\":\n if self.args.append_another_bos:\n self.add_bos_id = [self.tokenizer.bos_token_id] * 2\n else:\n self.add_bos_id = [self.tokenizer.bos_token_id]\n else:\n self.add_bos_id = []\n\n def __len__(self):\n return len(self.data)\n\n def linearize_v2(self, entity, entity_change, head_ids, rel_ids, tail_ids,\n relation_change, cnt_edge, adj_matrix):\n # string_label: encoder ids\n # string_label_tokens: encoder tokens\n\n if len(entity[0]) == 0:\n return [], '', [], [], cnt_edge, adj_matrix\n nodes, edges = [], []\n string_label = copy.deepcopy(head_ids)\n string_label_tokens = ' [head]'\n nodes.extend([-1] * len(string_label))\n edges.extend([-1] * len(string_label))\n\n\n string_label += entity_change[entity[0]][0]\n string_label_tokens += ' {}'.format(entity[0])\n nodes.extend([entity_change[entity[0]][1]] * len(entity_change[entity[0]][0]))\n edges.extend([-1] * len(entity_change[entity[0]][0]))\n\n\n for rel in entity[2]:\n if len(rel[0]) != 0 and len(rel[1]) != 0:\n rel_label = relation_change[rel[0]]\n rel_ent_label = entity_change[rel[0]][1]\n rel_label_token = copy.deepcopy(rel[0])\n words_label = rel_ids + rel_label + tail_ids + entity_change[rel[1]][0]\n words_label_tokens = ' [relation] {} [tail] {}'.format(rel_label_token, rel[1])\n nodes.extend(\n ([-1] * len(rel_ids)) + ([entity_change[rel[0]][1]] * len(rel_label)) + ([-1] * len(tail_ids)) + ([entity_change[rel[1]][1]] * len(\n entity_change[rel[1]][0])))\n\n \n edges.extend([-1] * len(rel_ids) + [cnt_edge] * len(rel_label) + [-1] * (\n len(tail_ids) + len(entity_change[rel[1]][0])))\n if entity_change[entity[0]][1] < len(adj_matrix) and entity_change[rel[1]][1] < len(adj_matrix):\n if self.topology['entity-entity']:\n adj_matrix[entity_change[entity[0]][1]][entity_change[rel[1]][1]] = 1\n adj_matrix[entity_change[rel[1]][1]][entity_change[entity[0]][1]] = 1\n\n if self.topology['entity-relation']:\n adj_matrix[entity_change[entity[0]][1]][entity_change[rel[0]][1]] = 2\n adj_matrix[entity_change[rel[1]][1]][entity_change[rel[0]][1]] = 2\n \n if self.topology['relation-entity']:\n adj_matrix[entity_change[rel[0]][1]][entity_change[entity[0]][1]] = 3\n adj_matrix[entity_change[rel[0]][1]][entity_change[rel[1]][1]] = 3\n \n if not self.topology['relation-entity'] and not self.topology['relation-relation']:\n adj_matrix[entity_change[rel[0]][1]][entity_change[rel[0]][1]] = 10\n \n if not self.topology['entity-relation'] and not self.topology['entity-entity']:\n adj_matrix[entity_change[entity[0]][1]][entity_change[entity[0]][1]] = 10\n adj_matrix[entity_change[rel[1]][1]][entity_change[rel[1]][1]] = 10\n\n cnt_edge += 1\n string_label += words_label\n string_label_tokens += words_label_tokens\n\n assert len(string_label) == len(nodes) == len(edges)\n\n return string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix\n\n \n def relation_to_relation_fill(self, node_dict, rel_dict, adj_matrix):\n adj_matrix_temp = np.array(adj_matrix)\n rel_idx_list = []\n for rel in rel_dict.keys():\n rel_idx = node_dict[rel][1]\n rel_idx_list.append(rel_idx)\n adj_matrix_np = np.array(adj_matrix)\n adj_matrix_np_bool = (adj_matrix_np==-1)\n #reassign -1s to 0s\n adj_matrix_np[adj_matrix_np_bool] = 0\n #get squared matrix for r-r\n adj_matrix_sq = adj_matrix_np@adj_matrix_np\n \n #old adj_matrix + squared matrix only r-r\n rel_idx_list = np.array(rel_idx_list, dtype=np.intp)\n adj_matrix_temp[rel_idx_list[:,np.newaxis], rel_idx_list] = (adj_matrix_sq[rel_idx_list][:,rel_idx_list] > 0)*4\n adj_matrix_new = adj_matrix_temp.tolist()\n \n return adj_matrix_new\n \n \n def get_all_entities_per_sample(self, mark_entity_number, mark_entity, entry):\n text_entity = set()\n text_relation = set()\n for entity_id in mark_entity_number:\n entity = entry['kbs'][entity_id]\n if len(entity[0]) == 0:\n continue\n for rel in entity[2]:\n if len(rel[0]) != 0 and len(rel[1]) != 0:\n text_relation.add(rel[0])\n text_entity.add(rel[1])\n\n text_entity_list = list(text_entity)+list(text_relation)\n text_relation_list = list(text_relation)\n for entity_ele in mark_entity:\n if entity_ele in text_entity_list:\n text_entity_list.remove(entity_ele)\n \n return text_entity_list, text_relation_list\n\n def get_change_per_sample(self, mark_entity, text_entity, text_relation):\n # during fine-tuning, we don't mask entities or relations\n ent_change = {}\n total_entity = mark_entity + text_entity\n\n for ent_id in range(len(total_entity)):\n entity_toks = self.tokenizer.encode(\" {}\".format(total_entity[ent_id]), add_special_tokens=False)\n ent_change[total_entity[ent_id]] = [entity_toks, ent_id]\n # relation change only includes the relation tokens and ids\n rel_change = {}\n for rel_id in range(len(text_relation)):\n rel_change[text_relation[rel_id]] = self.tokenizer.encode(' {}'.format(text_relation[rel_id]),\n add_special_tokens=False)\n return ent_change, rel_change\n\n def truncate_pair_ar(self, a, add_bos_id, graph_ids, text_ids, node_ids, edge_ids):\n # add_bos_id + graph_ids + a + text_ids + b + eos_token_id\n length_a_b = self.args.max_input_length - len(add_bos_id) - len(graph_ids) - len(text_ids) - 1\n if len(a) > length_a_b:\n a = a[:length_a_b]\n node_ids = node_ids[:length_a_b]\n edge_ids = edge_ids[:length_a_b]\n input_ids = add_bos_id + graph_ids + a + text_ids + [self.tokenizer.eos_token_id]\n input_node_ids = [-1] * (len(add_bos_id) + len(graph_ids)) + node_ids + [-1] * (len(text_ids) + 1)\n input_edge_ids = [-1] * (len(add_bos_id) + len(graph_ids)) + edge_ids + [-1] * (len(text_ids) + 1)\n attn_mask = [1] * len(input_ids) + [0] * (self.args.max_input_length - len(input_ids))\n input_ids += [self.tokenizer.pad_token_id] * (self.args.max_input_length - len(input_ids))\n input_node_ids += [-1] * (self.args.max_input_length - len(input_node_ids))\n input_edge_ids += [-1] * (self.args.max_input_length - len(input_edge_ids))\n assert len(input_ids) == len(attn_mask) == self.args.max_input_length == len(input_node_ids) == len(\n input_edge_ids)\n return input_ids, attn_mask, input_node_ids, input_edge_ids\n\n def ar_prep_data(self, questions, add_bos_id, graph_ids, text_ids, node_ids, edge_ids):\n input_ids, input_attn_mask, input_node_ids, input_edge_ids = self.truncate_pair_ar(questions, add_bos_id,\n graph_ids, text_ids,\n node_ids, edge_ids)\n\n return input_ids, input_attn_mask, input_node_ids, input_edge_ids\n \n\n\n def __getitem__(self, idx):\n\n entry = self.data[idx]\n\n entities = []\n for _ in entry['kbs']:\n entities.append(_)\n\n strings_label = []\n node_ids = []\n edge_ids = []\n strings_label_tokens = ''\n\n # mark_entity: entities with KB numbers which are important for this task\n # text_entity: entities without KB numbers but only with text, which are less important\n mark_entity = [entry['kbs'][ele_entity][0] for ele_entity in entities]\n mark_entity_number = entities\n text_entity, text_relation = self.get_all_entities_per_sample(mark_entity_number, mark_entity, entry)\n entity_change, relation_change = self.get_change_per_sample(mark_entity, text_entity, text_relation)\n total_entity = mark_entity + text_entity\n adj_matrix = [[-1] * (self.args.max_node_length + 1) for _ in range(self.args.max_node_length + 1)]\n\n cnt_edge = 0\n\n if 'title' in entry:\n entity = self.knowledge[entry['title_kb_id']]\n string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix = self.linearize_v2(\n entity,\n entity_change,\n self.head_ids,\n self.rel_ids, self.tail_ids,\n relation_change, cnt_edge, adj_matrix)\n\n strings_label += string_label\n strings_label_tokens += string_label_tokens\n\n for i, entity_id in enumerate(entities):\n entity = entry['kbs'][entity_id]\n string_label, string_label_tokens, nodes, edges, cnt_edge, adj_matrix = self.linearize_v2(\n entity,\n entity_change,\n self.head_ids,\n self.rel_ids, self.tail_ids,\n relation_change, cnt_edge, adj_matrix)\n \n strings_label += string_label\n strings_label_tokens += string_label_tokens\n node_ids += nodes\n edge_ids += edges\n \n if self.topology['relation-relation']:\n adj_matrix = self.relation_to_relation_fill(entity_change, relation_change, adj_matrix)\n \n\n words_label_ids, words_label_tokens, words_input_ids, words_input_tokens = [], '', [], ''\n\n\n input_ids_ar, attn_mask_ar, input_node_ids_ar, input_edge_ids_ar = \\\n self.ar_prep_data(strings_label, self.add_bos_id, self.graph_ids,\n self.text_ids, node_ids, edge_ids)\n\n node_length_ar = max(input_node_ids_ar) + 1\n edge_length_ar = max(input_edge_ids_ar) + 1\n \n\n def masked_fill(src, masked_value, fill_value):\n return [src[src_id] if src[src_id] != masked_value and src[src_id] < fill_value else fill_value for src_id\n in range(len(src))]\n\n input_node_ids_ar, input_edge_ids_ar = masked_fill(input_node_ids_ar, -1, self.args.max_node_length), \\\n masked_fill(input_edge_ids_ar, -1, self.args.max_edge_length)\n\n def masked_fill_matrix(adj_matrix_input, masked_value, fill_value):\n adj_matrix_tmp = copy.deepcopy(adj_matrix_input)\n for a_id in range(len(adj_matrix_tmp)):\n for b_id in range(len(adj_matrix_tmp)):\n if adj_matrix_tmp[a_id][b_id] == masked_value or adj_matrix_tmp[a_id][b_id] > fill_value:\n adj_matrix_tmp[a_id][b_id] = fill_value\n return adj_matrix_tmp\n\n adj_matrix_ar = masked_fill_matrix(adj_matrix, -1, self.args.max_edge_length)\n\n assert len(input_ids_ar) == len(attn_mask_ar) == self.args.max_input_length == len(input_node_ids_ar) == len(\n input_edge_ids_ar)\n\n input_ids_ar = torch.LongTensor(input_ids_ar)\n attn_mask_ar = torch.LongTensor(attn_mask_ar)\n \n input_node_ids_ar = torch.LongTensor(input_node_ids_ar)\n input_edge_ids_ar = torch.LongTensor(input_edge_ids_ar)\n node_length_ar = torch.LongTensor([node_length_ar])\n edge_length_ar = torch.LongTensor([edge_length_ar])\n adj_matrix_ar = torch.LongTensor(adj_matrix_ar)\n \n return input_ids_ar, attn_mask_ar, input_node_ids_ar, node_length_ar, adj_matrix_ar\n\nscoring/aggregate_scorer.py\nclass ScorerWrapper:\n def __init__(self, scorers, scoring_method=\"logsum\", batch_size=1):\n assert scoring_method in [\"product\", \"logsum\"], \"Unrecognized `scoring_method`\"\n \n self.scorers = scorers\n self.scoring_method = scoring_method\n\n # if self.scoring_method == \"logsum\":\n # self.score_func = logsum_score\n # elif self.scoring_method == \"product\":\n # self.score_func = product_score\n \n if batch_size > 1:\n exec(\"self.score_func = {}\".format(self.scoring_method+\"_\"+\"score_batched\"))\n else:\n exec(\"self.score_func = {}\").format(self.scoring_method+\"_\"+\"score\")\n self.batch_size = batch_size\n def get_score_names(self):\n return [s[\"name\"] for s in self.scorers]\n \n def score_batched(self, input_texts=None, generated_texts=None, old_kgs=None, new_kgs=None, dels_ents=None, partial=False, printing=False, timings=False, extras={}, progress=False):\n assert len(input_texts) == len(generated_texts) == len(old_kgs) == len(new_kgs) == len(dels_ents), \"Data lengths don't match\"\n \n data_list = []\n for inp, gen, old_kg, new_kg, del_ents in zip(input_texts, generated_texts, old_kgs, new_kgs, dels_ents):\n data_list.append({\"inp\": inp, \"gen\": gen, \"old_kg\": old_kg, \"new_kg\": new_kg, \"del_ents\": del_ents})\n\n if len(data_list) == 0:\n progress = False\n \n for batch in batcher(data_list, batch_size=self.batch_size, progress=progress):\n batch_inputs = [instance_dict[\"inp\"] for instance_dict in batch]\n batch_gens = [instance_dict[\"gen\"] for instance_dict in batch]\n batch_old_kgs = [instance_dict[\"old_kg\"] for instance_dict in batch]\n batch_new_kgs = [instance_dict[\"new_kg\"] for instance_dict in batch]\n batch_dels_ents = [instance_dict[\"del_ents\"] for instance_dict in batch]\n batch_scores = self.score_func(self.scorers, batch_inputs, batch_gens, batch_old_kgs, batch_new_kgs, batch_dels_ents)\n for score_type, scores in batch_scores.items():\n if type(scores) in [torch.Tensor, np.array, np.ndarray]:\n batch_scores[score_type] = scores.tolist()\n\n if printing:\n print(\"[total]\", all_outputs[\"total_scores\"])\n return batch_scores\n \n def score(self, input_text=None, generated_text=None, old_kg=None, new_kg=None, del_ents=None):\n aggregate_score = self.score_func(self.scorers, input_text, generated_text, old_kg, new_kg, del_ents)\n return aggregate_score\n \n\n def __call__(self, graphs, input_text, generated_text, **kwargs):\n return self.score(graphs, input_text, generated_text, **kwargs)\n\nGAP/modeling_gap.py\nclass GAPBartForConditionalGeneration(BartForConditionalGeneration):\n def __init__(self, config):\n super().__init__(config)\n base_model = GAPBartModel(config)\n self.model = base_model\n self.register_buffer(\"final_logits_bias\", torch.zeros((1, self.model.shared.num_embeddings)))\n\n def forward(self, input_ids, attention_mask=None, encoder_outputs=None,\n decoder_input_ids=None, decoder_attention_mask=None, input_node_ids=None, \n node_length=None, adj_matrix=None, decoder_whole_ids=None, decoder_cached_states=None,\n use_cache=False, is_training=False):\n\n if is_training:\n _decoder_input_ids = shift_tokens_right(decoder_input_ids, self.config.pad_token_id)\n else:\n _decoder_input_ids = decoder_input_ids\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=_decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n input_node_ids=input_node_ids,\n node_length=node_length,\n adj_matrix=adj_matrix,\n decoder_cached_states=decoder_cached_states,\n use_cache=use_cache,\n )\n lm_logits = F.linear(outputs[0], self.model.shared.weight, bias=self.final_logits_bias)\n if is_training:\n loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)\n loss = loss_fct(lm_logits.view(-1, self.config.vocab_size),\n decoder_input_ids.view(-1))\n return loss\n return (lm_logits, ) + outputs[1:]\n\n @torch.no_grad()\n def generate(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n max_length: Optional[int] = None,\n min_length: Optional[int] = None,\n do_sample: Optional[bool] = None,\n early_stopping: Optional[bool] = None,\n num_beams: Optional[int] = None,\n temperature: Optional[float] = None,\n top_k: Optional[int] = None,\n top_p: Optional[float] = None,\n repetition_penalty: Optional[float] = None,\n bad_words_ids: Optional[Iterable[int]] = None,\n bos_token_id: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[int] = None,\n length_penalty: Optional[float] = None,\n no_repeat_ngram_size: Optional[int] = None,\n num_return_sequences: Optional[int] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n input_node_ids=None,\n node_length=None,\n adj_matrix=None,\n decoder_start_token_id: Optional[int] = None,\n use_cache: Optional[bool] = None,\n **model_specific_kwargs\n ) -> torch.LongTensor:\n r\"\"\" Generates sequences for models with a LM head. The method currently supports greedy decoding, beam-search decoding, sampling with temperature, sampling with top-k or nucleus sampling.\n\n Adapted in part from `Facebook's XLM beam search code`_.\n\n .. _`Facebook's XLM beam search code`:\n https://github.com/facebookresearch/XLM/blob/9e6f6814d17be4fe5b15f2e6c43eb2b2d76daeb4/src/model/transformer.py#L529\n\n\n Parameters:\n\n input_ids: (`optional`) `torch.LongTensor` of shape `(batch_size, sequence_length)`\n The sequence used as a prompt for the generation. If `None` the method initializes\n it as an empty `torch.LongTensor` of shape `(1,)`.\n\n max_length: (`optional`) int\n The max length of the sequence to be generated. Between `min_length` and infinity. Default to 20.\n\n min_length: (`optional`) int\n The min length of the sequence to be generated. Between 0 and infinity. Default to 0.\n\n do_sample: (`optional`) bool\n If set to `False` greedy decoding is used. Otherwise sampling is used. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n early_stopping: (`optional`) bool\n if set to `True` beam search is stopped when at least `num_beams` sentences finished per batch. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n num_beams: (`optional`) int\n Number of beams for beam search. Must be between 1 and infinity. 1 means no beam search. Default to 1.\n\n temperature: (`optional`) float\n The value used to module the next token probabilities. Must be strictly positive. Default to 1.0.\n\n top_k: (`optional`) int\n The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.\n\n top_p: (`optional`) float\n The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.\n\n repetition_penalty: (`optional`) float\n The parameter for repetition penalty. Between 1.0 and infinity. 1.0 means no penalty. Default to 1.0.\n\n pad_token_id: (`optional`) int\n Padding token. Default to specicic model pad_token_id or None if it does not exist.\n\n bos_token_id: (`optional`) int\n BOS token. Defaults to `bos_token_id` as defined in the models config.\n\n eos_token_id: (`optional`) int\n EOS token. Defaults to `eos_token_id` as defined in the models config.\n\n length_penalty: (`optional`) float\n Exponential penalty to the length. Default to 1.\n\n no_repeat_ngram_size: (`optional`) int\n If set to int > 0, all ngrams of size `no_repeat_ngram_size` can only occur once.\n bad_words_ids: (`optional`) list of lists of int\n `bad_words_ids` contains tokens that are not allowed to be generated. In order to get the tokens of the words that should not appear in the generated text, use `tokenizer.encode(bad_word, add_prefix_space=True)`.\n\n num_return_sequences: (`optional`) int\n The number of independently computed returned sequences for each element in the batch. Default to 1.\n\n attention_mask (`optional`) obj: `torch.LongTensor` of same shape as `input_ids`\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n Defaults to `None`.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n\n decoder_start_token_id=None: (`optional`) int\n Start token id for the decoder. Defaults to ``decoder_start_token_id`` as defined the model's config or to the ``bos_token_id``\n if no ``decoder_start_token_id`` is found in the config.\n This is only relevant for encoder-decoder models.\n\n use_cache: (`optional`) bool\n If `use_cache` is True, past key values are used to speed up decoding if applicable to model. Defaults to `True`.\n\n model_specific_kwargs: (`optional`) dict\n Additional model specific kwargs will be forwarded to the `forward` function of the model.\n\n Return:\n\n output: `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`\n sequence_length is either equal to max_length or shorter if all batches finished early due to the `eos_token_id`\n\n Examples::\n\n from transformers import AutoTokenizer, AutoModelForCausalLM\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n outputs = model.generate(max_length=40) # do greedy decoding\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('openai-gpt') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('openai-gpt') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3, temperature=1.5) # generate 3 independent sequences using beam search decoding (5 beams) with sampling from initial context 'The dog'\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3, do_sample=True) # 3 generate sequences using by sampling\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('ctrl') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('ctrl') # Download model and configuration from S3 and cache.\n input_context = 'Legal My neighbor is' # \"Legal\" is one of the control codes for ctrl\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2) # generate sequences\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('gpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('gpt2') # Download model and configuration from S3 and cache.\n input_context = 'My cute dog' # \"Legal\" is one of the control codes for ctrl\n bad_words_ids = [tokenizer.encode(bad_word, add_prefix_space=True) for bad_word in ['idiot', 'stupid', 'shut up']]\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=100, do_sample=True, bad_words_ids=bad_words_ids) # generate sequences without allowing bad_words to be generated\n \"\"\"\n\n # We cannot generate if the model does not have a LM head\n if self.get_output_embeddings() is None:\n raise AttributeError(\n \"You tried to generate sequences with a model that does not have a LM Head.\"\n \"Please use another model class (e.g. `OpenAIGPTLMHeadModel`, `XLNetLMHeadModel`, `GPT2LMHeadModel`, `CTRLLMHeadModel`, `T5WithLMHeadModel`, `TransfoXLLMHeadModel`, `XLMWithLMHeadModel`, `BartForConditionalGeneration` )\"\n )\n\n max_length = max_length if max_length is not None else self.config.max_length\n min_length = min_length if min_length is not None else self.config.min_length\n do_sample = do_sample if do_sample is not None else self.config.do_sample\n early_stopping = early_stopping if early_stopping is not None else self.config.early_stopping\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n num_beams = num_beams if num_beams is not None else self.config.num_beams\n temperature = temperature if temperature is not None else self.config.temperature\n top_k = top_k if top_k is not None else self.config.top_k\n top_p = top_p if top_p is not None else self.config.top_p\n repetition_penalty = repetition_penalty if repetition_penalty is not None else self.config.repetition_penalty\n bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id\n pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n length_penalty = length_penalty if length_penalty is not None else self.config.length_penalty\n no_repeat_ngram_size = (\n no_repeat_ngram_size if no_repeat_ngram_size is not None else self.config.no_repeat_ngram_size\n )\n bad_words_ids = bad_words_ids if bad_words_ids is not None else self.config.bad_words_ids\n num_return_sequences = (\n num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences\n )\n decoder_start_token_id = (\n decoder_start_token_id if decoder_start_token_id is not None else self.config.decoder_start_token_id\n )\n\n if input_ids is not None:\n batch_size = input_ids.shape[0] # overriden by the input batch_size\n else:\n batch_size = 1\n\n assert isinstance(max_length, int) and max_length > 0, \"`max_length` should be a strictly positive integer.\"\n assert isinstance(min_length, int) and min_length >= 0, \"`min_length` should be a positive integer.\"\n assert isinstance(do_sample, bool), \"`do_sample` should be a boolean.\"\n assert isinstance(early_stopping, bool), \"`early_stopping` should be a boolean.\"\n assert isinstance(use_cache, bool), \"`use_cache` should be a boolean.\"\n assert isinstance(num_beams, int) and num_beams > 0, \"`num_beams` should be a strictly positive integer.\"\n assert temperature > 0, \"`temperature` should be strictly positive.\"\n assert isinstance(top_k, int) and top_k >= 0, \"`top_k` should be a positive integer.\"\n assert 0 <= top_p <= 1, \"`top_p` should be between 0 and 1.\"\n assert repetition_penalty >= 1.0, \"`repetition_penalty` should be >= 1.\"\n assert input_ids is not None or (\n isinstance(bos_token_id, int) and bos_token_id >= 0\n ), \"If input_ids is not defined, `bos_token_id` should be a positive integer.\"\n assert pad_token_id is None or (\n isinstance(pad_token_id, int) and (pad_token_id >= 0)\n ), \"`pad_token_id` should be a positive integer.\"\n assert (eos_token_id is None) or (\n isinstance(eos_token_id, int) and (eos_token_id >= 0)\n ), \"`eos_token_id` should be a positive integer.\"\n assert length_penalty > 0, \"`length_penalty` should be strictly positive.\"\n assert (\n isinstance(no_repeat_ngram_size, int) and no_repeat_ngram_size >= 0\n ), \"`no_repeat_ngram_size` should be a positive integer.\"\n assert (\n isinstance(num_return_sequences, int) and num_return_sequences > 0\n ), \"`num_return_sequences` should be a strictly positive integer.\"\n assert (\n bad_words_ids is None or isinstance(bad_words_ids, list) and isinstance(bad_words_ids[0], list)\n ), \"`bad_words_ids` is either `None` or a list of lists of tokens that should not be generated\"\n\n if input_ids is None:\n assert isinstance(bos_token_id, int) and bos_token_id >= 0, (\n \"you should either supply a context to complete as `input_ids` input \"\n \"or a `bos_token_id` (integer >= 0) as a first token to start the generation.\"\n )\n input_ids = torch.full(\n (batch_size, 1), bos_token_id, dtype=torch.long, device=next(self.parameters()).device,\n )\n else:\n assert input_ids.dim() == 2, \"Input prompt should be of shape (batch_size, sequence length).\"\n\n # not allow to duplicate outputs when greedy decoding\n if do_sample is False:\n if num_beams == 1:\n # no_beam_search greedy generation conditions\n assert (\n num_return_sequences == 1\n ), \"Greedy decoding will always produce the same output for num_beams == 1 and num_return_sequences > 1. Please set num_return_sequences = 1\"\n\n else:\n # beam_search greedy generation conditions\n assert (\n num_beams >= num_return_sequences\n ), \"Greedy beam search decoding cannot return more sequences than it has beams. Please set num_beams >= num_return_sequences\"\n\n # create attention mask if necessary\n # TODO (PVP): this should later be handled by the forward fn() in each model in the future see PR 3140\n if (attention_mask is None) and (pad_token_id is not None) and (pad_token_id in input_ids):\n attention_mask = input_ids.ne(pad_token_id).long()\n elif attention_mask is None:\n attention_mask = input_ids.new_ones(input_ids.shape)\n\n # set pad_token_id to eos_token_id if not set. Important that this is done after\n # attention_mask is created\n if pad_token_id is None and eos_token_id is not None:\n logger.warning(\n \"Setting `pad_token_id` to {} (first `eos_token_id`) to generate sequence\".format(eos_token_id)\n )\n pad_token_id = eos_token_id\n\n # current position and vocab size\n if hasattr(self.config, \"vocab_size\"):\n vocab_size = self.config.vocab_size\n elif (\n self.config.is_encoder_decoder\n and hasattr(self.config, \"decoder\")\n and hasattr(self.config.decoder, \"vocab_size\")\n ):\n vocab_size = self.config.decoder.vocab_size\n\n # set effective batch size and effective batch multiplier according to do_sample\n if do_sample:\n effective_batch_size = batch_size * num_return_sequences\n effective_batch_mult = num_return_sequences\n else:\n effective_batch_size = batch_size\n effective_batch_mult = 1\n\n if self.config.is_encoder_decoder:\n if decoder_start_token_id is None:\n decoder_start_token_id = bos_token_id\n\n assert (\n decoder_start_token_id is not None\n ), \"decoder_start_token_id or bos_token_id has to be defined for encoder-decoder generation\"\n assert hasattr(self, \"get_encoder\"), \"{} should have a 'get_encoder' function defined\".format(self)\n assert callable(self.get_encoder), \"{} should be a method\".format(self.get_encoder)\n\n # get encoder and store encoder outputs\n encoder = self.get_encoder()\n\n # add structural information when encoding\n encoder_outputs: tuple = encoder(input_ids, attention_mask=attention_mask, input_node_ids=input_node_ids,\n node_length=node_length, adj_matrix=adj_matrix)\n\n # Expand input ids if num_beams > 1 or num_return_sequences > 1\n if num_return_sequences > 1 or num_beams > 1:\n input_ids_len = input_ids.shape[-1]\n input_ids = input_ids.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)\n attention_mask = attention_mask.unsqueeze(1).expand(\n batch_size, effective_batch_mult * num_beams, input_ids_len\n )\n\n input_ids = input_ids.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n attention_mask = attention_mask.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n\n if self.config.is_encoder_decoder:\n # create empty decoder_input_ids\n input_ids = torch.full(\n (effective_batch_size * num_beams, 1),\n decoder_start_token_id,\n dtype=torch.long,\n device=next(self.parameters()).device,\n )\n cur_len = 1\n\n assert (\n batch_size == encoder_outputs[0].shape[0]\n ), f\"expected encoder_outputs[0] to have 1st dimension bs={batch_size}, got {encoder_outputs[0].shape[0]} \"\n\n # expand batch_idx to assign correct encoder output for expanded input_ids (due to num_beams > 1 and num_return_sequences > 1)\n expanded_batch_idxs = (\n torch.arange(batch_size)\n .view(-1, 1)\n .repeat(1, num_beams * effective_batch_mult)\n .view(-1)\n .to(input_ids.device)\n )\n # expand encoder_outputs\n encoder_outputs = (encoder_outputs[0].index_select(0, expanded_batch_idxs), *encoder_outputs[1:])\n\n else:\n encoder_outputs = None\n cur_len = input_ids.shape[-1]\n\n if num_beams > 1:\n output = self._generate_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n early_stopping=early_stopping,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n num_return_sequences=num_return_sequences,\n length_penalty=length_penalty,\n num_beams=num_beams,\n vocab_size=vocab_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n else:\n output = self._generate_no_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n\n return output\n\nGAP/modeling_gap_type.py\nclass GAPBartForConditionalGeneration(BartForConditionalGeneration):\n def __init__(self, config, **kwargs):\n super().__init__(config)\n base_model = GAPBartModel(config,**kwargs)\n self.model = base_model\n self.register_buffer(\"final_logits_bias\", torch.zeros((1, self.model.shared.num_embeddings)))\n \n def forward(self, input_ids, attention_mask=None, encoder_outputs=None,\n decoder_input_ids=None, decoder_attention_mask=None, input_node_ids=None,\n node_length=None, adj_matrix=None, decoder_whole_ids=None, decoder_cached_states=None,\n use_cache=False, is_training=False):\n\n if is_training:\n _decoder_input_ids = shift_tokens_right(decoder_input_ids, self.config.pad_token_id)\n else:\n _decoder_input_ids = decoder_input_ids\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n encoder_outputs=encoder_outputs,\n decoder_input_ids=_decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n input_node_ids=input_node_ids,\n node_length=node_length,\n adj_matrix=adj_matrix,\n decoder_cached_states=decoder_cached_states,\n use_cache=use_cache,\n )\n lm_logits = F.linear(outputs[0], self.model.shared.weight, bias=self.final_logits_bias)\n if is_training:\n loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)\n loss = loss_fct(lm_logits.view(-1, self.config.vocab_size),\n decoder_input_ids.view(-1))\n return loss\n return (lm_logits, ) + outputs[1:]\n\n @torch.no_grad()\n def generate(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n max_length: Optional[int] = None,\n min_length: Optional[int] = None,\n do_sample: Optional[bool] = None,\n early_stopping: Optional[bool] = None,\n num_beams: Optional[int] = None,\n temperature: Optional[float] = None,\n top_k: Optional[int] = None,\n top_p: Optional[float] = None,\n repetition_penalty: Optional[float] = None,\n bad_words_ids: Optional[Iterable[int]] = None,\n bos_token_id: Optional[int] = None,\n pad_token_id: Optional[int] = None,\n eos_token_id: Optional[int] = None,\n length_penalty: Optional[float] = None,\n no_repeat_ngram_size: Optional[int] = None,\n num_return_sequences: Optional[int] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n input_node_ids=None,\n node_length=None,\n adj_matrix=None,\n decoder_start_token_id: Optional[int] = None,\n use_cache: Optional[bool] = None,\n **model_specific_kwargs\n ) -> torch.LongTensor:\n r\"\"\" Generates sequences for models with a LM head. The method currently supports greedy decoding, beam-search decoding, sampling with temperature, sampling with top-k or nucleus sampling.\n\n Adapted in part from `Facebook's XLM beam search code`_.\n\n .. _`Facebook's XLM beam search code`:\n https://github.com/facebookresearch/XLM/blob/9e6f6814d17be4fe5b15f2e6c43eb2b2d76daeb4/src/model/transformer.py#L529\n\n\n Parameters:\n\n input_ids: (`optional`) `torch.LongTensor` of shape `(batch_size, sequence_length)`\n The sequence used as a prompt for the generation. If `None` the method initializes\n it as an empty `torch.LongTensor` of shape `(1,)`.\n\n max_length: (`optional`) int\n The max length of the sequence to be generated. Between `min_length` and infinity. Default to 20.\n\n min_length: (`optional`) int\n The min length of the sequence to be generated. Between 0 and infinity. Default to 0.\n\n do_sample: (`optional`) bool\n If set to `False` greedy decoding is used. Otherwise sampling is used. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n early_stopping: (`optional`) bool\n if set to `True` beam search is stopped when at least `num_beams` sentences finished per batch. Defaults to `False` as defined in `configuration_utils.PretrainedConfig`.\n\n num_beams: (`optional`) int\n Number of beams for beam search. Must be between 1 and infinity. 1 means no beam search. Default to 1.\n\n temperature: (`optional`) float\n The value used to module the next token probabilities. Must be strictly positive. Default to 1.0.\n\n top_k: (`optional`) int\n The number of highest probability vocabulary tokens to keep for top-k-filtering. Between 1 and infinity. Default to 50.\n\n top_p: (`optional`) float\n The cumulative probability of parameter highest probability vocabulary tokens to keep for nucleus sampling. Must be between 0 and 1. Default to 1.\n\n repetition_penalty: (`optional`) float\n The parameter for repetition penalty. Between 1.0 and infinity. 1.0 means no penalty. Default to 1.0.\n\n pad_token_id: (`optional`) int\n Padding token. Default to specicic model pad_token_id or None if it does not exist.\n\n bos_token_id: (`optional`) int\n BOS token. Defaults to `bos_token_id` as defined in the models config.\n\n eos_token_id: (`optional`) int\n EOS token. Defaults to `eos_token_id` as defined in the models config.\n\n length_penalty: (`optional`) float\n Exponential penalty to the length. Default to 1.\n\n no_repeat_ngram_size: (`optional`) int\n If set to int > 0, all ngrams of size `no_repeat_ngram_size` can only occur once.\n bad_words_ids: (`optional`) list of lists of int\n `bad_words_ids` contains tokens that are not allowed to be generated. In order to get the tokens of the words that should not appear in the generated text, use `tokenizer.encode(bad_word, add_prefix_space=True)`.\n\n num_return_sequences: (`optional`) int\n The number of independently computed returned sequences for each element in the batch. Default to 1.\n\n attention_mask (`optional`) obj: `torch.LongTensor` of same shape as `input_ids`\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n Defaults to `None`.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n\n decoder_start_token_id=None: (`optional`) int\n Start token id for the decoder. Defaults to ``decoder_start_token_id`` as defined the model's config or to the ``bos_token_id``\n if no ``decoder_start_token_id`` is found in the config.\n This is only relevant for encoder-decoder models.\n\n use_cache: (`optional`) bool\n If `use_cache` is True, past key values are used to speed up decoding if applicable to model. Defaults to `True`.\n\n model_specific_kwargs: (`optional`) dict\n Additional model specific kwargs will be forwarded to the `forward` function of the model.\n\n Return:\n\n output: `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`\n sequence_length is either equal to max_length or shorter if all batches finished early due to the `eos_token_id`\n\n Examples::\n\n from transformers import AutoTokenizer, AutoModelForCausalLM\n\n tokenizer = AutoTokenizer. ('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n outputs = model.generate(max_length=40) # do greedy decoding\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('openai-gpt') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('openai-gpt') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3, temperature=1.5) # generate 3 independent sequences using beam search decoding (5 beams) with sampling from initial context 'The dog'\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('distilgpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('distilgpt2') # Download model and configuration from S3 and cache.\n input_context = 'The dog'\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=40, temperature=0.7, num_return_sequences=3, do_sample=True) # 3 generate sequences using by sampling\n for i in range(3): # 3 output sequences were generated\n print('Generated {}: {}'.format(i, tokenizer.decode(outputs[i], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('ctrl') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('ctrl') # Download model and configuration from S3 and cache.\n input_context = 'Legal My neighbor is' # \"Legal\" is one of the control codes for ctrl\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2) # generate sequences\n print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))\n\n tokenizer = AutoTokenizer.from_pretrained('gpt2') # Initialize tokenizer\n model = AutoModelForCausalLM.from_pretrained('gpt2') # Download model and configuration from S3 and cache.\n input_context = 'My cute dog' # \"Legal\" is one of the control codes for ctrl\n bad_words_ids = [tokenizer.encode(bad_word, add_prefix_space=True) for bad_word in ['idiot', 'stupid', 'shut up']]\n input_ids = tokenizer.encode(input_context, return_tensors='pt') # encode input context\n outputs = model.generate(input_ids=input_ids, max_length=100, do_sample=True, bad_words_ids=bad_words_ids) # generate sequences without allowing bad_words to be generated\n \"\"\"\n\n # We cannot generate if the model does not have a LM head\n if self.get_output_embeddings() is None:\n raise AttributeError(\n \"You tried to generate sequences with a model that does not have a LM Head.\"\n \"Please use another model class (e.g. `OpenAIGPTLMHeadModel`, `XLNetLMHeadModel`, `GPT2LMHeadModel`, `CTRLLMHeadModel`, `T5WithLMHeadModel`, `TransfoXLLMHeadModel`, `XLMWithLMHeadModel`, `BartForConditionalGeneration` )\"\n )\n\n max_length = max_length if max_length is not None else self.config.max_length\n min_length = min_length if min_length is not None else self.config.min_length\n do_sample = do_sample if do_sample is not None else self.config.do_sample\n early_stopping = early_stopping if early_stopping is not None else self.config.early_stopping\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n num_beams = num_beams if num_beams is not None else self.config.num_beams\n temperature = temperature if temperature is not None else self.config.temperature\n top_k = top_k if top_k is not None else self.config.top_k\n top_p = top_p if top_p is not None else self.config.top_p\n repetition_penalty = repetition_penalty if repetition_penalty is not None else self.config.repetition_penalty\n bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id\n pad_token_id = pad_token_id if pad_token_id is not None else self.config.pad_token_id\n eos_token_id = eos_token_id if eos_token_id is not None else self.config.eos_token_id\n length_penalty = length_penalty if length_penalty is not None else self.config.length_penalty\n no_repeat_ngram_size = (\n no_repeat_ngram_size if no_repeat_ngram_size is not None else self.config.no_repeat_ngram_size\n )\n bad_words_ids = bad_words_ids if bad_words_ids is not None else self.config.bad_words_ids\n num_return_sequences = (\n num_return_sequences if num_return_sequences is not None else self.config.num_return_sequences\n )\n decoder_start_token_id = (\n decoder_start_token_id if decoder_start_token_id is not None else self.config.decoder_start_token_id\n )\n\n if input_ids is not None:\n batch_size = input_ids.shape[0] # overriden by the input batch_size\n else:\n batch_size = 1\n\n assert isinstance(max_length, int) and max_length > 0, \"`max_length` should be a strictly positive integer.\"\n assert isinstance(min_length, int) and min_length >= 0, \"`min_length` should be a positive integer.\"\n assert isinstance(do_sample, bool), \"`do_sample` should be a boolean.\"\n assert isinstance(early_stopping, bool), \"`early_stopping` should be a boolean.\"\n assert isinstance(use_cache, bool), \"`use_cache` should be a boolean.\"\n assert isinstance(num_beams, int) and num_beams > 0, \"`num_beams` should be a strictly positive integer.\"\n assert temperature > 0, \"`temperature` should be strictly positive.\"\n assert isinstance(top_k, int) and top_k >= 0, \"`top_k` should be a positive integer.\"\n assert 0 <= top_p <= 1, \"`top_p` should be between 0 and 1.\"\n assert repetition_penalty >= 1.0, \"`repetition_penalty` should be >= 1.\"\n assert input_ids is not None or (\n isinstance(bos_token_id, int) and bos_token_id >= 0\n ), \"If input_ids is not defined, `bos_token_id` should be a positive integer.\"\n assert pad_token_id is None or (\n isinstance(pad_token_id, int) and (pad_token_id >= 0)\n ), \"`pad_token_id` should be a positive integer.\"\n assert (eos_token_id is None) or (\n isinstance(eos_token_id, int) and (eos_token_id >= 0)\n ), \"`eos_token_id` should be a positive integer.\"\n assert length_penalty > 0, \"`length_penalty` should be strictly positive.\"\n assert (\n isinstance(no_repeat_ngram_size, int) and no_repeat_ngram_size >= 0\n ), \"`no_repeat_ngram_size` should be a positive integer.\"\n assert (\n isinstance(num_return_sequences, int) and num_return_sequences > 0\n ), \"`num_return_sequences` should be a strictly positive integer.\"\n assert (\n bad_words_ids is None or isinstance(bad_words_ids, list) and isinstance(bad_words_ids[0], list)\n ), \"`bad_words_ids` is either `None` or a list of lists of tokens that should not be generated\"\n\n if input_ids is None:\n assert isinstance(bos_token_id, int) and bos_token_id >= 0, (\n \"you should either supply a context to complete as `input_ids` input \"\n \"or a `bos_token_id` (integer >= 0) as a first token to start the generation.\"\n )\n input_ids = torch.full(\n (batch_size, 1), bos_token_id, dtype=torch.long, device=next(self.parameters()).device,\n )\n else:\n assert input_ids.dim() == 2, \"Input prompt should be of shape (batch_size, sequence length).\"\n\n # not allow to duplicate outputs when greedy decoding\n if do_sample is False:\n if num_beams == 1:\n # no_beam_search greedy generation conditions\n assert (\n num_return_sequences == 1\n ), \"Greedy decoding will always produce the same output for num_beams == 1 and num_return_sequences > 1. Please set num_return_sequences = 1\"\n\n else:\n # beam_search greedy generation conditions\n assert (\n num_beams >= num_return_sequences\n ), \"Greedy beam search decoding cannot return more sequences than it has beams. Please set num_beams >= num_return_sequences\"\n\n # create attention mask if necessary\n # TODO (PVP): this should later be handled by the forward fn() in each model in the future see PR 3140\n if (attention_mask is None) and (pad_token_id is not None) and (pad_token_id in input_ids):\n attention_mask = input_ids.ne(pad_token_id).long()\n elif attention_mask is None:\n attention_mask = input_ids.new_ones(input_ids.shape)\n\n # set pad_token_id to eos_token_id if not set. Important that this is done after\n # attention_mask is created\n if pad_token_id is None and eos_token_id is not None:\n logger.warning(\n \"Setting `pad_token_id` to {} (first `eos_token_id`) to generate sequence\".format(eos_token_id)\n )\n pad_token_id = eos_token_id\n\n # current position and vocab size\n if hasattr(self.config, \"vocab_size\"):\n vocab_size = self.config.vocab_size\n elif (\n self.config.is_encoder_decoder\n and hasattr(self.config, \"decoder\")\n and hasattr(self.config.decoder, \"vocab_size\")\n ):\n vocab_size = self.config.decoder.vocab_size\n\n # set effective batch size and effective batch multiplier according to do_sample\n if do_sample:\n effective_batch_size = batch_size * num_return_sequences\n effective_batch_mult = num_return_sequences\n else:\n effective_batch_size = batch_size\n effective_batch_mult = 1\n\n if self.config.is_encoder_decoder:\n if decoder_start_token_id is None:\n decoder_start_token_id = bos_token_id\n\n assert (\n decoder_start_token_id is not None\n ), \"decoder_start_token_id or bos_token_id has to be defined for encoder-decoder generation\"\n assert hasattr(self, \"get_encoder\"), \"{} should have a 'get_encoder' function defined\".format(self)\n assert callable(self.get_encoder), \"{} should be a method\".format(self.get_encoder)\n\n # get encoder and store encoder outputs\n encoder = self.get_encoder()\n\n # add structural information when encoding\n encoder_outputs: tuple = encoder(input_ids, attention_mask=attention_mask, input_node_ids=input_node_ids,\n node_length=node_length, adj_matrix=adj_matrix)\n\n # Expand input ids if num_beams > 1 or num_return_sequences > 1\n if num_return_sequences > 1 or num_beams > 1:\n input_ids_len = input_ids.shape[-1]\n input_ids = input_ids.unsqueeze(1).expand(batch_size, effective_batch_mult * num_beams, input_ids_len)\n attention_mask = attention_mask.unsqueeze(1).expand(\n batch_size, effective_batch_mult * num_beams, input_ids_len\n )\n\n input_ids = input_ids.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n attention_mask = attention_mask.contiguous().view(\n effective_batch_size * num_beams, input_ids_len\n ) # shape: (batch_size * num_return_sequences * num_beams, cur_len)\n\n if self.config.is_encoder_decoder:\n # create empty decoder_input_ids\n input_ids = torch.full(\n (effective_batch_size * num_beams, 1),\n decoder_start_token_id,\n dtype=torch.long,\n device=next(self.parameters()).device,\n )\n cur_len = 1\n\n assert (\n batch_size == encoder_outputs[0].shape[0]\n ), f\"expected encoder_outputs[0] to have 1st dimension bs={batch_size}, got {encoder_outputs[0].shape[0]} \"\n\n # expand batch_idx to assign correct encoder output for expanded input_ids (due to num_beams > 1 and num_return_sequences > 1)\n expanded_batch_idxs = (\n torch.arange(batch_size)\n .view(-1, 1)\n .repeat(1, num_beams * effective_batch_mult)\n .view(-1)\n .to(input_ids.device)\n )\n # expand encoder_outputs\n encoder_outputs = (encoder_outputs[0].index_select(0, expanded_batch_idxs), *encoder_outputs[1:])\n\n else:\n encoder_outputs = None\n cur_len = input_ids.shape[-1]\n\n if num_beams > 1:\n output = self._generate_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n early_stopping=early_stopping,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n num_return_sequences=num_return_sequences,\n length_penalty=length_penalty,\n num_beams=num_beams,\n vocab_size=vocab_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n else:\n output = self._generate_no_beam_search(\n input_ids,\n cur_len=cur_len,\n max_length=max_length,\n min_length=min_length,\n do_sample=do_sample,\n temperature=temperature,\n top_k=top_k,\n top_p=top_p,\n repetition_penalty=repetition_penalty,\n no_repeat_ngram_size=no_repeat_ngram_size,\n bad_words_ids=bad_words_ids,\n pad_token_id=pad_token_id,\n eos_token_id=eos_token_id,\n batch_size=effective_batch_size,\n encoder_outputs=encoder_outputs,\n attention_mask=attention_mask,\n use_cache=use_cache,\n model_specific_kwargs=model_specific_kwargs,\n )\n\n return output", "answers": [" model = T5.from_pretrained(checkpoint)\r"], "length": 5471, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "9706a209-b354-44fa-a959-a3d5a43ffd17", "reasoning": "The function run() is loading a model based on args. After handling type_encoding, the else branch checks if the model path contains 't5'. The next step is to instantiate the appropriate model class. Since T5 is imported as T5ForConditionalGeneration alias T5, the next line should load a T5 model from the checkpoint.", "reasoning_model_answer": "model = T5.from_pretrained(checkpoint)", "assistant_with_reasoning": "\nThe function run() is loading a model based on args. After handling type_encoding, the else branch checks if the model path contains 't5'. The next step is to instantiate the appropriate model class. Since T5 is imported as T5ForConditionalGeneration alias T5, the next line should load a T5 model from the checkpoint.\n\nmodel = T5.from_pretrained(checkpoint)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.855, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37085, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "model = T5.from_pretrained(checkpoint)", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "from typing import Dict\nfrom typing import Type\nfrom tasks.affect import ActivityAnalysis\nfrom tasks.affect import ActivityGet\nfrom tasks.affect import SleepAnalysis\nfrom tasks.affect import SleepGet\nfrom tasks.ask_user import AskUser\nfrom tasks.google_translator import GoogleTranslate\nfrom tasks.playwright import Click\nfrom tasks.playwright import CurrentWebPage\nfrom tasks.playwright import ExtractHyperlinks\nfrom tasks.playwright import ExtractText\nfrom tasks.playwright import GetElements\nfrom tasks.playwright import Navigate\nfrom tasks.playwright import NavigateBack\nfrom tasks.read_from_datapipe import ReadDataPipe\nfrom tasks.serpapi import SerpAPI\nfrom tasks.task import BaseTask\nfrom tasks.task_types import TaskType\nfrom tasks.test_file import TestFile", "context": "tasks/types.py\n\n\n\nTASK_TO_CLASS: Dict[TaskType, Type[BaseTask]] = {\n TaskType.SERPAPI: SerpAPI,\n TaskType.CLICK: Click,\n TaskType.GET_CURRENT_PAGE: CurrentWebPage,\n TaskType.EXTRACT_HYPERLINKS: ExtractHyperlinks,\n TaskType.EXTRACT_TEXT: ExtractText,\n TaskType.GET_ELEMENTS: GetElements,\n TaskType.NAVIGATE_BACK: NavigateBack,\n TaskType.NAVIGATE: Navigate,\n TaskType.AFFECT_SLEEP_GET: SleepGet,\n TaskType.AFFECT_ACTIVITY_GET: ActivityGet,\n TaskType.AFFECT_SLEEP_ANALYSIS: SleepAnalysis,\n TaskType.AFFECT_ACTIVITY_ANALYSIS: ActivityAnalysis,\n\n\ntasks/playwright/extract_hyperlinks.py\nclass ExtractHyperlinks(BaseBrowser):\n \"\"\"\n **Description:**\n\n This task extracts all hyperlinks from the current webpage.\n \"\"\"\n\n name: str = \"extract_hyperlinks\"\n chat_name: str = \"ExtractHyperLinks\"\n description: str = \"Extract all hyperlinks on the current webpage\"\n dependencies: List[str] = []\n inputs: List[str] = [\n \"Boolean: True/False. Return absolute URLs instead of relative URLs.\"\n ]\n outputs: List[str] = []\n output_type: bool = False\n\n @model_validator(mode=\"before\")\n def check_bs_import(cls, values: dict) -> dict:\n \"\"\"\n Check that the arguments are valid.\n\n Args:\n values (Dict): The current attribute values.\n Return:\n Dict: The updated attribute values.\n Raise:\n ImportError: If 'beautifulsoup4' package is not installed.\n\n \"\"\"\n\n try:\n from bs4 import BeautifulSoup # noqa: F401\n except ImportError:\n raise ImportError(\n \"The 'beautifulsoup4' package is required to use this tool.\"\n \" Please install it with 'pip install beautifulsoup4'.\"\n )\n return values\n\n @staticmethod\n def scrape_page(\n page: Any, html_content: str, absolute_urls: bool\n ) -> str:\n \"\"\"\n Scrape hyperlinks from the current webpage.\n\n Args:\n page (Any): The current webpage.\n html_content (str): The HTML content of the webpage.\n absolute_urls (bool): True if absolute URLs should be returned, False otherwise.\n Return:\n str: JSON string containing the extracted hyperlinks.\n\n\n \"\"\"\n\n from urllib.parse import urljoin\n from bs4 import BeautifulSoup\n\n # Parse the HTML content with BeautifulSoup\n soup = BeautifulSoup(html_content, \"lxml\")\n\n # Find all the anchor elements and extract their href attributes\n anchors = soup.find_all(\"a\")\n if absolute_urls:\n base_url = page.url\n links = [\n urljoin(base_url, anchor.get(\"href\", \"\"))\n for anchor in anchors\n ]\n else:\n links = [anchor.get(\"href\", \"\") for anchor in anchors]\n # Return the list of links as a JSON string\n return json.dumps(links)\n\n def _execute(\n self,\n inputs: List[Any],\n ) -> str:\n \"\"\"\n Execute the ExtractHyperlinks task.\n\n Args:\n input (str): The input parameter for the task.\n Return:\n str: JSON string containing the extracted hyperlinks.\n Raise:\n ValueError: If the synchronous browser is not provided.\n\n \"\"\"\n if self.sync_browser is None:\n raise ValueError(\n f\"Synchronous browser not provided to {self.name}\"\n )\n page = get_current_page(self.sync_browser)\n html_content = page.content()\n return self.scrape_page(page, html_content, inputs[0])\n\n def explain(\n self,\n ) -> str:\n \"\"\"\n Provide a brief explanation of the ExtractHyperlinks task.\n\n Return:\n str: An explanation of the task.\n\n\n \"\"\"\n\n return \"This task extracts all of the hyperlinks.\"\n\ntasks/affect/sleep_analysis.py\nclass SleepAnalysis(Affect):\n \"\"\"\n **Description:**\n\n This tasks performs average, sum, or trend analysis on the provided raw sleep affect data for specific patient.\n \"\"\"\n\n name: str = \"affect_sleep_analysis\"\n chat_name: str = \"AffectSleepAnalysis\"\n description: str = (\n \"Performs trend or average analysis on the provided sleep data. You must Call this whenever sleep trend or average is needed.\"\n \"For example, if the user asks for trends (or variations) in data, you must call this task\"\n )\n dependencies: List[str] = [\"affect_sleep_get\"]\n inputs: List[str] = [\n \"datapipe key to the data\",\n \"analysis_type. It can be one of [average, trend].\",\n ]\n outputs: List[str] = [\n (\n \"The analysis result for total_sleep_time. Look for analysis_type to find the type of analysis. \"\n \"total_sleep_time (in minutes) is Total amount of sleep (a.k.a. sleep duration) registered during the sleep period.\"\n ),\n (\n \"The analysis result for awake_duration. Look for analysis_type to find the type of analysis. \"\n \"awake_duration (in minutes) is the total amount of awake time registered during the sleep period.\"\n ),\n (\n \"The analysis result for light_sleep_duration. Look for analysis_type to find the type of analysis. \"\n \"light_sleep_duration (in minutes) is the total amount of light (N1 or N2) sleep registered during the sleep period.\"\n ),\n (\n \"The analysis result for rem_sleep_duration. Look for analysis_type to find the type of analysis. \"\n \"rem_sleep_duration (in minutes) is the total amount of REM sleep registered during the sleep period.\"\n ),\n (\n \"The analysis result for deep_sleep_duration. Look for analysis_type to find the type of analysis. \"\n \"deep_sleep_duration (in minutes) is the total amount of deep (N3) sleep registered during the sleep period.\"\n ),\n (\n \"The analysis result for sleep_onset_latency. Look for analysis_type to find the type of analysis. sleep_onset_latency (in minutes) \"\n \"is the detected latency from bedtime_start to the beginning of the first five minutes of persistent sleep.\"\n ),\n (\n \"The analysis result for midpoint_time_of_sleep. Look for analysis_type to find the type of analysis. \"\n \"midpoint_time_of_sleep (in minutes) is the time from the start of sleep to the midpoint of sleep. The midpoint ignores awake periods.\"\n ),\n (\n \"The analysis result for sleep_efficiency. Look for analysis_type to find the type of analysis. \"\n \"sleep_efficiency is the percentage of the sleep period spent asleep (100% * sleep duration / time in bed).\"\n ),\n (\n \"The analysis result for average_heart_rate. Look for analysis_type to find the type of analysis. \"\n \"average_heart_rate is the average heart rate registered during the sleep period.\"\n ),\n (\n \"The analysis result for minimum_heart_rate. Look for analysis_type to find the type of analysis. \"\n \"minimum_heart_rate is the lowest heart rate (5 minutes sliding average) registered during the sleep period.\"\n ),\n (\n \"The analysis result for rmssd. Look for analysis_type to find the type of analysis. \"\n \"rmssd is the average Root Mean Square of Successive Differences (RMSSD) registered during the sleep period.\"\n ),\n (\n \"The analysis result for average_breathing_rate. Look for analysis_type to find the type of analysis. \"\n \"average_breathing_rate is the average breathing rate registered during the sleep period.\"\n ),\n (\n \"The analysis result for temperature_variation. Look for analysis_type to find the type of analysis. \"\n \"temperature_variation is the skin temperature deviation from the long-term temperature average.\"\n ),\n ]\n # False if the output should directly passed back to the planner.\n # True if it should be stored in datapipe\n output_type: bool = True\n\n def _execute(\n self,\n inputs: List[Any],\n ) -> str:\n df = pd.read_json(\n StringIO(inputs[0][\"data\"].strip()), orient=\"records\"\n )\n analysis_type = inputs[1].strip()\n if analysis_type == \"average\":\n df = df.drop(\"date\", axis=1) # No average for date!\n df = df.mean().to_frame().T\n elif analysis_type == \"trend\":\n df = self._calculate_slope(df)\n else:\n raise ValueError(\n \"The input analysis type has not been defined!\"\n )\n df = df.round(2)\n json_out = df.to_json(orient=\"records\")\n return json_out\n\ntasks/google_translator.py\nclass GoogleTranslate(BaseTask):\n \"\"\"\n **Description:**\n\n This task uses google translate to autmatically convert from the user language to english or vise versa.\n\n \"\"\"\n\n name: str = \"google_translator\"\n chat_name: str = \"GoogleTranslator\"\n description: str = (\n \"Translates queries between different languages.\"\n )\n dependencies: List[str] = []\n inputs: List[str] = [\n \"text to be translated\",\n \"destination language\",\n ]\n outputs: List[str] = []\n output_type: bool = False\n\n translator: Any = None #: :meta private:\n\n @model_validator(mode=\"before\")\n def validate_environment(cls, values: Dict) -> Dict:\n \"\"\"\n Validate that api key and python package exists in environment.\n\n Args:\n cls (object): The class itself.\n values (Dict): The dictionary containing the values for validation.\n Return:\n Dict:The original values.\n Raise:\n ImportError: If the 'playwright' package is not installed.\n\n\n \"\"\"\n\n try:\n from googletrans import Translator\n\n values[\"translator\"] = Translator()\n except ImportError:\n raise ValueError(\n \"Could not import googletrans python package. \"\n \"Please install it with `pip install googletrans-py`.\"\n )\n return values\n\n def _parse_input(\n self,\n input_args: str,\n ) -> List[str]:\n \"\"\"\n Parse the input string into a list of strings.\n\n Args:\n input (str): Input string to be parsed.\n Return:\n List[str]: List of parsed strings.\n\n \"\"\"\n return input_args.split(\"$#\")\n\n def _execute(\n self,\n inputs: List[Any] = None,\n ) -> str:\n \"\"\"\n Abstract method representing the execution of the task.\n\n Args:\n input (str): Input data for the task.\n Return:\n str: Result of the task execution.\n Raise:\n NotImplementedError: Subclasses must implement the execute method.\n\n \"\"\"\n if len(inputs) < 2:\n return \"\", \"\"\n dest = inputs[1] if inputs[1] is not None else \"en\"\n result = self.translator.translate(inputs[0], dest=dest)\n return result.text, result.src\n\n def explain(\n self,\n ) -> str:\n \"\"\"\n Provide a sample explanation for the task.\n\n Return:\n str: Sample explanation for the task.\n\n \"\"\"\n\n return \"This task uses google translate to translate between languages\"\n\ntasks/serpapi.py\nclass SerpAPI(BaseTask):\n \"\"\"\n **Description:**\n\n This code defines a class named SerpAPI, which is a specific implementation of the abstract BaseTask class.\n The SerpAPI class represents a task that utilizes the SerpAPI (Google Search API) to perform internet searches\n and retrieve relevant information.\n\n \"\"\"\n\n name: str = \"serpapi\"\n chat_name: str = \"InternetSearchSerp\"\n description: str = (\n \"A low-cost Google Search API.\"\n \"Useful for when you need to answer questions about current events.\"\n )\n dependencies: List[str] = []\n inputs: List[str] = [\"It should be a search query.\"]\n outputs: List[str] = []\n output_type: bool = False\n\n search_engine: Any = None #: :meta private:\n params: Dict = Field(\n default={\n \"engine\": \"google\",\n \"google_domain\": \"google.com\",\n \"gl\": \"us\",\n \"hl\": \"en\",\n }\n )\n serpapi_api_key: Optional[str] = None\n aiosession: Optional[aiohttp.ClientSession] = None\n\n @model_validator(mode=\"before\")\n def validate_environment(cls, values: Dict) -> Dict:\n \"\"\"\n Validate that api key and python package exists in environment.\n\n Args:\n values (Dict): The dictionary of attribute values.\n Return:\n Dict: The updated dictionary of attribute values.\n Raise:\n ValueError: If the SerpAPI python package is not installed.\n\n \"\"\"\n\n serpapi_api_key = get_from_dict_or_env(\n values, \"serpapi_api_key\", \"SERPAPI_API_KEY\"\n )\n values[\"serpapi_api_key\"] = serpapi_api_key\n try:\n from serpapi import GoogleSearch\n\n values[\"search_engine\"] = GoogleSearch\n except ImportError:\n raise ValueError(\n \"Could not import serpapi python package. \"\n \"Please install it with `pip install google-search-results`.\"\n )\n return values\n\n def get_params(self, query: str) -> Dict[str, str]:\n \"\"\"\n Get parameters for SerpAPI.\n\n Args:\n query (str): The search query.\n Return:\n Dict[str, str]: The parameters for the SerpAPI.\n\n\n \"\"\"\n\n _params = {\n \"api_key\": self.serpapi_api_key,\n \"q\": query,\n }\n params = {**self.params, **_params}\n return params\n\n def results(self, query: str) -> Dict:\n \"\"\"\n Run query through SerpAPI and return the raw result.\n\n Args:\n query (str): The search query.\n Return:\n Dict: The raw result from the SerpAPI.\n\n\n \"\"\"\n\n params = self.get_params(query)\n search = self.search_engine(params)\n res = search.get_dict()\n return res\n\n @staticmethod\n def _process_response(res: Dict) -> str:\n \"\"\"\n Process response from SerpAPI.\n\n Args:\n res (Dict): The raw response from the SerpAPI.\n Return:\n str: Processed information from the SerpAPI response.\n\n \"\"\"\n\n try:\n if \"answer_box\" in res:\n toret = (\n \"url: \"\n + res[\"answer_box\"][\"link\"]\n + \"\\nmetadata: \"\n + res[\"answer_box\"][\"snippet\"]\n )\n else:\n toret = (\n \"url: \"\n + res[\"organic_results\"][0][\"link\"]\n + \"\\nmetadata: \"\n + res[\"organic_results\"][0][\"snippet\"]\n )\n except KeyError:\n return \"Could not get the proper response from the search. Try another search query.\"\n return toret\n\n def _execute(\n self,\n inputs: List[Any] = None,\n ) -> str:\n \"\"\"\n Run query through SerpAPI and parse result.\n\n Args:\n input (str): The input, which should be a search query.\n Return:\n str: The parsed result from the SerpAPI.\n\n\n \"\"\"\n if len(inputs) == 0:\n return \"\"\n return self._process_response(self.results(inputs[0]))\n\n def explain(\n self,\n ) -> str:\n \"\"\"\n Provide an explanation of the task.\n\n Return:\n str: Explanation of the SerpAPI task.\n\n \"\"\"\n\n return (\n \"This task searched in the internet using google search engine, returns the url\"\n \"and the first top result of the google search.\"\n )\n\ntasks/affect/sleep_get.py\nclass SleepGet(Affect):\r\n \"\"\"\r\n **Description:**\r\n\r\n This tasks gets sleep affect data for specific patient.\r\n \"\"\"\r\n\r\n name: str = \"affect_sleep_get\"\r\n chat_name: str = \"AffectSleepGet\"\r\n description: str = (\r\n \"Get the sleep parameters for a specific date or \"\r\n \"a period (if two dates are provided). \"\r\n \"You must Call $affect_sleep_analysis$ whenever sleep \"\r\n \"analysis (e.g., 'average' or 'trend') is needed. DON'T rely on your analysis\"\r\n )\r\n dependencies: List[str] = []\r\n inputs: List[str] = [\r\n \"user ID in string. It can be refered as user, patient, individual, etc. Start with 'par_' following with a number (e.g., 'par_1').\",\r\n \"start date of the sleep data in string with the following format: '%Y-%m-%d'\",\r\n (\r\n \"end date of the sleep data in string with the following format: '%Y-%m-%d'. \"\r\n \"If there is no end date, the value should be an empty string (i.e., '')\"\r\n ),\r\n ]\r\n outputs: List[str] = [\r\n \"total_sleep_time (in minutes) is Total amount of sleep (a.k.a. sleep duration) registered during the sleep period.\",\r\n \"awake_duration (in minutes) is the total amount of awake time registered during the sleep period.\",\r\n \"light_sleep_duration (in minutes) is the total amount of light (N1 or N2) sleep registered during the sleep period.\",\r\n \"rem_sleep_duration (in minutes) is the total amount of REM sleep registered during the sleep period.\",\r\n \"deep_sleep_duration (in minutes) is the total amount of deep (N3) sleep registered during the sleep period.\",\r\n \"sleep_onset_latency (in minutes) is detected latency from bedtime_start to the beginning of the first five minutes of persistent sleep.\",\r\n \"midpoint_time_of_sleep (in minutes) is the time from the start of sleep to the midpoint of sleep. The midpoint ignores awake periods.\",\r\n \"sleep_efficiency is the percentage of the sleep period spent asleep (100% * sleep duration / time in bed).\",\r\n \"average_heart_rate is the average heart rate registered during the sleep period.\",\r\n \"minimum_heart_rate is the lowest heart rate (5 minutes sliding average) registered during the sleep period.\",\r\n \"rmssd is the average Root Mean Square of Successive Differences (RMSSD) registered during the sleep period.\",\r\n \"average_breathing_rate is the average breathing rate registered during the sleep period.\",\r\n \"temperature_variation is the skin temperature deviation from the long-term temperature average.\",\r\n ]\r\n # False if the output should directly passed back to the planner.\r\n # True if it should be stored in datapipe\r\n output_type: bool = True\r\n #\r\n file_name: str = \"sleep.csv\"\r\n device_name: str = \"oura\"\r\n local_dir: str = \"data/affect\"\r\n columns_to_keep: List[str] = [\r\n \"date\",\r\n \"total\",\r\n \"awake\",\r\n \"light\",\r\n \"rem\",\r\n \"deep\",\r\n \"onset_latency\",\r\n \"midpoint_time\",\r\n \"efficiency\",\r\n \"hr_average\",\r\n \"hr_lowest\",\r\n \"rmssd\",\r\n \"breath_average\",\r\n \"temperature_delta\",\r\n ]\r\n columns_revised: List[str] = [\r\n \"date\",\r\n \"total_sleep_time\",\r\n \"awake_duration\",\r\n \"light_sleep_duration\",\r\n \"rem_sleep_duration\",\r\n \"deep_sleep_duration\",\r\n \"sleep_onset_latency\",\r\n \"midpoint_time_of_sleep\",\r\n \"sleep_efficiency\",\r\n \"average_heart_rate\",\r\n \"minimum_heart_rate\",\r\n \"rmssd\",\r\n \"average_breathing_rate\",\r\n \"temperature_variation\",\r\n ]\r\n variables_in_seconds: List[str] = [\r\n \"total_sleep_time\",\r\n \"awake_duration\",\r\n \"light_sleep_duration\",\r\n \"rem_sleep_duration\",\r\n \"deep_sleep_duration\",\r\n \"sleep_onset_latency\",\r\n \"midpoint_time_of_sleep\",\r\n ]\r\n\r\n def _execute(\r\n self,\r\n inputs: List[Any],\r\n ) -> str:\r\n user_id = inputs[0].strip()\r\n full_dir = os.path.join(\r\n self.local_dir, user_id, self.device_name\r\n )\r\n df = self._get_data(\r\n local_dir=full_dir,\r\n file_name=self.file_name,\r\n start_date=inputs[1].strip(),\r\n end_date=inputs[2].strip(),\r\n usecols=self.columns_to_keep,\r\n )\r\n df.columns = self.columns_revised\r\n df = self._convert_seconds_to_minutes(\r\n df, self.variables_in_seconds\r\n )\r\n df = df.round(2)\r\n json_out = df.to_json(orient=\"records\")\r\n return json_out\r\n\ntasks/affect/activity_get.py\nclass ActivityGet(Affect):\n \"\"\"\n **Description:**\n\n This tasks gets activity affect data for specific patient.\n \"\"\"\n\n name: str = \"affect_activity_get\"\n chat_name: str = \"AffectActivityGet\"\n description: str = (\n \"Get the physical activity parameters for a specific date or \"\n \"a period (if two dates are provided). \"\n \"You must Call $affect_analysis$ whenever physical activity \"\n \"analysis (e.g., 'average', 'sum', or 'trend') is needed. DON'T rely on your analysis\"\n )\n dependencies: List[str] = []\n inputs: List[str] = [\n \"user ID in string. It can be refered as user, patient, individual, etc. Start with 'par_' following with a number (e.g., 'par_1').\",\n \"start date of the physical activity data in string with the following format: '%Y-%m-%d'\",\n (\n \"end date of the physical activity data in string with the following format: '%Y-%m-%d'.\"\n \"If there is no end date, the value should be an empty string (i.e., '')\"\n ),\n ]\n outputs: List[str] = [\n \"steps_count is the total number of steps registered during the day.\",\n \"rest_time is the time (in minutes) during the day spent resting, i.e. sleeping or lying down.\",\n \"inactive_time is the time (in minutes) during the day spent resting, i.e. sitting or standing still.\",\n \"low_acitivity_time is the (in minutes) during the day with low intensity activity (e.g. household work).\",\n \"medimum_acitivity_time is the (in minutes) during the day with medium intensity activity (e.g. walking).\",\n \"high_acitivity_time is the (in minutes) during the day with high intensity activity (e.g. running).\",\n ]\n\n # False if the output should directly passed back to the planner.\n # True if it should be stored in datapipe\n output_type: bool = True\n #\n file_name: str = \"activity.csv\"\n device_name: str = \"oura\"\n local_dir: str = \"data/affect\"\n\n columns_to_keep: List[str] = [\n \"date\",\n \"steps\",\n \"rest\",\n \"inactive\",\n \"low\",\n \"medium\",\n \"high\",\n ]\n columns_revised: List[str] = [\n \"date\",\n \"steps_count\",\n \"rest_time\",\n \"inactive_time\",\n \"low_acitivity_time\",\n \"medimum_acitivity_time\",\n \"high_acitivity_time\",\n ]\n\n def _execute(\n self,\n inputs: List[Any] = None,\n ) -> str:\n user_id = inputs[0].strip()\n full_dir = os.path.join(\n self.local_dir, user_id, self.device_name\n )\n df = self._get_data(\n local_dir=full_dir,\n file_name=self.file_name,\n start_date=inputs[1].strip(),\n end_date=inputs[2].strip(),\n usecols=self.columns_to_keep,\n )\n df.columns = self.columns_revised\n df = df.round(2)\n json_out = df.to_json(orient=\"records\")\n return json_out\n\ntasks/test_file.py\nclass TestFile(BaseTask):\n name: str = \"test_file\"\n chat_name: str = \"TestFile\"\n description: str = \"analyzes the image and returns description.\"\n dependencies: List[str] = []\n inputs: List[str] = [\"the image file name\"]\n outputs: List[str] = []\n output_type: bool = False\n return_direct: bool = True\n\n translator: Any = None #: :meta private:\n\n def parse_input(\n self,\n input: str,\n ) -> List[str]:\n \"\"\"\n Parse the input string into a list of strings.\n\n Args:\n input (str): Input string to be parsed.\n Return:\n List[str]: List of parsed strings.\n\n\n\n Example:\n .. code-block:: python\n\n from langchain import ReActChain, OpenAI\n react = ReAct(llm=OpenAI())\n\n \"\"\"\n\n return input.split(\"$#\")\n\n def execute(\n self,\n input: str,\n ) -> str:\n \"\"\"\n Abstract method representing the execution of the task.\n\n Args:\n input (str): Input data for the task.\n Return:\n str: Result of the task execution.\n Raise:\n NotImplementedError: Subclasses must implement the execute method.\n\n\n\n Example:\n .. code-block:: python\n\n from langchain import ReActChain, OpenAI\n react = ReAct(llm=OpenAI())\n\n \"\"\"\n\n self.parse_input(input)\n return \"this image is a classification results of a data\"\n\n def explain(\n self,\n ) -> str:\n \"\"\"\n Provide a sample explanation for the task.\n\n Return:\n str: Sample explanation for the task.\n\n\n\n Example:\n .. code-block:: python\n\n from langchain import ReActChain, OpenAI\n react = ReAct(llm=OpenAI())\n\n \"\"\"\n\n return \"This task simply asks user to provide more information or continue interaction.\"\n\ntasks/read_from_datapipe.py\nclass ReadDataPipe(BaseTask):\n \"\"\"\n **Description:**\n\n This code reads raw data stored in datapipe. When different tasks are executed, there are situations that the final data is stored\n in the datapipe when the final called task's output_type=True. In these situations, this task is called to retireve the latest stored data\n to be used for final inference.\n \"\"\"\n\n name: str = \"read_from_datapipe\"\n chat_name: str = \"DataPipeReader\"\n description: str = (\n \"Get the stored information from datapipe to be used to answer user query accurately. \"\n \"This should be called when the final answer is in datapipe.\"\n )\n dependencies: List[str] = []\n inputs: List[str] = [\n \"the datapipe key in the format $datapipe:key$\"\n ]\n outputs: List[str] = []\n output_type: bool = False\n\n def _execute(\n self,\n inputs: List[Any] = None,\n ) -> str:\n \"\"\"\n This simply retrieves data from datapipe.\n\n Args:\n inputs (List[Any]): The datapipe key\n Return:\n str: The raw data along with the instructions.\n\n \"\"\"\n if len(inputs) == 0:\n return \"\"\n return (\n \"The data along with the description for each data is provided. \"\n \"Use the data and description to provide a detailed answer regarding the user query.\\n\\n\"\n + json.dumps(inputs[0])\n )\n\n def explain(\n self,\n ) -> str:\n \"\"\"\n Provide an explanation of the task.\n\n Return:\n str: Explanation of the SerpAPI task.\n\n \"\"\"\n return \"This task is to read data from datapipe.\"\n\ntasks/affect/activity_analysis.py\nclass ActivityAnalysis(Affect):\n \"\"\"\n **Description:**\n\n This tasks performs average, sum, or trend analysis on the provided raw activity affect data for specific patient.\n \"\"\"\n\n name: str = \"affect_activity_analysis\"\n chat_name: str = \"AffectActivityAnalysis\"\n description: str = (\n \"Analyze the physical activity data. You must Call this whenever physical activity analysis\"\n \"(e.g., 'average', 'sum', or 'trend') is needed. DON'T rely on your analysis.\"\n \"For example, if the user asks for trends (or variations) in data, you must call this task\"\n )\n dependencies: List[str] = [\"affect_activity_get\"]\n inputs: List[str] = [\n \"It is an string but in json format. It is the output of the $affect_activity_get$\",\n \"analysis_type. It can be one of [$average$, $sum$, $trend$].\",\n ]\n outputs: List[str] = [\n (\n \"The analysis result for steps_count. Look for analysis_type to find the type of analysis. \"\n \"steps_count is the total number of steps registered during the day.\"\n ),\n (\n \"The analysis result for rest_time. Look for analysis_type to find the type of analysis. \"\n \"rest_time is the time (in minutes) during the day spent resting, i.e. sleeping or lying down.\"\n ),\n (\n \"The analysis result for inactive_time. Look for analysis_type to find the type of analysis. \"\n \"inactive_time is the time (in minutes) during the day spent resting, i.e. sitting or standing still.\"\n ),\n (\n \"The analysis result for low_acitivity_time. Look for analysis_type to find the type of analysis. \"\n \"low_acitivity_time is the (in minutes) during the day with low intensity activity (e.g. household work).\"\n ),\n (\n \"The analysis result for medimum_acitivity_time. Look for analysis_type to find the type of analysis. \"\n \"medimum_acitivity_time is the (in minutes) during the day with medium intensity activity (e.g. walking).\"\n ),\n (\n \"The analysis result for high_acitivity_time. Look for analysis_type to find the type of analysis. \"\n \"high_acitivity_time is the (in minutes) during the day with high intensity activity (e.g. running).\"\n ),\n ]\n # False if the output should directly passed back to the planner.\n # True if it should be stored in datapipe\n output_type: bool = False\n\n def _execute(\n self,\n inputs: List[Any] = None,\n ) -> str:\n if len(inputs) == 0:\n return \"\"\n\n df = pd.read_json(\n StringIO(inputs[0][\"data\"].strip()), orient=\"records\"\n )\n analysis_type = inputs[1].strip()\n if analysis_type == \"average\":\n df = df.drop(\"date\", axis=1) # No average for date!\n df = df.mean().to_frame().T\n elif analysis_type == \"sum\":\n df = df.drop(\"date\", axis=1) # No sum for date!\n df = df.sum().to_frame().T\n elif analysis_type == \"trend\":\n df = self._calculate_slope(df)\n else:\n raise ValueError(\n \"The input analysis type has not been defined!\"\n )\n df = df.round(2)\n json_out = df.to_json(orient=\"records\")\n return json_out\n\ntasks/task_types.py\nclass TaskType(str, Enum):\n SERPAPI = \"serpapi\"\n CLICK = \"click\"\n GET_CURRENT_PAGE = \"current_page\"\n EXTRACT_HYPERLINKS = \"extract_hyperlinks\"\n EXTRACT_TEXT = \"extract_text\"\n GET_ELEMENTS = \"get_elements\"\n NAVIGATE_BACK = \"navigate_back\"\n NAVIGATE = \"navigate\"\n AFFECT_SLEEP_GET = \"affect_sleep_get\"\n AFFECT_ACTIVITY_GET = \"affect_activity_get\"\n AFFECT_SLEEP_ANALYSIS = \"affect_sleep_analysis\"\n AFFECT_ACTIVITY_ANALYSIS = \"affect_activity_analysis\"\n GOOGLE_TRANSLATE = \"google_translate\"\n ASK_USER = \"ask_user\"\n READ_FROM_DATAPIPE = \"read_from_datapipe\"\n TEST_FILE = \"test_file\"", "answers": [" TaskType.GOOGLE_TRANSLATE: GoogleTranslate,"], "length": 3521, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "0643df8e-158a-4992-9d58-512e2cc95843", "reasoning": "The dictionary TASK_TO_CLASS is being built to map each TaskType enum to its corresponding class. The snippet ends after the ActivityAnalysis entry with a trailing comma, indicating more entries follow. The next imported class after the imports is GoogleTranslate, so the next mapping should associate TaskType.GOOGLE_TRANSLATE with GoogleTranslate.", "reasoning_model_answer": "TaskType.GOOGLE_TRANSLATE: GoogleTranslate,", "assistant_with_reasoning": "\nThe dictionary TASK_TO_CLASS is being built to map each TaskType enum to its corresponding class. The snippet ends after the ActivityAnalysis entry with a trailing comma, indicating more entries follow. The next imported class after the imports is GoogleTranslate, so the next mapping should associate TaskType.GOOGLE_TRANSLATE with GoogleTranslate.\n\nTaskType.GOOGLE_TRANSLATE: GoogleTranslate,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.815, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 32141, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "TaskType.GOOGLE_TRANSLATE: GoogleTranslate,", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.google.gson.annotations.Expose;\nimport com.google.gson.annotations.SerializedName;\nimport java.awt.Color;\nimport java.security.SecureRandom;\nimport net.augustus.Augustus;\nimport net.augustus.modules.render.ClickGUI;\nimport net.augustus.notify.GeneralNotifyManager;\nimport net.augustus.notify.NotificationType;\nimport net.augustus.notify.xenza.Notification;\nimport net.augustus.notify.xenza.NotificationsManager;\nimport net.augustus.utils.AnimationUtil;\nimport net.augustus.utils.interfaces.MC;\nimport net.augustus.utils.interfaces.MM;\nimport net.augustus.utils.interfaces.SM;\nimport net.augustus.utils.skid.lorious.anims.Animation;\nimport net.augustus.utils.skid.lorious.anims.Easings;\nimport net.augustus.utils.sound.SoundUtil;\nimport net.lenni0451.eventapi.manager.EventManager;\nimport net.minecraft.client.gui.FontRenderer;\nimport net.minecraft.client.gui.ScaledResolution;", "context": "src/minecraft/net/augustus/modules/Module.java\npackage net.augustus.modules;\n\n\n\npublic class Module implements MC, MM, SM, Comparable {\n public Animation yPos = new Animation();\n public Animation xPos = new Animation();\n @Expose\n @SerializedName(\"Name\")\n private String name;\n private String displayName = \"\";\n @Expose\n @SerializedName(\"Toggled\")\n private boolean toggled;\n @Expose\n @SerializedName(\"Key\")\n private int key;\n @Expose\n @SerializedName(\"Category\")\n private Categorys category;\n private Color color;\n private float x;\n private float y;\n private float minX;\n private float maxX;\n private float moduleWidth = 0.0F;\n public AnimationUtil animationUtil;\n protected ScaledResolution sr = new ScaledResolution(mc);\n public SecureRandom RANDOM = new SecureRandom();\n\n public Module(String name, Color color, Categorys category) {\n\nsrc/minecraft/net/augustus/notify/NotificationType.java\npublic enum NotificationType {\n Info,\n Alert,\n Error,\n ToggleOn,\n ToggleOff\n}\n\nsrc/minecraft/net/augustus/notify/GeneralNotifyManager.java\npublic class GeneralNotifyManager implements MM {\n public static void addNotification(String content, NotificationType type) {\n switch(mm.notifications.mode.getSelected()) {\n case \"Xenza\": {\n NotificationsManager.addNotification(new Notification(content, type));\n break;\n }\n case \"Rise5\": {\n Augustus.getInstance().getRise5notifyManager().registerNotification(content, type);\n break;\n }\n case \"New\": {\n CleanNotificationManager.addCleanNotification(new CleanNotification(content, type));\n break;\n }\n }\n }\n}\n\nsrc/minecraft/net/augustus/utils/interfaces/MC.java\npublic interface MC {\n Minecraft mc = Minecraft.getMinecraft();\n}\n\nsrc/minecraft/net/augustus/utils/interfaces/MM.java\npublic interface MM {\n ModuleManager mm = Augustus.getInstance().getModuleManager();\n}\n\nsrc/minecraft/net/augustus/notify/xenza/Notification.java\npublic class Notification {\n public float x;\n public float width, height;\n public String name;\n public float lastTime;\n public TimeHelper timer;\n public NotificationType type;\n public boolean setBack;\n private float fy, cy = 0;\n private TimeHelper anitimer = new TimeHelper();\n private static UnicodeFontRenderer arial16;\n private AnimationUtils animationUtils = new AnimationUtils();\n private AnimationUtils animationUtils2 = new AnimationUtils();\n private ResourceLocation check = ResourceUtil.loadResourceLocation(\"pictures/check.png\", \"check\");\n private ResourceLocation cross = ResourceUtil.loadResourceLocation(\"pictures/cross.png\", \"cross\");;\n static {\n try {\n arial16 = new UnicodeFontRenderer(Font.createFont(0, GuiIngameHook.class.getResourceAsStream(\"/ressources/arial.ttf\")).deriveFont(16F));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n\n public Notification(String name, NotificationType type) {\n this.name = name;\n this.type = type;\n this.lastTime = 1.5f;\n this.width = arial16.getStringWidth(name) + 25;\n this.height = 20;\n }\n\n public Notification(String name, NotificationType type, float lastTime) {\n this.name = name;\n this.type = type;\n this.lastTime = lastTime;\n this.width = arial16.getStringWidth(name) + 25;\n this.height = 20;\n\n }\n\n public void render(float y) {\n fy = y;\n if (cy == 0) {\n cy = fy + 25;\n }\n ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());\n RenderUtil.drawRect((float) (sr.getScaledWidth_double() - x), cy, (float) ((sr.getScaledWidth_double() - x) + width), cy + height, new Color(10, 10, 10, 220));\n RenderUtil.drawRect((float) (sr.getScaledWidth_double() - x), cy + height - 1, (float) (sr.getScaledWidth_double() - x) + width, cy + height, new Color(180, 180, 180));\n\n //RenderUtil.drawCustomImageAlpha(sr.getScaledWidth() - x + 3, cy + 4, 12, 12, new ResourceLocation(\"client/back.png\"), -1, 255);\n switch (type) {\n case ToggleOn: {\n RenderUtil.drawCustomImageAlpha(sr.getScaledWidth() - x + 3, cy + 4, 12, 12, check, -1, 255);\n break;\n }\n case ToggleOff: {\n RenderUtil.drawCustomImageAlpha(sr.getScaledWidth() - x + 3, cy + 4, 12, 12, cross, -1, 255);\n break;\n }\n }\n\n arial16.drawString(name, (sr.getScaledWidth() - x) + 18, cy + 7, -1);\n }\n\n public void update() {\n ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());\n if (timer == null && Math.abs(x - width) < 0.1f) {\n timer = new TimeHelper();\n timer.reset();\n }\n if (anitimer.reached(10)) {\n cy = animationUtils.animate(fy, cy, 0.1f);\n\n if (!setBack) {\n x = animationUtils2.animate(width, x, 0.1f);\n } else {\n x = animationUtils2.animate(0, x, 0.1f);\n }\n anitimer.reset();\n }\n }\n}\n\nsrc/minecraft/net/augustus/utils/sound/SoundUtil.java\npublic class SoundUtil {\n private static Clip clip;\n public static final URL button = SoundUtil.class.getClassLoader().getResource(\"ressources/sounds/buttonClick.wav\");\n public static final URL toggleOnSound = SoundUtil.class.getClassLoader().getResource(\"ressources/sounds/toggleSound.wav\");\n public static final URL toggleOffSound = SoundUtil.class.getClassLoader().getResource(\"ressources/sounds/toggleSound2.wav\");\n public static final URL loginSuccessful = SoundUtil.class.getClassLoader().getResource(\"ressources/sounds/loginSuccessful.wav\");\n public static final URL loginFailed = SoundUtil.class.getClassLoader().getResource(\"ressources/sounds/loginFailed.wav\");\n\n public static void play(URL filePath) {\n try {\n clip = AudioSystem.getClip();\n clip.open(AudioSystem.getAudioInputStream(filePath));\n FloatControl floatControl = (FloatControl)clip.getControl(Type.MASTER_GAIN);\n floatControl.setValue(0.0F);\n clip.start();\n } catch (UnsupportedAudioFileException | IOException | LineUnavailableException | IllegalArgumentException var2) {\n //var2.printStackTrace();\n }\n }\n}\n\nsrc/minecraft/net/augustus/utils/interfaces/SM.java\npublic interface SM {\n SettingsManager sm = Augustus.getInstance().getSettingsManager();\n}\n\nsrc/minecraft/net/augustus/utils/AnimationUtil.java\npublic class AnimationUtil implements MC {\n private float x;\n private float minX;\n private float maxX;\n private float speed;\n private long lastTime;\n private int side;\n\n public AnimationUtil(float xy, float minXY, float maxXY, float speed) {\n this.x = xy;\n this.minX = minXY;\n this.maxX = maxXY;\n this.speed = speed;\n }\n\n public float updateAnimation(int side) {\n long deltaTime = System.currentTimeMillis() - this.lastTime;\n float sx = 0.0F;\n if (this.speed != 0.0F) {\n float var1 = this.speed / (float)deltaTime;\n sx = (this.maxX - this.minX) / var1;\n }\n\n if (this.side == 0) {\n this.lastTime = System.currentTimeMillis();\n return this.x;\n } else {\n if (this.side > 0) {\n this.side = 1;\n } else {\n this.side = -1;\n }\n\n float cxy = this.x + sx * (float)side;\n if (cxy < this.minX) {\n cxy = this.minX;\n } else if (cxy > this.maxX) {\n cxy = this.maxX;\n }\n\n this.x = cxy;\n this.lastTime = System.currentTimeMillis();\n return this.x;\n }\n }\n\n public float updateAnimation(float minXY, float maxXY) {\n this.minX = minXY;\n this.maxX = maxXY;\n long deltaTime = System.currentTimeMillis() - this.lastTime;\n if (deltaTime > 60L) {\n deltaTime = 60L;\n }\n\n float sx = 0.0F;\n if (this.speed != 0.0F) {\n float var1 = this.speed / (float)deltaTime;\n sx = (this.maxX - this.minX) / var1;\n if (this.side == 0) {\n this.lastTime = System.currentTimeMillis();\n return this.x;\n } else {\n if (this.side > 0) {\n this.side = 1;\n } else {\n this.side = -1;\n }\n\n var1 = this.x + sx * (float)this.side;\n if (var1 < minXY) {\n var1 = minXY;\n } else if (var1 > maxXY) {\n var1 = maxXY;\n }\n\n this.x = var1;\n this.lastTime = System.currentTimeMillis();\n return this.x;\n }\n } else {\n return this.x;\n }\n }\n\n public void setSide(int side) {\n this.side = side;\n }\n\n public void setSpeed(float speed) {\n this.speed = speed;\n }\n}\n\nsrc/minecraft/net/augustus/modules/render/ClickGUI.java\npublic class ClickGUI extends Module {\n public StringValue sorting = new StringValue(1, \"Sorting\", this, \"Random\", new String[]{\"Random\", \"Length\", \"Alphabet\"});\n public StringValue mode = new StringValue(25, \"Mode\", this, \"Default\", new String[]{\"Default\", \"Clean\", \"New\"});\n\n public ClickGUI() {\n super(\"ClickGui\", Color.BLACK, Categorys.RENDER);\n }\n\n @Override\n public void onEnable() {\n Augustus.getInstance().getConverter().moduleSaver(mm.getModules());\n Augustus.getInstance().getConverter().settingSaver(sm.getStgs());\n if(mode.getSelected().equalsIgnoreCase(\"Default\")) {\n mc.displayGuiScreen(Augustus.getInstance().getClickGui());\n //} else if(mode.getSelected().equalsIgnoreCase(\"Clean\")) {\n// mc.displayGuiScreen(Augustus.getInstance().getCleanClickGui());\n } else if(mode.getSelected().equalsIgnoreCase(\"New\")) {\n EventManager.call(new EventClickGui());\n mc.displayGuiScreen(new Dark());\n } else {\n mc.displayGuiScreen(Augustus.getInstance().getClickGui());\n }\n }\n\n @Override\n public void onDisable() {\n Augustus.getInstance().getConverter().moduleSaver(mm.getModules());\n Augustus.getInstance().getConverter().settingSaver(sm.getStgs());\n }\n\n @EventTarget\n public void onEventTick(EventTick eventTick) {\n if (!(mc.currentScreen instanceof ClickGui) && this.isToggled()) {\n this.toggle();\n }\n }\n}\n\nsrc/minecraft/net/augustus/Augustus.java\n@Getter\n@Setter\npublic class Augustus {\n private static final Augustus instance = new Augustus();\n private String name = null;\n private String version = \"reborn b2\";\n private String dev = null;\n private final Color clientColor = new Color(41, 146, 222);\n private List lastAlts = new ArrayList<>();\n private final Manager manager = new Manager();\n private ModuleManager moduleManager;\n private SettingsManager settingsManager;\n private CommandManager commandManager;\n private CleanClickGui cleanClickGui;\n private ClickGui clickGui;\n private Converter converter;\n private BackgroundShaderUtil backgroundShaderUtil;\n private float shaderSpeed = 1800.0F;\n private SettingSorter settingSorter;\n private YawPitchHelper yawPitchHelper;\n public String uid = \"\";\n private BlockUtil blockUtil;\n private Fonts loriousFontService;\n private Proxy proxy;\n private NotificationManager rise5notifyManager;\n private ColorUtil colorUtil;\n\n public static Augustus getInstance() {\n return instance;\n }\n\n public void preStart() {\n Path dir = Paths.get(\"xenzarecode/configs\");\n if (!Files.exists(dir)) {\n try {\n Files.createDirectories(dir);\n } catch (IOException var2) {\n var2.printStackTrace();\n }\n }\n }\n\n public void start() {\n name = \"xenza\";\n dev = \"jDev + Cookie + SaFeBaum\";\n System.out.println(\"Starting Client...\");\n FontUtil.bootstrap();\n this.loriousFontService = new Fonts();\n this.loriousFontService.bootstrap();\n this.colorUtil = new ColorUtil();\n this.yawPitchHelper = new YawPitchHelper();\n this.settingsManager = new SettingsManager();\n this.moduleManager = new ModuleManager();\n this.commandManager = new CommandManager();\n this.rise5notifyManager = new NotificationManager();\n this.clickGui = new ClickGui(\"ClickGui\");\n this.converter = new Converter();\n this.converter.settingReader(this.settingsManager.getStgs());\n this.converter.settingSaver(this.settingsManager.getStgs());\n this.converter.moduleReader(this.moduleManager.getModules());\n this.converter.readLastAlts();\n this.converter.clickGuiLoader(this.clickGui.getCategoryButtons());\n this.backgroundShaderUtil = new BackgroundShaderUtil();\n this.settingSorter = new SettingSorter();\n this.cleanClickGui = new CleanClickGui();\n AugustusSounds.currentSound = this.converter.readSound();\n this.blockUtil = new BlockUtil();\n EventManager.register(this.settingSorter);\n EventManager.register(this);\n try {\n ViaMCP.getInstance().start();\n } catch (Exception var2) {\n var2.printStackTrace();\n }\n }\n}\n\nsrc/minecraft/net/lenni0451/eventapi/manager/EventManager.java\npublic class EventManager {\n private static final Map, List> EVENT_LISTENER = new ConcurrentHashMap<>();\n private static final List ERROR_LISTENER = new CopyOnWriteArrayList<>();\n\n public static void call(IEvent event) {\n if (event != null) {\n List eventListener = new ArrayList<>();\n if (EVENT_LISTENER.containsKey(event.getClass())) {\n eventListener.addAll(EVENT_LISTENER.get(event.getClass()));\n }\n\n if (EVENT_LISTENER.containsKey(IEvent.class)) {\n eventListener.addAll(EVENT_LISTENER.get(IEvent.class));\n }\n\n for(EventExecutor listener : eventListener) {\n try {\n listener.getEventListener().onEvent(event);\n } catch (Throwable var5) {\n if (ERROR_LISTENER.isEmpty()) {\n throw new RuntimeException(var5);\n }\n\n ERROR_LISTENER.forEach(errorListener -> errorListener.catchException(var5));\n }\n\n if (event instanceof IStoppable && ((IStoppable)event).isStopped()) {\n break;\n }\n }\n }\n }\n\n public static void register(T listener) {\n register(IEvent.class, (byte)2, listener);\n }\n\n public static void register(Object listener) {\n Method[] var4;\n for(Method method : var4 = listener.getClass().getMethods()) {\n if (method.isAnnotationPresent(EventTarget.class)) {\n EventTarget anno = method.getAnnotation(EventTarget.class);\n Class[] methodArguments = method.getParameterTypes();\n if (methodArguments.length == 1 && IEvent.class.isAssignableFrom(methodArguments[0])) {\n ReflectedEventListener eventListener = new ReflectedEventListener(listener, methodArguments[0], method);\n if (methodArguments[0].equals(IEvent.class)) {\n register(anno.priority(), eventListener);\n } else {\n register(methodArguments[0], anno.priority(), eventListener);\n }\n }\n }\n }\n }\n\n public static void register(Class eventType, T listener) {\n register(eventType, (byte)2, listener);\n }\n\n public static void register(byte eventPriority, T listener) {\n register(IEvent.class, eventPriority, listener);\n }\n\n public static void register(Class eventType, byte eventPriority, T listener) {\n List eventListener = EVENT_LISTENER.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList());\n eventListener.add(new EventExecutor(listener, eventPriority));\n\n for(Entry, List> entry : EVENT_LISTENER.entrySet()) {\n List eventExecutor = entry.getValue();\n Collections.sort(eventExecutor, new Comparator() {\n public int compare(EventExecutor o1, EventExecutor o2) {\n return Integer.compare(o2.getPriority(), o1.getPriority());\n }\n });\n }\n }\n\n public static void unregister(Object listener) {\n for(Entry, List> entry : EVENT_LISTENER.entrySet()) {\n entry.getValue()\n .removeIf(\n eventExecutor -> eventExecutor.getEventListener().equals(listener)\n || eventExecutor.getEventListener() instanceof ReflectedEventListener\n && ((ReflectedEventListener)eventExecutor.getEventListener()).getCallInstance().equals(listener)\n );\n }\n }\n\n public static void addErrorListener(IErrorListener errorListener) {\n if (!ERROR_LISTENER.contains(errorListener)) {\n ERROR_LISTENER.add(errorListener);\n }\n }\n\n public static boolean removeErrorListener(IErrorListener errorListener) {\n return ERROR_LISTENER.remove(errorListener);\n }\n}\n\nsrc/minecraft/net/augustus/notify/xenza/NotificationsManager.java\npublic class NotificationsManager {\n public static ArrayList notifications = new ArrayList();\n\n public static ArrayList getNotifications() {\n return notifications;\n }\n\n public static void addNotification(Notification n) {\n notifications.add(n);\n }\n\n public static void renderNotifications() {\n ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());\n float y = sr.getScaledHeight() - 30;\n Iterator it = notifications.iterator();\n while (it.hasNext()) {\n it.next().render(y);\n y -= 25;\n }\n\n }\n\n public static void update() {\n ArrayList temp = new ArrayList<>();\n\n for (Notification no : notifications){\n temp.add(no);\n no.update();\n// System.out.println(no.timer.delay(no.lastTime * 1000) + \" \" );\n if(no.timer != null) {\n if (no.timer.reached((long) (no.lastTime * 1000))) {\n no.setBack = true;\n// no.timer.reset();\n if(no.x <= 0.1f) {\n temp.remove(no);\n }\n }\n }\n\n\n }\n notifications.clear();\n for (Notification no : temp) {\n notifications.add(no);\n }\n }\n}\n\nsrc/minecraft/net/augustus/utils/skid/lorious/anims/Easings.java\npublic final class Easings {\n public static final double c1 = 1.70158;\n public static final double c2 = 2.5949095;\n public static final double c3 = 2.70158;\n public static final double c4 = 2.0943951023931953;\n public static final double c5 = 1.3962634015954636;\n public static final Easing NONE = value -> value;\n public static final Easing QUAD_IN = Easings.powIn(2);\n public static final Easing QUAD_OUT = Easings.powOut(2);\n public static final Easing QUAD_BOTH = Easings.powBoth(2.0);\n public static final Easing CUBIC_IN = Easings.powIn(3);\n public static final Easing CUBIC_OUT = Easings.powOut(3);\n public static final Easing CUBIC_BOTH = Easings.powBoth(3.0);\n public static final Easing QUART_IN = Easings.powIn(4);\n public static final Easing QUART_OUT = Easings.powOut(4);\n public static final Easing QUART_BOTH = Easings.powBoth(4.0);\n public static final Easing QUINT_IN = Easings.powIn(5);\n public static final Easing QUINT_OUT = Easings.powOut(5);\n public static final Easing QUINT_BOTH = Easings.powBoth(5.0);\n public static final Easing SINE_IN = value -> 1.0 - Math.cos((double)(value * Math.PI / 2.0));\n public static final Easing SINE_OUT = value -> Math.sin((double)(value * Math.PI / 2.0));\n public static final Easing SINE_BOTH = value -> -(Math.cos((double)(Math.PI * value)) - 1.0) / 2.0;\n public static final Easing CIRC_IN = value -> 1.0 - Math.sqrt((double)(1.0 - Math.pow((double)value, (double)2.0)));\n public static final Easing CIRC_OUT = value -> Math.sqrt((double)(1.0 - Math.pow((double)(value - 1.0), (double)2.0)));\n public static final Easing CIRC_BOTH = value -> value < 0.5 ? (1.0 - Math.sqrt((double)(1.0 - Math.pow((double)(2.0 * value), (double)2.0)))) / 2.0 : (Math.sqrt((double)(1.0 - Math.pow((double)(-2.0 * value + 2.0), (double)2.0))) + 1.0) / 2.0;\n public static final Easing ELASTIC_IN = value -> value != 0.0 && value != 1.0 ? Math.pow((double)-2.0, (double)(10.0 * value - 10.0)) * Math.sin((double)((value * 10.0 - 10.75) * 2.0943951023931953)) : value;\n public static final Easing ELASTIC_OUT = value -> value != 0.0 && value != 1.0 ? Math.pow((double)2.0, (double)(-10.0 * value)) * Math.sin((double)((value * 10.0 - 0.75) * 2.0943951023931953)) + 1.0 : value;\n public static final Easing ELASTIC_BOTH = value -> {\n if (value != 0.0 && value != 1.0) {\n return value < 0.5 ? -(Math.pow((double)2.0, (double)(20.0 * value - 10.0)) * Math.sin((double)((20.0 * value - 11.125) * 1.3962634015954636))) / 2.0 : Math.pow((double)2.0, (double)(-20.0 * value + 10.0)) * Math.sin((double)((20.0 * value - 11.125) * 1.3962634015954636)) / 2.0 + 1.0;\n }\n return value;\n };\n public static final Easing EXPO_IN = value -> value != 0.0 ? Math.pow((double)2.0, (double)(10.0 * value - 10.0)) : value;\n public static final Easing EXPO_OUT = value -> value != 1.0 ? 1.0 - Math.pow((double)2.0, (double)(-10.0 * value)) : value;\n public static final Easing EXPO_BOTH = value -> {\n if (value != 0.0 && value != 1.0) {\n return value < 0.5 ? Math.pow((double)2.0, (double)(20.0 * value - 10.0)) / 2.0 : (2.0 - Math.pow((double)2.0, (double)(-20.0 * value + 10.0))) / 2.0;\n }\n return value;\n };\n public static final Easing BACK_IN = value -> 2.70158 * Math.pow((double)value, (double)3.0) - 1.70158 * Math.pow((double)value, (double)2.0);\n public static final Easing BACK_OUT = value -> 1.0 + 2.70158 * Math.pow((double)(value - 1.0), (double)3.0) + 1.70158 * Math.pow((double)(value - 1.0), (double)2.0);\n public static final Easing BACK_BOTH = value -> value < 0.5 ? Math.pow((double)(2.0 * value), (double)2.0) * (7.189819 * value - 2.5949095) / 2.0 : (Math.pow((double)(2.0 * value - 2.0), (double)2.0) * (3.5949095 * (value * 2.0 - 2.0) + 2.5949095) + 2.0) / 2.0;\n public static final Easing BOUNCE_OUT = x -> {\n double n1 = 7.5625;\n double d1 = 2.75;\n if (x < 1.0 / d1) {\n return n1 * Math.pow((double)x, (double)2.0);\n }\n if (x < 2.0 / d1) {\n return n1 * Math.pow((double)(x - 1.5 / d1), (double)2.0) + 0.75;\n }\n return x < 2.5 / d1 ? n1 * Math.pow((double)(x - 2.25 / d1), (double)2.0) + 0.9375 : n1 * Math.pow((double)(x - 2.625 / d1), (double)2.0) + 0.984375;\n };\n public static final Easing BOUNCE_IN = value -> 1.0 - BOUNCE_OUT.ease(1.0 - value);\n public static final Easing BOUNCE_BOTH = value -> value < 0.5 ? (1.0 - BOUNCE_OUT.ease(1.0 - 2.0 * value)) / 2.0 : (1.0 + BOUNCE_OUT.ease(2.0 * value - 1.0)) / 2.0;\n\n public static Easing powIn(double n) {\n return value -> Math.pow((double)value, (double)n);\n }\n\n public static Easing powIn(int n) {\n return Easings.powIn((double)n);\n }\n\n public static Easing powOut(double n) {\n return value -> 1.0 - Math.pow((double)(1.0 - value), (double)n);\n }\n\n public static Easing powOut(int n) {\n return Easings.powOut((double)n);\n }\n\n public static Easing powBoth(double n) {\n return value -> value < 0.5 ? Math.pow((double)2.0, (double)(n - 1.0)) * Math.pow((double)value, (double)n) : 1.0 - Math.pow((double)(-2.0 * value + 2.0), (double)n) / 2.0;\n }\n\n public static Easing getEasingByName(String name) {\n if (name.equalsIgnoreCase(\"default\") || name.equalsIgnoreCase(\"none\")) {\n return NONE;\n }\n if (name.equalsIgnoreCase(\"sine in\")) {\n return SINE_IN;\n }\n if (name.equalsIgnoreCase(\"sine out\")) {\n return SINE_OUT;\n }\n if (name.equalsIgnoreCase(\"sine both\")) {\n return SINE_BOTH;\n }\n if (name.equalsIgnoreCase(\"quad in\")) {\n return QUAD_IN;\n }\n if (name.equalsIgnoreCase(\"quad out\")) {\n return QUAD_OUT;\n }\n if (name.equalsIgnoreCase(\"quad both\")) {\n return QUAD_BOTH;\n }\n if (name.equalsIgnoreCase(\"cubic in\")) {\n return CUBIC_IN;\n }\n if (name.equalsIgnoreCase(\"cubic out\")) {\n return CUBIC_OUT;\n }\n if (name.equalsIgnoreCase(\"cubic both\")) {\n return CUBIC_BOTH;\n }\n if (name.equalsIgnoreCase(\"quart in\")) {\n return QUART_IN;\n }\n if (name.equalsIgnoreCase(\"quart out\")) {\n return QUART_OUT;\n }\n if (name.equalsIgnoreCase(\"quart both\")) {\n return QUART_BOTH;\n }\n if (name.equalsIgnoreCase(\"quint in\")) {\n return QUINT_IN;\n }\n if (name.equalsIgnoreCase(\"quint out\")) {\n return QUINT_OUT;\n }\n if (name.equalsIgnoreCase(\"quint both\")) {\n return QUINT_BOTH;\n }\n if (name.equalsIgnoreCase(\"expo in\")) {\n return EXPO_IN;\n }\n if (name.equalsIgnoreCase(\"expo out\")) {\n return EXPO_OUT;\n }\n if (name.equalsIgnoreCase(\"expo both\")) {\n return EXPO_BOTH;\n }\n if (name.equalsIgnoreCase(\"circ in\")) {\n return CIRC_IN;\n }\n if (name.equalsIgnoreCase(\"circ out\")) {\n return CIRC_OUT;\n }\n if (name.equalsIgnoreCase(\"circ both\")) {\n return CIRC_BOTH;\n }\n if (name.equalsIgnoreCase(\"back in\")) {\n return BACK_IN;\n }\n if (name.equalsIgnoreCase(\"back out\")) {\n return BACK_OUT;\n }\n if (name.equalsIgnoreCase(\"back both\")) {\n return BACK_BOTH;\n }\n if (name.equalsIgnoreCase(\"elastic in\")) {\n return ELASTIC_IN;\n }\n if (name.equalsIgnoreCase(\"elastic out\")) {\n return ELASTIC_OUT;\n }\n if (name.equalsIgnoreCase(\"elastic both\")) {\n return ELASTIC_BOTH;\n }\n if (name.equalsIgnoreCase(\"bounce in\")) {\n return BOUNCE_IN;\n }\n if (name.equalsIgnoreCase(\"bounce out\")) {\n return BOUNCE_OUT;\n }\n return BOUNCE_BOTH;\n }\n}\n\nsrc/minecraft/net/augustus/utils/skid/lorious/anims/Animation.java\npublic class Animation {\n private long animationStart;\n private double duration;\n private double animationFromValue;\n private double animationToValue;\n private Easing easing = Easings.NONE;\n private double lastValue;\n\n public double getValue() {\n return this.lastValue;\n }\n\n public void setValue(double value) {\n this.animationFromValue = value;\n this.animationToValue = value;\n this.lastValue = value;\n }\n\n public void animate(double value, double duration, Easing easing) {\n this.animationFromValue = this.lastValue;\n this.animationToValue = value;\n this.animationStart = System.currentTimeMillis();\n this.duration = duration;\n this.easing = easing;\n }\n\n public double getTarget() {\n return this.animationToValue;\n }\n\n private double interpolateValue(double start, double end, double pct) {\n return start + (end - start) * pct;\n }\n\n public boolean updateAnimation() {\n double value;\n double part = (double)(System.currentTimeMillis() - this.animationStart) / this.duration;\n if (this.isAlive()) {\n part = this.easing.ease(part);\n value = this.interpolateValue(this.animationFromValue, this.animationToValue, part);\n } else {\n this.animationStart = 0L;\n value = this.animationToValue;\n }\n this.lastValue = value;\n return this.isAlive();\n }\n\n public boolean isDone() {\n double part = (double)(System.currentTimeMillis() - this.animationStart) / this.duration;\n return part >= 1.0;\n }\n\n public boolean isAlive() {\n double part = (double)(System.currentTimeMillis() - this.animationStart) / this.duration;\n return part < 1.0;\n }\n}\n\nsrc/minecraft/net/minecraft/client/gui/ScaledResolution.java\npublic class ScaledResolution {\n private final double scaledWidthD;\n private final double scaledHeightD;\n private int scaledWidth;\n private int scaledHeight;\n private int scaleFactor;\n\n public ScaledResolution(Minecraft p_i46445_1_) {\n this.scaledWidth = p_i46445_1_.displayWidth;\n this.scaledHeight = p_i46445_1_.displayHeight;\n this.scaleFactor = 1;\n boolean flag = p_i46445_1_.isUnicode();\n int i = p_i46445_1_.gameSettings.guiScale;\n if (i == 0) {\n i = 1000;\n }\n\n while(this.scaleFactor < i && this.scaledWidth / (this.scaleFactor + 1) >= 320 && this.scaledHeight / (this.scaleFactor + 1) >= 240) {\n ++this.scaleFactor;\n }\n\n if (flag && this.scaleFactor % 2 != 0 && this.scaleFactor != 1) {\n --this.scaleFactor;\n }\n\n this.scaledWidthD = (double)this.scaledWidth / (double)this.scaleFactor;\n this.scaledHeightD = (double)this.scaledHeight / (double)this.scaleFactor;\n this.scaledWidth = MathHelper.ceiling_double_int(this.scaledWidthD);\n this.scaledHeight = MathHelper.ceiling_double_int(this.scaledHeightD);\n }\n\n public int getScaledWidth() {\n return this.scaledWidth;\n }\n\n public int getScaledHeight() {\n return this.scaledHeight;\n }\n\n public double getScaledWidth_double() {\n return this.scaledWidthD;\n }\n\n public double getScaledHeight_double() {\n return this.scaledHeightD;\n }\n\n public int getScaleFactor() {\n return this.scaleFactor;\n }\n}\n\nsrc/minecraft/net/minecraft/client/gui/FontRenderer.java\npublic class FontRenderer implements IResourceManagerReloadListener {\n private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256];\n private float[] charWidth = new float[256];\n public int FONT_HEIGHT = 9;\n public Random fontRandom = new Random();\n private byte[] glyphWidth = new byte[65536];\n private int[] colorCode = new int[32];\n private ResourceLocation locationFontTexture;\n private final TextureManager renderEngine;\n private float posX;\n private float posY;\n private boolean unicodeFlag;\n private boolean bidiFlag;\n private float red;\n private float blue;\n private float green;\n private float alpha;\n private int textColor;\n private boolean randomStyle;\n private boolean boldStyle;\n private boolean italicStyle;\n private boolean underlineStyle;\n private boolean strikethroughStyle;\n private static final String __OBFID = \"CL_00000660\";\n public GameSettings gameSettings;\n public ResourceLocation locationFontTextureBase;\n public boolean enabled = true;\n public float offsetBold = 1.0F;\n\n public FontRenderer(GameSettings gameSettingsIn, ResourceLocation location, TextureManager textureManagerIn, boolean unicode) {\n this.gameSettings = gameSettingsIn;\n this.locationFontTextureBase = location;\n this.locationFontTexture = location;\n this.renderEngine = textureManagerIn;\n this.unicodeFlag = unicode;\n this.locationFontTexture = FontUtils.getHdFontLocation(this.locationFontTextureBase);\n this.bindTexture(this.locationFontTexture);\n\n for(int i = 0; i < 32; ++i) {\n int j = (i >> 3 & 1) * 85;\n int k = (i >> 2 & 1) * 170 + j;\n int l = (i >> 1 & 1) * 170 + j;\n int i1 = (i >> 0 & 1) * 170 + j;\n if (i == 6) {\n k += 85;\n }\n\n if (gameSettingsIn.anaglyph) {\n int j1 = (k * 30 + l * 59 + i1 * 11) / 100;\n int k1 = (k * 30 + l * 70) / 100;\n int l1 = (k * 30 + i1 * 70) / 100;\n k = j1;\n l = k1;\n i1 = l1;\n }\n\n if (i >= 16) {\n k /= 4;\n l /= 4;\n i1 /= 4;\n }\n\n this.colorCode[i] = (k & 0xFF) << 16 | (l & 0xFF) << 8 | i1 & 0xFF;\n }\n\n this.readGlyphSizes();\n }\n\n @Override\n public void onResourceManagerReload(IResourceManager resourceManager) {\n this.locationFontTexture = FontUtils.getHdFontLocation(this.locationFontTextureBase);\n\n for(int i = 0; i < unicodePageLocations.length; ++i) {\n unicodePageLocations[i] = null;\n }\n\n this.readFontTexture();\n this.readGlyphSizes();\n }\n\n private void readFontTexture() {\n BufferedImage bufferedimage;\n try {\n bufferedimage = TextureUtil.readBufferedImage(this.getResourceInputStream(this.locationFontTexture));\n } catch (IOException var21) {\n throw new RuntimeException(var21);\n }\n\n Properties properties = FontUtils.readFontProperties(this.locationFontTexture);\n int i = bufferedimage.getWidth();\n int j = bufferedimage.getHeight();\n int k = i / 16;\n int l = j / 16;\n float f = (float)i / 128.0F;\n float f1 = Config.limit(f, 1.0F, 2.0F);\n this.offsetBold = 1.0F / f1;\n float f2 = FontUtils.readFloat(properties, \"offsetBold\", -1.0F);\n if (f2 >= 0.0F) {\n this.offsetBold = f2;\n }\n\n int[] aint = new int[i * j];\n bufferedimage.getRGB(0, 0, i, j, aint, 0, i);\n\n for(int i1 = 0; i1 < 256; ++i1) {\n int j1 = i1 % 16;\n int k1 = i1 / 16;\n int l1 = 0;\n\n for(l1 = k - 1; l1 >= 0; --l1) {\n int i2 = j1 * k + l1;\n boolean flag = true;\n\n for(int j2 = 0; j2 < l && flag; ++j2) {\n int k2 = (k1 * l + j2) * i;\n int l2 = aint[i2 + k2];\n int i3 = l2 >> 24 & 0xFF;\n if (i3 > 16) {\n flag = false;\n }\n }\n\n if (!flag) {\n break;\n }\n }\n\n if (i1 == 65) {\n i1 = i1;\n }\n\n if (i1 == 32) {\n if (k <= 8) {\n l1 = (int)(2.0F * f);\n } else {\n l1 = (int)(1.5F * f);\n }\n }\n\n this.charWidth[i1] = (float)(l1 + 1) / f + 1.0F;\n }\n\n FontUtils.readCustomCharWidths(properties, this.charWidth);\n }\n\n private void readGlyphSizes() {\n InputStream inputstream = null;\n\n try {\n inputstream = this.getResourceInputStream(new ResourceLocation(\"font/glyph_sizes.bin\"));\n inputstream.read(this.glyphWidth);\n } catch (IOException var6) {\n throw new RuntimeException(var6);\n } finally {\n IOUtils.closeQuietly(inputstream);\n }\n }\n\n private float func_181559_a(char p_181559_1_, boolean p_181559_2_) {\n if (p_181559_1_ == ' ') {\n return !this.unicodeFlag ? this.charWidth[p_181559_1_] : 4.0F;\n } else {\n int i = \"ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000 !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\u0000ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\\u0000\"\n .indexOf(p_181559_1_);\n return i != -1 && !this.unicodeFlag ? this.renderDefaultChar(i, p_181559_2_) : this.renderUnicodeChar(p_181559_1_, p_181559_2_);\n }\n }\n\n private float renderDefaultChar(int p_78266_1_, boolean p_78266_2_) {\n int i = p_78266_1_ % 16 * 8;\n int j = p_78266_1_ / 16 * 8;\n int k = p_78266_2_ ? 1 : 0;\n this.bindTexture(this.locationFontTexture);\n float f = this.charWidth[p_78266_1_];\n float f1 = 7.99F;\n GL11.glBegin(5);\n GL11.glTexCoord2f((float)i / 128.0F, (float)j / 128.0F);\n GL11.glVertex3f(this.posX + (float)k, this.posY, 0.0F);\n GL11.glTexCoord2f((float)i / 128.0F, ((float)j + 7.99F) / 128.0F);\n GL11.glVertex3f(this.posX - (float)k, this.posY + 7.99F, 0.0F);\n GL11.glTexCoord2f(((float)i + f1 - 1.0F) / 128.0F, (float)j / 128.0F);\n GL11.glVertex3f(this.posX + f1 - 1.0F + (float)k, this.posY, 0.0F);\n GL11.glTexCoord2f(((float)i + f1 - 1.0F) / 128.0F, ((float)j + 7.99F) / 128.0F);\n GL11.glVertex3f(this.posX + f1 - 1.0F - (float)k, this.posY + 7.99F, 0.0F);\n GL11.glEnd();\n return f;\n }\n\n private ResourceLocation getUnicodePageLocation(int p_111271_1_) {\n if (unicodePageLocations[p_111271_1_] == null) {\n unicodePageLocations[p_111271_1_] = new ResourceLocation(String.format(\"textures/font/unicode_page_%02x.png\", p_111271_1_));\n unicodePageLocations[p_111271_1_] = FontUtils.getHdFontLocation(unicodePageLocations[p_111271_1_]);\n }\n\n return unicodePageLocations[p_111271_1_];\n }\n\n private void loadGlyphTexture(int p_78257_1_) {\n this.bindTexture(this.getUnicodePageLocation(p_78257_1_));\n }\n\n private float renderUnicodeChar(char p_78277_1_, boolean p_78277_2_) {\n if (this.glyphWidth[p_78277_1_] == 0) {\n return 0.0F;\n } else {\n int i = p_78277_1_ / 256;\n this.loadGlyphTexture(i);\n int j = this.glyphWidth[p_78277_1_] >>> 4;\n int k = this.glyphWidth[p_78277_1_] & 15;\n j &= 15;\n float f = (float)j;\n float f1 = (float)(k + 1);\n float f2 = (float)(p_78277_1_ % 16 * 16) + f;\n float f3 = (float)((p_78277_1_ & 255) / 16 * 16);\n float f4 = f1 - f - 0.02F;\n float f5 = p_78277_2_ ? 1.0F : 0.0F;\n GL11.glBegin(5);\n GL11.glTexCoord2f(f2 / 256.0F, f3 / 256.0F);\n GL11.glVertex3f(this.posX + f5, this.posY, 0.0F);\n GL11.glTexCoord2f(f2 / 256.0F, (f3 + 15.98F) / 256.0F);\n GL11.glVertex3f(this.posX - f5, this.posY + 7.99F, 0.0F);\n GL11.glTexCoord2f((f2 + f4) / 256.0F, f3 / 256.0F);\n GL11.glVertex3f(this.posX + f4 / 2.0F + f5, this.posY, 0.0F);\n GL11.glTexCoord2f((f2 + f4) / 256.0F, (f3 + 15.98F) / 256.0F);\n GL11.glVertex3f(this.posX + f4 / 2.0F - f5, this.posY + 7.99F, 0.0F);\n GL11.glEnd();\n return (f1 - f) / 2.0F + 1.0F;\n }\n }\n\n public int drawStringWithShadow(String text, float x, float y, int color) {\n return this.drawString(text, x, y, color, true);\n }\n\n public int drawString(String text, int x, int y, int color) {\n return !this.enabled ? 0 : this.drawString(text, (float)x, (float)y, color, false);\n }\n\n public int drawString(String text, float x, float y, int color, boolean dropShadow) {\n this.enableAlpha();\n this.resetStyles();\n int i;\n if (dropShadow) {\n i = this.renderString(text, x + 1.0F, y + 1.0F, color, true);\n i = Math.max(i, this.renderString(text, x, y, color, false));\n } else {\n i = this.renderString(text, x, y, color, false);\n }\n\n return i;\n }\n\n public int drawString(String text, float x, float y, int color, boolean dropShadow, float dropAdd) {\n this.enableAlpha();\n this.resetStyles();\n int i;\n if (dropShadow) {\n i = this.renderString(text, x + dropAdd, y + dropAdd, color, true);\n i = Math.max(i, this.renderString(text, x, y, color, false));\n } else {\n i = this.renderString(text, x, y, color, false);\n }\n\n return i;\n }\n\n private String bidiReorder(String p_147647_1_) {\n try {\n Bidi bidi = new Bidi(new ArabicShaping(8).shape(p_147647_1_), 127);\n bidi.setReorderingMode(0);\n return bidi.writeReordered(2);\n } catch (ArabicShapingException var31) {\n return p_147647_1_;\n }\n }\n\n private void resetStyles() {\n this.randomStyle = false;\n this.boldStyle = false;\n this.italicStyle = false;\n this.underlineStyle = false;\n this.strikethroughStyle = false;\n }\n\n private void renderStringAtPos(String p_78255_1_, boolean p_78255_2_) {\n for(int i = 0; i < p_78255_1_.length(); ++i) {\n char c0 = p_78255_1_.charAt(i);\n if (c0 == 167 && i + 1 < p_78255_1_.length()) {\n int i1 = \"0123456789abcdefklmnor\".indexOf(p_78255_1_.toLowerCase().charAt(i + 1));\n if (i1 < 16) {\n this.randomStyle = false;\n this.boldStyle = false;\n this.strikethroughStyle = false;\n this.underlineStyle = false;\n this.italicStyle = false;\n if (i1 < 0 || i1 > 15) {\n i1 = 15;\n }\n\n if (p_78255_2_) {\n i1 += 16;\n }\n\n int j1 = this.colorCode[i1];\n if (Config.isCustomColors()) {\n j1 = CustomColors.getTextColor(i1, j1);\n }\n\n this.textColor = j1;\n this.setColor((float)(j1 >> 16) / 255.0F, (float)(j1 >> 8 & 0xFF) / 255.0F, (float)(j1 & 0xFF) / 255.0F, this.alpha);\n } else if (i1 == 16) {\n this.randomStyle = true;\n } else if (i1 == 17) {\n this.boldStyle = true;\n } else if (i1 == 18) {\n this.strikethroughStyle = true;\n } else if (i1 == 19) {\n this.underlineStyle = true;\n } else if (i1 == 20) {\n this.italicStyle = true;\n } else if (i1 == 21) {\n this.randomStyle = false;\n this.boldStyle = false;\n this.strikethroughStyle = false;\n this.underlineStyle = false;\n this.italicStyle = false;\n this.setColor(this.red, this.blue, this.green, this.alpha);\n }\n\n ++i;\n } else {\n int j = \"ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000 !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\u0000ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\\u0000\"\n .indexOf(c0);\n if (this.randomStyle && j != -1) {\n int k = this.getCharWidth(c0);\n\n char c1;\n do {\n j = this.fontRandom\n .nextInt(\n \"ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000 !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\u0000ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\\u0000\"\n .length()\n );\n c1 = \"ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000 !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\u0000ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\\u0000\"\n .charAt(j);\n } while(k != this.getCharWidth(c1));\n\n c0 = c1;\n }\n\n float f1 = j != -1 && !this.unicodeFlag ? this.offsetBold : 0.5F;\n boolean flag = (c0 == 0 || j == -1 || this.unicodeFlag) && p_78255_2_;\n if (flag) {\n this.posX -= f1;\n this.posY -= f1;\n }\n\n float f = this.func_181559_a(c0, this.italicStyle);\n if (flag) {\n this.posX += f1;\n this.posY += f1;\n }\n\n if (this.boldStyle) {\n this.posX += f1;\n if (flag) {\n this.posX -= f1;\n this.posY -= f1;\n }\n\n this.func_181559_a(c0, this.italicStyle);\n this.posX -= f1;\n if (flag) {\n this.posX += f1;\n this.posY += f1;\n }\n\n f += f1;\n }\n\n if (this.strikethroughStyle) {\n Tessellator tessellator = Tessellator.getInstance();\n WorldRenderer worldrenderer = tessellator.getWorldRenderer();\n GlStateManager.disableTexture2D();\n worldrenderer.begin(7, DefaultVertexFormats.POSITION);\n worldrenderer.pos((double)this.posX, (double)(this.posY + (float)(this.FONT_HEIGHT / 2)), 0.0).endVertex();\n worldrenderer.pos((double)(this.posX + f), (double)(this.posY + (float)(this.FONT_HEIGHT / 2)), 0.0).endVertex();\n worldrenderer.pos((double)(this.posX + f), (double)(this.posY + (float)(this.FONT_HEIGHT / 2) - 1.0F), 0.0).endVertex();\n worldrenderer.pos((double)this.posX, (double)(this.posY + (float)(this.FONT_HEIGHT / 2) - 1.0F), 0.0).endVertex();\n tessellator.draw();\n GlStateManager.enableTexture2D();\n }\n\n if (this.underlineStyle) {\n Tessellator tessellator1 = Tessellator.getInstance();\n WorldRenderer worldrenderer1 = tessellator1.getWorldRenderer();\n GlStateManager.disableTexture2D();\n worldrenderer1.begin(7, DefaultVertexFormats.POSITION);\n int l = this.underlineStyle ? -1 : 0;\n worldrenderer1.pos((double)(this.posX + (float)l), (double)(this.posY + (float)this.FONT_HEIGHT), 0.0).endVertex();\n worldrenderer1.pos((double)(this.posX + f), (double)(this.posY + (float)this.FONT_HEIGHT), 0.0).endVertex();\n worldrenderer1.pos((double)(this.posX + f), (double)(this.posY + (float)this.FONT_HEIGHT - 1.0F), 0.0).endVertex();\n worldrenderer1.pos((double)(this.posX + (float)l), (double)(this.posY + (float)this.FONT_HEIGHT - 1.0F), 0.0).endVertex();\n tessellator1.draw();\n GlStateManager.enableTexture2D();\n }\n\n this.posX += f;\n }\n }\n }\n\n private int renderStringAligned(String text, int x, int y, int p_78274_4_, int color, boolean dropShadow) {\n if (this.bidiFlag) {\n int i = this.getStringWidth(this.bidiReorder(text));\n x = x + p_78274_4_ - i;\n }\n\n return this.renderString(text, (float)x, (float)y, color, dropShadow);\n }\n\n private int renderString(String text, float x, float y, int color, boolean dropShadow) {\n if (text == null) {\n return 0;\n } else {\n if (this.bidiFlag) {\n text = this.bidiReorder(text);\n }\n\n if ((color & -67108864) == 0) {\n color |= -16777216;\n }\n\n if (dropShadow) {\n color = (color & 16579836) >> 2 | color & 0xFF000000;\n }\n\n this.red = (float)(color >> 16 & 0xFF) / 255.0F;\n this.blue = (float)(color >> 8 & 0xFF) / 255.0F;\n this.green = (float)(color & 0xFF) / 255.0F;\n this.alpha = (float)(color >> 24 & 0xFF) / 255.0F;\n this.setColor(this.red, this.blue, this.green, this.alpha);\n this.posX = x;\n this.posY = y;\n this.renderStringAtPos(text, dropShadow);\n return (int)this.posX;\n }\n }\n\n public int getStringWidth(String text) {\n if (text == null) {\n return 0;\n } else {\n float f = 0.0F;\n boolean flag = false;\n\n for(int i = 0; i < text.length(); ++i) {\n char c0 = text.charAt(i);\n float f1 = this.getCharWidthFloat(c0);\n if (f1 < 0.0F && i < text.length() - 1) {\n c0 = text.charAt(++i);\n if (c0 == 'l' || c0 == 'L') {\n flag = true;\n } else if (c0 == 'r' || c0 == 'R') {\n flag = false;\n }\n\n f1 = 0.0F;\n }\n\n f += f1;\n if (flag && f1 > 0.0F) {\n f += this.unicodeFlag ? 1.0F : this.offsetBold;\n }\n }\n\n return (int)f;\n }\n }\n\n public int getCharWidth(char character) {\n return Math.round(this.getCharWidthFloat(character));\n }\n\n private float getCharWidthFloat(char p_getCharWidthFloat_1_) {\n if (p_getCharWidthFloat_1_ == 167) {\n return -1.0F;\n } else if (p_getCharWidthFloat_1_ == ' ') {\n return this.charWidth[32];\n } else {\n int i = \"ÀÁÂÈÊËÍÓÔÕÚßãõğİıŒœŞşŴŵžȇ\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000 !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\u0000ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αβΓπΣσμτΦΘΩδ∞∅∈∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\\u0000\"\n .indexOf(p_getCharWidthFloat_1_);\n if (p_getCharWidthFloat_1_ > 0 && i != -1 && !this.unicodeFlag) {\n return this.charWidth[i];\n } else if (this.glyphWidth[p_getCharWidthFloat_1_] != 0) {\n int j = this.glyphWidth[p_getCharWidthFloat_1_] >>> 4;\n int k = this.glyphWidth[p_getCharWidthFloat_1_] & 15;\n j &= 15;\n ++k;\n return (float)((k - j) / 2 + 1);\n } else {\n return 0.0F;\n }\n }\n }\n\n public String trimStringToWidth(String text, int width) {\n return this.trimStringToWidth(text, width, false);\n }\n\n public String trimStringToWidth(String text, int width, boolean reverse) {\n StringBuilder stringbuilder = new StringBuilder();\n float f = 0.0F;\n int i = reverse ? text.length() - 1 : 0;\n int j = reverse ? -1 : 1;\n boolean flag = false;\n boolean flag1 = false;\n\n for(int k = i; k >= 0 && k < text.length() && f < (float)width; k += j) {\n char c0 = text.charAt(k);\n float f1 = this.getCharWidthFloat(c0);\n if (flag) {\n flag = false;\n if (c0 == 'l' || c0 == 'L') {\n flag1 = true;\n } else if (c0 == 'r' || c0 == 'R') {\n flag1 = false;\n }\n } else if (f1 < 0.0F) {\n flag = true;\n } else {\n f += f1;\n if (flag1) {\n ++f;\n }\n }\n\n if (f > (float)width) {\n break;\n }\n\n if (reverse) {\n stringbuilder.insert(0, c0);\n } else {\n stringbuilder.append(c0);\n }\n }\n\n return stringbuilder.toString();\n }\n\n private String trimStringNewline(String text) {\n while(text != null && text.endsWith(\"\\n\")) {\n text = text.substring(0, text.length() - 1);\n }\n\n return text;\n }\n\n public void drawSplitString(String str, int x, int y, int wrapWidth, int textColor) {\n this.resetStyles();\n this.textColor = textColor;\n str = this.trimStringNewline(str);\n this.renderSplitString(str, x, y, wrapWidth, false);\n }\n\n private void renderSplitString(String str, int x, int y, int wrapWidth, boolean addShadow) {\n for(Object s : this.listFormattedStringToWidth(str, wrapWidth)) {\n this.renderStringAligned((String)s, x, y, wrapWidth, this.textColor, addShadow);\n y += this.FONT_HEIGHT;\n }\n }\n\n public int splitStringWidth(String p_78267_1_, int p_78267_2_) {\n return this.FONT_HEIGHT * this.listFormattedStringToWidth(p_78267_1_, p_78267_2_).size();\n }\n\n public void setUnicodeFlag(boolean unicodeFlagIn) {\n this.unicodeFlag = unicodeFlagIn;\n }\n\n public boolean getUnicodeFlag() {\n return this.unicodeFlag;\n }\n\n public void setBidiFlag(boolean bidiFlagIn) {\n this.bidiFlag = bidiFlagIn;\n }\n\n public List listFormattedStringToWidth(String str, int wrapWidth) {\n return Arrays.asList(this.wrapFormattedStringToWidth(str, wrapWidth).split(\"\\n\"));\n }\n\n String wrapFormattedStringToWidth(String str, int wrapWidth) {\n int i = this.sizeStringToWidth(str, wrapWidth);\n if (str.length() <= i) {\n return str;\n } else {\n String s = str.substring(0, i);\n char c0 = str.charAt(i);\n boolean flag = c0 == ' ' || c0 == '\\n';\n String s1 = getFormatFromString(s) + str.substring(i + (flag ? 1 : 0));\n return s + \"\\n\" + this.wrapFormattedStringToWidth(s1, wrapWidth);\n }\n }\n\n private int sizeStringToWidth(String str, int wrapWidth) {\n int i = str.length();\n float f = 0.0F;\n int j = 0;\n int k = -1;\n\n for(boolean flag = false; j < i; ++j) {\n char c0 = str.charAt(j);\n switch(c0) {\n case '\\n':\n --j;\n break;\n case ' ':\n k = j;\n default:\n f += this.getCharWidthFloat(c0);\n if (flag) {\n ++f;\n }\n break;\n case '§':\n if (j < i - 1) {\n char c1 = str.charAt(++j);\n if (c1 == 'l' || c1 == 'L') {\n flag = true;\n } else if (c1 == 'r' || c1 == 'R' || isFormatColor(c1)) {\n flag = false;\n }\n }\n }\n\n if (c0 == '\\n') {\n k = ++j;\n break;\n }\n\n if (f > (float)wrapWidth) {\n break;\n }\n }\n\n return j != i && k != -1 && k < j ? k : j;\n }\n\n private static boolean isFormatColor(char colorChar) {\n return colorChar >= '0' && colorChar <= '9' || colorChar >= 'a' && colorChar <= 'f' || colorChar >= 'A' && colorChar <= 'F';\n }\n\n private static boolean isFormatSpecial(char formatChar) {\n return formatChar >= 'k' && formatChar <= 'o' || formatChar >= 'K' && formatChar <= 'O' || formatChar == 'r' || formatChar == 'R';\n }\n\n public static String getFormatFromString(String text) {\n String s = \"\";\n int i = -1;\n int j = text.length();\n\n while((i = text.indexOf(167, i + 1)) != -1) {\n if (i < j - 1) {\n char c0 = text.charAt(i + 1);\n if (isFormatColor(c0)) {\n s = \"§\" + c0;\n } else if (isFormatSpecial(c0)) {\n s = s + \"§\" + c0;\n }\n }\n }\n\n return s;\n }\n\n public boolean getBidiFlag() {\n return this.bidiFlag;\n }\n\n public int getColorCode(char character) {\n int i = \"0123456789abcdef\".indexOf(character);\n if (i >= 0 && i < this.colorCode.length) {\n int j = this.colorCode[i];\n if (Config.isCustomColors()) {\n j = CustomColors.getTextColor(i, j);\n }\n\n return j;\n } else {\n return 16777215;\n }\n }\n\n protected void setColor(float p_setColor_1_, float p_setColor_2_, float p_setColor_3_, float p_setColor_4_) {\n GlStateManager.color(p_setColor_1_, p_setColor_2_, p_setColor_3_, p_setColor_4_);\n }\n\n protected void enableAlpha() {\n GlStateManager.enableAlpha();\n }\n\n protected void bindTexture(ResourceLocation p_bindTexture_1_) {\n this.renderEngine.bindTexture(p_bindTexture_1_);\n }\n\n protected InputStream getResourceInputStream(ResourceLocation p_getResourceInputStream_1_) throws IOException {\n return Minecraft.getMinecraft().getResourceManager().getResource(p_getResourceInputStream_1_).getInputStream();\n }\n\n public void drawString(String string, float x, float y, int rgb) {\n drawString(string, (int)x, (int)y, rgb);\n }\n}", "answers": [" this.name = name;"], "length": 5524, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ac6c14b6-a168-464a-9305-72fffe1af15d", "reasoning": "In the Module class, the constructor begins with the signature `public Module(String name, Color color, Categorys category) {`. The first logical step inside the constructor is to assign the passed-in name to the instance field `name`. This matches typical Java practice of initializing fields at the start of a constructor.", "reasoning_model_answer": "this.name = name;", "assistant_with_reasoning": "\nIn the Module class, the constructor begins with the signature `public Module(String name, Color color, Categorys category) {`. The first logical step inside the constructor is to assign the passed-in name to the instance field `name`. This matches typical Java practice of initializing fields at the start of a constructor.\n\nthis.name = name;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.798, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36914, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "this.name = name;", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "import net.sourceforge.offroad.OsmWindow;\nimport java.awt.event.ActionEvent;\nimport net.osmand.plus.views.DrawPolylineLayer.Polyline;", "context": "src/net/sourceforge/offroad/actions/RemovePolylineAction.java\n/** \n OffRoad\n Copyright (C) 2017 Christian Foltin\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\npackage net.sourceforge.offroad.actions;\n\n\n\n/**\n * @author foltin\n * @date 19.05.2017\n */\npublic class RemovePolylineAction extends OffRoadAction {\n\n\tprivate Polyline mPolyline;\n\n\nsrc/net/osmand/plus/views/DrawPolylineLayer.java\n@XmlRootElement\npublic static class Polyline {\n\tprivate Vector mCoordinates = new Vector<>();\n\tpublic LatLon set(int pIndex, LatLon pElement) {\n\t\treturn mCoordinates.set(pIndex, pElement);\n\t}\n\tpublic boolean contains(Object pO) {\n\t\treturn mCoordinates.contains(pO);\n\t}\n\tpublic int indexOf(Object pO) {\n\t\treturn mCoordinates.indexOf(pO);\n\t}\n\tpublic boolean remove(Object pO) {\n\t\treturn mCoordinates.remove(pO);\n\t}\n\tpublic int size() {\n\t\treturn mCoordinates.size();\n\t}\n\tpublic boolean isEmpty() {\n\t\treturn mCoordinates.isEmpty();\n\t}\n\tpublic LatLon get(int pIndex) {\n\t\treturn mCoordinates.get(pIndex);\n\t}\n\tpublic boolean add(LatLon pE) {\n\t\treturn mCoordinates.add(pE);\n\t}\n\t@XmlElement(name=\"latlon\")\n\tpublic Vector getCoordinates() {\n\t\treturn mCoordinates;\n\t}\n\tpublic void setCoordinates(Vector pItems) {\n\t\tmCoordinates = pItems;\n\t}\n\t\t\n\tpublic Polyline() {\n\t}\n\tpublic EdgeDistance getDistanceToEdges(LatLon pDest, OsmBitmapPanel pDrawPanel) {\n\t\treturn getDistanceToEdges(pDrawPanel.getPoint(pDest), pDrawPanel);\n\t}\n\tpublic EdgeDistance getDistanceToEdges(Point pDest, OsmBitmapPanel pDrawPanel) {\n\t\tdouble minDist = Double.MAX_VALUE;\n\t\tPoint minPointP = null;\n\t\tint index = 0;\n\t\tint minIndex = -1;\n\t\tfor (LatLon latLonP : this.getCoordinates()) {\n\t\t\tPoint pointP = pDrawPanel.getPoint(latLonP);\n\t\t\tdouble dist = pDest.distance(pointP);\n\t\t\tif (dist < minDist) {\n\t\t\t\tminIndex = index;\n\t\t\t\tminDist = dist;\n\t\t\t\tminPointP = pointP;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t\tEdgeDistance ret = new EdgeDistance(minDist, this, minIndex, minPointP);\n\t\treturn ret;\n\t}\n\n\tpublic double getDistance(Point pDest, OsmBitmapPanel pDrawPanel) {\n\t\tPolylineDistance distanceInfo = getDistanceInformation(pDest, pDrawPanel);\n\t\tif(distanceInfo == null) {\n\t\t\treturn Double.MAX_VALUE;\n\t\t}\n\t\treturn distanceInfo.distance;\n\t}\n\tpublic PolylineDistance getDistanceInformation(Point pDest, OsmBitmapPanel pDrawPanel) {\n\t\tdouble minDist = Double.MAX_VALUE;\n\t\tPoint lastPointInLine = null;\n\t\tint indexAfterSegment = 0;\n\t\tint minDistanceIndex = -1;\n\t\tfor (LatLon latLonP : this.getCoordinates()) {\n\t\t\tPoint pointP = pDrawPanel.getPoint(latLonP);\n\t\t\tif (lastPointInLine != null) {\n\t\t\t\tdouble dist = getDistance(pDest, pointP, lastPointInLine);\n\t\t\t\tif(dist < minDist) {\n\t\t\t\t\tminDistanceIndex = indexAfterSegment;\n\t\t\t\t}\n\t\t\t\tminDist = Math.min(dist, minDist);\n\t\t\t}\n\t\t\tlastPointInLine = pointP;\n\t\t\tindexAfterSegment++;\n\t\t}\n\t\tif(minDistanceIndex < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn new PolylineDistance(minDist, this, minDistanceIndex-1, minDistanceIndex);\n\t}\n\n\tpublic double getDistance(Point pDest, Point pointA, Point pointB) {\n\t\t// adapted from\n\t\t// http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment\n\t\tfloat x1 = pointA.x;\n\t\tfloat y1 = pointA.y;\n\t\tfloat x2 = pointB.x;\n\t\tfloat y2 = pointB.y;\n\t\tfloat x = pDest.x;\n\t\tfloat y = pDest.y;\n\t\tfloat A = x - x1;\n\t\tfloat B = y - y1;\n\t\tfloat C = x2 - x1;\n\t\tfloat D = y2 - y1;\n\n\t\tfloat dot = A * C + B * D;\n\t\tfloat len_sq = C * C + D * D;\n\t\tfloat param = -1;\n\t\t// in case of 0 length line\n\t\tif (len_sq != 0) {\n\t\t\tparam = dot / len_sq;\n\t\t}\n\n\t\tfloat xx, yy;\n\n\t\tif (param < 0) {\n\t\t\txx = x1;\n\t\t\tyy = y1;\n\t\t} else if (param > 1) {\n\t\t\txx = x2;\n\t\t\tyy = y2;\n\t\t} else {\n\t\t\txx = x1 + param * C;\n\t\t\tyy = y1 + param * D;\n\t\t}\n\n\t\tfloat dx = x - xx;\n\t\tfloat dy = y - yy;\n\t\treturn Math.sqrt(dx * dx + dy * dy);\n\t}\n\n\n\tpublic double calculateArea() {\n\t\tVector v = new Vector<>();\n\t\tfor (LatLon latLon : this.getCoordinates()) {\n\t\t\tv.add(new Node(latLon.getLatitude(), latLon.getLongitude(), 1));\n\t\t}\n\t\treturn OsmMapUtils.getArea(v);\n\t}\n\n\t/**\n\t * @return the length of the polyline in kilometers\n\t */\n\tpublic float calculateLength() {\n\t\tfloat polyDist = 0f;\n\t\tfor (int i = 0; i < size(); i++) {\n\t\t\tLatLon pos = get(i);\n\t\t\tif (i + 1 < size()) {\n\t\t\t\tLatLon pos2 = get(i + 1);\n\t\t\t\tpolyDist += MapUtils.getDistance(pos, pos2);\n\t\t\t}\n\t\t}\n\t\tpolyDist /= 1000d;\n\t\treturn polyDist;\n\t}\n\tpublic void insert(LatLon pLatLon, int pIndexToInsert) {\n\t\tmCoordinates.insertElementAt(pLatLon, pIndexToInsert);\n\t}\n}\n\nsrc/net/sourceforge/offroad/OsmWindow.java\npublic class OsmWindow implements IRouteInformationListener {\n\tpublic static class MapPointStorage {\n\n\t\tprivate final LatLon mPoint;\n\t\tprivate final int mZoom;\n\n\t\tpublic MapPointStorage(LatLon pPoint, int pZoom) {\n\t\t\tmPoint = pPoint;\n\t\t\tmZoom = pZoom;\n\t\t}\n\n\t}\n\n\tprivate final static Log log = PlatformUtil.getLog(OsmWindow.class);\n\n\t\n\tpublic static final int MAX_ZOOM = 22;\n\tpublic static final String RENDERING_STYLES_DIR = \"rendering_styles/\"; //$NON-NLS-1$\n\tprivate static final String OSMAND_ICONS_DIR = RENDERING_STYLES_DIR + \"style-icons/drawable-\"; //$NON-NLS-1$\n\tpublic static final String IMAGE_PATH = \"drawable-\"; //$NON-NLS-1$\n\tpublic static final String PROXY_PORT = \"proxy.port\";\n\tpublic static final String PROXY_HOST = \"proxy.host\";\n\tpublic static final String PROXY_PASSWORD = \"proxy.password\";\n\tpublic static final String PROXY_USER = \"proxy.user\";\n\tpublic static final String PROXY_IS_AUTHENTICATED = \"proxy.is_authenticated\";\n\tpublic static final String PROXY_USE_SETTINGS = \"proxy.use_settings\";\n\tpublic static final String PROXY_EXCEPTION = \"proxy.exception\";\n\tprivate static final String OFFROAD_PROPERTIES = \"offroad\";\n\tpublic static final int MIN_ZOOM = 5;\n\tprivate static final String MODE_WORLD_WRITEABLE = \"mode_world_writeable\";\n\tprivate static final String VECTOR_INDEXES_CHECK = \"vector_indexes_check\";\n\tpublic static final String OSMAND_ICONS_DIR_PREFIX = \"osmand_icons_dir_prefix\";\n\tpublic static final String OSMAND_ICONS_DIR_DEFAULT_PREFIX = \"hdpi\";\n\tprivate static final String[] sOsmandIconsPrefixes = new String[]{\"mdpi\", OSMAND_ICONS_DIR_DEFAULT_PREFIX, \"xhdpi\", \"xxhdpi\"};\n\n\tprivate static OsmWindow sInstance = null;\n\tprivate ResourceManager mResourceManager;\n\tprivate OffRoadSettings settings = new OffRoadSettings(this);\n\tprivate OsmandSettings prefs = new OsmandSettings(this, settings);\n\tprivate Properties mOffroadProperties = (Properties) settings.getPreferenceObject(\"offroad\");\n\tprivate R.string mStrings;\n\tprivate OsmandRegions mRegions;\n\tprivate OsmBitmapPanel mDrawPanel;\n\tprivate OsmBitmapPanelMouseAdapter mAdapter;\n\tprivate JFrame mFrame;\n\tprivate JLabel mStatusLabel;\n\tprivate JLabel mRouteProgressStatus;\n\tprivate JProgressBar mRouteProgressBar;\n\tprivate Timer mMouseMoveTimer;\n\tprivate GeoServer mGeoServer;\n\tpublic int widthPixels;\n\tpublic float density;\n\tpublic int heightPixels;\n\tprivate RendererRegistry mRendererRegistry;\n\tprivate TargetPointsHelper mTargetPointsHelper;\n\tprivate RoutingHelper mRoutingHelper;\n\tprivate GeocodingLookupService mGeocodingLookupService;\n\tprivate MapPoiTypes mMapPoiTypes;\n\tprivate int mDontUpdateStatusLabelCounter;\n\tprivate Resources mResourceStrings;\n\tprivate PropertyResourceBundle mOffroadResources;\n\tprivate Vector mPointStorage = new Vector<>();\n\tprivate int mPointStorageIndex = -1;\n\tprivate JPanel mStatusBar;\n\tprivate PoiFiltersHelper mPoiFilters;\n\tprivate AmenityTablePanel mAmenityTable;\n\tprivate MapMarkersHelper mMapMarkersHelper;\n\n\n\tprivate JToolBar mToolBar;\n\tprivate JTextField mSearchTextField;\n\tprivate JComboBox mComboBox;\n\tprivate DefaultComboBoxModel mComboBoxModel;\n\tprivate boolean mSearchBarVisible = true;\n\tVector mCursorPositionListeners = new Vector<>();\n\tprivate PoiUIFilter mCurrentPoiFilter;\n\n\n\tprivate SQLiteImpl mSqLiteImpl;\n\n\n\tprivate FavouritesDbHelper mFavorites;\n\n\n\tprivate OsmAndLocationProvider mOsmAndLocationProvider;\n\n\n\tprivate JSplitPane mSplitPane;\n\n\n\tprivate OffRoadResources mOffRoadResources;\n\n\n\tprivate GpxSelectionHelper mGpxSelectionHelper;\n\n\n\tprivate SavingTrackHelper mSavingTrackHelper;\n\n\n\tprivate VersionInfo mVersionInfo;\n\t\n\tprivate enum SearchType {\n\t\tAMENITY, ROUTE\n\t}\n\n\tprivate SearchType mSearchType = SearchType.AMENITY;\n\n\n\tprivate List mRouteResult = new Vector<>();\n\n\n\tprivate JMenuItem mAddFavourite;\n\n\n\tprivate JMenuItem mSelectTrack;\n\n\n\tprivate HashMap mBufferedImageCache = new HashMap<>();\n\n\n\tprivate JTextField mDirectSearchTextField;\n\n\n\tpublic DirectSearchAction mDirectSearchAction;\n\n\n\tprivate JPanel mDirectSearchPanel;\n\n\n\tprivate JCheckBox mDirectSearchFuzzy;\n\n\n\tprivate JButton mDirectSearchBackward;\n\n\n\tprivate JButton mDirectSearchForward;\n\n\n\tprivate JButton mDirectSearchClose;\n\n\n\tprivate boolean mDirectSearchVisible;\n\n\n\tprivate JLabel mQueueStatus; \n\t\n\tprivate static void addFavoriteGroups(OsmWindow context, JMenu parent, List fgs) {\n\t\tHashMap groupMenus = new HashMap<>();\n\t\tfor (FavoriteGroup fg : fgs) {\n\t\t\tJMenu groupMenu = groupMenus.getOrDefault(fg.name, null);\n\t\t\tif (groupMenu == null) {\n\t\t\t\tString[] levels = fg.name.split(\"/\");\n\t\t\t\tJMenu prev = parent;\n\t\t\t\tString path = null;\n\t\t\t\tfor (String currName : levels) {\n\t\t\t\t\tpath = path == null ? currName : path + \"/\" + currName;\n\t\t\t\t\tJMenu curr = groupMenus.getOrDefault(path, null);\n\t\t\t\t\tif (curr == null) {\n\t\t\t\t\t\tcurr = new JMenu(currName);\n\t\t\t\t\t\tprev.add(curr);\n\t\t\t\t\t\tgroupMenus.put(path, curr);\n\t\t\t\t\t}\n\t\t\t\t\tprev = curr;\n\t\t\t\t}\n\t\t\t\tgroupMenu = prev;\n\t\t\t}\n\t\t\tfor (FavouritePoint fp : fg.points) {\n\t\t\t\tJMenuItem lFavoritesItem = new JMenuItem(new ShowFavoriteAction(context, fp));\n\t\t\t\tgroupMenu.add(lFavoritesItem);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void createAndShowUI() {\n\t\tmDirectSearchTextField = new JTextField(getOffRoadString(\"offroad.DirectSearchText\"));\n\t\tmDirectSearchFuzzy = new JCheckBox(getOffRoadString(\"offroad.fuzzy_search\"));\n\t\tmDirectSearchFuzzy.setFocusable(false);\n\t\tmDirectSearchClose = new JButton(new ImageIcon(readImageInternally(\"button_cancel.png\")));\n\t\tmDirectSearchBackward = new JButton(new ImageIcon(readImageInternally(\"up.png\")));\n\t\tmDirectSearchForward = new JButton(new ImageIcon(readImageInternally(\"down.png\")));\n\t\tmDirectSearchAction = new DirectSearchAction(this, mDirectSearchTextField, mDirectSearchFuzzy,\n\t\t\t\tmDirectSearchBackward, mDirectSearchForward, mDirectSearchClose);\n\t\tmDirectSearchClose.addActionListener(pE -> {\n\t\t\tmStatusBar.remove(mDirectSearchPanel);\n\t\t\tmDirectSearchVisible = false;\n\t\t\tmFrame.revalidate();\n\t\t});\n\t\tmDrawPanel = new OsmBitmapPanel(this);\n\t\tmAdapter = new OsmBitmapPanelMouseAdapter(mDrawPanel);\n\t\tmDrawPanel.addMouseListener(mAdapter);\n\t\tmDrawPanel.addMouseMotionListener(mAdapter);\n\t\tmDrawPanel.addMouseWheelListener(mAdapter);\n\t\t\n\t\tmStatusLabel = new JLabel(\"!\"); //$NON-NLS-1$\n\t\tmStatusLabel.setPreferredSize(mStatusLabel.getPreferredSize());\n\t\tmQueueStatus = new JLabel(\"!\"); //$NON-NLS-1$\n\t\tmQueueStatus.setPreferredSize(mQueueStatus.getPreferredSize());\n\t\tmRouteProgressBar = new JProgressBar();\n\t\tmRouteProgressBar.setMaximum(100);\n\t\tmRouteProgressBar.setStringPainted(true);\n\t\tmRouteProgressBar.setVisible(false);\n\t\tmRouteProgressStatus = new JLabel(\"!\");\n\t\tmDirectSearchPanel = new JPanel();\n\t\tmDirectSearchPanel.setLayout(new GridBagLayout());\n\t\tint x = 0;\n\t\tmDirectSearchPanel.add(mDirectSearchClose, new GridBagConstraints(x++, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tmDirectSearchPanel.add(mDirectSearchTextField, new GridBagConstraints(x++, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\t\tmDirectSearchPanel.add(mDirectSearchBackward, new GridBagConstraints(x++, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tmDirectSearchPanel.add(mDirectSearchForward, new GridBagConstraints(x++, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tmDirectSearchPanel.add(mDirectSearchFuzzy, new GridBagConstraints(x++, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tadaptMenuMnemonics(mDirectSearchPanel.getComponents());\n\t\tmStatusBar=new JPanel();\n\t\tmStatusBar.setLayout(new GridBagLayout());\n\t\tx = 0;\n\t\tmStatusBar.add(mStatusLabel, new GridBagConstraints(x++, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n//\t\tmStatusBar.add(mDirectSearchPanel, new GridBagConstraints(x++, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\t\tmDirectSearchVisible = false;\n\t\tx++;\n\t\tmStatusBar.add(mQueueStatus, new GridBagConstraints(x++, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\t\tmStatusBar.add(mRouteProgressStatus, new GridBagConstraints(x++, 0, 1, 1, 0, 1, GridBagConstraints.EAST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tmStatusBar.add(mRouteProgressBar, new GridBagConstraints(x++, 0, 1, 1, 1, 1, GridBagConstraints.EAST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\t\n\n\t\tmMouseMoveTimer = new Timer(500, new StatusLabelAction() );\n\t\tmMouseMoveTimer.setRepeats(true);\n\t\tmMouseMoveTimer.start();\n\n\t\tmToolBar = new JToolBar(JToolBar.HORIZONTAL);\n\t\tmToolBar.setLayout(new GridBagLayout());\n\t\tmToolBar.add(new JLabel(getOffRoadString(\"offroad.search\")), new GridBagConstraints(0, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\t\n\t\tmSearchTextField = new JTextField();\n\t\tmSearchTextField.getInputMap().put(KeyStroke.getKeyStroke(\"control LEFT\"), \"none\");\n\t\tmSearchTextField.getInputMap().put(KeyStroke.getKeyStroke(\"control RIGHT\"), \"none\");\n\t\tmSearchTextField.setText(getSettings().SELECTED_POI_FILTER_STRING_FOR_MAP.get());\n\t\tmAmenityTable = new AmenityTablePanel(this);\n\t\tgetSearchTextField().addActionListener(pE -> setPoiFilter(getCurrentPoiUIFilter(), getSearchTextField().getText()));\n\t\tgetSearchTextField().addKeyListener(new KeyListener() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void keyTyped(KeyEvent pE) {\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void keyReleased(KeyEvent pE) {\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void keyPressed(KeyEvent pE) {\n\t\t\t\tif(!pE.isControlDown()){\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tswitch (pE.getKeyCode()) {\n\t\t\t\tcase KeyEvent.VK_UP:\n\t\t\t\t\tif(mComboBox.getSelectedIndex()>0){\n\t\t\t\t\t\tmComboBox.setSelectedIndex(mComboBox.getSelectedIndex()-1);\n\t\t\t\t\t}\n\t\t\t\t\tpE.consume();\n\t\t\t\t\tbreak;\n\t\t\t\tcase KeyEvent.VK_DOWN:\n\t\t\t\t\tif(mComboBox.getSelectedIndex()();\n\t\tmComboBoxModel = new DefaultComboBoxModel<>();\n\t\tmCurrentPoiFilter = mPoiFilters.getSearchByNamePOIFilter();\n\t\tmComboBoxModel.addElement(mPoiFilters.getSearchByNamePOIFilter());\n\t\tmComboBoxModel.addElement(mPoiFilters.getNominatimAddressFilter());\n\t\tmComboBoxModel.addElement(mPoiFilters.getNominatimPOIFilter());\n\t\tfor (PoiUIFilter filter : mPoiFilters.getTopDefinedPoiFilters()) {\n\t\t\tmComboBoxModel.addElement(filter);\n\t\t}\n\t\tmComboBox.setModel(mComboBoxModel);\n\t\tmComboBox.setFocusable(false);\n\t\tmComboBox.addActionListener(pE -> {\n\t\t\tif(mComboBox.getSelectedIndex() >= 0){\n\t\t\t\tmCurrentPoiFilter = mComboBoxModel.getElementAt(mComboBox.getSelectedIndex());\n\t\t\t}\n\t\t});\n\t\tmComboBox.setRenderer(new PoiFilterRenderer<>());\n\t\tmToolBar.add(mComboBox, new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\tmFrame = new JFrame(getOffRoadString(\"offroad.string4\")); //$NON-NLS-1$\n\t\tmFrame.setIconImage(readImageInternally(\"offroad_icon.png\"));\n\t\tmFrame.getContentPane().setLayout(new BorderLayout());\n\t\tmFrame.getContentPane().add(mToolBar, BorderLayout.NORTH);\n\t\tmSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mAmenityTable, mDrawPanel);\n\t\tmFrame.getContentPane().add(mSplitPane);\n\t\tmFrame.getContentPane().add(mStatusBar, BorderLayout.SOUTH);\n\t\tmFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\n\t\tmFrame.addWindowListener(new WindowAdapter() {\n\t\t\t@Override\n\t\t\tpublic void windowClosing(WindowEvent pE) {\n\t\t\t\tcloseWindow();\n\t\t\t}\n\t\t});\n\t\tmFrame.setResizable(true);\n\t\tmDrawPanel.addComponentListener(mAdapter);\n\t\tJMenuBar menubar = new JMenuBar();\n\t\tJMenu jFileMenu = new JMenu(getOffRoadString(\"offroad.string5\")); //$NON-NLS-1$\n\t\tJMenuItem saveItem = new JMenuItem(getOffRoadString(\"offroad.string6\")); //$NON-NLS-1$\n\t\tsaveItem.addActionListener(pE -> {\n\t\t\tJFileChooser chooser = new JFileChooser();\n\t\t\tint showSaveDialog = chooser.showSaveDialog(mFrame);\n\t\t\tif(showSaveDialog == JFileChooser.APPROVE_OPTION){\n\t\t\t\t// TODO: Ask for overwrite.\n\t\t\t\tmDrawPanel.saveImage(chooser.getSelectedFile());\n\t\t\t}\n\t\t});\n\t\tjFileMenu.add(saveItem);\n\t\tJMenuItem importGpxItem = new JMenuItem(getOffRoadString(\"offroad.import_gpx\")); //$NON-NLS-1$\n\t\timportGpxItem.addActionListener(new GpxImportAction(this));\n\t\tjFileMenu.add(importGpxItem);\n\t\taddToMenu(jFileMenu, \"offroad.export_route\", new ExportRouteAction(this), null);\n\t\taddToMenu(jFileMenu, \"offroad.export_tracks\", new ExportTracksAction(this), null);\n\t\taddToMenu(jFileMenu, \"offroad.copy_location\", new CopyLocationToClipboardAction(this), \"alt C\");\n\t\taddToMenu(jFileMenu, \"offroad.exit\", item -> closeWindow(), \"control Q\");\n\t\tmenubar.add(jFileMenu);\n\t\tJMenu jSearchMenu = new JMenu(getOffRoadString(\"offroad.string7\")); //$NON-NLS-1$\n\t\tJMenuItem findItem = new JMenuItem(getOffRoadString(\"offroad.string8\")); //$NON-NLS-1$\n\t\tfindItem.addActionListener(new SearchAddressAction(this));\n\t\tfindItem.setAccelerator(KeyStroke.getKeyStroke(\"control F\")); //$NON-NLS-1$\n\t\tjSearchMenu.add(findItem);\n\t\t\n\t\tJMenuItem gotoSearchFieldItem = new JMenuItem(getOffRoadString(\"offroad.gotoSearchField\")); //$NON-NLS-1$\n\t\tgotoSearchFieldItem.addActionListener(pE -> {\n\t\t\tgetSearchTextField().selectAll();\n\t\t\tgetSearchTextField().requestFocus();\n\t\t});\n\t\tgotoSearchFieldItem.setAccelerator(KeyStroke.getKeyStroke(\"control K\")); //$NON-NLS-1$\n\t\tjSearchMenu.add(gotoSearchFieldItem);\n\t\taddToMenu(jSearchMenu, null, mDirectSearchAction, \"control shift F\");\n\t\tmenubar.add(jSearchMenu);\n\t\t// Download\n\t\tJMenu jDownloadMenu = new JMenu(getOffRoadString(\"offroad.download\")); //$NON-NLS-1$\n\t\tJMenuItem lDownloadItem = new JMenuItem(getOffRoadString(\"offroad.string11\")); //$NON-NLS-1$\n\t\tlDownloadItem.addActionListener(new DownloadAction(this));\n\t\tlDownloadItem.setAccelerator(KeyStroke.getKeyStroke(\"control G\")); //$NON-NLS-1$\n\t\tjDownloadMenu.add(lDownloadItem);\n\t\tmenubar.add(jDownloadMenu);\n\t\t// View\n\t\tJMenu jViewMenu = new JMenu(getOffRoadString(\"offroad.view\")); //$NON-NLS-1$\n\t\tJMenuItem lViewItem = new JMenuItem(getOffRoadString(\"offroad.toggle_search\")); //$NON-NLS-1$\n\t\tlViewItem.addActionListener(item-> toggleSearchBar());\n\t\tlViewItem.setAccelerator(KeyStroke.getKeyStroke(\"F11\")); //$NON-NLS-1$\n\t\tjViewMenu.add(lViewItem);\n\t\tjViewMenu.add(new JMenuItem(new SetCursorRadiusAction(this, \"offroad.cursor_radius_1km\", 1000d)));\n\t\tjViewMenu.add(new JMenuItem(new SetCursorRadiusAction(this, \"offroad.cursor_radius_2km\", 2000d)));\n\t\tjViewMenu.add(new JMenuItem(new SetCursorRadiusAction(this, \"offroad.cursor_radius_5km\", 5000d)));\n\t\tjViewMenu.add(new JMenuItem(new SetCursorRadiusAction(this, \"offroad.remove_cursor_radius\", 0d)));\n\t\tjViewMenu.add(new JSeparator());\n\t\tJMenu jMetricSystemMenu = new JMenu(getString(\"unit_of_length\"));\n jMetricSystemMenu.add(new OffRoadMenuItem(new ChooseMetricSystemAction(this, MetricsConstants.KILOMETERS_AND_METERS), jMetricSystemMenu));\n jMetricSystemMenu.add(new OffRoadMenuItem(new ChooseMetricSystemAction(this, MetricsConstants.MILES_AND_FOOTS), jMetricSystemMenu));\n jMetricSystemMenu.add(new OffRoadMenuItem(new ChooseMetricSystemAction(this, MetricsConstants.NAUTICAL_MILES), jMetricSystemMenu));\n jMetricSystemMenu.add(new OffRoadMenuItem(new ChooseMetricSystemAction(this, MetricsConstants.MILES_AND_YARDS), jMetricSystemMenu));\n jViewMenu.add(jMetricSystemMenu);\n\t\tJMenu jApplicationModeMenu = new JMenu(getString(\"app_modes_choose\"));\n\t\tjApplicationModeMenu.add(new OffRoadMenuItem(new ChooseApplicationModeAction(this, ApplicationMode.DEFAULT), jApplicationModeMenu));\n\t\tjApplicationModeMenu.add(new OffRoadMenuItem(new ChooseApplicationModeAction(this, ApplicationMode.CAR), jApplicationModeMenu));\n\t\tjApplicationModeMenu.add(new OffRoadMenuItem(new ChooseApplicationModeAction(this, ApplicationMode.BICYCLE), jApplicationModeMenu));\n\t\tjApplicationModeMenu.add(new OffRoadMenuItem(new ChooseApplicationModeAction(this, ApplicationMode.PEDESTRIAN), jApplicationModeMenu));\n\t\tjViewMenu.add(jApplicationModeMenu);\n\t\tJMenu jRendererMenu = new JMenu(getOffRoadString(\"offroad.renderer\"));\n\t\tfor (String renderer : getRendererRegistry().getRendererNames()) {\n\t\t\tlViewItem = new OffRoadMenuItem(new ChooseRendererAction(this, getOffRoadString(\"offroad.renderer_\"+renderer.replaceAll(\"[^a-zA-Z]\", \"_\")), null, renderer), jRendererMenu);\n\t\t\tjRendererMenu.add(lViewItem);\n\t\t}\n\t\tjViewMenu.add(jRendererMenu);\n\t\t// rendering properties\n\t\tJMenu jRenderPropertiesMenu = new JMenu(getString(\"map_widget_renderer\"));\n\t\t\n\t\tHashMap categoryMenus = new HashMap<>();\n\t\tfor (RenderingRuleProperty customProp : getRenderingRulesStorage().PROPS.getCustomRules()) {\n\t\t\tif(customProp.getCategory()==null){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!customProp.isBoolean() && !customProp.isString()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(!categoryMenus.containsKey(customProp.getCategory())){\n\t\t\t\tJMenu jMenu = new JMenu(getString(\"rendering_category_\" + customProp.getCategory()));\n\t\t\t\tjRenderPropertiesMenu.add(jMenu);\n\t\t\t\tcategoryMenus.put(customProp.getCategory(), jMenu);\n\t\t\t}\n\t\t\tJMenu jMenu = categoryMenus.get(customProp.getCategory());\n\t\t\tif (customProp.isBoolean()) {\n\t\t\t\tCommonPreference pref = prefs.getCustomRenderBooleanProperty(customProp.getAttrName());\n\t\t\t\tlog.debug(\"PROP: \" + customProp.getAttrName()+ \", \" + customProp.getCategory() + \"=\" + pref.get());\n\t\t\t\tJMenuItem item = new OffRoadMenuItem(new SetRenderingRule(this, customProp), jMenu);\n\t\t\t\tjMenu.add(item);\n\t\t\t} else {\n\t\t\t\tJMenu submenu = new JMenu(getString(\"rendering_attr_\" + customProp.getAttrName() + \"_name\"));\n\t\t\t\tString defaultValue = customProp.getDefaultValueDescription();\n\t\t\t\tif (defaultValue != null) {\n\t\t\t\t\t// Add default item\n\t\t\t\t\tJMenuItem item = new OffRoadMenuItem(new SetRenderingRule(this, customProp, customProp.getDefaultValueDescription(), true), submenu);\n\t\t\t\t\tsubmenu.add(item);\n\t\t\t\t}\n\t\t\t\tfor (String val: customProp.getPossibleValues())\n\t\t\t\t{\n\t\t\t\t\tJMenuItem item = new OffRoadMenuItem(new SetRenderingRule(this, customProp, val, false), submenu);\n\t\t\t\t\tsubmenu.add(item);\n\t\t\t\t}\n\t\t\t\tjMenu.add(submenu);\n\t\t\t}\n\t\t}\n\t\tjViewMenu.add(jRenderPropertiesMenu);\n\t\tJMenu jIconSizePropertiesMenu = new JMenu(getOffRoadString(\"offroad.icons_size_menu\"));\n\t\tfor (String prefix : sOsmandIconsPrefixes) {\n\t\t\tJMenuItem item = new OffRoadMenuItem(new ChangeIconSizeAction(this, prefix), jIconSizePropertiesMenu);\n\t\t\tjIconSizePropertiesMenu.add(item);\n\t\t}\n\t\tjViewMenu.add(jIconSizePropertiesMenu);\n\t\tmenubar.add(jViewMenu);\n\t\t// Navigation\n\t\tJMenu jNavigationMenu = new JMenu(getOffRoadString(\"offroad.navigation\")); //$NON-NLS-1$\n\t\taddToMenu(jNavigationMenu, null, new RouteAction(this, ApplicationMode.CAR), \"F1\");\n\t\taddToMenu(jNavigationMenu, null, new RouteAction(this, ApplicationMode.BICYCLE), \"F2\");\n\t\taddToMenu(jNavigationMenu, null, new RouteAction(this, ApplicationMode.PEDESTRIAN), \"F3\");\n\t\tjNavigationMenu.add(new JSeparator());\n\t\taddToMenu(jNavigationMenu, \"offroad.go_source\", new ShowTargetPointAction(this, TargetPointsHelper::getPointToStart), \"control HOME\");\n\t\taddToMenu(jNavigationMenu, \"offroad.go_dest\", new ShowTargetPointAction(this, TargetPointsHelper::getPointToNavigate), \"control END\");\n\t\tjNavigationMenu.add(new JSeparator());\n\t\tjNavigationMenu.add(new JMenuItem(new ClearRouteAction(this)));\n\t\tPointNavigationAction clearIntermediatePointsAction = new PointNavigationAction(this, \"offroad.clear_intermediate_points\",\n\t\t\t\t(pHelper, pPosition) -> {\n\t\t\t\t\twhile(!pHelper.getIntermediatePoints().isEmpty()){\n\t\t\t\t\t\tpHelper.removeWayPoint(false, 0);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\tPointNavigationAction clearAllPointsAction = new PointNavigationAction(this, \"offroad.clear_all_points\",\n\t\t\t\t(helper, pos) -> helper.removeAllWayPoints(false, false));\n\t\tjNavigationMenu.add(clearIntermediatePointsAction);\n\t\tjNavigationMenu.add(clearAllPointsAction);\n\t\tjNavigationMenu.add(new JSeparator());\n\t\tJMenu lRoutingServiceMenu = new JMenu(getOffRoadString(\"offroad.routing_service\"));\n\t\tfor (int i = 0; i < RouteService.values().length; i++) {\n\t\t\tRouteService service = RouteService.values()[i];\n\t\t\tif(service.isAvailable(this)){\n\t\t\t\tJMenuItem lRoutingServiceItem = new OffRoadMenuItem(new ChooseRouteServiceAction(this, service), lRoutingServiceMenu);\n\t\t\t\tlRoutingServiceMenu.add(lRoutingServiceItem);\n\t\t\t}\n\t\t}\n\t\tjNavigationMenu.add(lRoutingServiceMenu);\n\t\tjNavigationMenu.add(new JSeparator());\n\t\taddToMenu(jNavigationMenu, \"offroad.up\", item -> mDrawPanel.moveImageAnimatedInPercentage(0,-1f/3), \"control UP\");\n\t\taddToMenu(jNavigationMenu, \"offroad.down\", item -> mDrawPanel.moveImageAnimatedInPercentage(0,1f/3), \"control DOWN\");\n\t\taddToMenu(jNavigationMenu, \"offroad.left\", item -> mDrawPanel.moveImageAnimatedInPercentage(-1f/3,0), \"control LEFT\");\n\t\taddToMenu(jNavigationMenu, \"offroad.right\", item -> mDrawPanel.moveImageAnimatedInPercentage(1f/3,0), \"control RIGHT\");\n\t\tjNavigationMenu.add(new JSeparator());\n\t\taddToMenu(jNavigationMenu, \"offroad.zoomin\", item -> mAdapter.addWheelEvent(-1, mDrawPanel.copyCurrentTileBox()), \"control PLUS\");\n\t\taddToMenu(jNavigationMenu, \"offroad.zoomout\", item -> mAdapter.addWheelEvent(1, mDrawPanel.copyCurrentTileBox()), \"control MINUS\");\n\t\tjNavigationMenu.add(new JSeparator());\n\t\taddToMenu(jNavigationMenu, \"offroad.back\", new NavigationBackAction(this), \"alt LEFT\");\n\t\taddToMenu(jNavigationMenu, \"offroad.forward\", new NavigationForwardAction(this), \"alt RIGHT\");\n\t\tjNavigationMenu.add(new JSeparator());\n\t\taddToMenu(jNavigationMenu, \"offroad.reset_north\", new NavigationRotationAction(this).setAbsolute(0d), \"alt HOME\");\n\t\taddToMenu(jNavigationMenu, \"offroad.increase_rotation\", new NavigationRotationAction(this).setIncrement(30d), \"alt PAGE_UP\");\n\t\taddToMenu(jNavigationMenu, \"offroad.decrease_rotation\", new NavigationRotationAction(this).setIncrement(-30d), \"alt PAGE_DOWN\");\n\t\tmenubar.add(jNavigationMenu);\n\t\t// PointOfInterest\n\t\tJMenu jPointOfInterestMenu = new JMenu(getOffRoadString(\"offroad.PointOfInterest\")); //$NON-NLS-1$\n\t\tJMenuItem lPointOfInterestOffItem = new OffRoadMenuItem(new PoiFilterAction(this, null, true), jPointOfInterestMenu);\n\t\tjPointOfInterestMenu.add(lPointOfInterestOffItem);\n\t\tfor (PoiUIFilter filter : mPoiFilters.getTopDefinedPoiFilters()) {\n\t\t\tJMenuItem lPointOfInterestItem = new OffRoadMenuItem(new PoiFilterAction(this, filter, false), jPointOfInterestMenu); \n\t\t\tjPointOfInterestMenu.add(lPointOfInterestItem);\n\t\t}\n\t\tmenubar.add(jPointOfInterestMenu);\n\t\t// Favorites\n\t\tJMenu jFavoritesMenu = new JMenu(getOffRoadString(\"offroad.Favorites\")); //$NON-NLS-1$\n\t\tmAddFavourite = new JMenuItem(new AddFavoriteAction(this, getOffRoadString(\"offroad.addFavorite\"), null, null));\n\t\tmAddFavourite.setAccelerator(KeyStroke.getKeyStroke(\"control D\")); //$NON-NLS-1$\n\t\tmSelectTrack = new JMenuItem(new SelectTrackAction(this, getOffRoadString(\"offroad.selectTrack\")));\n\t\tmSelectTrack.setAccelerator(KeyStroke.getKeyStroke(\"control T\")); //$NON-NLS-1$\n\t\tjFavoritesMenu.addMenuListener(new MenuListener(){\n\n\t\t\t@Override\n\t\t\tpublic void menuSelected(MenuEvent pE) {\n\t\t\t\t// Must be dynamic, as the favorites may change...\n\t\t\t\tjFavoritesMenu.removeAll();\n\t\t\t\tjFavoritesMenu.add(mAddFavourite);\n\t\t\t\taddFavoriteGroups(OsmWindow.this, jFavoritesMenu, getFavorites().getFavoriteGroups());\n\t\t\t\tjFavoritesMenu.add(mSelectTrack);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void menuDeselected(MenuEvent pE) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void menuCanceled(MenuEvent pE) {\n\t\t\t}});\n\t\tmenubar.add(jFavoritesMenu);\n\t\tJMenu jHelpMenu = new JMenu(getOffRoadString(\"offroad.Help\")); //$NON-NLS-1$\n\t\taddToMenu(jHelpMenu, \"offroad.about\", new AboutDialogAction(this), null);\n\t\tmenubar.add(jHelpMenu);\n\t\t\n\t\tadaptMenuMnemonics(menubar.getComponents());\n\t\tJPopupMenu popupMenu = new JPopupMenu();\n\t\tpopupMenu.add(new JMenuItem(new PointNavigationAction(this, \"offroad.set_start_point\",\n\t\t\t\t(helper, pos) -> helper.setStartPoint(pos, false, null))));\n\t\tpopupMenu.add(new JMenuItem(new PointNavigationAction(this, \"offroad.set_intermediate_point\",\n\t\t\t\t(helper, pos) -> helper.navigateToPoint(pos, false, helper.getIntermediatePoints().size()))));\n\t\tpopupMenu.add(new JMenuItem(new PointNavigationAction(this, \"offroad.set_destination_point\",\n\t\t\t\t(helper, pos) -> helper.navigateToPoint(pos, false, -1))));\n\t\tpopupMenu.add(new JSeparator());\n//\t\tpopupMenu.add(new JMenuItem(new RouteAction(this, ApplicationMode.CAR)));\n//\t\tpopupMenu.add(new JMenuItem(new RouteAction(this, ApplicationMode.BICYCLE)));\n//\t\tpopupMenu.add(new JMenuItem(new RouteAction(this, ApplicationMode.PEDESTRIAN)));\n//\t\tpopupMenu.add(new JSeparator());\n\t\tpopupMenu.add(new JMenuItem(clearIntermediatePointsAction));\n\t\tpopupMenu.add(new JMenuItem(clearAllPointsAction));\n\t\tpopupMenu.add(new JMenuItem(new SetCursorRadiusAction(this, \"offroad.set_cursor_radius\", -1d)));\n\t\tpopupMenu.add(new JMenuItem(new SetCursorRadiusAction(this, \"offroad.remove_cursor_radius\", 0d)));\n\t\tmDrawPanel.setComponentPopupMenu(popupMenu);\n\t\tpopupMenu.addPopupMenuListener(new OffRoadPopupMenuListener(this, popupMenu));\n\t\tmFrame.setJMenuBar(menubar);\n\t\tmFrame.pack();\n\t\tOsmWindowLocationStorage storage = (OsmWindowLocationStorage) ComponentLocationStorage.decorateDialog(this, mFrame, getClass().getName());\n\t\tif (storage!= null) {\n\t\t\tmFrame.addComponentListener(new ComponentAdapter() {\n\t\t\t\t@Override\n\t\t\t\tpublic void componentResized(ComponentEvent pE) {\n\t\t\t\t\tint splitPanePosition = storage.getSplitLocation();\n\t\t\t\t\tint lastSplitPanePosition = storage.getSplitLocation();\n\t\t\t\t\tif (mSplitPane != null && splitPanePosition != -1 && lastSplitPanePosition != -1) {\n\t\t\t\t\t\tmSplitPane.setDividerLocation(splitPanePosition);\n\t\t\t\t\t\tmSplitPane.setLastDividerLocation(lastSplitPanePosition);\n\t\t\t\t\t}\n\t\t\t\t\tmFrame.removeComponentListener(this);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tmFrame.addComponentListener(new ComponentAdapter() {\n\t\t\tpublic void componentShown(ComponentEvent e) {\n\t\t\t\tmFrame.removeComponentListener(this);\n\t\t\t\tSwingUtilities.invokeLater(OsmWindow.this::checkMaps);\n\t\t\t}\n\t\t});\n\t\tmFrame.setVisible(true);\n\t}\n\n\tpublic void showDirectSearch() {\n\t\tif(!mDirectSearchVisible){\n\t\t\tmStatusBar.add(mDirectSearchPanel, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\t\t\tmFrame.revalidate();\n\t\t\tmDirectSearchVisible = true;\n\t\t\tmDirectSearchTextField.selectAll();\n\t\t}\n\t}\n\n\tpublic void checkMaps() {\n\t\tMapRenderRepositories maps = getRenderer();\n\t\tboolean check = \"true\".equals(getOffroadProperties().getProperty(VECTOR_INDEXES_CHECK, \"true\"));\n\t\tif (check) {\n\t\t\tif (!maps.basemapExists()) {\n\t\t\t\tint result = JOptionPane.showConfirmDialog(mFrame, getString(R.string.basemap_missing),\n\t\t\t\t\t\tgetString(R.string.base_world_map), JOptionPane.YES_NO_CANCEL_OPTION,\n\t\t\t\t\t\tJOptionPane.QUESTION_MESSAGE, null);\n\t\t\t\tif (result == JOptionPane.CANCEL_OPTION) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result == JOptionPane.NO_OPTION) {\n\t\t\t\t\tgetOffroadProperties().setProperty(VECTOR_INDEXES_CHECK, \"false\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tSwingUtilities.invokeLater(() -> {\n\t\t\t\t\tDownloadAction downloadAction = new DownloadAction(getInstance(), WorldRegion.WORLD_BASEMAP);\n\t\t\t\t\tdownloadAction.actionPerformed(null);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void adaptMenuMnemonics(Component[] components) {\n\t\tfor (Component comp : components) {\n\t\t\tif (comp instanceof AbstractButton) {\n\t\t\t\tAbstractButton but = (AbstractButton) comp;\n\t\t\t\tsetMnemonic(but);\n\t\t\t}\n\t\t\tif (comp instanceof JMenu) {\n\t\t\t\tJMenu cont = (JMenu) comp;\n\t\t\t\tadaptMenuMnemonics(cont.getPopupMenu().getComponents());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static boolean isMacOsX() {\n\t\tboolean underMac = false;\n\t\tString osName = System.getProperty(\"os.name\");\n\t\tif (osName.startsWith(\"Mac OS\")) {\n\t\t\tunderMac = true;\n\t\t}\n\t\treturn underMac;\n\t}\n\t\n\tprivate void setMnemonic(AbstractButton item){\n\t\tString rawLabel = item.getText();\n\t\titem.setText(rawLabel.replaceFirst(\"&([^ ])\", \"$1\"));\n\t\tint mnemoSignIndex = rawLabel.indexOf(\"&\");\n\t\tif (mnemoSignIndex >= 0 && mnemoSignIndex + 1 < rawLabel.length()) {\n\t\t\tchar charAfterMnemoSign = rawLabel.charAt(mnemoSignIndex + 1);\n\t\t\tif (charAfterMnemoSign != ' ') {\n\t\t\t\t// no mnemonics under Mac OS:\n\t\t\t\tif (!isMacOsX()) {\n\t\t\t\t\titem.setMnemonic(charAfterMnemoSign);\n\t\t\t\t\t// sets the underline to exactly this character.\n\t\t\t\t\titem.setDisplayedMnemonicIndex(mnemoSignIndex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * @param jNavigationMenu\n\t * @param name may be null, if set later.\n\t * @param action\n\t * @param keyStroke\n\t */\n\tvoid addToMenu(JMenu jNavigationMenu, String name, ActionListener action, String keyStroke) {\n\t\tString actionName = (name!=null)?getOffRoadString(name):\"UNKNOWN\";\n\t\tif (name==null && action instanceof AbstractAction) {\n\t\t\tAbstractAction abstractAction = (AbstractAction) action;\n\t\t\tactionName = (String) abstractAction.getValue(AbstractAction.NAME);\n\t\t}\n\t\tJMenuItem navigationBackItem = new JMenuItem(actionName); //$NON-NLS-1$\n\t\tnavigationBackItem.addActionListener(action);\n\t\tif (keyStroke != null) {\n\t\t\tnavigationBackItem.setAccelerator(KeyStroke.getKeyStroke(keyStroke)); //$NON-NLS-1$\n\t\t}\n\t\tjNavigationMenu.add(navigationBackItem);\n\t}\n\n\tpublic void startServer() {\n\t\tString portFile = getAppPath(\"port.txt\").getAbsolutePath(); //$NON-NLS-1$\n\t\tif (portFile == null) {\n\t\t\treturn;\n\t\t}\n\t\tmGeoServer = new GeoServer(portFile, this);\n\t\tmGeoServer.start();\n\t}\n\t\n\tpublic String getOffRoadString(String pString) {\n\t\tif(mOffroadResources.containsKey(pString)){\n\t\t\treturn mOffroadResources.getString(pString);\n\t\t}\n\t\tlog.error(\"TRANSLATE ME: \" + pString);\n\t\treturn \"TRANSLATE_ME:\" + pString; //$NON-NLS-1$\n\t}\n\n\tpublic OsmBitmapPanel getDrawPanel() {\n\t\treturn mDrawPanel;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tfinal OsmWindow win = OsmWindow.getInstance();\n\t\tVersionInfo version = win.getVersion();\n\t\tlog.info(\"Version: \" + version.version + \", hash=\" + version.hash);\n\t\twin.init();\n\t\tjava.awt.EventQueue.invokeLater(win::createAndShowUI);\n\n\t}\n\n\tprotected void saveSettings() {\n\t\tRotatedTileBox tileBox = mDrawPanel.copyCurrentTileBox();\n\t\tprefs.setLastKnownMapLocation(tileBox.getLatitude(), tileBox.getLongitude());\n\t\tprefs.setLastKnownMapZoom(tileBox.getZoom());\n\t\tgetSettings().SELECTED_POI_FILTER_STRING_FOR_MAP.set(mSearchTextField.getText());\n\t\tOsmWindowLocationStorage storage = new OsmWindowLocationStorage();\n\t\tstorage.setSplitLocation(mSplitPane.getDividerLocation());\n\t\tComponentLocationStorage.storeDialogPositions(this, mFrame, storage, getClass().getName());\n\t\tsettings.save();\n\t}\n\n\tpublic OsmWindow() {\n\t\tinitStrings();\n\t\tsetupProxy();\n\t\tprefs.APPLICATION_MODE.set(ApplicationMode.DEFAULT);\n\t\tprefs.MAP_PREFERRED_LOCALE.set(getLanguage());\n\t\tprefs.PREFERRED_LOCALE.set(getLanguage());\n\t\tmStrings = new R.string();\n\t}\n\n\tprivate void init() {\n\t\tDimension size = java.awt.Toolkit.getDefaultToolkit().getScreenSize();\n\t\twidthPixels = size.width;\n\t\theightPixels = size.height;\n\t\tdensity = java.awt.Toolkit.getDefaultToolkit().getScreenResolution()/96f;\n\t\tmOsmAndLocationProvider = new OsmAndLocationProvider(this);\n\t\tmRegions = new OsmandRegions();\n\t\tmResourceManager = new ResourceManager(this);\n\t\tmResourceManager.indexingMaps(IProgress.EMPTY_PROGRESS);\n\t\ttry {\n\t\t\tUIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n\t\t} catch (Exception e) {\n\t\t}\n\t\tstartServer();\n\t\tmRendererRegistry = new RendererRegistry(this);\n\t\tmRendererRegistry.initRenderers(IProgress.EMPTY_PROGRESS);\n\t\tmRoutingHelper = new RoutingHelper(this);\n\t\tgetRoutingHelper().addListener(this);\n\t\tmGeocodingLookupService = new GeocodingLookupService(this);\n\t\tmTargetPointsHelper = new TargetPointsHelper(this);\n\t\tmPoiFilters = new PoiFiltersHelper(this);\n\t\tmMapPoiTypes = MapPoiTypes.getDefault();\n\t\tmMapPoiTypes.setPoiTranslator(new MapPoiTypes.PoiTranslator() {\n\t\t\t@Override\n\t\t\tpublic String getTranslation(AbstractPoiType type) {\n\t\t\t\tif (type.getBaseLangType() != null) {\n\t\t\t\t\treturn getTranslation(type.getBaseLangType()) + \" (\"\n\t\t\t\t\t\t\t+ getLangTranslation(type.getLang()).toLowerCase() + \")\";\n\t\t\t\t}\n\t\t\t\treturn getString(\"poi_\" + type.getIconKeyName());\n\t\t\t}\n\t\t});\n\t\tmMapMarkersHelper = new MapMarkersHelper(this);\n\t}\n\n\n\tprivate void initStrings() {\n\t\t// read resources:\n\t\tString ct = getCountry();\n\t\tloadStrings(ct, \"strings.xml\");\n\t\tloadStrings(ct, \"phrases.xml\");\n\t\t// get offroad strings:\n\t\ttry {\n\t\t\tmOffroadResources = getLanguageResources(ct);\n\t\t\tif(mOffroadResources==null){\n\t\t\t\tmOffroadResources = getLanguageResources(\"en\"); //$NON-NLS-1$\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tprivate void setupProxy() {\n\t\t// proxy settings\n\t\tProperties props = (Properties) settings.getPreferenceObject(OFFROAD_PROPERTIES);\n\t\tif(\"true\".equals(settings.getString(props, PROXY_USE_SETTINGS, \"\"))) {\n\t\t\tif (\"true\".equals(settings.getString(props, PROXY_IS_AUTHENTICATED, \"\"))) {\n\t\t\t\ttry {\n\t\t\t\t\tAuthenticator.setDefault(new ProxyAuthenticator(settings.getString(props, PROXY_USER, \"\"), new String(Base64.decode(settings.getString(props, PROXY_PASSWORD, \"\")))));\n\t\t\t\t} catch (Base64DecoderException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tSystem.setProperty(\"http.proxyHost\", settings.getString(props, PROXY_HOST, \"\"));\n\t\t\tSystem.setProperty(\"http.proxyPort\", settings.getString(props, PROXY_PORT, \"\"));\n\t\t\tSystem.setProperty(\"https.proxyHost\", settings.getString(props, PROXY_HOST, \"\"));\n\t\t\tSystem.setProperty(\"https.proxyPort\", settings.getString(props, PROXY_PORT, \"\"));\n\t\t\tSystem.setProperty(\"http.nonProxyHosts\", settings.getString(props, PROXY_EXCEPTION, \"\"));\n\t\t}\n\t}\n\n\n\tprivate void loadStrings(String ct, String fileName) {\n\t\tInputStream is = getResource(\"res/values-\" + ct + \"/\" + fileName);\n\t\tif (is == null) {\n\t\t\tis = getResource(\"res/values/\" + fileName); // $NON-NLS-1$\n\t\t}\n\t\tlog.info(\"Trying to load resources \" + is); //$NON-NLS-1$\n\t\tResources resourceStrings;\n\t\ttry {\n\t\t\tJAXBContext jc = JAXBContext.newInstance(Resources.class);\n\t\t\tUnmarshaller u = jc.createUnmarshaller();\n\t\t\tresourceStrings = (Resources) u.unmarshal(is);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tresourceStrings = new Resources();\n\t\t}\n\t\tif(mResourceStrings == null){\n\t\t\tmResourceStrings = new Resources();\n\t\t}\n\t\tmResourceStrings.getString().addAll(resourceStrings.getString());\n\t}\n\n\tprivate PropertyResourceBundle getLanguageResources(String lang)\n\t\t\tthrows IOException {\n\t\tInputStream is = getResource(\"res/OffRoad_Resources_\" + lang //$NON-NLS-1$\n\t\t\t\t+ \".properties\"); //$NON-NLS-1$\n\t\tif (is == null) {\n\t\t\treturn null;\n\t\t}\n\t\tPropertyResourceBundle bundle = new PropertyResourceBundle(is);\n\t\tis.close();\n\t\treturn bundle;\n\t}\n\n\tpublic static class VersionInfo {\n\t\tpublic String version;\n\t\tpublic String hash;\n\t\tpublic VersionInfo(String pVersion, String pHash) {\n\t\t\tsuper();\n\t\t\tversion = pVersion;\n\t\t\thash = pHash;\n\t\t}\n\t\t\n\t}\n\tpublic VersionInfo getVersion(){\n\t\tif(mVersionInfo == null){\n\t\t\ttry {\n\t\t\t\tmVersionInfo = new VersionInfo(\"x.x.x\", \"0815\");\n\t\t\t\tInputStream is = getResource(\"version.properties\"); //$NON-NLS-1$\n\t\t\t\tif (is == null) {\n\t\t\t\t\treturn mVersionInfo;\n\t\t\t\t}\n\t\t\t\tPropertyResourceBundle bundle = new PropertyResourceBundle(is);\n\t\t\t\tis.close();\n\t\t\t\tmVersionInfo = new VersionInfo(bundle.getString(\"version\"), bundle.getString(\"hash\"));\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn mVersionInfo;\n\t}\n\t\n\tpublic String getLangTranslation(String l) {\n\t\treturn getString(\"lang_\" + l);\n\t}\n\n\tpublic static void scaleAllFonts(float pScale) {\n\t\tlog.info(\"Scaling fonts with scale \" + pScale);\n\t\tfor (Object next : UIManager.getLookAndFeelDefaults().keySet()) {\n\t\t\tif (next instanceof String) {\n\t\t\t\tString key = (String) next;\n\t\t\t\tif (key.endsWith(\".font\")) { //$NON-NLS-1$\n\t\t\t\t\tFont font = UIManager.getFont(key);\n\t\t\t\t\tFont biggerFont = font.deriveFont(pScale * font.getSize2D());\n\t\t\t\t\t// change ui default to bigger font\n\t\t\t\t\tUIManager.put(key, biggerFont);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tpublic RenderingResult loadMGap(Graphics2D pG2, RotatedTileBox pTileRect, IntermediateImageListener pListener) {\n\t\treturn getRenderer().loadMGap(pG2, pTileRect, getRenderingRulesStorage(), pListener);\n\t}\n\n\tpublic MapRenderRepositories getRenderer() {\n\t\treturn mResourceManager.getRenderer();\n\t}\n\n\tstatic public void printClassPath() {\n\t\tClassLoader cl = ClassLoader.getSystemClassLoader();\n\n\t\tif (cl instanceof URLClassLoader) {\n\t\t\tURL[] urls = ((URLClassLoader) cl).getURLs();\n\t\t\tSystem.out.println(\"Classpath:\"); //$NON-NLS-1$\n\t\t\tfor (URL url : urls) {\n\t\t\t\tSystem.out.println(url.getFile());\n\t\t\t} \n\t\t} else {\n\t\t\tSystem.out.println(\"Can' determine classpath for classloader \" + cl);\n\t\t}\n\t}\n\n\tpublic InputStream getResource(String pIndex){\n\t\tif(pIndex != null){\n\t\t\tString name = pIndex;\n\t\t\tInputStream is = OsmWindow.class.getResourceAsStream(name);\n\t\t\tif(is == null){\n\t\t\t\tname = \"/\" + pIndex; //$NON-NLS-1$\n\t\t\t\tis = OsmWindow.class.getResourceAsStream(name);\n\t\t\t\tif(is == null){\n\t\t\t\t\tSystem.err.println(\"ERROR: Resource not found: \" + pIndex); //$NON-NLS-1$\n\t\t\t\t\tprintClassPath();\n\t\t\t\t} else {\n\t\t\t\t\tSystem.err.println(\"WARNING: Found path as \" + name + \" instead of \" + pIndex); //$NON-NLS-1$ //$NON-NLS-2$\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn is;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic BufferedImage getBitmap(MapObject obj) {\n\t\tBufferedImage bmp = null;\n\t\tif (obj instanceof Amenity) {\n\t\t\tAmenity o = (Amenity) obj;\n\t\t\tPoiType st = o.getType().getPoiTypeByKeyName(o.getSubType());\n\t\t\tif (st != null) {\n\t\t\t\tbmp = RenderingIcons.getIcon(st.getIconKeyName(), false);\n\t\t\t\tif (bmp == null) bmp = RenderingIcons.getIcon(st.getOsmTag() + \"_\" + st.getOsmValue(), false);\n\t\t\t}\n\t\t}\n\t\treturn bmp;\n\t}\n\n\n\t\n\tpublic File getAppPath(String pIndex) {\n\t\tif (pIndex == null) {\n\t\t\tpIndex = \"\"; //$NON-NLS-1$\n\t\t}\n\t\tString pathname = getAppPathName(pIndex);\n\t\tlog.info(\"Searching for \" + pathname); //$NON-NLS-1$\n\t\treturn new File(pathname);\n\t}\n\n\tpublic static String getAppPathName(String pIndex) {\n\t\treturn System.getProperty(\"user.home\") + File.separator + \".OffRoad\" + File.separator + pIndex; //$NON-NLS-1$ //$NON-NLS-2$\n\t}\n\n\tpublic OsmandSettings getSettings() {\n\t\treturn prefs;\n\t}\n\n\tpublic String getString(int pKey) {\n\t\tString stringKey = mStrings.hash.get(pKey);\n\t\treturn getString(stringKey);\n\t}\n\n\tpublic String getString(String stringKey) {\n\t\tfor (Resources.String str : mResourceStrings.getString()) {\n\t\t\tif(str.getName() != null && str.getName().equals(stringKey)){\n\t\t\t\tlog.debug(\"String \" + stringKey + \"=\" + str.getValue()) ;\n\t\t\t\treturn str.getValue();\n\t\t\t}\n\t\t}\n\t\tlog.error(\"String key \" + stringKey + \" not found!\");\n\t\treturn stringKey;\n\t}\n\n\tpublic static OsmWindow getInstance() {\n\t\tif (sInstance == null) {\n\t\t\tsInstance = new OsmWindow();\n\t\t}\n\t\treturn sInstance;\n\t}\n\n\tpublic OsmandRegions getRegions() {\n\t\treturn mRegions;\n\t}\n\n\tpublic ResourceManager getResourceManager() {\n\t\treturn mResourceManager;\n\t}\n\n\tpublic Frame getWindow() {\n\t\treturn mFrame;\n\t}\n\n\tpublic void move(LatLon pLocation, QuadRectExtendable pQuadRectExtendable) {\n\t\tRotatedTileBox ctb = mDrawPanel.copyCurrentTileBox();\n\t\t// camera movement, find intermediate zoom, such that current and destination points are in:\n\t\tQuadRectExtendable joint = new QuadRectExtendable(ctb.getCenterLatLon());\n\t\tif(pQuadRectExtendable != null){\n\t\t\tjoint.insert(pQuadRectExtendable.getTopLeft());\n\t\t\tjoint.insert(pQuadRectExtendable.getBottomRight());\n\t\t}\n\t\tRotatedTileBox cameraTileBox = getCommonTileBox(pLocation, joint);\n\t\tRotatedTileBox tileBox = mDrawPanel.copyCurrentTileBox();\n\t\ttileBox.setLatLonCenter(pLocation.getLatitude(), pLocation.getLongitude());\n\t\ttileBox = getCommonTileBox(tileBox, pLocation, pQuadRectExtendable);\n\t\tmoveAnimated(cameraTileBox, ctb, ctb.getCenterLatLon());\n\t\tmoveAnimated(tileBox, cameraTileBox, pLocation);\n\t\tsetCursorPosition(pLocation);\n\t}\n\n\tpublic void moveAnimated(RotatedTileBox pNextTileBox, RotatedTileBox pCurrentTileBox, LatLon pLocation){\n\t\tif(pNextTileBox.getZoom() == pCurrentTileBox.getZoom()){\n\t\t\t// no zoom change at all:\n\t\t\tPoint delta = pCurrentTileBox.getPoint(pNextTileBox.getLeftTopLatLon());\n\t\t\tmDrawPanel.moveAnimated(delta.x, delta.y, pNextTileBox);\n\t\t} else {\n\t\t\tmDrawPanel.zoomChange(pNextTileBox.getZoom()-pCurrentTileBox.getZoom(), pCurrentTileBox.getPoint(pLocation));\n\t\t}\n\t\t\n\t}\n\t\n\tprotected RotatedTileBox getCommonTileBox(LatLon pLocation, QuadRectExtendable pQuadRectExtendable) {\n\t\t// make sure that all points of the rect are in:\n\t\tRotatedTileBox tileBox = mDrawPanel.copyCurrentTileBox();\n\t\ttileBox.setZoom(MAX_ZOOM);\n\t\treturn getCommonTileBox(tileBox, pLocation, pQuadRectExtendable);\n\t}\n\tprotected RotatedTileBox getCommonTileBox(RotatedTileBox pTileBox, LatLon pLocation, QuadRectExtendable pQuadRectExtendable) {\n\t\tif (pQuadRectExtendable!= null) {\n// \t\ttileBox.setLatLonCenter(pLocation.getLatitude(), pLocation.getLongitude());\n\t\t\tzoomOutUntilFits(pTileBox, pQuadRectExtendable.getTopLeft());\n\t\t\tzoomOutUntilFits(pTileBox, pQuadRectExtendable.getBottomRight());\n\t\t}\n\t\tzoomOutUntilFits(pTileBox, pLocation);\n\t\treturn pTileBox;\n\t}\n\n\tpublic void zoomOutUntilFits(RotatedTileBox tileBox, LatLon latlon) {\n\t\twhile (!tileBox.containsLatLon(latlon)) {\n\t\t\ttileBox.setZoom(tileBox.getZoom() - 1);\n\t\t}\n\t}\n\n\tpublic void setWaitingCursor(boolean waiting) {\n\t\tComponent glassPane = mFrame.getRootPane().getGlassPane();\n\t\tif (waiting) {\n\t\t\tglassPane.setCursor(\n\t\t\t\t\tCursor.getPredefinedCursor(Cursor.WAIT_CURSOR));\n\t\t\tglassPane.setVisible(true);\n\t\t} else {\n\t\t\tglassPane.setCursor(\n\t\t\t\t\tCursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));\n\t\t\tglassPane.setVisible(false);\n\t\t}\n\t}\n\t\n\tpublic class StatusLabelAction extends AbstractAction {\n\n\t\t@Override\n\t\tpublic void actionPerformed(ActionEvent pE) {\n\t\t\tif(mDontUpdateStatusLabelCounter>0){\n\t\t\t\tmDontUpdateStatusLabelCounter--;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// calculate the distance to the cursor\n\t\t\tMouseEvent e = getLastMouseEvent();\n\t\t\tLatLon cursorPosition = mDrawPanel.getCursorPosition();\n\t\t\tif(e == null || cursorPosition == null){\n\t\t\t\tmStatusLabel.setText(\"\"); //$NON-NLS-1$\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tLatLon mousePosition = mDrawPanel.copyCurrentTileBox().getLatLonFromPixel(e.getX(), e.getY());\n\t\t\tdouble distance = MapUtils.getDistance(mousePosition, cursorPosition)/1000d;\n\t\t\t// now, check if polyline is present:\n\t\t\tPolyline selectedPolyline = mDrawPanel.getPolylineLayer().getSelectedPolyline();\n\t\t\tdouble polyDist = 0;\n\t\t\tdouble polyArea = 0;\n\t\t\tif(selectedPolyline != null){\n\t\t\t\tpolyDist = selectedPolyline.calculateLength();\n\t\t\t\tpolyArea = selectedPolyline.calculateArea();\n\t\t\t}\n\t\t\tObject[] messageArguments = {distance,\n\t\t\t\t\tcursorPosition.getLatitude(),\n\t\t\t\t\tcursorPosition.getLongitude()};\n\t\t\tObject[] polyArguments = {polyDist, polyArea};\n\t\t\tMessageFormat formatter = new MessageFormat(\n\t\t\t\t\tgetOffRoadString(\"offroad.string47\")); //$NON-NLS-1$\n\t\t\tString message = formatter.format(messageArguments);\n\t\t\tif (polyDist != 0 || polyArea != 0) {\n\t\t\t\tformatter = new MessageFormat(getOffRoadString(\"offroad.string47.poly\"));\n\t\t\t\tmessage += \" \" + formatter.format(polyArguments);\n\t\t\t}\n\t\t\tmStatusLabel.setText(message);\n\t\t}\n\t\t\n\t}\n\t\n\tpublic RendererRegistry getRendererRegistry() {\n\t\treturn mRendererRegistry;\n\t}\n\n\tpublic Builder getDefaultRoutingConfig() {\n\t\tlong tm = System.currentTimeMillis();\n\t\ttry {\n\t\t\tInputStream routingXml = getResource(IndexConstants.ROUTING_XML_FILE);\n\t\t\tif (routingXml != null) {\n\t\t\t\ttry {\n\t\t\t\t\treturn RoutingConfiguration.parseFromInputStream(routingXml);\n\t\t\t\t} catch (XmlPullParserException | IOException e) {\n\t\t\t\t\tthrow new IllegalStateException(e);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tSystem.err.println(\"Routing configuration not found!\"); //$NON-NLS-1$\n\t\t\t\treturn RoutingConfiguration.getDefault();\n\t\t\t}\n\t\t} finally {\n\t\t\tlong te = System.currentTimeMillis();\n\t\t\tif (te - tm > 30) {\n\t\t\t\tSystem.err.println(\"Defalt routing config init took \" + (te - tm) + \" ms\"); //$NON-NLS-1$ //$NON-NLS-2$\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static GeneralRouter getRouter(net.osmand.router.RoutingConfiguration.Builder builder, ApplicationMode am) {\n\t\tGeneralRouter router = builder.getRouter(am.getStringKey());\n\t\tif (router == null && am.getParent() != null) {\n\t\t\trouter = builder.getRouter(am.getParent().getStringKey());\n\t\t}\n\t\treturn router;\n\t}\n\n\tpublic String getString(int pKey, Object... pObj) {\n\t\treturn MessageFormat.format(getString(pKey), pObj);\n\t}\n\n\tpublic String getOffRoadString(String pKey, Object... pObj) {\n\t\treturn MessageFormat.format(getOffRoadString(pKey), pObj);\n\t}\n\t\n\tpublic TargetPointsHelper getTargetPointsHelper() {\n\t\treturn mTargetPointsHelper;\n\t}\n\n\tpublic MapMarkersHelper getMapMarkersHelper() {\n\t\treturn mMapMarkersHelper;\n\t}\n\t\n\tpublic RoutingHelper getRoutingHelper() {\n\t\treturn mRoutingHelper;\n\t}\n\n\tpublic GeocodingLookupService getGeocodingLookupService() {\n\t\treturn mGeocodingLookupService;\n\t}\n\n\tpublic OsmAndLocationProvider getLocationProvider() {\n\t\treturn mOsmAndLocationProvider;\n\t}\n\n\tpublic MapPoiTypes getPoiTypes() {\n\t\treturn mMapPoiTypes;\n\t}\n\n\tpublic MouseEvent getLastMouseEvent() {\n\t\treturn mAdapter.getMouseEvent();\n\t}\n\t\n\tpublic RenderingRulesStorage getRenderingRulesStorage() {\n\t\tRenderingRulesStorage storage = mRendererRegistry.getCurrentSelectedRenderer();\n//\t\tSystem.out.println(\"\\n\\n--------- TEXT ----- \");\n//\t\tstorage.printDebug(storage.TEXT_RULES, System.out);\n\t\treturn storage;\n\t}\n\n\tpublic void showToastMessage(String pMsg) {\n//\t\tmStatusLabel.setBackground(Color.red);\n\t\tmStatusLabel.setText(pMsg);\n//\t\tmStatusLabel.repaint();\n\t\tmDontUpdateStatusLabelCounter = 4;\n\t}\n\n\tpublic void showQueueInformation(String pMsg) {\n\t\tmQueueStatus.setText(pMsg);\n\t}\n\t\n\tpublic void runInUIThread(Runnable pRunnable) {\n\t\tSwingUtilities.invokeLater(pRunnable);\n\t}\n\t\n\tpublic void addPoint(LatLon pPoint){\n\t\tMapPointStorage storage = new MapPointStorage(pPoint, getZoom());\n\t\tif(mPointStorageIndex < mPointStorage.size()-1){\n\t\t\t// remove all subsequent:\n\t\t\tmPointStorage.setSize(mPointStorageIndex + 1);\n\t\t}\n\t\tmPointStorage.add(storage);\n\t\tmPointStorageIndex = mPointStorage.size()-1;\n\t}\n\n\tpublic int getZoom() {\n\t\treturn getDrawPanel().copyCurrentTileBox().getZoom();\n\t}\n\n\tpublic void back() {\n\t\tif(mPointStorage.isEmpty()){\n\t\t\treturn;\n\t\t}\n\t\tif(mPointStorageIndex <= 0 || mPointStorageIndex >= mPointStorage.size()){\n\t\t\treturn;\n\t\t}\n\t\tmPointStorageIndex--;\n\t\tMapPointStorage pointStorage = mPointStorage.get(mPointStorageIndex);\n\t\tmDrawPanel.move(pointStorage.mPoint, pointStorage.mZoom);\n\t\tmDrawPanel.setCursor(pointStorage.mPoint);\n\t}\n\n\tpublic void forward() {\n\t\tif(mPointStorage.isEmpty()){\n\t\t\treturn;\n\t\t}\n\t\tif(mPointStorageIndex < 0 || mPointStorageIndex >= mPointStorage.size()-1){\n\t\t\treturn;\n\t\t}\n\t\tmPointStorageIndex++;\n\t\tMapPointStorage pointStorage = mPointStorage.get(mPointStorageIndex);\n\t\tmDrawPanel.move(pointStorage.mPoint, pointStorage.mZoom);\n\t\tmDrawPanel.setCursor(pointStorage.mPoint);\n\t}\n\t\n\tpublic interface CursorPositionListener {\n\t\tvoid cursorPositionChanged(LatLon pPosition);\n\t}\n\n\t\n\tpublic void addCursorPositionListener(CursorPositionListener pListener){\n\t\tmCursorPositionListeners.add(pListener);\n\t}\n\tpublic void removeCursorPositionListener(CursorPositionListener pListener){\n\t\tmCursorPositionListeners.remove(pListener);\n\t}\n\t\t\t\n\t\n\tpublic void setCursorPosition(Point pPoint) {\n\t\tmDrawPanel.setCursor(pPoint);\n\t\tsetCursorPosition(mDrawPanel.getCursorPosition());\n\t}\n\n\tpublic void setCursorPosition(LatLon pLoc) {\n\t\tmDrawPanel.setCursor(pLoc);\n\t\taddPoint(pLoc);\n\t\tqueueAmenityTableUpdate();\n\t\tfor (CursorPositionListener listener : mCursorPositionListeners) {\n\t\t\tlistener.cursorPositionChanged(pLoc);\n\t\t}\n\t}\n\n\tprivate void queueAmenityTableUpdate() {\n\t\t// queue update of the amenity table.\n\t\tgetDrawPanel().queue(new AmenityTableUpdateThread(getDrawPanel(), mAmenityTable), OsmBitmapPanel.PoolType.BACKGROUND);\n\t}\n\n\t\n\tpublic void runInUIThread(Runnable pRunnable, int pDelay) {\n\t\tTimer timer = new Timer(pDelay, pE -> pRunnable.run());\n\t\ttimer.setRepeats(false);\n\t\ttimer.start();\n\t}\n\n\tpublic void setProgress(int pPercent){\n\t\tif(pPercent < 100){\n\t\t\tmRouteProgressBar.setVisible(true);\n\t\t\tmRouteProgressBar.setValue(pPercent);\n\t\t} else {\n\t\t\tmRouteProgressBar.setVisible(false);\n\t\t}\n\t}\n\t\n\tpublic void setStatus(String pStatus){\n\t\tmRouteProgressStatus.setText(pStatus);\n\t}\n\n\tpublic String getLanguage() {\n\t\tLocale locale = Locale.getDefault();\n\t\treturn locale.getLanguage().toLowerCase();\n\t}\n\n\tpublic String getCountry() {\n\t\tLocale locale = Locale.getDefault();\n\t\treturn locale.getCountry().toLowerCase();\n\t}\n\n\tpublic PoiFiltersHelper getPoiFilters() {\n\t\treturn mPoiFilters;\n\t}\n\n\tpublic void showWikipedia(String pContent, String pTitle, String pArticle) {\n\t\tShowWikipediaAction action = new ShowWikipediaAction(this, pContent, pTitle, pArticle);\n\t\taction.actionPerformed(null);\n\t}\n\n\tpublic LatLon getCursorPosition() {\n\t\tLatLon cursorPosition = mDrawPanel.getCursorPosition();\n\t\tif(cursorPosition == null){\n\t\t\tcursorPosition = getCenterPosition();\n\t\t\tsetCursorPosition(cursorPosition);\n\t\t}\n\t\treturn cursorPosition;\n\t}\n\t\n\tpublic LatLon getMouseLocation() {\n\t\tMouseEvent lastMouseEvent = getLastMouseEvent();\n\t\tPoint destination;\n\t\tif(lastMouseEvent == null){\n\t\t\tdestination = new Point(0,0);\n\t\t} else {\n\t\t\tdestination = lastMouseEvent.getPoint();\n\t\t}\n\t\treturn mDrawPanel.copyCurrentTileBox().getLatLonFromPixel(destination.x, destination.y);\n\t}\n\n\tpublic PoiUIFilter getCurrentPoiUIFilter() {\n\t\treturn mCurrentPoiFilter;\n\t}\n\n\tpublic LatLon getCenterPosition() {\n\t\treturn mDrawPanel.copyCurrentTileBox().getCenterLatLon();\n\t}\n\n\t/**\n\t * @param filter == null: means, clear filter and table\n\t * @param pFilterText \n\t */\n\tpublic void setPoiFilter(PoiUIFilter filter, String pFilterText) {\n\t\tString filterId = null;\n\t\tif (filter != null) {\n\t\t\tfilterId = filter.getFilterId();\n\t\t}\n\t\tgetSettings().SELECTED_POI_FILTER_FOR_MAP.set(filterId);\n\t\tgetSettings().SELECTED_POI_FILTER_STRING_FOR_MAP.set(pFilterText);\n\t\tsetWaitingCursor(true);\n\t\tmAmenityTable.setSearchResult(getSearchResult());\n\t\tsetSearchType(SearchType.AMENITY);\n\t\tsetWaitingCursor(false);\n\t\tgetDrawPanel().refreshMap();\n\t}\n\n\tpublic List getSearchResult() {\n\t\tList result = new Vector<>();\n\t\tString filterId = getSettings().SELECTED_POI_FILTER_FOR_MAP.get();\n\t\tswitch(mSearchType){\n\t\tcase AMENITY:\n\t\t\tif (filterId != null) {\n\t\t\t\tPoiUIFilter filter = getPoiFilters().getFilterById(filterId);\n\t\t\t\tString filterString = getSettings().SELECTED_POI_FILTER_STRING_FOR_MAP.get();\n\t\t\t\tif(filterString != null && !filterString.isEmpty()){\n\t\t\t\t\tfilter.setFilterByName(filterString);\n\t\t\t\t}\n\t\t\t\tLatLon latLon = getCursorPosition();\n\t\t\t\tresult.addAll(filter.initializeNewSearch(latLon.getLatitude(), latLon.getLongitude(), -1,\n\t\t\t\t\t\tnew ResultMatcher() {\n\t\t\t\t\t\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic boolean publish(Amenity pObject) {\n\t\t\t\t\t\tlog.debug(\"Adding \" + pObject.getName(getLanguage()));\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic boolean isCancelled() {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ROUTE:\n\t\t\tresult.addAll(mRouteResult);\n\t\t}\n\t\treturn result;\n\t}\n\n//\tpublic String getOffRoadString(String pString, Object[] pObjects) {\n//\t\tMessageFormat formatter = new MessageFormat(\n//\t\t\t\tgetOffRoadString(pString)); //$NON-NLS-1$\n//\t\treturn formatter.format(pObjects);\n//\t}\n\n\tpublic JTextField getSearchTextField() {\n\t\treturn mSearchTextField;\n\t}\n\n\tvoid toggleSearchBar() {\n\t\tif(mSearchBarVisible){\n\t\t\tmFrame.getContentPane().remove(mToolBar);\n//\t\t\tmFrame.getContentPane().remove(mAmenityTable);\n\t\t\tmSplitPane.setDividerLocation(0);\n\t\t} else {\n\t\t\tmFrame.getContentPane().add(mToolBar, BorderLayout.NORTH);\n//\t\t\tmFrame.getContentPane().add(mAmenityTable, BorderLayout.WEST);\n\t\t}\n\t\tmSearchBarVisible = ! mSearchBarVisible;\n\t\tmFrame.revalidate();\n\t\tmDrawPanel.requestFocus();\n\t}\n\n\tpublic SQLiteAPI getSQLiteAPI() {\n\t\tif(mSqLiteImpl == null){\n\t\t\tmSqLiteImpl = new SQLiteImpl(this);\n\t\t}\n\t\treturn mSqLiteImpl;\n\t}\n\n\tpublic File getDatabasePath(String pFavouriteDbName) {\n\t\treturn getAppPath(pFavouriteDbName);\n\t}\n\n\tpublic File getFileStreamPath(String pFileToBackup) {\n\t\treturn getAppPath(pFileToBackup);\n\t}\n\n\tpublic FavouritesDbHelper getFavorites() {\n\t\tif(mFavorites == null){\n\t\t\tmFavorites = new FavouritesDbHelper(this);\n\t\t\tmFavorites.loadFavorites();\n\t\t}\n\t\treturn mFavorites;\n\t}\n\n\tpublic Properties getOffroadProperties() {\n\t\treturn mOffroadProperties;\n\t}\n\n\tpublic OffRoadResources getResources() {\n\t\tif(mOffRoadResources == null){\n\t\t\tmOffRoadResources = new OffRoadResources(this);\n\t\t}\n\t\treturn mOffRoadResources;\n\t}\n\t\n\t\n\n\tpublic GpxSelectionHelper getSelectedGpxHelper() {\n\t\tif(mGpxSelectionHelper==null){\n\t\t\tmGpxSelectionHelper = new GpxSelectionHelper(this, getSavingTrackHelper());\n\t\t\tmGpxSelectionHelper.loadGPXTracks(IProgress.EMPTY_PROGRESS);\n\t\t}\n\t\treturn mGpxSelectionHelper;\n\t}\n\n\tprotected SavingTrackHelper getSavingTrackHelper() {\n\t\tif (mSavingTrackHelper==null) {\n\t\t\tmSavingTrackHelper = new SavingTrackHelper(this);\n\t\t}\n\t\treturn mSavingTrackHelper;\n\t}\n\n\tprivate void closeWindow() {\n\t\tmDrawPanel.removeAllLayers();\n\t\t// save properties:\n\t\tsaveSettings();\n\t\tmFrame.dispose();\n\t\tSystem.exit(0);\n\t}\n\n\t/**\n\t * Cached loading of buffered images.\n\t * The image is the name of the image. Path and extension (.png) are \n\t * added by this method.\n\t * \n\t * @param image\n\t * @return\n\t */\n\tpublic BufferedImage readImage(String image) {\n\t\tif(mBufferedImageCache.containsKey(image)){\n\t\t\treturn mBufferedImageCache .get(image);\n\t\t}\n\t\tString path = IMAGE_PATH + getIconSize() + \"/\" + image + \".png\";\n\t\tBufferedImage res = readImageInternally(path);\n\t\tmBufferedImageCache.put(image, res);\n\t\treturn res;\n\t}\n\n\tprotected BufferedImage readImageInternally(String path) {\n\t\tBufferedImage res = null;\n\t\ttry {\n\t\t\tInputStream resource = getResource(path);\n\t\t\tif (resource == null) {\n\t\t\t\tlog.error(\"Resource \" + path + \" not found!\");\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tres = ImageIO.read(resource);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn res;\n\t}\n\n\tpublic void setRouteCalculated() {\n\t\tRouteCalculationResult route = getRoutingHelper().getRoute();\n\t\tList currentRoute = route.getRouteDirections();\n\t\tList locations = route.getImmutableAllLocations();\n\t\tList routeResult = new Vector<>();\n\t\tfor (RouteDirectionInfo directionInfo : currentRoute) {\n\t\t\trouteResult.add(new LocationAsMapObject(locations.get(directionInfo.routePointOffset), directionInfo.getDescriptionRoutePart(),\n\t\t\t\t\troute.getDistanceToPoint(directionInfo.routePointOffset)));\n\t\t}\n\t\tmRouteResult = routeResult;\n\t\tsetSearchType(SearchType.ROUTE);\n\t}\n\n\tprivate void setSearchType(SearchType pSearchType) {\n\t\tmSearchType = pSearchType;\n\t\tqueueAmenityTableUpdate();\n\t}\n\t\n\t\n\t@Override\n\tpublic void newRouteIsCalculated(boolean pNewRoute, ValueHolder pShowToast) {\n\t\tfloat dist = getRoutingHelper().getRoute().getWholeDistance()/1000f;\n\t\tsetStatus(getOffRoadString(\"offroad.routing_finished\", dist));\n\t\tsetRouteCalculated();\n\t\tgetDrawPanel().drawLater();\n\t}\n\n\t@Override\n\tpublic void routeWasCancelled() {\n\t\tgetDrawPanel().drawLater();\n\t}\n\n\t@Override\n\tpublic void routeWasFinished() {\n\t}\n\n\tpublic JMenuItem createJMenuItemForObject(IContextMenuProvider provider, Object am) {\n\t\tPointDescription pointDescription = provider.getObjectName(am);\n\t\tString name=\"UNKNOWN\";\n\t\tif(pointDescription != null){\n\t\t\tname = pointDescription.getName();\n\t\t} else {\n\t\t\t// strange...\n\t\t}\n\t\tString description = provider.getObjectDescription(am);\n\t\tIcon icon = null;\n\t\tif (am instanceof MapObject) {\n\t\t\tMapObject mapObject = (MapObject) am;\n\t\t\ticon = getImageIcon(mapObject);\n\t\t}\n\t\tJMenuItem item = new JMenuItem(name, icon);\n\t\titem.setToolTipText(description);\n\t\treturn item;\n\t}\n\t\n\tpublic javax.swing.Icon getImageIcon(MapObject am) {\n\t\tBufferedImage bitmap = getBitmap(am);\n\t\tif (bitmap != null) {\n\t\t\treturn new ImageIcon(bitmap);\n\t\t} else {\n\t\t\treturn new BlindIcon(20);\n\t\t}\n\t}\n\n\tpublic List getContextActionsForObject(IContextMenuProvider pProvider, Object pAm) {\n\t\tList result = new Vector<>();\n\t\tif (pAm instanceof Amenity) {\n\t\t\tAmenity am = (Amenity) pAm;\n\t\t\tJMenuItem item = createJMenuItemForObject(pProvider, pAm);\n\t\t\titem.addActionListener(pE -> {\n\t\t\t\tif (am.getType().isWiki()) {\n\t\t\t\t\tPOIMapLayer.showWikipediaDialog(OsmWindow.this, OsmWindow.this, am);\n\t\t\t\t} else {\n\t\t\t\t\tString locationName = PointDescription.getLocationName(OsmWindow.this,\n\t\t\t\t\t\t\tam.getLocation().getLatitude(), am.getLocation().getLongitude(), true);\n\t\t\t\t\tPOIMapLayer.showDescriptionDialog(OsmWindow.this, getInstance(),\n\t\t\t\t\t\t\tam.getAdditionalInfo().toString(), am.getName(getLanguage()));\n\t\t\t\t}\n\t\t\t});\n\t\t\tresult.add(item);\n\t\t} \n\t\tif (pAm instanceof FavouritePoint) {\n\t\t\tFavouritePoint point = (FavouritePoint) pAm;\n\t\t\tString editString = getOffRoadString(\"offroad.editFavourite\", point.getName(), point.getCategory());\n\t\t\tJMenuItem item = new JMenuItem(new AddFavoriteAction(this, editString, null, point){\n\t\t\t\t@Override\n\t\t\t\tprotected String getWindowTitle() {\n\t\t\t\t\treturn editString;\n\t\t\t\t}\n\t\t\t});\n\t\t\tresult.add(item);\n\t\t\titem = new JMenuItem(new DeleteFavoriteAction(this, getOffRoadString(\"offroad.deleteFavourite\", point.getName(), point.getCategory()), null, point));\n\t\t\tresult.add(item);\n\t\t\t\n\t\t}\n\t\tif (pAm instanceof TargetPoint) {\n\t\t\tTargetPoint targetPoint = (TargetPoint) pAm;\n\t\t\tPointNavigationAction removePointAction = new PointNavigationAction(this, \"offroad.remove_navigation_point\",\n\t\t\t\t\t(pHelper, pPosition) -> {\n\t\t\t\t\t\tif(targetPoint == pHelper.getPointToStart()){\n\t\t\t\t\t\t\tpHelper.clearStartPoint(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(targetPoint == pHelper.getPointToNavigate()){\n\t\t\t\t\t\t\tpHelper.clearPointToNavigate(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint index = pHelper.getIntermediatePoints().indexOf(targetPoint);\n\t\t\t\t\t\tif(index >= 0){\n\t\t\t\t\t\t\tpHelper.removeWayPoint(false, index);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\tJMenuItem item = new JMenuItem(removePointAction);\n\t\t\tresult.add(item);\n\t\t\t\n\t\t}\n\t\tif (pAm instanceof WptPt) {\n\t\t\tWptPt waypt = (WptPt) pAm;\n\t\t\t// TODO: What to do here?\n\t\t}\n\t\tif (pAm instanceof SelectedGpxFile) {\n\t\t\tSelectedGpxFile sgf = (SelectedGpxFile) pAm;\n\t\t\tJMenuItem trackInfoItem = new JMenuItem(new ShowTrackDetailsAction(this, sgf.getGpxFile()));\n\t\t\tresult.add(trackInfoItem);\n\t\t}\n\t\tif (pAm instanceof RouteCalculationResult) {\n\t\t\tRouteCalculationResult rcr = (RouteCalculationResult) pAm;\n\t\t\tJMenuItem routeInfoItem = new JMenuItem(new ShowRouteDetailsAction(this, rcr));\n\t\t\tresult.add(routeInfoItem);\n\t\t}\n\t\tif (pAm instanceof Polyline) {\n\t\t\tPolyline polyline = (Polyline) pAm;\n\t\t\tresult.add(new JMenuItem(new InsertPointIntoPolylineAction(this, polyline, getDrawPanel().getMouseLocation())));\n\t\t\tif (getDrawPanel().getPolylineLayer().isDragPoint(null, getDrawPanel().getMousePosition()) != null) {\n\t\t\t\tresult.add(new JMenuItem(\n\t\t\t\t\t\tnew RemovePointFromPolylineAction(this, polyline, getDrawPanel().getMouseLocation())));\n\t\t\t}\n\t\t\tresult.add(new JMenuItem(new RemovePolylineAction(this, polyline)));\n\t\t\tresult.add(new JMenuItem(new ShowPolylineDetailsAction(this, polyline)));\n\t\t}\n\t\treturn result;\n\t}\n\n\n\tpublic String getOsmandIconsDir(){\n\t\treturn OSMAND_ICONS_DIR + getIconSize() + \"/\";\n\t}\n\n\tpublic String getIconSize() {\n\t\treturn getOffroadProperties().getProperty(OSMAND_ICONS_DIR_PREFIX, OSMAND_ICONS_DIR_DEFAULT_PREFIX);\n\t}\n\n\tpublic void openDocument(URL url) {\n\t\tDesktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;\n\t\tif (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {\n\t\t\ttry {\n\t\t\t\t// fix for https://sourceforge.net/p/freemind/discussion/22102/thread/cf032151/?limit=25#c631\n\t\t\t\tURI uri = new URI(url.toString().replaceAll(\"^file:////\", \"file://\"));\n\t\t\t\tdesktop.browse(uri);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.fatal(\"Caught: \" + e, e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic DrawPolylineLayer getPolylineLayer(){\n\t\treturn mDrawPanel.getPolylineLayer();\n\t}\n\t\n\tpublic static String marshall(Object pStorage, Class[] pClasses){\n\t\ttry {\n\t\t\tJAXBContext jaxbContext = JAXBContext.newInstance(pClasses, null);\n\t\t\tMarshaller m = jaxbContext.createMarshaller();\n\t\t\tStringWriter writer = new StringWriter();\n\t\t\tm.marshal(pStorage, writer);\n\t\t\treturn writer.toString();\n\t\t} catch (JAXBException ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Object unmarshall(String pInput, Class[] pClasses){\n\t\ttry {\n\t\t\tJAXBContext jaxbContext = JAXBContext.newInstance(pClasses, null);\n\t\t\tUnmarshaller m = jaxbContext.createUnmarshaller();\n\t\t\treturn m.unmarshal(new StringReader(pInput));\n\t\t} catch (JAXBException ex) {\n\t\t\tex.printStackTrace();\n\t\t} catch (NullPointerException ex) {\n\t\t\t// Seems to happen when loading the .OffRoad config\n\t\t\t// from a pre-JAXB version, error is\n\t\t\t// java.lang.NullPointerException: Cannot invoke \"java.lang.reflect.Method.invoke(Object, Object[])\" because \"com.sun.xml.bind.v2.runtime.reflect.opt.Injector.defineClass\" is null\n\t\t\t// See issue 20.\n\t\t\tex.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void moveDirectly(LatLon pLatLon) {\n\t\tif(mDrawPanel.isNearCenter(pLatLon, 0.5f)) {\n\t\t\tmDrawPanel.setCursor(pLatLon);\n\t\t\treturn;\n\t\t}\n\t\tmDrawPanel.move(pLatLon, getZoom());\n\t\tmDrawPanel.setCursor(pLatLon);\n\t}\n\n\t\n}", "answers": ["\tpublic RemovePolylineAction(OsmWindow pContext, Polyline pPolyline) {"], "length": 5499, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "b02ada94-98e3-43a6-999c-001af9a6c06f", "reasoning": "The file RemovePolylineAction.java defines a class extending OffRoadAction with a private Polyline field. After the imports, the next logical line is the constructor that initializes the action with the context and the polyline to be removed. This matches typical pattern in the codebase for action classes.", "reasoning_model_answer": "public RemovePolylineAction(OsmWindow context, Polyline polyline) {", "assistant_with_reasoning": "\nThe file RemovePolylineAction.java defines a class extending OffRoadAction with a private Polyline field. After the imports, the next logical line is the constructor that initializes the action with the context and the polyline to be removed. This matches typical pattern in the codebase for action classes.\n\npublic RemovePolylineAction(OsmWindow context, Polyline polyline) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.039, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36160, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public RemovePolylineAction(OsmWindow context, Polyline polyline) {", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.dawex.sigourney.trustframework.vc.core.Proof;\nimport com.dawex.sigourney.trustframework.vc.core.SignedObject;\nimport com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdContexts;\nimport com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.FormatProvider;\nimport com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdContextsSerializer;\nimport com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdSerializer;\nimport com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.SignedObjectJsonLdSerializer;\nimport com.dawex.sigourney.trustframework.vc.model.shared.Did;\nimport com.dawex.sigourney.trustframework.vc.model.shared.JsonWebKey2020;\nimport com.dawex.sigourney.trustframework.vc.model.shared.VerifiablePresentation;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.common.Address;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct.AggregationOf;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct.DataAccountExport;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct.DataProductCredentialSubject;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct.DataProductVerifiableCredential;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct.ProvidedBy;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct.TermsAndConditionURI;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataresource.DataResourceVerifiableCredential;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataresource.Distribution;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataresource.ProducedBy;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataresource.DataResourceCredentialSubject;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataresource.ExposedThrough;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.dataresource.Location;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.organisation.OrganisationCredentialSubject;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.organisation.OrganisationLegalRegistrationNumber;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.organisation.OrganisationVerifiableCredential;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.termsandconditions.TermsAndConditionsCredentialSubject;\nimport com.dawex.sigourney.trustframework.vc.model.v2210.termsandconditions.TermsAndConditionsVerifiableCredential;\nimport com.fasterxml.jackson.databind.Module;\nimport com.fasterxml.jackson.databind.module.SimpleModule;\nimport java.util.List;\nimport java.util.function.Supplier;", "context": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/serialization/JacksonModuleFactory.java\npackage com.dawex.sigourney.trustframework.vc.model.v2210.serialization;\n\n\n\npublic class JacksonModuleFactory {\n\n\t/**\n\t * Create a configured Jackson module for serializing organisation verifiable credentials\n\t */\n\tpublic static Module organisationSerializationModule(FormatProvider formatProvider, Supplier baseIriSupplier) {\n\t\tfinal List domainClasses = List.of(Address.class,\n\t\t\t\tOrganisationCredentialSubject.class,\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataresource/Distribution.java\npublic class Distribution {\n\t@JsonLdProperty(value = \"title\", namespace = Namespace.DAWEX_NS, mandatory = true)\n\tprivate final String title;\n\n\t@JsonLdProperty(value = \"mediaType\", namespace = Namespace.DAWEX_NS, mandatory = true)\n\tprivate final String mediaType;\n\n\t@JsonLdProperty(value = \"byteSize\", namespace = Namespace.DAWEX_NS, mandatory = true)\n\tprivate final Long byteSize;\n\n\t@JsonLdProperty(value = \"fileHash\", namespace = Namespace.DAWEX_NS, mandatory = true)\n\tprivate final String fileHash;\n\n\t@JsonLdProperty(value = \"algorithm\", namespace = Namespace.DAWEX_NS, mandatory = true)\n\tprivate final String algorithm;\n\n\t@JsonLdProperty(value = \"location\", namespace = Namespace.DAWEX_NS)\n\tprivate final Location location;\n\n\tpublic Distribution(String title, String mediaType, Long byteSize, String fileHash, String algorithm,\n\t\t\tLocation location) {\n\t\tthis.title = title;\n\t\tthis.mediaType = mediaType;\n\t\tthis.byteSize = byteSize;\n\t\tthis.fileHash = fileHash;\n\t\tthis.algorithm = algorithm;\n\t\tthis.location = location;\n\t}\n\n\tpublic static DistributionBuilder builder() {\n\t\treturn new DistributionBuilder();\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic String getMediaType() {\n\t\treturn mediaType;\n\t}\n\n\tpublic Long getByteSize() {\n\t\treturn byteSize;\n\t}\n\n\tpublic String getFileHash() {\n\t\treturn fileHash;\n\t}\n\n\tpublic String getAlgorithm() {\n\t\treturn algorithm;\n\t}\n\n\tpublic Location getLocation() {\n\t\treturn location;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tDistribution that = (Distribution) o;\n\t\treturn Objects.equals(title, that.title) && Objects.equals(mediaType, that.mediaType) &&\n\t\t\t\tObjects.equals(byteSize, that.byteSize) && Objects.equals(fileHash, that.fileHash) &&\n\t\t\t\tObjects.equals(algorithm, that.algorithm) && Objects.equals(location, that.location);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(title, mediaType, byteSize, fileHash, algorithm, location);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Distribution{\" +\n\t\t\t\t\"title='\" + title + '\\'' +\n\t\t\t\t\", mediaType='\" + mediaType + '\\'' +\n\t\t\t\t\", byteSize=\" + byteSize +\n\t\t\t\t\", fileHash='\" + fileHash + '\\'' +\n\t\t\t\t\", algorithm='\" + algorithm + '\\'' +\n\t\t\t\t\", location=\" + location +\n\t\t\t\t'}';\n\t}\n\n\tpublic static class DistributionBuilder {\n\t\tprivate String title;\n\n\t\tprivate String mediaType;\n\n\t\tprivate Long byteSize;\n\n\t\tprivate String fileHash;\n\n\t\tprivate String algorithm;\n\n\t\tprivate Location location;\n\n\t\tDistributionBuilder() {\n\t\t}\n\n\t\tpublic DistributionBuilder title(String title) {\n\t\t\tthis.title = title;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DistributionBuilder mediaType(String mediaType) {\n\t\t\tthis.mediaType = mediaType;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DistributionBuilder byteSize(Long byteSize) {\n\t\t\tthis.byteSize = byteSize;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DistributionBuilder fileHash(String fileHash) {\n\t\t\tthis.fileHash = fileHash;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DistributionBuilder algorithm(String algorithm) {\n\t\t\tthis.algorithm = algorithm;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DistributionBuilder location(Location location) {\n\t\t\tthis.location = location;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Distribution build() {\n\t\t\treturn new Distribution(title, mediaType, byteSize, fileHash, algorithm, location);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"DistributionBuilder{\" +\n\t\t\t\t\t\"title='\" + title + '\\'' +\n\t\t\t\t\t\", mediaType='\" + mediaType + '\\'' +\n\t\t\t\t\t\", byteSize=\" + byteSize +\n\t\t\t\t\t\", fileHash='\" + fileHash + '\\'' +\n\t\t\t\t\t\", algorithm='\" + algorithm + '\\'' +\n\t\t\t\t\t\", location=\" + location +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataresource/ProducedBy.java\npublic class ProducedBy {\n\t@JsonLdProperty(value = \"id\", formatName = DATA_RESOURCE_PRODUCED_BY)\n\tprivate final String id;\n\n\tpublic ProducedBy(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic static ProducedByBuilder builder() {\n\t\treturn new ProducedByBuilder();\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tProducedBy that = (ProducedBy) o;\n\t\treturn Objects.equals(id, that.id);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ProducedBy{\" +\n\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t'}';\n\t}\n\n\tpublic static class ProducedByBuilder {\n\t\tprivate String id;\n\n\t\tProducedByBuilder() {\n\t\t}\n\n\t\tpublic ProducedByBuilder id(String id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic ProducedBy build() {\n\t\t\treturn new ProducedBy(id);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"ProducedByBuilder{\" +\n\t\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/JsonLdContextsSerializer.java\npublic class JsonLdContextsSerializer extends JsonSerializer {\n\n\tprivate static final String CONTEXT_BASE = \"@base\";\n\n\tprivate Supplier baseIri;\n\n\tpublic JsonLdContextsSerializer(Supplier baseIri) {\n\t\tthis.baseIri = baseIri;\n\t}\n\n\t@Override\n\tpublic void serialize(JsonLdContexts jsonLdContexts, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)\n\t\t\tthrows IOException {\n\t\tjsonGenerator.writeStartArray();\n\t\twriteEmbeddedContexts(jsonLdContexts, jsonGenerator);\n\t\twriteReferencedContexts(jsonLdContexts, jsonGenerator);\n\t\tjsonGenerator.writeEndArray();\n\t}\n\n\tprivate void writeEmbeddedContexts(JsonLdContexts jsonLdContexts, JsonGenerator jsonGenerator) throws IOException {\n\t\tif ((!jsonLdContexts.addBaseContext() || baseIri == null) && jsonLdContexts.embeddedContexts().length == 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tjsonGenerator.writeStartObject();\n\t\tif (jsonLdContexts.addBaseContext() && baseIri != null) {\n\t\t\tjsonGenerator.writeStringField(CONTEXT_BASE, baseIri.get());\n\t\t}\n\t\tfor (JsonLdEmbeddedContext embeddedContext : jsonLdContexts.embeddedContexts()) {\n\t\t\tjsonGenerator.writeStringField(embeddedContext.term(), embeddedContext.iri());\n\t\t}\n\t\tjsonGenerator.writeEndObject();\n\t}\n\n\tprivate static void writeReferencedContexts(JsonLdContexts jsonLdContexts, JsonGenerator jsonGenerator) throws IOException {\n\t\tfor (String referencedContext : jsonLdContexts.referencedContexts()) {\n\t\t\tjsonGenerator.writeString(referencedContext);\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/organisation/OrganisationCredentialSubject.java\n@JsonLdType(\"gx:LegalParticipant\")\npublic class OrganisationCredentialSubject {\n\t@JsonLdProperty(value = \"id\", formatName = Format.ORGANISATION_CREDENTIAL_SUBJECT)\n\tprivate final String id;\n\n\t@JsonLdProperty(value = \"name\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final String name;\n\n\t@JsonLdProperty(value = \"legalRegistrationNumber\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final OrganisationLegalRegistrationNumber registrationNumber;\n\n\t@JsonLdProperty(value = \"headquarterAddress\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final Address headquarterAddress;\n\n\t@JsonLdProperty(value = \"legalAddress\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final Address legalAddress;\n\n\tpublic OrganisationCredentialSubject(String id, String name, OrganisationLegalRegistrationNumber registrationNumber,\n\t\t\tAddress headquarterAddress, Address legalAddress) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.registrationNumber = registrationNumber;\n\t\tthis.headquarterAddress = headquarterAddress;\n\t\tthis.legalAddress = legalAddress;\n\t}\n\n\tpublic static OrganisationCredentialSubjectBuilder builder() {\n\t\treturn new OrganisationCredentialSubjectBuilder();\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic OrganisationLegalRegistrationNumber getRegistrationNumber() {\n\t\treturn registrationNumber;\n\t}\n\n\tpublic Address getHeadquarterAddress() {\n\t\treturn headquarterAddress;\n\t}\n\n\tpublic Address getLegalAddress() {\n\t\treturn legalAddress;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null || obj.getClass() != this.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tvar that = (OrganisationCredentialSubject) obj;\n\t\treturn Objects.equals(this.id, that.id) &&\n\t\t\t\tObjects.equals(this.name, that.name) &&\n\t\t\t\tObjects.equals(this.registrationNumber, that.registrationNumber) &&\n\t\t\t\tObjects.equals(this.headquarterAddress, that.headquarterAddress) &&\n\t\t\t\tObjects.equals(this.legalAddress, that.legalAddress);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id, name, registrationNumber, headquarterAddress, legalAddress);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"OrganisationCredentialSubject[\" +\n\t\t\t\t\"id=\" + id + \", \" +\n\t\t\t\t\"name=\" + name + \", \" +\n\t\t\t\t\"registrationNumber=\" + registrationNumber + \", \" +\n\t\t\t\t\"headquarterAddress=\" + headquarterAddress + \", \" +\n\t\t\t\t\"legalAddress=\" + legalAddress + ']';\n\t}\n\n\tpublic static class OrganisationCredentialSubjectBuilder {\n\t\tprivate String id;\n\n\t\tprivate String name;\n\n\t\tprivate OrganisationLegalRegistrationNumber registrationNumber;\n\n\t\tprivate Address headquarterAddress;\n\n\t\tprivate Address legalAddress;\n\n\t\tOrganisationCredentialSubjectBuilder() {\n\t\t}\n\n\t\tpublic OrganisationCredentialSubjectBuilder id(String id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationCredentialSubjectBuilder name(String name) {\n\t\t\tthis.name = name;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationCredentialSubjectBuilder registrationNumber(OrganisationLegalRegistrationNumber registrationNumber) {\n\t\t\tthis.registrationNumber = registrationNumber;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationCredentialSubjectBuilder headquarterAddress(Address headquarterAddress) {\n\t\t\tthis.headquarterAddress = headquarterAddress;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationCredentialSubjectBuilder legalAddress(Address legalAddress) {\n\t\t\tthis.legalAddress = legalAddress;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationCredentialSubject build() {\n\t\t\treturn new OrganisationCredentialSubject(id, name, registrationNumber, headquarterAddress, legalAddress);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"OrganisationCredentialSubjectBuilder{\" +\n\t\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\t\", name='\" + name + '\\'' +\n\t\t\t\t\t\", registrationNumber='\" + registrationNumber + '\\'' +\n\t\t\t\t\t\", headquarterAddress=\" + headquarterAddress +\n\t\t\t\t\t\", legalAddress=\" + legalAddress +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/shared/VerifiablePresentation.java\n@JsonLdContexts(referencedContexts = {VERIFIABLE_CREDENTIALS})\n@JsonLdType(\"VerifiablePresentation\")\npublic class VerifiablePresentation {\n\n\t@JsonLdProperty(value = \"verifiableCredential\")\n\tprivate final Collection verifiableCredential;\n\n\tpublic VerifiablePresentation(Collection verifiableCredential) {\n\t\tthis.verifiableCredential = verifiableCredential;\n\t}\n\n\tpublic Collection getVerifiableCredential() {\n\t\treturn verifiableCredential;\n\t}\n\n\tpublic static VerifiablePresentationBuilder builder() {\n\t\treturn new VerifiablePresentationBuilder();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tVerifiablePresentation that = (VerifiablePresentation) o;\n\t\treturn Objects.equals(verifiableCredential, that.verifiableCredential);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(verifiableCredential);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"VerifiablePresentation{\" +\n\t\t\t\t\"verifiableCredential=\" + verifiableCredential +\n\t\t\t\t'}';\n\t}\n\n\tpublic static class VerifiablePresentationBuilder {\n\t\tprivate Collection verifiableCredential;\n\n\t\tVerifiablePresentationBuilder() {\n\t\t}\n\n\t\tpublic VerifiablePresentationBuilder verifiableCredential(Collection verifiableCredential) {\n\t\t\tthis.verifiableCredential = verifiableCredential;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic VerifiablePresentation build() {\n\t\t\treturn new VerifiablePresentation(this.verifiableCredential);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"VerifiablePresentationBuilder{\" +\n\t\t\t\t\t\"verifiableCredential=\" + verifiableCredential +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataresource/DataResourceCredentialSubject.java\n@JsonLdType(\"gx:DataResource\")\npublic class DataResourceCredentialSubject {\n\t@JsonLdProperty(value = \"id\", formatName = Format.DATA_RESOURCE_CREDENTIAL_SUBJECT)\n\tprivate final String id;\n\n\t@JsonLdProperty(value = \"name\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS)\n\tprivate final String name;\n\n\t@JsonLdProperty(value = \"description\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS)\n\tprivate final String description;\n\n\t@JsonLdProperty(value = \"policy\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final Collection policy;\n\n\t@JsonLdProperty(value = \"license\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final Collection licenses;\n\n\t@JsonLdProperty(value = \"copyrightOwnedBy\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, formatName = Format.DATA_RESOURCE_COPYRIGHT_OWNED_BY, mandatory = true)\n\tprivate final Collection copyrightOwnedBy;\n\n\t@JsonLdProperty(value = \"producedBy\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final ProducedBy producedBy;\n\n\t@JsonLdProperty(value = \"containsPII\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final boolean containsPII;\n\n\t@JsonLdProperty(value = \"exposedThrough\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final ExposedThrough exposedThrough;\n\n\t@JsonLdProperty(value = \"distribution\", namespace = Namespace.DAWEX_NS)\n\tprivate final Distribution distribution;\n\n\tpublic DataResourceCredentialSubject(String id, String name, String description, Collection policy, Collection licenses,\n\t\t\tCollection copyrightOwnedBy, ProducedBy producedBy, boolean containsPII, ExposedThrough exposedThrough,\n\t\t\tDistribution distribution) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t\tthis.policy = policy;\n\t\tthis.licenses = licenses;\n\t\tthis.copyrightOwnedBy = copyrightOwnedBy;\n\t\tthis.producedBy = producedBy;\n\t\tthis.containsPII = containsPII;\n\t\tthis.exposedThrough = exposedThrough;\n\t\tthis.distribution = distribution;\n\t}\n\n\tpublic static DataResourceCredentialSubjectBuilder builder() {\n\t\treturn new DataResourceCredentialSubjectBuilder();\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic Collection getPolicy() {\n\t\treturn policy;\n\t}\n\n\tpublic Collection getLicenses() {\n\t\treturn licenses;\n\t}\n\n\tpublic Collection getCopyrightOwnedBy() {\n\t\treturn copyrightOwnedBy;\n\t}\n\n\tpublic ProducedBy getProducedBy() {\n\t\treturn producedBy;\n\t}\n\n\tpublic boolean getContainsPII() {\n\t\treturn containsPII;\n\t}\n\n\tpublic ExposedThrough getExposedThrough() {\n\t\treturn exposedThrough;\n\t}\n\n\tpublic Distribution getDistribution() {\n\t\treturn distribution;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tDataResourceCredentialSubject that = (DataResourceCredentialSubject) o;\n\t\treturn containsPII == that.containsPII && Objects.equals(id, that.id) && Objects.equals(name, that.name) &&\n\t\t\t\tObjects.equals(description, that.description) && Objects.equals(policy, that.policy) &&\n\t\t\t\tObjects.equals(licenses, that.licenses) && Objects.equals(copyrightOwnedBy, that.copyrightOwnedBy) &&\n\t\t\t\tObjects.equals(producedBy, that.producedBy) && Objects.equals(exposedThrough, that.exposedThrough) &&\n\t\t\t\tObjects.equals(distribution, that.distribution);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id, name, description, policy, licenses, copyrightOwnedBy, producedBy, containsPII, exposedThrough,\n\t\t\t\tdistribution);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"DataResourceCredentialSubject{\" +\n\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\", name='\" + name + '\\'' +\n\t\t\t\t\", description='\" + description + '\\'' +\n\t\t\t\t\", policy=\" + policy +\n\t\t\t\t\", licenses=\" + licenses +\n\t\t\t\t\", copyrightOwnedBy=\" + copyrightOwnedBy +\n\t\t\t\t\", producedBy=\" + producedBy +\n\t\t\t\t\", containsPII=\" + containsPII +\n\t\t\t\t\", exposedThrough=\" + exposedThrough +\n\t\t\t\t\", distribution=\" + distribution +\n\t\t\t\t'}';\n\t}\n\n\tpublic static class DataResourceCredentialSubjectBuilder {\n\t\tprivate String id;\n\n\t\tprivate String name;\n\n\t\tprivate String description;\n\n\t\tprivate Collection policy;\n\n\t\tprivate Collection licenses;\n\n\t\tprivate Collection copyrightOwnedBy;\n\n\t\tprivate ProducedBy producedBy;\n\n\t\tprivate boolean containsPII;\n\n\t\tprivate ExposedThrough exposedThrough;\n\n\t\tprivate Distribution distribution;\n\n\t\tDataResourceCredentialSubjectBuilder() {\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder id(String id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder name(String name) {\n\t\t\tthis.name = name;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder description(String description) {\n\t\t\tthis.description = description;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder policy(Collection policy) {\n\t\t\tthis.policy = policy;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder licenses(Collection licenses) {\n\t\t\tthis.licenses = licenses;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder copyrightOwnedBy(Collection copyrightOwnedBy) {\n\t\t\tthis.copyrightOwnedBy = copyrightOwnedBy;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder producedBy(ProducedBy producedBy) {\n\t\t\tthis.producedBy = producedBy;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder containsPII(boolean containsPII) {\n\t\t\tthis.containsPII = containsPII;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder exposedThrough(ExposedThrough exposedThrough) {\n\t\t\tthis.exposedThrough = exposedThrough;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubjectBuilder distribution(Distribution distribution) {\n\t\t\tthis.distribution = distribution;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataResourceCredentialSubject build() {\n\t\t\treturn new DataResourceCredentialSubject(id, name, description, policy, licenses, copyrightOwnedBy, producedBy, containsPII,\n\t\t\t\t\texposedThrough, distribution);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"DataResourceCredentialSubjectBuilder{\" +\n\t\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\t\", name='\" + name + '\\'' +\n\t\t\t\t\t\", description='\" + description + '\\'' +\n\t\t\t\t\t\", policy=\" + policy +\n\t\t\t\t\t\", licenses=\" + licenses +\n\t\t\t\t\t\", copyrightOwnedBy=\" + copyrightOwnedBy +\n\t\t\t\t\t\", producedBy=\" + producedBy +\n\t\t\t\t\t\", containsPII=\" + containsPII +\n\t\t\t\t\t\", exposedThrough=\" + exposedThrough +\n\t\t\t\t\t\", distribution=\" + distribution +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/SignedObjectJsonLdSerializer.java\npublic class SignedObjectJsonLdSerializer extends JsonLdSerializer {\n\n\tpublic SignedObjectJsonLdSerializer(FormatProvider formatProvider) {\n\t\tsuper(SignedObject.class, formatProvider);\n\t}\n\n\t@Override\n\tpublic void serialize(SignedObject value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {\n\t\tfinal Class serializablePayloadClass = value.payload().getClass();\n\t\tjsonGenerator.writeStartObject();\n\t\twriteContext(serializablePayloadClass, jsonGenerator);\n\t\twriteType(serializablePayloadClass, jsonGenerator);\n\t\twriteJsonLdProperties(value.payload(), serializablePayloadClass, jsonGenerator);\n\t\twriteJsonLdProperties(value, SignedObject.class, jsonGenerator);\n\t\tjsonGenerator.writeEndObject();\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataresource/ExposedThrough.java\npublic class ExposedThrough {\n\t@JsonLdProperty(value = \"id\", formatName = Format.DATA_RESOURCE_EXPOSED_THROUGH)\n\tprivate final String id;\n\n\tpublic ExposedThrough(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic static ExposedThroughBuilder builder() {\n\t\treturn new ExposedThroughBuilder();\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tExposedThrough that = (ExposedThrough) o;\n\t\treturn Objects.equals(id, that.id);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ExposedThrough{\" +\n\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t'}';\n\t}\n\n\tpublic static class ExposedThroughBuilder {\n\t\tprivate String id;\n\n\t\tExposedThroughBuilder() {\n\t\t}\n\n\t\tpublic ExposedThroughBuilder id(String id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic ExposedThrough build() {\n\t\t\treturn new ExposedThrough(id);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"ExposedThroughBuilder{\" +\n\t\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/organisation/OrganisationVerifiableCredential.java\n@JsonLdContexts(\n\t\taddBaseContext = true,\n\t\treferencedContexts = {\n\t\t\t\tVERIFIABLE_CREDENTIALS,\n\t\t\t\tSECURITY_JWS_2020,\n\t\t\t\tGAIAX_TRUST_FRAMEWORK\n\t\t})\n@JsonLdType(\"VerifiableCredential\")\npublic class OrganisationVerifiableCredential {\n\t@JsonLdProperty(value = \"id\", formatName = Format.ORGANISATION_VERIFIABLE_CREDENTIAL)\n\tprivate final String id;\n\n\t@JsonLdProperty(value = \"issuer\", formatName = Format.ORGANISATION_ISSUER)\n\tprivate final String issuer;\n\n\t@JsonLdProperty(value = \"issuanceDate\")\n\tprivate final ZonedDateTime issuanceDate;\n\n\t@JsonLdProperty(value = \"credentialSubject\")\n\tprivate final OrganisationCredentialSubject organisationCredentialSubject;\n\n\tpublic OrganisationVerifiableCredential(String id, String issuer, ZonedDateTime issuanceDate,\n\t\t\tOrganisationCredentialSubject organisationCredentialSubject) {\n\t\tthis.id = id;\n\t\tthis.issuer = issuer;\n\t\tthis.issuanceDate = issuanceDate;\n\t\tthis.organisationCredentialSubject = organisationCredentialSubject;\n\t}\n\n\tpublic static OrganisationVerifiableCredentialBuilder builder() {\n\t\treturn new OrganisationVerifiableCredentialBuilder();\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getIssuer() {\n\t\treturn issuer;\n\t}\n\n\tpublic ZonedDateTime getIssuanceDate() {\n\t\treturn issuanceDate;\n\t}\n\n\tpublic OrganisationCredentialSubject getOrganisationCredentialSubject() {\n\t\treturn organisationCredentialSubject;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null || obj.getClass() != this.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tvar that = (OrganisationVerifiableCredential) obj;\n\t\treturn Objects.equals(this.id, that.id) &&\n\t\t\t\tObjects.equals(this.issuer, that.issuer) &&\n\t\t\t\tObjects.equals(this.issuanceDate, that.issuanceDate) &&\n\t\t\t\tObjects.equals(this.organisationCredentialSubject, that.organisationCredentialSubject);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id, issuer, issuanceDate, organisationCredentialSubject);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"OrganisationVerifiableCredential[\" +\n\t\t\t\t\"id=\" + id + \", \" +\n\t\t\t\t\"issuer=\" + issuer + \", \" +\n\t\t\t\t\"issuanceDate=\" + issuanceDate + \", \" +\n\t\t\t\t\"organisationCredentialSubject=\" + organisationCredentialSubject + ']';\n\t}\n\n\tpublic static class OrganisationVerifiableCredentialBuilder {\n\t\tprivate String id;\n\n\t\tprivate String issuer;\n\n\t\tprivate ZonedDateTime issuanceDate;\n\n\t\tprivate OrganisationCredentialSubject organisationCredentialSubject;\n\n\t\tOrganisationVerifiableCredentialBuilder() {\n\t\t}\n\n\t\tpublic OrganisationVerifiableCredentialBuilder id(String id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationVerifiableCredentialBuilder issuer(String issuer) {\n\t\t\tthis.issuer = issuer;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationVerifiableCredentialBuilder issuanceDate(ZonedDateTime issuanceDate) {\n\t\t\tthis.issuanceDate = issuanceDate;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationVerifiableCredentialBuilder organisationCredentialSubject(\n\t\t\t\tOrganisationCredentialSubject organisationCredentialSubject) {\n\t\t\tthis.organisationCredentialSubject = organisationCredentialSubject;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic OrganisationVerifiableCredential build() {\n\t\t\treturn new OrganisationVerifiableCredential(id, issuer, issuanceDate, organisationCredentialSubject);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"OrganisationVerifiableCredentialBuilder{\" +\n\t\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\t\", issuer='\" + issuer + '\\'' +\n\t\t\t\t\t\", issuanceDate=\" + issuanceDate +\n\t\t\t\t\t\", organisationCredentialSubject=\" + organisationCredentialSubject +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataproduct/ProvidedBy.java\npublic class ProvidedBy {\n\t@JsonLdProperty(value = \"id\", formatName = DATA_PRODUCT_PROVIDED_BY)\n\tprivate final String id;\n\n\tpublic ProvidedBy(String id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic static ProvidedByBuilder builder() {\n\t\treturn new ProvidedByBuilder();\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tProvidedBy that = (ProvidedBy) o;\n\t\treturn Objects.equals(id, that.id);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ProvidedBy{\" +\n\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t'}';\n\t}\n\n\tpublic static class ProvidedByBuilder {\n\t\tprivate String id;\n\n\t\tProvidedByBuilder() {\n\t\t}\n\n\t\tpublic ProvidedByBuilder id(String id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic ProvidedBy build() {\n\t\t\treturn new ProvidedBy(id);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"ProvidedByBuilder{\" +\n\t\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataproduct/TermsAndConditionURI.java\npublic class TermsAndConditionURI {\n\t@JsonLdProperty(value = \"URL\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, formatName = DATA_PRODUCT_TERMS_AND_CONDITIONS_URI, mandatory = true)\n\tprivate final String url;\n\n\t@JsonLdProperty(value = \"hash\", namespace = Namespace.GAIAX_TRUST_FRAMEWORK_NS, mandatory = true)\n\tprivate final String hash;\n\n\tpublic TermsAndConditionURI(String url, String hash) {\n\t\tthis.url = url;\n\t\tthis.hash = hash;\n\t}\n\n\tpublic static TermsAndConditionURIBuilder builder() {\n\t\treturn new TermsAndConditionURIBuilder();\n\t}\n\n\tpublic String getUrl() {\n\t\treturn url;\n\t}\n\n\tpublic String getHash() {\n\t\treturn hash;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tTermsAndConditionURI that = (TermsAndConditionURI) o;\n\t\treturn Objects.equals(url, that.url) && Objects.equals(hash, that.hash);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(url, hash);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"TermsAndConditionURI{\" +\n\t\t\t\t\"url='\" + url + '\\'' +\n\t\t\t\t\", hash='\" + hash + '\\'' +\n\t\t\t\t'}';\n\t}\n\n\tpublic static class TermsAndConditionURIBuilder {\n\t\tprivate String url;\n\n\t\tprivate String hash;\n\n\t\tTermsAndConditionURIBuilder() {\n\t\t}\n\n\t\tpublic TermsAndConditionURIBuilder url(String url) {\n\t\t\tthis.url = url;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic TermsAndConditionURIBuilder hash(String hash) {\n\t\t\tthis.hash = hash;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic TermsAndConditionURI build() {\n\t\t\treturn new TermsAndConditionURI(url, hash);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"TermsAndConditionURIBuilder{\" +\n\t\t\t\t\t\"url='\" + url + '\\'' +\n\t\t\t\t\t\", hash='\" + hash + '\\'' +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataresource/Location.java\npublic class Location {\n\t@JsonLdProperty(value = \"dataCenterLocation\", namespace = Namespace.DAWEX_NS)\n\tprivate final String dataCenterLocation;\n\n\tpublic Location(String dataCenterLocation) {\n\t\tthis.dataCenterLocation = dataCenterLocation;\n\t}\n\n\tpublic static LocationBuilder builder() {\n\t\treturn new LocationBuilder();\n\t}\n\n\tpublic String getDataCenterLocation() {\n\t\treturn dataCenterLocation;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null || obj.getClass() != this.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tvar that = (Location) obj;\n\t\treturn Objects.equals(this.dataCenterLocation, that.dataCenterLocation);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(dataCenterLocation);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Location[\" +\n\t\t\t\t\"dataCenterLocation=\" + dataCenterLocation + ']';\n\t}\n\n\tpublic static class LocationBuilder {\n\t\tprivate String dataCenterLocation;\n\n\t\tLocationBuilder() {\n\t\t}\n\n\t\tpublic LocationBuilder dataCenterLocation(String dataCenterLocation) {\n\t\t\tthis.dataCenterLocation = dataCenterLocation;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Location build() {\n\t\t\treturn new Location(dataCenterLocation);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"LocationBuilder{\" +\n\t\t\t\t\t\"dataCenterLocation='\" + dataCenterLocation + '\\'' +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataproduct/DataProductVerifiableCredential.java\n@JsonLdContexts(\n\t\taddBaseContext = true,\n\t\tembeddedContexts = {\n\t\t\t\t@JsonLdEmbeddedContext(term = Namespace.DC_TERMS_NS, iri = Namespace.DC_TERMS_IRI),\n\t\t},\n\t\treferencedContexts = {\n\t\t\t\tVERIFIABLE_CREDENTIALS,\n\t\t\t\tSECURITY_JWS_2020,\n\t\t\t\tGAIAX_TRUST_FRAMEWORK\n\t\t})\n@JsonLdType(\"VerifiableCredential\")\npublic class DataProductVerifiableCredential {\n\t@JsonLdProperty(value = \"id\", formatName = DATA_PRODUCT_VERIFIABLE_CREDENTIAL)\n\tprivate final Id id;\n\n\t@JsonLdProperty(value = \"issuer\", formatName = DATA_PRODUCT_ISSUER)\n\tprivate final String issuer;\n\n\t@JsonLdProperty(value = \"issuanceDate\")\n\tprivate final ZonedDateTime issuanceDate;\n\n\t@JsonLdProperty(value = \"credentialSubject\")\n\tprivate final DataProductCredentialSubject credentialSubject;\n\n\tpublic DataProductVerifiableCredential(Id id, String issuer, ZonedDateTime issuanceDate,\n\t\t\tDataProductCredentialSubject credentialSubject) {\n\t\tthis.id = id;\n\t\tthis.issuer = issuer;\n\t\tthis.issuanceDate = issuanceDate;\n\t\tthis.credentialSubject = credentialSubject;\n\t}\n\n\tpublic static DataProductVerifiableCredentialBuilder builder() {\n\t\treturn new DataProductVerifiableCredentialBuilder();\n\t}\n\n\tpublic Id getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getIssuer() {\n\t\treturn issuer;\n\t}\n\n\tpublic ZonedDateTime getIssuanceDate() {\n\t\treturn issuanceDate;\n\t}\n\n\tpublic DataProductCredentialSubject getCredentialSubject() {\n\t\treturn credentialSubject;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null || obj.getClass() != this.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tvar that = (DataProductVerifiableCredential) obj;\n\t\treturn Objects.equals(this.id, that.id) &&\n\t\t\t\tObjects.equals(this.issuer, that.issuer) &&\n\t\t\t\tObjects.equals(this.issuanceDate, that.issuanceDate) &&\n\t\t\t\tObjects.equals(this.credentialSubject, that.credentialSubject);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id, issuer, issuanceDate, credentialSubject);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"DataProductVerifiableCredential[\" +\n\t\t\t\t\"id=\" + id + \", \" +\n\t\t\t\t\"issuer=\" + issuer + \", \" +\n\t\t\t\t\"issuanceDate=\" + issuanceDate + \", \" +\n\t\t\t\t\"credentialSubject=\" + credentialSubject + ']';\n\t}\n\n\tpublic static class DataProductVerifiableCredentialBuilder {\n\t\tprivate Id id;\n\n\t\tprivate String issuer;\n\n\t\tprivate ZonedDateTime issuanceDate;\n\n\t\tprivate DataProductCredentialSubject credentialSubject;\n\n\t\tDataProductVerifiableCredentialBuilder() {\n\t\t}\n\n\t\tpublic DataProductVerifiableCredentialBuilder id(Id id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataProductVerifiableCredentialBuilder issuer(String issuer) {\n\t\t\tthis.issuer = issuer;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataProductVerifiableCredentialBuilder issuanceDate(ZonedDateTime issuanceDate) {\n\t\t\tthis.issuanceDate = issuanceDate;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataProductVerifiableCredentialBuilder credentialSubject(DataProductCredentialSubject credentialSubject) {\n\t\t\tthis.credentialSubject = credentialSubject;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic DataProductVerifiableCredential build() {\n\t\t\treturn new DataProductVerifiableCredential(id, issuer, issuanceDate, credentialSubject);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"DataProductVerifiableCredentialBuilder{\" +\n\t\t\t\t\t\"id=\" + id +\n\t\t\t\t\t\", issuer='\" + issuer + '\\'' +\n\t\t\t\t\t\", issuanceDate=\" + issuanceDate +\n\t\t\t\t\t\", credentialSubject=\" + credentialSubject +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n\n\tpublic record Id(String dataProductId, String organisationId) implements CompositeValue {\n\t\t@Override\n\t\tpublic Object[] getValues() {\n\t\t\treturn new Object[]{organisationId, dataProductId};\n\t\t}\n\t}\n}\n\ntrust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/shared/JsonWebKey2020.java\n@JsonLdContexts(referencedContexts = SECURITY_JWS_2020)\n@JsonLdType(\"JsonWebKey2020\")\npublic class JsonWebKey2020 implements VerificationMethod {\n\n\t@JsonLdProperty(value = \"id\")\n\tprivate final String id;\n\n\t@JsonLdProperty(value = \"controller\")\n\tprivate final String controller;\n\n\t@JsonLdProperty(value = \"publicKeyJwk\")\n\tprivate final Map publicKeyJwk;\n\n\tpublic JsonWebKey2020(String id, String controller, Map publicKeyJwk) {\n\t\tthis.id = id;\n\t\tthis.controller = controller;\n\t\tthis.publicKeyJwk = publicKeyJwk;\n\t}\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getController() {\n\t\treturn controller;\n\t}\n\n\tpublic Map getPublicKeyJwk() {\n\t\treturn publicKeyJwk;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (o == null || getClass() != o.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tJsonWebKey2020 that = (JsonWebKey2020) o;\n\t\treturn Objects.equals(id, that.id) && Objects.equals(controller, that.controller) &&\n\t\t\t\tObjects.equals(publicKeyJwk, that.publicKeyJwk);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id, controller, publicKeyJwk);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"JsonWebKey2020{\" +\n\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\", controller='\" + controller + '\\'' +\n\t\t\t\t\", publicKeyJwk=\" + publicKeyJwk +\n\t\t\t\t'}';\n\t}\n\n\tpublic static JsonWebKey2020Builder builder() {\n\t\treturn new JsonWebKey2020Builder();\n\t}\n\n\tpublic static class JsonWebKey2020Builder {\n\n\t\tprivate String id;\n\n\t\tprivate String controller;\n\n\t\tprivate Map publicKeyJwk;\n\n\t\tJsonWebKey2020Builder() {\n\t\t}\n\n\t\tpublic JsonWebKey2020Builder id(String id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic JsonWebKey2020Builder controller(String controller) {\n\t\t\tthis.controller = controller;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic JsonWebKey2020Builder publicKeyJwk(Map publicKeyJwk) {\n\t\t\tthis.publicKeyJwk = publicKeyJwk;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic JsonWebKey2020 build() {\n\t\t\treturn new JsonWebKey2020(id, controller, publicKeyJwk);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"JsonWebKey2020Builder{\" +\n\t\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\t\", controller='\" + controller + '\\'' +\n\t\t\t\t\t\", publicKeyJwk=\" + publicKeyJwk +\n\t\t\t\t\t'}';\n\t\t}\n\t}\n}", "answers": ["\t\t\t\tOrganisationLegalRegistrationNumber.class,"], "length": 3532, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "47c067f1-ed7d-42a2-ba39-ac8984d4d7ad", "reasoning": "The method `organisationSerializationModule` starts building a list of domain classes to register with Jackson. The list already includes `Address.class` and `OrganisationCredentialSubject.class,` and the next class needed for organisation credential serialization is the registration number type. Therefore the next line adds `OrganisationLegalRegistrationNumber.class,` to the list.", "reasoning_model_answer": "OrganisationLegalRegistrationNumber.class,", "assistant_with_reasoning": "\nThe method `organisationSerializationModule` starts building a list of domain classes to register with Jackson. The list already includes `Address.class` and `OrganisationCredentialSubject.class,` and the next class needed for organisation credential serialization is the registration number type. Therefore the next line adds `OrganisationLegalRegistrationNumber.class,` to the list.\n\nOrganisationLegalRegistrationNumber.class,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.796, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 38684, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "OrganisationLegalRegistrationNumber.class,", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import numpy as np\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport os; os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\nfrom PIL import Image\nfrom mask_generator import SamMaskGenerator\nfrom utils.utils import show_masks\nfrom build_sam import sam_model_registry\nfrom PIL import Image\nfrom build_sam import sam_model_registry\nfrom predictor import SamPredictor\nfrom utils.utils import show_mask, show_box, show_points\nfrom PIL import Image\nfrom mask_generator import SamMaskGenerator\nfrom utils.utils import show_mask, show_masks, show_points\nfrom build_sam import sam_model_registry\nfrom PIL import Image\nfrom mask_generator import SamMaskGenerator\nfrom utils.utils import show_mask, show_masks, show_points\nfrom build_sam import sam_model_registry\nfrom PIL import Image\nfrom mask_generator import SamMaskGenerator\nfrom utils.utils import show_mask, show_masks, show_points\nfrom build_sam import sam_model_registry\nfrom PIL import Image\nfrom mask_generator import SamMaskGenerator\nfrom utils.utils import show_mask, show_points, show_lbk_masks\nfrom build_sam import sam_model_registry\nfrom utils.amg import build_all_layer_point_grids", "context": "example.py\n# %%\n\"\"\" Example 1: All mask generation \"\"\"\n# basic module\n\n\n\n\nsam = sam_model_registry['vit_b'](checkpoint='ckpt/sam_vit_b_01ec64.pth').cuda()\nauto_to_mask = SamMaskGenerator(sam, stability_score_thresh=0.8)\n\n# image upload\nimg = np.array(Image.open(\"figure/paris2.jpg\"))\nmasks = auto_to_mask.generate(img)\n\n# visualization\nplt.figure(figsize=(20,20))\nplt.imshow(img)\nimg = show_masks(masks, plt)\nplt.axis('off')\nplt.show()\n\"\"\" End \"\"\"\n# %%\n\"\"\" Example 2: Prompts -> one mask generation for one image \"\"\"\nsam = sam_model_registry['vit_b'](checkpoint='ckpt/sam_vit_b_01ec64.pth').cuda()\nprompt_to_mask = SamPredictor(sam)\n\n\n# image upload\nimg = np.array(Image.open(\"figure/paris2.jpg\"))\nprompt_to_mask.set_image(img)\n\n\n# prompt\n# input_point = np.array([[500, 375], [370, 1200]])\n# input_label = np.array([1, 1])\n# input_point = np.array([[370, 1200]])\n# input_label = np.array([1])\n\ninput_box = np.array([200, 600, 500, 1400])\n\n# visualization\nplt.figure(figsize=(10,10))\nplt.imshow(img)\nshow_box(input_box, plt.gca(), plt)\n# show_points(input_point, input_label, plt.gca())\nplt.axis('on')\nplt.show()\n\n# sam prediction\nmasks, scores, logits = prompt_to_mask.predict(\n box = input_box,\n multimask_output=True,\n)\n\n\n# image proposal\nfor i, (mask, score) in enumerate(zip(masks, scores)):\n plt.figure(figsize=(10,10))\n plt.imshow(img)\n show_mask(mask, plt.gca())\n show_box(input_box, plt.gca(), plt)\n # show_points(input_point, input_label, plt.gca())\n plt.title(f\"Mask {i+1}, Score: {score:.3f}\", fontsize=18)\n plt.axis('off')\n plt.show()\n\"\"\" End \"\"\"\n\n# %%\n\"\"\" Example 3: Individual prompt -> Multi-mask generation for one image \"\"\"\n\n\n\n\n\nbuild_sam.py\ndef build_sam_vit_h(checkpoint=None, custom_img_size=1024):\ndef build_sam_vit_l(checkpoint=None, custom_img_size=1024):\ndef build_sam_vit_b(checkpoint=None, custom_img_size=1024):\ndef _build_sam(\n encoder_embed_dim,\n encoder_depth,\n encoder_num_heads,\n encoder_global_attn_indexes,\n checkpoint=None,\n custom_img_size=1024, # by LBK EDIT\n):\ndef build_sam_vit_t(checkpoint=None, custom_img_size=1024):\n\nutils/utils.py\ndef show_mask(mask, ax, random_color=True):\n if random_color:\n color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n else:\n color = np.array([30/255, 144/255, 255/255, 0.6])\n h, w = mask.shape[-2:]\n mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n ax.imshow(mask_image)\n\nutils/utils.py\ndef show_points(coords, labels, ax, marker_size=50):\n pos_points = coords[labels==1]\n neg_points = coords[labels==0]\n ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='o', s=marker_size, edgecolor='white', linewidth=1.25)\n ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='o', s=marker_size, edgecolor='white', linewidth=1.25) \n\nutils/utils.py\ndef show_masks(masks, plt, alpha=0.7):\n if len(masks) == 0: return\n sorted_masks = sorted(masks, key=(lambda x: x['area']), reverse=True)\n ax = plt.gca()\n ax.set_autoscale_on(False)\n\n img = np.ones((masks[0]['segmentation'].shape[0], masks[0]['segmentation'].shape[1], 4))\n img[:,:,3] = 0\n for ann in sorted_masks:\n m = ann['segmentation']\n color_mask = np.concatenate([np.random.random(3), [alpha]])\n img[m] = color_mask\n ax.imshow(img)\n return img\n\nbuild_sam.py\ndef build_sam_vit_h(checkpoint=None, custom_img_size=1024):\ndef build_sam_vit_l(checkpoint=None, custom_img_size=1024):\ndef build_sam_vit_b(checkpoint=None, custom_img_size=1024):\ndef _build_sam(\n encoder_embed_dim,\n encoder_depth,\n encoder_num_heads,\n encoder_global_attn_indexes,\n checkpoint=None,\n custom_img_size=1024, # by LBK EDIT\n):\ndef build_sam_vit_t(checkpoint=None, custom_img_size=1024):\n\nmask_generator.py\nclass SamMaskGenerator:\n def __init__(\n self,\n model: Sam,\n points_per_side: Optional[int] = 32,\n points_per_batch: int = 64,\n pred_iou_thresh: float = 0.88,\n stability_score_thresh: float = 0.95,\n stability_score_offset: float = 1.0,\n box_nms_thresh: float = 0.7,\n crop_n_layers: int = 0,\n crop_nms_thresh: float = 0.7,\n crop_overlap_ratio: float = 512 / 1500,\n crop_n_points_downscale_factor: int = 1,\n point_grids: Optional[List[np.ndarray]] = None,\n min_mask_region_area: int = 0,\n output_mode: str = \"binary_mask\",\n ) -> None:\n \"\"\"\n Using a SAM model, generates masks for the entire image.\n Generates a grid of point prompts over the image, then filters\n low quality and duplicate masks. The default settings are chosen\n for SAM with a ViT-H backbone.\n\n Arguments:\n model (Sam): The SAM model to use for mask prediction.\n points_per_side (int or None): The number of points to be sampled\n along one side of the image. The total number of points is\n points_per_side**2. If None, 'point_grids' must provide explicit\n point sampling.\n points_per_batch (int): Sets the number of points run simultaneously\n by the model. Higher numbers may be faster but use more GPU memory.\n pred_iou_thresh (float): A filtering threshold in [0,1], using the\n model's predicted mask quality.\n stability_score_thresh (float): A filtering threshold in [0,1], using\n the stability of the mask under changes to the cutoff used to binarize\n the model's mask predictions.\n stability_score_offset (float): The amount to shift the cutoff when\n calculated the stability score.\n box_nms_thresh (float): The box IoU cutoff used by non-maximal\n suppression to filter duplicate masks.\n crop_n_layers (int): If >0, mask prediction will be run again on\n crops of the image. Sets the number of layers to run, where each\n layer has 2**i_layer number of image crops.\n crop_nms_thresh (float): The box IoU cutoff used by non-maximal\n suppression to filter duplicate masks between different crops.\n crop_overlap_ratio (float): Sets the degree to which crops overlap.\n In the first crop layer, crops will overlap by this fraction of\n the image length. Later layers with more crops scale down this overlap.\n crop_n_points_downscale_factor (int): The number of points-per-side\n sampled in layer n is scaled down by crop_n_points_downscale_factor**n.\n point_grids (list(np.ndarray) or None): A list over explicit grids\n of points used for sampling, normalized to [0,1]. The nth grid in the\n list is used in the nth crop layer. Exclusive with points_per_side.\n min_mask_region_area (int): If >0, postprocessing will be applied\n to remove disconnected regions and holes in masks with area smaller\n than min_mask_region_area. Requires opencv.\n output_mode (str): The form masks are returned in. Can be 'binary_mask',\n 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.\n For large resolutions, 'binary_mask' may consume large amounts of\n memory.\n \"\"\"\n\n assert (points_per_side is None) != (\n point_grids is None\n ), \"Exactly one of points_per_side or point_grid must be provided.\"\n if points_per_side is not None:\n self.point_grids = build_all_layer_point_grids(\n points_per_side,\n crop_n_layers,\n crop_n_points_downscale_factor,\n )\n elif point_grids is not None:\n self.point_grids = point_grids\n else:\n raise ValueError(\"Can't have both points_per_side and point_grid be None.\")\n\n assert output_mode in [\n \"binary_mask\",\n \"uncompressed_rle\",\n \"coco_rle\",\n ], f\"Unknown output_mode {output_mode}.\"\n if output_mode == \"coco_rle\":\n from pycocotools import mask as mask_utils # type: ignore # noqa: F401\n\n if min_mask_region_area > 0:\n import cv2 # type: ignore # noqa: F401\n\n self.predictor = SamPredictor(model)\n self.points_per_batch = points_per_batch\n self.pred_iou_thresh = pred_iou_thresh\n self.stability_score_thresh = stability_score_thresh\n self.stability_score_offset = stability_score_offset\n self.box_nms_thresh = box_nms_thresh\n self.crop_n_layers = crop_n_layers\n self.crop_nms_thresh = crop_nms_thresh\n self.crop_overlap_ratio = crop_overlap_ratio\n self.crop_n_points_downscale_factor = crop_n_points_downscale_factor\n self.min_mask_region_area = min_mask_region_area\n self.output_mode = output_mode\n\n @torch.no_grad()\n def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:\n \"\"\"\n Generates masks for the given image.\n\n Arguments:\n image (np.ndarray): The image to generate masks for, in HWC uint8 format.\n\n Returns:\n list(dict(str, any)): A list over records for masks. Each record is\n a dict containing the following keys:\n segmentation (dict(str, any) or np.ndarray): The mask. If\n output_mode='binary_mask', is an array of shape HW. Otherwise,\n is a dictionary containing the RLE.\n bbox (list(float)): The box around the mask, in XYWH format.\n area (int): The area in pixels of the mask.\n predicted_iou (float): The model's own prediction of the mask's\n quality. This is filtered by the pred_iou_thresh parameter.\n point_coords (list(list(float))): The point coordinates input\n to the model to generate this mask.\n stability_score (float): A measure of the mask's quality. This\n is filtered on using the stability_score_thresh parameter.\n crop_box (list(float)): The crop of the image used to generate\n the mask, given in XYWH format.\n \"\"\"\n\n # Generate masks\n mask_data = self._generate_masks(image)\n\n # Filter small disconnected regions and holes in masks\n if self.min_mask_region_area > 0:\n mask_data = self.postprocess_small_regions(\n mask_data,\n self.min_mask_region_area,\n max(self.box_nms_thresh, self.crop_nms_thresh),\n )\n\n # Encode masks\n if self.output_mode == \"coco_rle\":\n mask_data[\"segmentations\"] = [coco_encode_rle(rle) for rle in mask_data[\"rles\"]]\n elif self.output_mode == \"binary_mask\":\n mask_data[\"segmentations\"] = [rle_to_mask(rle) for rle in mask_data[\"rles\"]]\n else:\n mask_data[\"segmentations\"] = mask_data[\"rles\"]\n\n # Write mask records\n curr_anns = []\n for idx in range(len(mask_data[\"segmentations\"])):\n ann = {\n \"segmentation\": mask_data[\"segmentations\"][idx],\n \"area\": area_from_rle(mask_data[\"rles\"][idx]),\n \"bbox\": box_xyxy_to_xywh(mask_data[\"boxes\"][idx]).tolist(),\n \"predicted_iou\": mask_data[\"iou_preds\"][idx].item(),\n \"point_coords\": [mask_data[\"points\"][idx].tolist()],\n \"stability_score\": mask_data[\"stability_score\"][idx].item(),\n \"crop_box\": box_xyxy_to_xywh(mask_data[\"crop_boxes\"][idx]).tolist(),\n }\n curr_anns.append(ann)\n\n return curr_anns\n\n\n def _generate_masks(self, image: np.ndarray) -> MaskData:\n orig_size = image.shape[:2]\n crop_boxes, layer_idxs = generate_crop_boxes(\n orig_size, self.crop_n_layers, self.crop_overlap_ratio\n )\n\n # Iterate over image crops\n data = MaskData()\n for crop_box, layer_idx in zip(crop_boxes, layer_idxs):\n crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)\n data.cat(crop_data)\n\n # Remove duplicate masks between crops\n if len(crop_boxes) > 1:\n # Prefer masks from smaller crops\n scores = 1 / box_area(data[\"crop_boxes\"])\n scores = scores.to(data[\"boxes\"].device)\n keep_by_nms = batched_nms(\n data[\"boxes\"].float(),\n scores,\n torch.zeros_like(data[\"boxes\"][:, 0]), # categories\n iou_threshold=self.crop_nms_thresh,\n )\n data.filter(keep_by_nms)\n\n data.to_numpy()\n return data\n \n def _process_crop(\n self,\n image: np.ndarray,\n crop_box: List[int],\n crop_layer_idx: int,\n orig_size: Tuple[int, ...],\n ) -> MaskData:\n # Crop the image and calculate embeddings\n x0, y0, x1, y1 = crop_box\n cropped_im = image[y0:y1, x0:x1, :]\n cropped_im_size = cropped_im.shape[:2]\n self.predictor.set_image(cropped_im)\n\n # Get points for this crop\n points_scale = np.array(cropped_im_size)[None, ::-1]\n points_for_image = self.point_grids[crop_layer_idx] * points_scale\n\n # Generate masks for this crop in batches\n data = MaskData()\n for (points,) in batch_iterator(self.points_per_batch, points_for_image):\n batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size)\n data.cat(batch_data)\n del batch_data\n self.predictor.reset_image()\n\n # Remove duplicates within this crop.\n keep_by_nms = batched_nms(\n data[\"boxes\"].float(),\n data[\"iou_preds\"],\n torch.zeros_like(data[\"boxes\"][:, 0]), # categories\n iou_threshold=self.box_nms_thresh,\n )\n data.filter(keep_by_nms)\n\n # Return to the original image frame\n data[\"boxes\"] = uncrop_boxes_xyxy(data[\"boxes\"], crop_box)\n data[\"points\"] = uncrop_points(data[\"points\"], crop_box)\n data[\"crop_boxes\"] = torch.tensor([crop_box for _ in range(len(data[\"rles\"]))])\n\n return data\n\n def _process_batch(\n self,\n points: np.ndarray,\n im_size: Tuple[int, ...],\n crop_box: List[int],\n orig_size: Tuple[int, ...],\n ) -> MaskData:\n orig_h, orig_w = orig_size\n\n # Run model on this batch\n transformed_points = self.predictor.transform.apply_coords(points, im_size)\n in_points = torch.as_tensor(transformed_points, device=self.predictor.device)\n in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device)\n masks, iou_preds, _ = self.predictor.predict_torch(\n in_points[:, None, :],\n in_labels[:, None],\n multimask_output=True,\n return_logits=True,\n )\n\n # Serialize predictions and store in MaskData\n data = MaskData(\n masks=masks.flatten(0, 1),\n iou_preds=iou_preds.flatten(0, 1),\n points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),\n )\n del masks\n\n # Filter by predicted IoU\n if self.pred_iou_thresh > 0.0:\n keep_mask = data[\"iou_preds\"] > self.pred_iou_thresh\n data.filter(keep_mask)\n\n # Calculate stability score\n data[\"stability_score\"] = calculate_stability_score(\n data[\"masks\"], self.predictor.model.mask_threshold, self.stability_score_offset\n )\n if self.stability_score_thresh > 0.0:\n keep_mask = data[\"stability_score\"] >= self.stability_score_thresh\n data.filter(keep_mask)\n\n # Threshold masks and calculate boxes\n data[\"masks\"] = data[\"masks\"] > self.predictor.model.mask_threshold\n data[\"boxes\"] = batched_mask_to_box(data[\"masks\"])\n\n # Filter boxes that touch crop boundaries\n keep_mask = ~is_box_near_crop_edge(data[\"boxes\"], crop_box, [0, 0, orig_w, orig_h])\n if not torch.all(keep_mask):\n data.filter(keep_mask)\n\n # Compress to RLE\n data[\"masks\"] = uncrop_masks(data[\"masks\"], crop_box, orig_h, orig_w)\n data[\"rles\"] = mask_to_rle_pytorch(data[\"masks\"])\n del data[\"masks\"]\n\n return data\n\n @staticmethod\n def postprocess_small_regions(\n mask_data: MaskData, min_area: int, nms_thresh: float\n ) -> MaskData:\n \"\"\"\n Removes small disconnected regions and holes in masks, then reruns\n box NMS to remove any new duplicates.\n\n Edits mask_data in place.\n\n Requires open-cv as a dependency.\n \"\"\"\n if len(mask_data[\"rles\"]) == 0:\n return mask_data\n\n # Filter small disconnected regions and holes\n new_masks = []\n scores = []\n for rle in mask_data[\"rles\"]:\n mask = rle_to_mask(rle)\n\n mask, changed = remove_small_regions(mask, min_area, mode=\"holes\")\n unchanged = not changed\n mask, changed = remove_small_regions(mask, min_area, mode=\"islands\")\n unchanged = unchanged and not changed\n\n new_masks.append(torch.as_tensor(mask).unsqueeze(0))\n # Give score=0 to changed masks and score=1 to unchanged masks\n # so NMS will prefer ones that didn't need postprocessing\n scores.append(float(unchanged))\n\n # Recalculate boxes and remove any new duplicates\n masks = torch.cat(new_masks, dim=0)\n boxes = batched_mask_to_box(masks)\n keep_by_nms = batched_nms(\n boxes.float(),\n torch.as_tensor(scores),\n torch.zeros_like(boxes[:, 0]), # categories\n iou_threshold=nms_thresh,\n )\n\n # Only recalculate RLEs for masks that have changed\n for i_mask in keep_by_nms:\n if scores[i_mask] == 0.0:\n mask_torch = masks[i_mask].unsqueeze(0)\n mask_data[\"rles\"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]\n mask_data[\"boxes\"][i_mask] = boxes[i_mask] # update res directly\n mask_data.filter(keep_by_nms)\n\n return mask_data\n\n # Individual Prompting by LBK\n @torch.no_grad()\n def individual_generate(\n self, \n image: np.ndarray, \n points_for_image: np.array,\n ) -> List[Dict[str, Any]]:\n\n def _individual_process_crop(\n image: np.ndarray,\n img_box: List[int],\n orig_size: Tuple[int, ...],\n ) -> MaskData:\n # Crop the image and calculate embeddings\n im_size = image.shape[:2]\n self.predictor.set_image(image)\n\n # Generate masks for this crop in batches\n data = MaskData()\n for (points,) in batch_iterator(self.points_per_batch, points_for_image):\n batch_data = self._process_batch(points, im_size, img_box, orig_size)\n data.cat(batch_data)\n del batch_data\n self.predictor.reset_image()\n\n # Remove duplicates within this crop.\n keep_by_nms = batched_nms(\n data[\"boxes\"].float(),\n data[\"iou_preds\"],\n torch.zeros_like(data[\"boxes\"][:, 0]), # categories\n iou_threshold=self.box_nms_thresh,\n )\n data.filter(keep_by_nms)\n\n # Return to the original image frame\n data[\"boxes\"] = uncrop_boxes_xyxy(data[\"boxes\"], img_box)\n data[\"points\"] = uncrop_points(data[\"points\"], img_box)\n data[\"crop_boxes\"] = torch.tensor([img_box for _ in range(len(data[\"rles\"]))])\n\n return data\n\n def _individual_generate_masks(image: np.ndarray)-> MaskData:\n im_h, im_w = image.shape[:2]\n\n # Iterate over image crops\n data = MaskData()\n data.cat(_individual_process_crop(image, [0, 0, im_w, im_h], (im_h, im_w)))\n data.to_numpy()\n return data\n\n # Generate masks\n mask_data = _individual_generate_masks(image)\n\n # Filter small disconnected regions and holes in masks\n if self.min_mask_region_area > 0:\n mask_data = self.postprocess_small_regions(\n mask_data,\n self.min_mask_region_area,\n max(self.box_nms_thresh, self.crop_nms_thresh),\n )\n\n # Encode masks\n if self.output_mode == \"coco_rle\":\n mask_data[\"segmentations\"] = [coco_encode_rle(rle) for rle in mask_data[\"rles\"]]\n elif self.output_mode == \"binary_mask\":\n mask_data[\"segmentations\"] = [rle_to_mask(rle) for rle in mask_data[\"rles\"]]\n else:\n mask_data[\"segmentations\"] = mask_data[\"rles\"]\n\n # Write mask records\n curr_anns = []\n for idx in range(len(mask_data[\"segmentations\"])):\n ann = {\n \"segmentation\": mask_data[\"segmentations\"][idx],\n \"area\": area_from_rle(mask_data[\"rles\"][idx]),\n \"bbox\": box_xyxy_to_xywh(mask_data[\"boxes\"][idx]).tolist(),\n \"predicted_iou\": mask_data[\"iou_preds\"][idx].item(),\n \"point_coords\": [mask_data[\"points\"][idx].tolist()],\n \"stability_score\": mask_data[\"stability_score\"][idx].item(),\n \"crop_box\": box_xyxy_to_xywh(mask_data[\"crop_boxes\"][idx]).tolist(),\n }\n curr_anns.append(ann)\n\n return curr_anns\n\nutils/utils.py\ndef show_lbk_masks(masks, plt, alpha=0.7):\n if len(masks) == 0: return\n ax = plt.gca()\n ax.set_autoscale_on(False)\n\n img = np.ones((masks.shape[1], masks.shape[2], 4))\n img[:,:,3] = 0\n for ann in masks:\n color_mask = np.concatenate([np.random.random(3), [alpha]])\n img[ann] = color_mask\n ax.imshow(img)\n return img\n\nutils/utils.py\ndef show_points(coords, labels, ax, marker_size=50):\n pos_points = coords[labels==1]\n neg_points = coords[labels==0]\n ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='o', s=marker_size, edgecolor='white', linewidth=1.25)\n ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='o', s=marker_size, edgecolor='white', linewidth=1.25) \n\nmask_generator.py\nclass SamMaskGenerator:\n def __init__(\n self,\n model: Sam,\n points_per_side: Optional[int] = 32,\n points_per_batch: int = 64,\n pred_iou_thresh: float = 0.88,\n stability_score_thresh: float = 0.95,\n stability_score_offset: float = 1.0,\n box_nms_thresh: float = 0.7,\n crop_n_layers: int = 0,\n crop_nms_thresh: float = 0.7,\n crop_overlap_ratio: float = 512 / 1500,\n crop_n_points_downscale_factor: int = 1,\n point_grids: Optional[List[np.ndarray]] = None,\n min_mask_region_area: int = 0,\n output_mode: str = \"binary_mask\",\n ) -> None:\n \"\"\"\n Using a SAM model, generates masks for the entire image.\n Generates a grid of point prompts over the image, then filters\n low quality and duplicate masks. The default settings are chosen\n for SAM with a ViT-H backbone.\n\n Arguments:\n model (Sam): The SAM model to use for mask prediction.\n points_per_side (int or None): The number of points to be sampled\n along one side of the image. The total number of points is\n points_per_side**2. If None, 'point_grids' must provide explicit\n point sampling.\n points_per_batch (int): Sets the number of points run simultaneously\n by the model. Higher numbers may be faster but use more GPU memory.\n pred_iou_thresh (float): A filtering threshold in [0,1], using the\n model's predicted mask quality.\n stability_score_thresh (float): A filtering threshold in [0,1], using\n the stability of the mask under changes to the cutoff used to binarize\n the model's mask predictions.\n stability_score_offset (float): The amount to shift the cutoff when\n calculated the stability score.\n box_nms_thresh (float): The box IoU cutoff used by non-maximal\n suppression to filter duplicate masks.\n crop_n_layers (int): If >0, mask prediction will be run again on\n crops of the image. Sets the number of layers to run, where each\n layer has 2**i_layer number of image crops.\n crop_nms_thresh (float): The box IoU cutoff used by non-maximal\n suppression to filter duplicate masks between different crops.\n crop_overlap_ratio (float): Sets the degree to which crops overlap.\n In the first crop layer, crops will overlap by this fraction of\n the image length. Later layers with more crops scale down this overlap.\n crop_n_points_downscale_factor (int): The number of points-per-side\n sampled in layer n is scaled down by crop_n_points_downscale_factor**n.\n point_grids (list(np.ndarray) or None): A list over explicit grids\n of points used for sampling, normalized to [0,1]. The nth grid in the\n list is used in the nth crop layer. Exclusive with points_per_side.\n min_mask_region_area (int): If >0, postprocessing will be applied\n to remove disconnected regions and holes in masks with area smaller\n than min_mask_region_area. Requires opencv.\n output_mode (str): The form masks are returned in. Can be 'binary_mask',\n 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.\n For large resolutions, 'binary_mask' may consume large amounts of\n memory.\n \"\"\"\n\n assert (points_per_side is None) != (\n point_grids is None\n ), \"Exactly one of points_per_side or point_grid must be provided.\"\n if points_per_side is not None:\n self.point_grids = build_all_layer_point_grids(\n points_per_side,\n crop_n_layers,\n crop_n_points_downscale_factor,\n )\n elif point_grids is not None:\n self.point_grids = point_grids\n else:\n raise ValueError(\"Can't have both points_per_side and point_grid be None.\")\n\n assert output_mode in [\n \"binary_mask\",\n \"uncompressed_rle\",\n \"coco_rle\",\n ], f\"Unknown output_mode {output_mode}.\"\n if output_mode == \"coco_rle\":\n from pycocotools import mask as mask_utils # type: ignore # noqa: F401\n\n if min_mask_region_area > 0:\n import cv2 # type: ignore # noqa: F401\n\n self.predictor = SamPredictor(model)\n self.points_per_batch = points_per_batch\n self.pred_iou_thresh = pred_iou_thresh\n self.stability_score_thresh = stability_score_thresh\n self.stability_score_offset = stability_score_offset\n self.box_nms_thresh = box_nms_thresh\n self.crop_n_layers = crop_n_layers\n self.crop_nms_thresh = crop_nms_thresh\n self.crop_overlap_ratio = crop_overlap_ratio\n self.crop_n_points_downscale_factor = crop_n_points_downscale_factor\n self.min_mask_region_area = min_mask_region_area\n self.output_mode = output_mode\n\n @torch.no_grad()\n def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:\n \"\"\"\n Generates masks for the given image.\n\n Arguments:\n image (np.ndarray): The image to generate masks for, in HWC uint8 format.\n\n Returns:\n list(dict(str, any)): A list over records for masks. Each record is\n a dict containing the following keys:\n segmentation (dict(str, any) or np.ndarray): The mask. If\n output_mode='binary_mask', is an array of shape HW. Otherwise,\n is a dictionary containing the RLE.\n bbox (list(float)): The box around the mask, in XYWH format.\n area (int): The area in pixels of the mask.\n predicted_iou (float): The model's own prediction of the mask's\n quality. This is filtered by the pred_iou_thresh parameter.\n point_coords (list(list(float))): The point coordinates input\n to the model to generate this mask.\n stability_score (float): A measure of the mask's quality. This\n is filtered on using the stability_score_thresh parameter.\n crop_box (list(float)): The crop of the image used to generate\n the mask, given in XYWH format.\n \"\"\"\n\n # Generate masks\n mask_data = self._generate_masks(image)\n\n # Filter small disconnected regions and holes in masks\n if self.min_mask_region_area > 0:\n mask_data = self.postprocess_small_regions(\n mask_data,\n self.min_mask_region_area,\n max(self.box_nms_thresh, self.crop_nms_thresh),\n )\n\n # Encode masks\n if self.output_mode == \"coco_rle\":\n mask_data[\"segmentations\"] = [coco_encode_rle(rle) for rle in mask_data[\"rles\"]]\n elif self.output_mode == \"binary_mask\":\n mask_data[\"segmentations\"] = [rle_to_mask(rle) for rle in mask_data[\"rles\"]]\n else:\n mask_data[\"segmentations\"] = mask_data[\"rles\"]\n\n # Write mask records\n curr_anns = []\n for idx in range(len(mask_data[\"segmentations\"])):\n ann = {\n \"segmentation\": mask_data[\"segmentations\"][idx],\n \"area\": area_from_rle(mask_data[\"rles\"][idx]),\n \"bbox\": box_xyxy_to_xywh(mask_data[\"boxes\"][idx]).tolist(),\n \"predicted_iou\": mask_data[\"iou_preds\"][idx].item(),\n \"point_coords\": [mask_data[\"points\"][idx].tolist()],\n \"stability_score\": mask_data[\"stability_score\"][idx].item(),\n \"crop_box\": box_xyxy_to_xywh(mask_data[\"crop_boxes\"][idx]).tolist(),\n }\n curr_anns.append(ann)\n\n return curr_anns\n\n\n def _generate_masks(self, image: np.ndarray) -> MaskData:\n orig_size = image.shape[:2]\n crop_boxes, layer_idxs = generate_crop_boxes(\n orig_size, self.crop_n_layers, self.crop_overlap_ratio\n )\n\n # Iterate over image crops\n data = MaskData()\n for crop_box, layer_idx in zip(crop_boxes, layer_idxs):\n crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)\n data.cat(crop_data)\n\n # Remove duplicate masks between crops\n if len(crop_boxes) > 1:\n # Prefer masks from smaller crops\n scores = 1 / box_area(data[\"crop_boxes\"])\n scores = scores.to(data[\"boxes\"].device)\n keep_by_nms = batched_nms(\n data[\"boxes\"].float(),\n scores,\n torch.zeros_like(data[\"boxes\"][:, 0]), # categories\n iou_threshold=self.crop_nms_thresh,\n )\n data.filter(keep_by_nms)\n\n data.to_numpy()\n return data\n \n def _process_crop(\n self,\n image: np.ndarray,\n crop_box: List[int],\n crop_layer_idx: int,\n orig_size: Tuple[int, ...],\n ) -> MaskData:\n # Crop the image and calculate embeddings\n x0, y0, x1, y1 = crop_box\n cropped_im = image[y0:y1, x0:x1, :]\n cropped_im_size = cropped_im.shape[:2]\n self.predictor.set_image(cropped_im)\n\n # Get points for this crop\n points_scale = np.array(cropped_im_size)[None, ::-1]\n points_for_image = self.point_grids[crop_layer_idx] * points_scale\n\n # Generate masks for this crop in batches\n data = MaskData()\n for (points,) in batch_iterator(self.points_per_batch, points_for_image):\n batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size)\n data.cat(batch_data)\n del batch_data\n self.predictor.reset_image()\n\n # Remove duplicates within this crop.\n keep_by_nms = batched_nms(\n data[\"boxes\"].float(),\n data[\"iou_preds\"],\n torch.zeros_like(data[\"boxes\"][:, 0]), # categories\n iou_threshold=self.box_nms_thresh,\n )\n data.filter(keep_by_nms)\n\n # Return to the original image frame\n data[\"boxes\"] = uncrop_boxes_xyxy(data[\"boxes\"], crop_box)\n data[\"points\"] = uncrop_points(data[\"points\"], crop_box)\n data[\"crop_boxes\"] = torch.tensor([crop_box for _ in range(len(data[\"rles\"]))])\n\n return data\n\n def _process_batch(\n self,\n points: np.ndarray,\n im_size: Tuple[int, ...],\n crop_box: List[int],\n orig_size: Tuple[int, ...],\n ) -> MaskData:\n orig_h, orig_w = orig_size\n\n # Run model on this batch\n transformed_points = self.predictor.transform.apply_coords(points, im_size)\n in_points = torch.as_tensor(transformed_points, device=self.predictor.device)\n in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device)\n masks, iou_preds, _ = self.predictor.predict_torch(\n in_points[:, None, :],\n in_labels[:, None],\n multimask_output=True,\n return_logits=True,\n )\n\n # Serialize predictions and store in MaskData\n data = MaskData(\n masks=masks.flatten(0, 1),\n iou_preds=iou_preds.flatten(0, 1),\n points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),\n )\n del masks\n\n # Filter by predicted IoU\n if self.pred_iou_thresh > 0.0:\n keep_mask = data[\"iou_preds\"] > self.pred_iou_thresh\n data.filter(keep_mask)\n\n # Calculate stability score\n data[\"stability_score\"] = calculate_stability_score(\n data[\"masks\"], self.predictor.model.mask_threshold, self.stability_score_offset\n )\n if self.stability_score_thresh > 0.0:\n keep_mask = data[\"stability_score\"] >= self.stability_score_thresh\n data.filter(keep_mask)\n\n # Threshold masks and calculate boxes\n data[\"masks\"] = data[\"masks\"] > self.predictor.model.mask_threshold\n data[\"boxes\"] = batched_mask_to_box(data[\"masks\"])\n\n # Filter boxes that touch crop boundaries\n keep_mask = ~is_box_near_crop_edge(data[\"boxes\"], crop_box, [0, 0, orig_w, orig_h])\n if not torch.all(keep_mask):\n data.filter(keep_mask)\n\n # Compress to RLE\n data[\"masks\"] = uncrop_masks(data[\"masks\"], crop_box, orig_h, orig_w)\n data[\"rles\"] = mask_to_rle_pytorch(data[\"masks\"])\n del data[\"masks\"]\n\n return data\n\n @staticmethod\n def postprocess_small_regions(\n mask_data: MaskData, min_area: int, nms_thresh: float\n ) -> MaskData:\n \"\"\"\n Removes small disconnected regions and holes in masks, then reruns\n box NMS to remove any new duplicates.\n\n Edits mask_data in place.\n\n Requires open-cv as a dependency.\n \"\"\"\n if len(mask_data[\"rles\"]) == 0:\n return mask_data\n\n # Filter small disconnected regions and holes\n new_masks = []\n scores = []\n for rle in mask_data[\"rles\"]:\n mask = rle_to_mask(rle)\n\n mask, changed = remove_small_regions(mask, min_area, mode=\"holes\")\n unchanged = not changed\n mask, changed = remove_small_regions(mask, min_area, mode=\"islands\")\n unchanged = unchanged and not changed\n\n new_masks.append(torch.as_tensor(mask).unsqueeze(0))\n # Give score=0 to changed masks and score=1 to unchanged masks\n # so NMS will prefer ones that didn't need postprocessing\n scores.append(float(unchanged))\n\n # Recalculate boxes and remove any new duplicates\n masks = torch.cat(new_masks, dim=0)\n boxes = batched_mask_to_box(masks)\n keep_by_nms = batched_nms(\n boxes.float(),\n torch.as_tensor(scores),\n torch.zeros_like(boxes[:, 0]), # categories\n iou_threshold=nms_thresh,\n )\n\n # Only recalculate RLEs for masks that have changed\n for i_mask in keep_by_nms:\n if scores[i_mask] == 0.0:\n mask_torch = masks[i_mask].unsqueeze(0)\n mask_data[\"rles\"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]\n mask_data[\"boxes\"][i_mask] = boxes[i_mask] # update res directly\n mask_data.filter(keep_by_nms)\n\n return mask_data\n\n # Individual Prompting by LBK\n @torch.no_grad()\n def individual_generate(\n self, \n image: np.ndarray, \n points_for_image: np.array,\n ) -> List[Dict[str, Any]]:\n\n def _individual_process_crop(\n image: np.ndarray,\n img_box: List[int],\n orig_size: Tuple[int, ...],\n ) -> MaskData:\n # Crop the image and calculate embeddings\n im_size = image.shape[:2]\n self.predictor.set_image(image)\n\n # Generate masks for this crop in batches\n data = MaskData()\n for (points,) in batch_iterator(self.points_per_batch, points_for_image):\n batch_data = self._process_batch(points, im_size, img_box, orig_size)\n data.cat(batch_data)\n del batch_data\n self.predictor.reset_image()\n\n # Remove duplicates within this crop.\n keep_by_nms = batched_nms(\n data[\"boxes\"].float(),\n data[\"iou_preds\"],\n torch.zeros_like(data[\"boxes\"][:, 0]), # categories\n iou_threshold=self.box_nms_thresh,\n )\n data.filter(keep_by_nms)\n\n # Return to the original image frame\n data[\"boxes\"] = uncrop_boxes_xyxy(data[\"boxes\"], img_box)\n data[\"points\"] = uncrop_points(data[\"points\"], img_box)\n data[\"crop_boxes\"] = torch.tensor([img_box for _ in range(len(data[\"rles\"]))])\n\n return data\n\n def _individual_generate_masks(image: np.ndarray)-> MaskData:\n im_h, im_w = image.shape[:2]\n\n # Iterate over image crops\n data = MaskData()\n data.cat(_individual_process_crop(image, [0, 0, im_w, im_h], (im_h, im_w)))\n data.to_numpy()\n return data\n\n # Generate masks\n mask_data = _individual_generate_masks(image)\n\n # Filter small disconnected regions and holes in masks\n if self.min_mask_region_area > 0:\n mask_data = self.postprocess_small_regions(\n mask_data,\n self.min_mask_region_area,\n max(self.box_nms_thresh, self.crop_nms_thresh),\n )\n\n # Encode masks\n if self.output_mode == \"coco_rle\":\n mask_data[\"segmentations\"] = [coco_encode_rle(rle) for rle in mask_data[\"rles\"]]\n elif self.output_mode == \"binary_mask\":\n mask_data[\"segmentations\"] = [rle_to_mask(rle) for rle in mask_data[\"rles\"]]\n else:\n mask_data[\"segmentations\"] = mask_data[\"rles\"]\n\n # Write mask records\n curr_anns = []\n for idx in range(len(mask_data[\"segmentations\"])):\n ann = {\n \"segmentation\": mask_data[\"segmentations\"][idx],\n \"area\": area_from_rle(mask_data[\"rles\"][idx]),\n \"bbox\": box_xyxy_to_xywh(mask_data[\"boxes\"][idx]).tolist(),\n \"predicted_iou\": mask_data[\"iou_preds\"][idx].item(),\n \"point_coords\": [mask_data[\"points\"][idx].tolist()],\n \"stability_score\": mask_data[\"stability_score\"][idx].item(),\n \"crop_box\": box_xyxy_to_xywh(mask_data[\"crop_boxes\"][idx]).tolist(),\n }\n curr_anns.append(ann)\n\n return curr_anns", "answers": ["sam = sam_model_registry['vit_b'](checkpoint='ckpt/sam_vit_b_01ec64.pth').cuda()"], "length": 3615, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ad55ae29-9f4c-45af-9189-2dbf9f00e62a", "reasoning": "After the series of import statements, the next logical step is to instantiate the SAM model using the imported sam_model_registry, as done in the example scripts. This creates the model object needed for subsequent mask generation.", "reasoning_model_answer": "sam = sam_model_registry['vit_b'](checkpoint='ckpt/sam_vit_b_01ec64.pth').cuda()", "assistant_with_reasoning": "\nAfter the series of import statements, the next logical step is to instantiate the SAM model using the imported sam_model_registry, as done in the example scripts. This creates the model object needed for subsequent mask generation.\n\nsam = sam_model_registry['vit_b'](checkpoint='ckpt/sam_vit_b_01ec64.pth').cuda()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.484, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37493, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "sam = sam_model_registry['vit_b'](checkpoint='ckpt/sam_vit_b_01ec64.pth').cuda()", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "import cn.hutool.core.bean.BeanUtil;\nimport cn.hutool.core.collection.CollUtil;\nimport cn.hutool.core.date.DateTime;\nimport cn.hutool.core.date.DateUtil;\nimport cn.hutool.core.util.EnumUtil;\nimport cn.hutool.core.util.ObjUtil;\nimport cn.hutool.core.util.ObjectUtil;\nimport com.github.pagehelper.PageHelper;\nimport com.github.pagehelper.PageInfo;\nimport com.steve.train.business.domain.DailyTrain;\nimport com.steve.train.business.domain.DailyTrainTicket;\nimport com.steve.train.business.domain.DailyTrainTicketExample;\nimport com.steve.train.business.domain.TrainStation;\nimport com.steve.train.business.enums.TrainTypeEnum;\nimport com.steve.train.business.mapper.DailyTrainTicketMapper;\nimport com.steve.train.business.req.DailyTrainTicketQueryReq;\nimport com.steve.train.business.req.DailyTrainTicketSaveReq;\nimport com.steve.train.business.resp.DailyTrainTicketQueryResp;\nimport com.steve.train.common.enums.SeatTypeEnum;\nimport com.steve.train.common.resp.PageResp;\nimport com.steve.train.common.util.SnowFlakeUtil;\nimport jakarta.annotation.Resource;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.cache.annotation.CachePut;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.util.Date;\nimport java.util.List;", "context": "business/src/main/java/com/steve/train/business/service/DailyTrainTicketService.java\npackage com.steve.train.business.service;\n\n\n\n/*\n * @author : Steve Hu\n * @date : 2023-11-02 15:01:09\n * @description: 余票信息服务(FreeMarker生成)\n */\n@Service\npublic class DailyTrainTicketService {\n\n private static final Logger LOG = LoggerFactory.getLogger(DailyTrainTicketService.class);\n\n @Resource\n private DailyTrainTicketMapper dailyTrainTicketMapper;\n\n @Resource\n private TrainStationService trainStationService;\n\n @Resource\n private DailyTrainSeatService dailyTrainSeatService;\n\n public void save(DailyTrainTicketSaveReq req) {\n DateTime now = DateTime.now();\n DailyTrainTicket dailyTrainTicket = BeanUtil.copyProperties(req, DailyTrainTicket.class);\n if (ObjectUtil.isNull(dailyTrainTicket.getId())) {\n dailyTrainTicket.setId(SnowFlakeUtil.getSnowFlakeNextId());\n dailyTrainTicket.setCreateTime(now);\n dailyTrainTicket.setUpdateTime(now);\n dailyTrainTicketMapper.insert(dailyTrainTicket);\n } else {\n dailyTrainTicket.setUpdateTime(now);\n dailyTrainTicketMapper.updateByPrimaryKey(dailyTrainTicket);\n }\n }\n\n // @cacheable是Spring内置缓存,无过期时间。value值为缓存名\n // @cacheable开辟一块空间,根据不同的请求参数,空间内会缓存多个结果。会根据请求参数生成一个 key,需要对请求参数生成hashCode和equals方法,用于生成key\n // 可通过配置spring.cache.type=redis参数将缓存存放到redis上\n // @Cacheable(value = \"DailyTrainTicketService.queryList\")\n public PageResp queryList(DailyTrainTicketQueryReq req) {\n DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();\n dailyTrainTicketExample.setOrderByClause(\"id asc\");\n DailyTrainTicketExample.Criteria criteria = dailyTrainTicketExample.createCriteria();\n if (ObjUtil.isNotNull(req.getDate())) {\n criteria.andDateEqualTo(req.getDate());\n }\n if (ObjUtil.isNotEmpty(req.getTrainCode())) {\n criteria.andTrainCodeEqualTo(req.getTrainCode());\n }\n if (ObjUtil.isNotEmpty(req.getStart())) {\n criteria.andStartEqualTo(req.getStart());\n }\n if (ObjUtil.isNotEmpty(req.getEnd())) {\n criteria.andEndEqualTo(req.getEnd());\n }\n\n LOG.info(\"查询页码:{}\", req.getPage());\n LOG.info(\"每页条数:{}\", req.getSize());\n PageHelper.startPage(req.getPage(), req.getSize());\n List dailyTrainTicketList = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);\n\n PageInfo pageInfo = new PageInfo<>(dailyTrainTicketList);\n LOG.info(\"总行数:{}\", pageInfo.getTotal());\n LOG.info(\"总页数:{}\", pageInfo.getPages());\n\n List list = BeanUtil.copyToList(dailyTrainTicketList, DailyTrainTicketQueryResp.class);\n\n PageResp pageResp = new PageResp<>();\n pageResp.setTotal(pageInfo.getTotal());\n pageResp.setList(list);\n return pageResp;\n }\n\n // @cacheput用于强制刷新Spring内置缓存。这里的queryList和queryList_RW用于演示两个服务方法分别仅读取和读写强制刷新同一个缓存\n @CachePut(value = \"DailyTrainTicketService.queryList\")\n public PageResp queryList_RW(DailyTrainTicketQueryReq req) {\n return queryList(req);\n }\n\n public void delete(Long id) {\n dailyTrainTicketMapper.deleteByPrimaryKey(id);\n }\n\n // 开发规范-事务嵌套:A事务中包含B子事务,那么子事务没必要加@Transactional,只要确保A加了就能起到回滚作用。\n // 但是良好的开发规范是为每个子事务也都加上。\n @Transactional\n public void genDaily(DailyTrain dailyTrain, Date date, String trainCode) {\n LOG.info(\"生成日期【{}】车次【{}】的余票信息开始\", DateUtil.formatDate(date), trainCode);\n\n // 删除某日某车次的余票信息\n DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();\n dailyTrainTicketExample.createCriteria()\n .andDateEqualTo(date)\n .andTrainCodeEqualTo(trainCode);\n dailyTrainTicketMapper.deleteByExample(dailyTrainTicketExample);\n\n // 查出某车次的所有的车站信息\n\ncommon/src/main/java/com/steve/train/common/resp/PageResp.java\npublic class PageResp implements Serializable {\n\n // 总条数\n private Long total;\n\n // 当前页的列表\n private List list;\n\n public Long getTotal() {\n return total;\n }\n\n public void setTotal(Long total) {\n this.total = total;\n }\n\n public List getList() {\n return list;\n }\n\n public void setList(List list) {\n this.list = list;\n }\n\n @Override\n public String toString() {\n return \"PageResp{\" +\n \"total=\" + total +\n \", list=\" + list +\n '}';\n }\n}\n\ncommon/src/main/java/com/steve/train/common/enums/SeatTypeEnum.java\npublic enum SeatTypeEnum {\n\n YDZ(\"1\", \"一等座\", new BigDecimal(\"0.4\")),\n EDZ(\"2\", \"二等座\", new BigDecimal(\"0.3\")),\n RW(\"3\", \"软卧\", new BigDecimal(\"0.6\")),\n YW(\"4\", \"硬卧\", new BigDecimal(\"0.5\"));\n\n private String code;\n\n private String desc;\n\n /**\n * 基础票价 N元/公里,0.4即为0.4元/公里\n */\n private BigDecimal price;\n\n SeatTypeEnum(String code, String desc, BigDecimal price) {\n this.code = code;\n this.desc = desc;\n this.price = price;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public BigDecimal getPrice() {\n return price;\n }\n\n public void setPrice(BigDecimal price) {\n this.price = price;\n }\n\n public static List> getEnumList() {\n List> list = new ArrayList<>();\n for (SeatTypeEnum anEnum : EnumSet.allOf(SeatTypeEnum.class)) {\n HashMap map = new HashMap<>();\n map.put(\"code\",anEnum.code);\n map.put(\"desc\",anEnum.desc);\n list.add(map);\n }\n return list;\n }\n\n public static SeatTypeEnum getEnumByCode(String code) {\n for (SeatTypeEnum enums : SeatTypeEnum.values()) {\n if (enums.getCode().equalsIgnoreCase(code)) {\n return enums;\n }\n }\n return null;\n }\n}\n\ncommon/src/main/java/com/steve/train/common/util/SnowFlakeUtil.java\npublic class SnowFlakeUtil {\n private static long workerId = 1;\n private static long datercenterId = 1;\n\n public static long getSnowFlakeNextId() {\n return IdUtil.getSnowflake(workerId, datercenterId).nextId();\n }\n\n public static String getSnowFlakeNextIdStr() {\n return IdUtil.getSnowflake(workerId, datercenterId).nextIdStr();\n }\n}\n\nbusiness/src/main/java/com/steve/train/business/enums/TrainTypeEnum.java\npublic enum TrainTypeEnum {\n\n G(\"G\", \"高铁\", new BigDecimal(\"1.2\")),\n D(\"D\", \"动车\", new BigDecimal(\"1\")),\n K(\"K\", \"快速\", new BigDecimal(\"0.8\"));\n\n private String code;\n\n private String desc;\n\n /**\n * 票价比例,例:1.1,则票价 = 1.1 * 每公里单价(SeatTypeEnum.price) * 公里(station.km)\n */\n private BigDecimal priceRate;\n\n TrainTypeEnum(String code, String desc, BigDecimal priceRate) {\n this.code = code;\n this.desc = desc;\n this.priceRate = priceRate;\n }\n\n @Override\n public String toString() {\n return \"TrainTypeEnum{\" +\n \"code='\" + code + '\\'' +\n \", desc='\" + desc + '\\'' +\n \", priceRate=\" + priceRate +\n \"} \" + super.toString();\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public BigDecimal getPriceRate() {\n return priceRate;\n }\n\n public void setPriceRate(BigDecimal priceRate) {\n this.priceRate = priceRate;\n }\n\n public static List> getEnumList() {\n List> list = new ArrayList<>();\n for (TrainTypeEnum anEnum : EnumSet.allOf(TrainTypeEnum.class)) {\n HashMap map = new HashMap<>();\n map.put(\"code\",anEnum.code);\n map.put(\"desc\",anEnum.desc);\n list.add(map);\n }\n return list;\n }\n}\n\nbusiness/src/main/java/com/steve/train/business/domain/DailyTrainTicketExample.java\npublic class DailyTrainTicketExample {\n protected String orderByClause;\n\n protected boolean distinct;\n\n protected List oredCriteria;\n\n public DailyTrainTicketExample() {\n oredCriteria = new ArrayList<>();\n }\n\n public void setOrderByClause(String orderByClause) {\n this.orderByClause = orderByClause;\n }\n\n public String getOrderByClause() {\n return orderByClause;\n }\n\n public void setDistinct(boolean distinct) {\n this.distinct = distinct;\n }\n\n public boolean isDistinct() {\n return distinct;\n }\n\n public List getOredCriteria() {\n return oredCriteria;\n }\n\n public void or(Criteria criteria) {\n oredCriteria.add(criteria);\n }\n\n public Criteria or() {\n Criteria criteria = createCriteriaInternal();\n oredCriteria.add(criteria);\n return criteria;\n }\n\n public Criteria createCriteria() {\n Criteria criteria = createCriteriaInternal();\n if (oredCriteria.size() == 0) {\n oredCriteria.add(criteria);\n }\n return criteria;\n }\n\n protected Criteria createCriteriaInternal() {\n Criteria criteria = new Criteria();\n return criteria;\n }\n\n public void clear() {\n oredCriteria.clear();\n orderByClause = null;\n distinct = false;\n }\n\n protected abstract static class GeneratedCriteria {\n protected List criteria;\n\n protected GeneratedCriteria() {\n super();\n criteria = new ArrayList<>();\n }\n\n public boolean isValid() {\n return criteria.size() > 0;\n }\n\n public List getAllCriteria() {\n return criteria;\n }\n\n public List getCriteria() {\n return criteria;\n }\n\n protected void addCriterion(String condition) {\n if (condition == null) {\n throw new RuntimeException(\"Value for condition cannot be null\");\n }\n criteria.add(new Criterion(condition));\n }\n\n protected void addCriterion(String condition, Object value, String property) {\n if (value == null) {\n throw new RuntimeException(\"Value for \" + property + \" cannot be null\");\n }\n criteria.add(new Criterion(condition, value));\n }\n\n protected void addCriterion(String condition, Object value1, Object value2, String property) {\n if (value1 == null || value2 == null) {\n throw new RuntimeException(\"Between values for \" + property + \" cannot be null\");\n }\n criteria.add(new Criterion(condition, value1, value2));\n }\n\n protected void addCriterionForJDBCDate(String condition, Date value, String property) {\n if (value == null) {\n throw new RuntimeException(\"Value for \" + property + \" cannot be null\");\n }\n addCriterion(condition, new java.sql.Date(value.getTime()), property);\n }\n\n protected void addCriterionForJDBCDate(String condition, List values, String property) {\n if (values == null || values.size() == 0) {\n throw new RuntimeException(\"Value list for \" + property + \" cannot be null or empty\");\n }\n List dateList = new ArrayList<>();\n Iterator iter = values.iterator();\n while (iter.hasNext()) {\n dateList.add(new java.sql.Date(iter.next().getTime()));\n }\n addCriterion(condition, dateList, property);\n }\n\n protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {\n if (value1 == null || value2 == null) {\n throw new RuntimeException(\"Between values for \" + property + \" cannot be null\");\n }\n addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);\n }\n\n protected void addCriterionForJDBCTime(String condition, Date value, String property) {\n if (value == null) {\n throw new RuntimeException(\"Value for \" + property + \" cannot be null\");\n }\n addCriterion(condition, new java.sql.Time(value.getTime()), property);\n }\n\n protected void addCriterionForJDBCTime(String condition, List values, String property) {\n if (values == null || values.size() == 0) {\n throw new RuntimeException(\"Value list for \" + property + \" cannot be null or empty\");\n }\n List timeList = new ArrayList<>();\n Iterator iter = values.iterator();\n while (iter.hasNext()) {\n timeList.add(new java.sql.Time(iter.next().getTime()));\n }\n addCriterion(condition, timeList, property);\n }\n\n protected void addCriterionForJDBCTime(String condition, Date value1, Date value2, String property) {\n if (value1 == null || value2 == null) {\n throw new RuntimeException(\"Between values for \" + property + \" cannot be null\");\n }\n addCriterion(condition, new java.sql.Time(value1.getTime()), new java.sql.Time(value2.getTime()), property);\n }\n\n public Criteria andIdIsNull() {\n addCriterion(\"id is null\");\n return (Criteria) this;\n }\n\n public Criteria andIdIsNotNull() {\n addCriterion(\"id is not null\");\n return (Criteria) this;\n }\n\n public Criteria andIdEqualTo(Long value) {\n addCriterion(\"id =\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotEqualTo(Long value) {\n addCriterion(\"id <>\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdGreaterThan(Long value) {\n addCriterion(\"id >\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdGreaterThanOrEqualTo(Long value) {\n addCriterion(\"id >=\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdLessThan(Long value) {\n addCriterion(\"id <\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdLessThanOrEqualTo(Long value) {\n addCriterion(\"id <=\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdIn(List values) {\n addCriterion(\"id in\", values, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotIn(List values) {\n addCriterion(\"id not in\", values, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdBetween(Long value1, Long value2) {\n addCriterion(\"id between\", value1, value2, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotBetween(Long value1, Long value2) {\n addCriterion(\"id not between\", value1, value2, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andDateIsNull() {\n addCriterion(\"`date` is null\");\n return (Criteria) this;\n }\n\n public Criteria andDateIsNotNull() {\n addCriterion(\"`date` is not null\");\n return (Criteria) this;\n }\n\n public Criteria andDateEqualTo(Date value) {\n addCriterionForJDBCDate(\"`date` =\", value, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateNotEqualTo(Date value) {\n addCriterionForJDBCDate(\"`date` <>\", value, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateGreaterThan(Date value) {\n addCriterionForJDBCDate(\"`date` >\", value, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateGreaterThanOrEqualTo(Date value) {\n addCriterionForJDBCDate(\"`date` >=\", value, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateLessThan(Date value) {\n addCriterionForJDBCDate(\"`date` <\", value, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateLessThanOrEqualTo(Date value) {\n addCriterionForJDBCDate(\"`date` <=\", value, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateIn(List values) {\n addCriterionForJDBCDate(\"`date` in\", values, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateNotIn(List values) {\n addCriterionForJDBCDate(\"`date` not in\", values, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateBetween(Date value1, Date value2) {\n addCriterionForJDBCDate(\"`date` between\", value1, value2, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andDateNotBetween(Date value1, Date value2) {\n addCriterionForJDBCDate(\"`date` not between\", value1, value2, \"date\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeIsNull() {\n addCriterion(\"train_code is null\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeIsNotNull() {\n addCriterion(\"train_code is not null\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeEqualTo(String value) {\n addCriterion(\"train_code =\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeNotEqualTo(String value) {\n addCriterion(\"train_code <>\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeGreaterThan(String value) {\n addCriterion(\"train_code >\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeGreaterThanOrEqualTo(String value) {\n addCriterion(\"train_code >=\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeLessThan(String value) {\n addCriterion(\"train_code <\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeLessThanOrEqualTo(String value) {\n addCriterion(\"train_code <=\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeLike(String value) {\n addCriterion(\"train_code like\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeNotLike(String value) {\n addCriterion(\"train_code not like\", value, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeIn(List values) {\n addCriterion(\"train_code in\", values, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeNotIn(List values) {\n addCriterion(\"train_code not in\", values, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeBetween(String value1, String value2) {\n addCriterion(\"train_code between\", value1, value2, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andTrainCodeNotBetween(String value1, String value2) {\n addCriterion(\"train_code not between\", value1, value2, \"trainCode\");\n return (Criteria) this;\n }\n\n public Criteria andStartIsNull() {\n addCriterion(\"`start` is null\");\n return (Criteria) this;\n }\n\n public Criteria andStartIsNotNull() {\n addCriterion(\"`start` is not null\");\n return (Criteria) this;\n }\n\n public Criteria andStartEqualTo(String value) {\n addCriterion(\"`start` =\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartNotEqualTo(String value) {\n addCriterion(\"`start` <>\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartGreaterThan(String value) {\n addCriterion(\"`start` >\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartGreaterThanOrEqualTo(String value) {\n addCriterion(\"`start` >=\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartLessThan(String value) {\n addCriterion(\"`start` <\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartLessThanOrEqualTo(String value) {\n addCriterion(\"`start` <=\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartLike(String value) {\n addCriterion(\"`start` like\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartNotLike(String value) {\n addCriterion(\"`start` not like\", value, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartIn(List values) {\n addCriterion(\"`start` in\", values, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartNotIn(List values) {\n addCriterion(\"`start` not in\", values, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartBetween(String value1, String value2) {\n addCriterion(\"`start` between\", value1, value2, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartNotBetween(String value1, String value2) {\n addCriterion(\"`start` not between\", value1, value2, \"start\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinIsNull() {\n addCriterion(\"start_pinyin is null\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinIsNotNull() {\n addCriterion(\"start_pinyin is not null\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinEqualTo(String value) {\n addCriterion(\"start_pinyin =\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinNotEqualTo(String value) {\n addCriterion(\"start_pinyin <>\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinGreaterThan(String value) {\n addCriterion(\"start_pinyin >\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinGreaterThanOrEqualTo(String value) {\n addCriterion(\"start_pinyin >=\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinLessThan(String value) {\n addCriterion(\"start_pinyin <\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinLessThanOrEqualTo(String value) {\n addCriterion(\"start_pinyin <=\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinLike(String value) {\n addCriterion(\"start_pinyin like\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinNotLike(String value) {\n addCriterion(\"start_pinyin not like\", value, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinIn(List values) {\n addCriterion(\"start_pinyin in\", values, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinNotIn(List values) {\n addCriterion(\"start_pinyin not in\", values, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinBetween(String value1, String value2) {\n addCriterion(\"start_pinyin between\", value1, value2, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartPinyinNotBetween(String value1, String value2) {\n addCriterion(\"start_pinyin not between\", value1, value2, \"startPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeIsNull() {\n addCriterion(\"start_time is null\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeIsNotNull() {\n addCriterion(\"start_time is not null\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeEqualTo(Date value) {\n addCriterionForJDBCTime(\"start_time =\", value, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeNotEqualTo(Date value) {\n addCriterionForJDBCTime(\"start_time <>\", value, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeGreaterThan(Date value) {\n addCriterionForJDBCTime(\"start_time >\", value, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeGreaterThanOrEqualTo(Date value) {\n addCriterionForJDBCTime(\"start_time >=\", value, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeLessThan(Date value) {\n addCriterionForJDBCTime(\"start_time <\", value, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeLessThanOrEqualTo(Date value) {\n addCriterionForJDBCTime(\"start_time <=\", value, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeIn(List values) {\n addCriterionForJDBCTime(\"start_time in\", values, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeNotIn(List values) {\n addCriterionForJDBCTime(\"start_time not in\", values, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeBetween(Date value1, Date value2) {\n addCriterionForJDBCTime(\"start_time between\", value1, value2, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartTimeNotBetween(Date value1, Date value2) {\n addCriterionForJDBCTime(\"start_time not between\", value1, value2, \"startTime\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexIsNull() {\n addCriterion(\"start_index is null\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexIsNotNull() {\n addCriterion(\"start_index is not null\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexEqualTo(Integer value) {\n addCriterion(\"start_index =\", value, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexNotEqualTo(Integer value) {\n addCriterion(\"start_index <>\", value, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexGreaterThan(Integer value) {\n addCriterion(\"start_index >\", value, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"start_index >=\", value, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexLessThan(Integer value) {\n addCriterion(\"start_index <\", value, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexLessThanOrEqualTo(Integer value) {\n addCriterion(\"start_index <=\", value, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexIn(List values) {\n addCriterion(\"start_index in\", values, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexNotIn(List values) {\n addCriterion(\"start_index not in\", values, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexBetween(Integer value1, Integer value2) {\n addCriterion(\"start_index between\", value1, value2, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andStartIndexNotBetween(Integer value1, Integer value2) {\n addCriterion(\"start_index not between\", value1, value2, \"startIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIsNull() {\n addCriterion(\"`end` is null\");\n return (Criteria) this;\n }\n\n public Criteria andEndIsNotNull() {\n addCriterion(\"`end` is not null\");\n return (Criteria) this;\n }\n\n public Criteria andEndEqualTo(String value) {\n addCriterion(\"`end` =\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndNotEqualTo(String value) {\n addCriterion(\"`end` <>\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndGreaterThan(String value) {\n addCriterion(\"`end` >\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndGreaterThanOrEqualTo(String value) {\n addCriterion(\"`end` >=\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndLessThan(String value) {\n addCriterion(\"`end` <\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndLessThanOrEqualTo(String value) {\n addCriterion(\"`end` <=\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndLike(String value) {\n addCriterion(\"`end` like\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndNotLike(String value) {\n addCriterion(\"`end` not like\", value, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndIn(List values) {\n addCriterion(\"`end` in\", values, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndNotIn(List values) {\n addCriterion(\"`end` not in\", values, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndBetween(String value1, String value2) {\n addCriterion(\"`end` between\", value1, value2, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndNotBetween(String value1, String value2) {\n addCriterion(\"`end` not between\", value1, value2, \"end\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinIsNull() {\n addCriterion(\"end_pinyin is null\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinIsNotNull() {\n addCriterion(\"end_pinyin is not null\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinEqualTo(String value) {\n addCriterion(\"end_pinyin =\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinNotEqualTo(String value) {\n addCriterion(\"end_pinyin <>\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinGreaterThan(String value) {\n addCriterion(\"end_pinyin >\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinGreaterThanOrEqualTo(String value) {\n addCriterion(\"end_pinyin >=\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinLessThan(String value) {\n addCriterion(\"end_pinyin <\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinLessThanOrEqualTo(String value) {\n addCriterion(\"end_pinyin <=\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinLike(String value) {\n addCriterion(\"end_pinyin like\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinNotLike(String value) {\n addCriterion(\"end_pinyin not like\", value, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinIn(List values) {\n addCriterion(\"end_pinyin in\", values, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinNotIn(List values) {\n addCriterion(\"end_pinyin not in\", values, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinBetween(String value1, String value2) {\n addCriterion(\"end_pinyin between\", value1, value2, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndPinyinNotBetween(String value1, String value2) {\n addCriterion(\"end_pinyin not between\", value1, value2, \"endPinyin\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeIsNull() {\n addCriterion(\"end_time is null\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeIsNotNull() {\n addCriterion(\"end_time is not null\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeEqualTo(Date value) {\n addCriterionForJDBCTime(\"end_time =\", value, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeNotEqualTo(Date value) {\n addCriterionForJDBCTime(\"end_time <>\", value, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeGreaterThan(Date value) {\n addCriterionForJDBCTime(\"end_time >\", value, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeGreaterThanOrEqualTo(Date value) {\n addCriterionForJDBCTime(\"end_time >=\", value, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeLessThan(Date value) {\n addCriterionForJDBCTime(\"end_time <\", value, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeLessThanOrEqualTo(Date value) {\n addCriterionForJDBCTime(\"end_time <=\", value, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeIn(List values) {\n addCriterionForJDBCTime(\"end_time in\", values, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeNotIn(List values) {\n addCriterionForJDBCTime(\"end_time not in\", values, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeBetween(Date value1, Date value2) {\n addCriterionForJDBCTime(\"end_time between\", value1, value2, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndTimeNotBetween(Date value1, Date value2) {\n addCriterionForJDBCTime(\"end_time not between\", value1, value2, \"endTime\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexIsNull() {\n addCriterion(\"end_index is null\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexIsNotNull() {\n addCriterion(\"end_index is not null\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexEqualTo(Integer value) {\n addCriterion(\"end_index =\", value, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexNotEqualTo(Integer value) {\n addCriterion(\"end_index <>\", value, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexGreaterThan(Integer value) {\n addCriterion(\"end_index >\", value, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"end_index >=\", value, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexLessThan(Integer value) {\n addCriterion(\"end_index <\", value, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexLessThanOrEqualTo(Integer value) {\n addCriterion(\"end_index <=\", value, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexIn(List values) {\n addCriterion(\"end_index in\", values, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexNotIn(List values) {\n addCriterion(\"end_index not in\", values, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexBetween(Integer value1, Integer value2) {\n addCriterion(\"end_index between\", value1, value2, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andEndIndexNotBetween(Integer value1, Integer value2) {\n addCriterion(\"end_index not between\", value1, value2, \"endIndex\");\n return (Criteria) this;\n }\n\n public Criteria andYdzIsNull() {\n addCriterion(\"ydz is null\");\n return (Criteria) this;\n }\n\n public Criteria andYdzIsNotNull() {\n addCriterion(\"ydz is not null\");\n return (Criteria) this;\n }\n\n public Criteria andYdzEqualTo(Integer value) {\n addCriterion(\"ydz =\", value, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzNotEqualTo(Integer value) {\n addCriterion(\"ydz <>\", value, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzGreaterThan(Integer value) {\n addCriterion(\"ydz >\", value, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"ydz >=\", value, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzLessThan(Integer value) {\n addCriterion(\"ydz <\", value, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzLessThanOrEqualTo(Integer value) {\n addCriterion(\"ydz <=\", value, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzIn(List values) {\n addCriterion(\"ydz in\", values, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzNotIn(List values) {\n addCriterion(\"ydz not in\", values, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzBetween(Integer value1, Integer value2) {\n addCriterion(\"ydz between\", value1, value2, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzNotBetween(Integer value1, Integer value2) {\n addCriterion(\"ydz not between\", value1, value2, \"ydz\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceIsNull() {\n addCriterion(\"ydz_price is null\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceIsNotNull() {\n addCriterion(\"ydz_price is not null\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceEqualTo(BigDecimal value) {\n addCriterion(\"ydz_price =\", value, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceNotEqualTo(BigDecimal value) {\n addCriterion(\"ydz_price <>\", value, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceGreaterThan(BigDecimal value) {\n addCriterion(\"ydz_price >\", value, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceGreaterThanOrEqualTo(BigDecimal value) {\n addCriterion(\"ydz_price >=\", value, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceLessThan(BigDecimal value) {\n addCriterion(\"ydz_price <\", value, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceLessThanOrEqualTo(BigDecimal value) {\n addCriterion(\"ydz_price <=\", value, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceIn(List values) {\n addCriterion(\"ydz_price in\", values, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceNotIn(List values) {\n addCriterion(\"ydz_price not in\", values, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"ydz_price between\", value1, value2, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYdzPriceNotBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"ydz_price not between\", value1, value2, \"ydzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzIsNull() {\n addCriterion(\"edz is null\");\n return (Criteria) this;\n }\n\n public Criteria andEdzIsNotNull() {\n addCriterion(\"edz is not null\");\n return (Criteria) this;\n }\n\n public Criteria andEdzEqualTo(Integer value) {\n addCriterion(\"edz =\", value, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzNotEqualTo(Integer value) {\n addCriterion(\"edz <>\", value, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzGreaterThan(Integer value) {\n addCriterion(\"edz >\", value, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"edz >=\", value, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzLessThan(Integer value) {\n addCriterion(\"edz <\", value, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzLessThanOrEqualTo(Integer value) {\n addCriterion(\"edz <=\", value, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzIn(List values) {\n addCriterion(\"edz in\", values, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzNotIn(List values) {\n addCriterion(\"edz not in\", values, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzBetween(Integer value1, Integer value2) {\n addCriterion(\"edz between\", value1, value2, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzNotBetween(Integer value1, Integer value2) {\n addCriterion(\"edz not between\", value1, value2, \"edz\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceIsNull() {\n addCriterion(\"edz_price is null\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceIsNotNull() {\n addCriterion(\"edz_price is not null\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceEqualTo(BigDecimal value) {\n addCriterion(\"edz_price =\", value, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceNotEqualTo(BigDecimal value) {\n addCriterion(\"edz_price <>\", value, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceGreaterThan(BigDecimal value) {\n addCriterion(\"edz_price >\", value, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceGreaterThanOrEqualTo(BigDecimal value) {\n addCriterion(\"edz_price >=\", value, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceLessThan(BigDecimal value) {\n addCriterion(\"edz_price <\", value, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceLessThanOrEqualTo(BigDecimal value) {\n addCriterion(\"edz_price <=\", value, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceIn(List values) {\n addCriterion(\"edz_price in\", values, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceNotIn(List values) {\n addCriterion(\"edz_price not in\", values, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"edz_price between\", value1, value2, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andEdzPriceNotBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"edz_price not between\", value1, value2, \"edzPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwIsNull() {\n addCriterion(\"rw is null\");\n return (Criteria) this;\n }\n\n public Criteria andRwIsNotNull() {\n addCriterion(\"rw is not null\");\n return (Criteria) this;\n }\n\n public Criteria andRwEqualTo(Integer value) {\n addCriterion(\"rw =\", value, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwNotEqualTo(Integer value) {\n addCriterion(\"rw <>\", value, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwGreaterThan(Integer value) {\n addCriterion(\"rw >\", value, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"rw >=\", value, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwLessThan(Integer value) {\n addCriterion(\"rw <\", value, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwLessThanOrEqualTo(Integer value) {\n addCriterion(\"rw <=\", value, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwIn(List values) {\n addCriterion(\"rw in\", values, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwNotIn(List values) {\n addCriterion(\"rw not in\", values, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwBetween(Integer value1, Integer value2) {\n addCriterion(\"rw between\", value1, value2, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwNotBetween(Integer value1, Integer value2) {\n addCriterion(\"rw not between\", value1, value2, \"rw\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceIsNull() {\n addCriterion(\"rw_price is null\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceIsNotNull() {\n addCriterion(\"rw_price is not null\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceEqualTo(BigDecimal value) {\n addCriterion(\"rw_price =\", value, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceNotEqualTo(BigDecimal value) {\n addCriterion(\"rw_price <>\", value, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceGreaterThan(BigDecimal value) {\n addCriterion(\"rw_price >\", value, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceGreaterThanOrEqualTo(BigDecimal value) {\n addCriterion(\"rw_price >=\", value, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceLessThan(BigDecimal value) {\n addCriterion(\"rw_price <\", value, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceLessThanOrEqualTo(BigDecimal value) {\n addCriterion(\"rw_price <=\", value, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceIn(List values) {\n addCriterion(\"rw_price in\", values, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceNotIn(List values) {\n addCriterion(\"rw_price not in\", values, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"rw_price between\", value1, value2, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andRwPriceNotBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"rw_price not between\", value1, value2, \"rwPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwIsNull() {\n addCriterion(\"yw is null\");\n return (Criteria) this;\n }\n\n public Criteria andYwIsNotNull() {\n addCriterion(\"yw is not null\");\n return (Criteria) this;\n }\n\n public Criteria andYwEqualTo(Integer value) {\n addCriterion(\"yw =\", value, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwNotEqualTo(Integer value) {\n addCriterion(\"yw <>\", value, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwGreaterThan(Integer value) {\n addCriterion(\"yw >\", value, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwGreaterThanOrEqualTo(Integer value) {\n addCriterion(\"yw >=\", value, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwLessThan(Integer value) {\n addCriterion(\"yw <\", value, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwLessThanOrEqualTo(Integer value) {\n addCriterion(\"yw <=\", value, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwIn(List values) {\n addCriterion(\"yw in\", values, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwNotIn(List values) {\n addCriterion(\"yw not in\", values, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwBetween(Integer value1, Integer value2) {\n addCriterion(\"yw between\", value1, value2, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwNotBetween(Integer value1, Integer value2) {\n addCriterion(\"yw not between\", value1, value2, \"yw\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceIsNull() {\n addCriterion(\"yw_price is null\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceIsNotNull() {\n addCriterion(\"yw_price is not null\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceEqualTo(BigDecimal value) {\n addCriterion(\"yw_price =\", value, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceNotEqualTo(BigDecimal value) {\n addCriterion(\"yw_price <>\", value, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceGreaterThan(BigDecimal value) {\n addCriterion(\"yw_price >\", value, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceGreaterThanOrEqualTo(BigDecimal value) {\n addCriterion(\"yw_price >=\", value, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceLessThan(BigDecimal value) {\n addCriterion(\"yw_price <\", value, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceLessThanOrEqualTo(BigDecimal value) {\n addCriterion(\"yw_price <=\", value, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceIn(List values) {\n addCriterion(\"yw_price in\", values, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceNotIn(List values) {\n addCriterion(\"yw_price not in\", values, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"yw_price between\", value1, value2, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andYwPriceNotBetween(BigDecimal value1, BigDecimal value2) {\n addCriterion(\"yw_price not between\", value1, value2, \"ywPrice\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIsNull() {\n addCriterion(\"create_time is null\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIsNotNull() {\n addCriterion(\"create_time is not null\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeEqualTo(Date value) {\n addCriterion(\"create_time =\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotEqualTo(Date value) {\n addCriterion(\"create_time <>\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeGreaterThan(Date value) {\n addCriterion(\"create_time >\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {\n addCriterion(\"create_time >=\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeLessThan(Date value) {\n addCriterion(\"create_time <\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeLessThanOrEqualTo(Date value) {\n addCriterion(\"create_time <=\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIn(List values) {\n addCriterion(\"create_time in\", values, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotIn(List values) {\n addCriterion(\"create_time not in\", values, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeBetween(Date value1, Date value2) {\n addCriterion(\"create_time between\", value1, value2, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotBetween(Date value1, Date value2) {\n addCriterion(\"create_time not between\", value1, value2, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeIsNull() {\n addCriterion(\"update_time is null\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeIsNotNull() {\n addCriterion(\"update_time is not null\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeEqualTo(Date value) {\n addCriterion(\"update_time =\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeNotEqualTo(Date value) {\n addCriterion(\"update_time <>\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeGreaterThan(Date value) {\n addCriterion(\"update_time >\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {\n addCriterion(\"update_time >=\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeLessThan(Date value) {\n addCriterion(\"update_time <\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {\n addCriterion(\"update_time <=\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeIn(List values) {\n addCriterion(\"update_time in\", values, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeNotIn(List values) {\n addCriterion(\"update_time not in\", values, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeBetween(Date value1, Date value2) {\n addCriterion(\"update_time between\", value1, value2, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {\n addCriterion(\"update_time not between\", value1, value2, \"updateTime\");\n return (Criteria) this;\n }\n }\n\n public static class Criteria extends GeneratedCriteria {\n protected Criteria() {\n super();\n }\n }\n\n public static class Criterion {\n private String condition;\n\n private Object value;\n\n private Object secondValue;\n\n private boolean noValue;\n\n private boolean singleValue;\n\n private boolean betweenValue;\n\n private boolean listValue;\n\n private String typeHandler;\n\n public String getCondition() {\n return condition;\n }\n\n public Object getValue() {\n return value;\n }\n\n public Object getSecondValue() {\n return secondValue;\n }\n\n public boolean isNoValue() {\n return noValue;\n }\n\n public boolean isSingleValue() {\n return singleValue;\n }\n\n public boolean isBetweenValue() {\n return betweenValue;\n }\n\n public boolean isListValue() {\n return listValue;\n }\n\n public String getTypeHandler() {\n return typeHandler;\n }\n\n protected Criterion(String condition) {\n super();\n this.condition = condition;\n this.typeHandler = null;\n this.noValue = true;\n }\n\n protected Criterion(String condition, Object value, String typeHandler) {\n super();\n this.condition = condition;\n this.value = value;\n this.typeHandler = typeHandler;\n if (value instanceof List) {\n this.listValue = true;\n } else {\n this.singleValue = true;\n }\n }\n\n protected Criterion(String condition, Object value) {\n this(condition, value, null);\n }\n\n protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {\n super();\n this.condition = condition;\n this.value = value;\n this.secondValue = secondValue;\n this.typeHandler = typeHandler;\n this.betweenValue = true;\n }\n\n protected Criterion(String condition, Object value, Object secondValue) {\n this(condition, value, secondValue, null);\n }\n }\n}", "answers": [" List stationList = trainStationService.selectByTrainCode(trainCode);"], "length": 4893, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ba67eba9-dc17-4e71-adb9-fa1cf698562f", "reasoning": "The method genDaily is incomplete. After deleting existing tickets for the given date and train code, the next logical step is to retrieve all station information for that train to generate new ticket entries. The service provides a TrainStationService, so the next line should call it to get the list of stations for the specified train code.", "reasoning_model_answer": "List stationList = trainStationService.listByTrainCode(trainCode);", "assistant_with_reasoning": "\nThe method genDaily is incomplete. After deleting existing tickets for the given date and train code, the next logical step is to retrieve all station information for that train to generate new ticket entries. The service provides a TrainStationService, so the next line should call it to get the list of stations for the specified train code.\n\nList stationList = trainStationService.listByTrainCode(trainCode);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.411, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37410, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "List stationList = trainStationService.listByTrainCode(trainCode);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import ppt4j.annotation.MethodProfiler;\nimport ppt4j.annotation.Property;\nimport ppt4j.database.DatabaseType;\nimport ppt4j.database.Vulnerability;\nimport ppt4j.diff.BlockDiff;\nimport ppt4j.diff.DiffParser;\nimport ppt4j.diff.FileDiff;\nimport ppt4j.factory.DatabaseFactory;\nimport ppt4j.factory.ExtractorFactory;\nimport ppt4j.feature.FeatureMatcher;\nimport ppt4j.feature.Features;\nimport ppt4j.feature.java.JavaExtractor;\nimport ppt4j.feature.java.JavaFeatures;\nimport ppt4j.util.StringUtils;\nimport lombok.extern.log4j.Log4j;\nimport java.io.IOException;\nimport java.util.*;", "context": "framework/src/main/java/ppt4j/analysis/patch/PatchAnalyzer.java\npackage ppt4j.analysis.patch;\n\n\n\n@Log4j\npublic class PatchAnalyzer {\n\n @Property(\"ppt4j.analysis.patch.presence_threshold\")\n\nframework/src/main/java/ppt4j/factory/DatabaseFactory.java\n@Log4j\npublic final class DatabaseFactory {\n\n private static final JavaCompiler\n compiler = ToolProvider.getSystemJavaCompiler();\n\n private static final StandardJavaFileManager\n stdManager = compiler.getStandardFileManager(null, null, null);\n\n private static final String classTemplate;\n\n private static final Map\n cachedClasses = new HashMap<>();\n\n private static final Map\n cachedClassesByCVE = new HashMap<>();\n\n static {\n try (InputStream data = ResourceUtils.readVulTemplate()) {\n classTemplate = new String(data.readAllBytes());\n } catch (IOException e) {\n log.error(e);\n throw new RuntimeException();\n }\n }\n\n public static Vulnerability makeDataset(@NonNull VulnerabilityInfo info) {\n if(cachedClasses.containsKey(StringUtils.extractDatabaseId(info.vul_id)) ||\n cachedClassesByCVE.containsKey(info.cve_id)) {\n log.error(String.format(\n \"Vulnerability with Database ID %s or\" +\n \"CVE ID %s is already loaded.\",\n info.vul_id, info.cve_id));\n throw new IllegalStateException();\n }\n try {\n Vulnerability instance = compileAndLoad(info);\n cachedClasses.put(instance.getDatabaseId(), instance);\n cachedClassesByCVE.put(instance.getCVEId(), instance);\n return instance;\n } catch (Exception e) {\n log.error(e);\n throw new IllegalStateException();\n }\n }\n\n public static Vulnerability makeDataset(InputStream jsonInput)\n throws IOException {\n VulnerabilityInfo info = VulnerabilityInfo.fromJSON(jsonInput);\n return makeDataset(info);\n }\n\n public static Vulnerability getByDatabaseId(int id) {\n if(cachedClasses.containsKey(id)) {\n return cachedClasses.get(id);\n }\n InputStream data = ResourceUtils.readDatabase(String.format(\"VUL4J-%d.json\", id));\n if(data == null) {\n log.error(\"No vulnerability with id \" + id + \" found\");\n throw new IllegalStateException();\n }\n try {\n return makeDataset(data);\n } catch (IOException e) {\n log.error(e);\n throw new IllegalStateException();\n }\n }\n\n private static Vulnerability compileAndLoad(VulnerabilityInfo info)\n throws NoSuchMethodException, ClassNotFoundException,\n InvocationTargetException, InstantiationException,\n IllegalAccessException {\n if(info.isEmpty()) {\n log.error(\"VulnerabilityInfo object is not valid\");\n throw new IllegalStateException();\n }\n String className = info.cve_id.replace(\"-\", \"_\");\n String code = String.format(classTemplate,\n info.cve_id,\n StringUtils.extractDatabaseId(info.vul_id),\n className,\n className,\n info.project_url,\n info.fixing_commit_hash,\n info.human_patch_url + \".diff\",\n StringUtils.getJavaSrcTopLevelDir(info),\n info.src_classes_dir,\n info.should_scan_all_modules,\n StringUtils.getThirdPartySrcDirsString(info),\n StringUtils.getThirdPartyLibDirsString(info)\n );\n MemoryJavaFileManager manager =\n new MemoryJavaFileManager(stdManager);\n JavaFileObject file = manager.makeStringSource(\n className + \".java\", code);\n DiagnosticCollector diagnostics =\n new DiagnosticCollector<>();\n JavaCompiler.CompilationTask task =\n compiler.getTask(\n null, manager, diagnostics, null, null,\n List.of(file)\n );\n Boolean result = task.call();\n if (result == null || !result) {\n for (var diagnostic : diagnostics.getDiagnostics()) {\n log.error(diagnostic.getMessage(null));\n }\n throw new RuntimeException(\"Compilation failed.\");\n\n }\n Map classBytes = manager.getClassBytes();\n manager.close();\n MemoryClassLoader loader = new MemoryClassLoader(classBytes);\n Class clazz = loader.loadClass(\"ppt4j.database.\" + className);\n return (Vulnerability) clazz.getConstructor().newInstance();\n }\n\n static class MemoryJavaFileManager\n extends ForwardingJavaFileManager {\n\n final Map classBytes = new HashMap<>();\n\n MemoryJavaFileManager(JavaFileManager fileManager) {\n super(fileManager);\n }\n\n public Map getClassBytes() {\n return new HashMap<>(this.classBytes);\n }\n\n @Override\n public void flush() {}\n\n @Override\n public void close() {\n classBytes.clear();\n }\n\n @Override\n public JavaFileObject getJavaFileForOutput(\n JavaFileManager.Location location, String className,\n JavaFileObject.Kind kind, FileObject sibling)\n throws IOException {\n if (kind == JavaFileObject.Kind.CLASS) {\n return new MemoryOutputJavaFileObject(className);\n } else {\n return super.getJavaFileForOutput(\n location, className, kind, sibling);\n }\n }\n\n JavaFileObject makeStringSource(String name, String code) {\n return new MemoryInputJavaFileObject(name, code);\n }\n\n static class MemoryInputJavaFileObject extends SimpleJavaFileObject {\n\n final String code;\n\n MemoryInputJavaFileObject(String name, String code) {\n super(URI.create(\"string:///\" + name), Kind.SOURCE);\n this.code = code;\n }\n\n @Override\n public CharBuffer getCharContent(boolean ignoreEncodingErrors) {\n return CharBuffer.wrap(code);\n }\n }\n\n class MemoryOutputJavaFileObject extends SimpleJavaFileObject {\n final String name;\n\n MemoryOutputJavaFileObject(String name) {\n super(URI.create(\"string:///\" + name), Kind.CLASS);\n this.name = name;\n }\n\n @Override\n public OutputStream openOutputStream() {\n return new FilterOutputStream(new ByteArrayOutputStream()) {\n @Override\n public void close() throws IOException {\n out.close();\n ByteArrayOutputStream bos =\n (ByteArrayOutputStream) out;\n classBytes.put(name, bos.toByteArray());\n }\n };\n }\n\n }\n\n }\n\n static class MemoryClassLoader extends URLClassLoader {\n\n Map classBytes = new HashMap<>();\n\n public MemoryClassLoader(Map classBytes) {\n super(new URL[0], MemoryClassLoader.class.getClassLoader());\n this.classBytes.putAll(classBytes);\n }\n\n @Override\n protected Class findClass(String name)\n throws ClassNotFoundException {\n byte[] buf = classBytes.get(name);\n if (buf == null) {\n return super.findClass(name);\n }\n classBytes.remove(name);\n return defineClass(name, buf, 0, buf.length);\n }\n\n }\n\n}\n\nframework/src/main/java/ppt4j/diff/FileDiff.java\npublic class FileDiff {\n\n @Getter\n private final List blocks = new ArrayList<>();\n\n public FileDiff(List> lines) {\n int offset = 0;\n int idx = 0;\n while (idx < lines.size()) {\n int start = idx;\n int end = idx;\n if (lines.get(start).getRight().getLineType() == Line.LineType.TO) {\n while (end < lines.size() - 1 &&\n lines.get(end + 1).getLeft() == lines.get(end).getLeft() + 1 &&\n lines.get(end + 1).getRight().getLineType() != Line.LineType.FROM) {\n end++;\n }\n offset += end - start + 1;\n } else {\n while (end < lines.size() - 1 &&\n lines.get(end + 1).getLeft() == lines.get(end).getLeft() + 1 &&\n lines.get(end + 1).getRight().getLineType() != Line.LineType.TO) {\n end++;\n }\n offset -= end - start + 1;\n if (end < lines.size() - 1 &&\n lines.get(end + 1).getRight().getLineType() == Line.LineType.TO &&\n lines.get(end + 1).getLeft() - offset - 1 <= lines.get(end).getLeft()) {\n end++;\n while (end < lines.size() - 1 &&\n lines.get(end + 1).getLeft() == lines.get(end).getLeft() + 1) {\n end++;\n }\n offset += end - start + 1;\n }\n }\n blocks.add(new BlockDiff(lines.subList(start, end + 1)));\n idx = end + 1;\n }\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (BlockDiff block : blocks) {\n sb.append(block.toString());\n sb.append(\"\\n\");\n }\n return sb.toString();\n }\n\n}\n\nframework/src/main/java/ppt4j/feature/Features.java\n@Getter\npublic class Features implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n public enum SourceType {\n JAVA, BYTECODE\n }\n\n @SuppressWarnings(\"SpellCheckingInspection\")\n public enum InstType {\n THROW, MONITOR, SWITCH, INSTANCEOF, RETURN, LOOP,\n BRLT, BRLE, BRGT, BRGE, SHL, SHR, USHR\n }\n\n @Property(\"ppt4j.features.similarity.threshold\")\n private static double SIM_THRESHOLD;\n\n @Property(\"ppt4j.features.similarity.algorithm\")\n private static String SIM_ALGORITHM;\n\n protected final SourceType sourceType;\n\n protected String className;\n protected int lineNo;\n\n protected final Set Constants = new HashSet<>();\n protected final Set MethodInvocations = new HashSet<>();\n protected final Set FieldAccesses = new HashSet<>();\n protected final Set ObjCreations = new HashSet<>();\n protected final Set Instructions = new HashSet<>();\n protected final Set Misc = new HashSet<>();\n\n protected Features(@NonNull SourceType sourceType,\n @NonNull String className, int lineNo) {\n this.sourceType = sourceType;\n this.className = className;\n this.lineNo = lineNo;\n }\n\n public boolean isEmpty() {\n return Constants.isEmpty() &&\n MethodInvocations.isEmpty() &&\n FieldAccesses.isEmpty() &&\n ObjCreations.isEmpty() &&\n Instructions.isEmpty() &&\n Misc.isEmpty();\n }\n\n public int size() {\n return Constants.size() +\n MethodInvocations.size() +\n FieldAccesses.size() +\n ObjCreations.size() +\n Instructions.size() +\n Misc.size();\n }\n\n @Override\n public String toString() {\n String constants = String.format(\"Constants: %s\\n\",\n StringUtils.printSet(Constants, true, true));\n String methodInvocations = String.format(\"Method Invocations: %s\\n\",\n StringUtils.printSet(MethodInvocations));\n String fieldAccesses = String.format(\"Field Accesses: %s\\n\",\n StringUtils.printSet(FieldAccesses));\n String objCreations = String.format(\"Object Creations: %s\\n\",\n StringUtils.printSet(ObjCreations));\n String instructions = String.format(\"Instructions: %s\\n\",\n StringUtils.printSet(Instructions));\n String misc = String.format(\"Misc: %s\\n\",\n StringUtils.printSet(Misc));\n return constants + methodInvocations + fieldAccesses\n + objCreations + instructions + misc;\n }\n\n @Override\n public boolean equals(Object rhs) {\n if(rhs == null) return false;\n if(!(rhs instanceof Features _rhs)) return false;\n return FeatureMatcher.get(SIM_ALGORITHM).isMatch(this, _rhs, SIM_THRESHOLD);\n }\n\n}\n\nframework/src/main/java/ppt4j/feature/java/JavaExtractor.java\n@SuppressWarnings(\"unused\")\n@Log4j\npublic final class JavaExtractor implements Extractor {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private transient final CtClass root;\n\n @Getter\n private final Map\n innerClasses = new HashMap<>();\n\n @Getter\n private final Map featuresMap = new TreeMap<>();\n\n private boolean isParsed = false;\n\n @Getter\n private final String className;\n\n @Getter\n private final String superClassName;\n\n private final Set validLines = new HashSet<>();\n\n private final Map splitLinesToLogical = new TreeMap<>();\n\n public JavaExtractor(InputStream inputStream)\n throws IOException {\n this(Launcher.parseClass(new String(inputStream.readAllBytes())));\n }\n\n public JavaExtractor(String path)\n throws IOException {\n this(new FileInputStream(path));\n }\n\n public JavaExtractor(CtClass clazz) {\n String superClassName1;\n this.root = clazz;\n this.className = clazz.getQualifiedName().replace('.', '/');\n CtTypeReference superClass = clazz.getSuperclass();\n if(superClass != null) {\n superClassName1 = superClass.getQualifiedName().replace('.', '/');\n } else {\n superClassName1 = null;\n }\n this.superClassName = superClassName1;\n }\n\n public JavaExtractor(ClassFactory factory, String className) {\n this(factory.get(className));\n }\n\n private JavaExtractor() {\n root = null;\n className = \"fake\";\n superClassName = \"fake\";\n }\n\n public static JavaExtractor nil() {\n return new JavaExtractor();\n }\n\n @Override\n public Features.SourceType getSourceType() {\n return Features.SourceType.JAVA;\n }\n\n @Override\n public void parse() {\n if (isParsed) {\n return;\n }\n root.getFields().forEach(this::parseField);\n root.getElements(new LineFilter()).forEach(this::parseLine);\n root.getNestedTypes().forEach(ty -> {\n if (ty instanceof CtClass _class) {\n\n JavaExtractor ex = new JavaExtractor(_class);\n innerClasses.put(ex.getClassName(), ex);\n }\n });\n root.getElements(new AnonymousClassFilter()).forEach(ty -> {\n CtClass _class = ty.getAnonymousClass();\n JavaExtractor ex = new JavaExtractor(_class);\n innerClasses.put(ex.getClassName(), ex);\n });\n innerClasses.values().forEach(JavaExtractor::parse);\n isParsed = true;\n }\n\n public Collection getInnerClass() {\n return innerClasses.values();\n }\n\n @SuppressWarnings(\"BooleanMethodIsAlwaysInverted\")\n public boolean isValidLine(int line) {\n return validLines.contains(line);\n }\n\n public int getLogicalLine(int line) {\n if(!splitLinesToLogical.containsKey(line)) {\n return -1;\n }\n return splitLinesToLogical.get(line);\n }\n\n private void parseField(CtField field) {\n if(field.getPosition().equals(SourcePosition.NOPOSITION)) {\n return;\n }\n CtFieldReference fieldRef = field.getReference();\n CtTypeReference fieldTypeRef = fieldRef.getType();\n CtExpression assignment = field.getAssignment();\n ConstPropAnalysis analysis = new ConstPropAnalysis<>(assignment);\n analysis.analyze();\n if(!analysis.isLiteral()) {\n String fieldAccess =\n StringUtils.convertQualifiedName(fieldRef.getQualifiedName(), root.getQualifiedName())\n + \":\" + StringUtils.convertToDescriptor(fieldTypeRef.getQualifiedName());\n JavaFeatures features;\n if(assignment instanceof CtStatement stmt) {\n features = new JavaFeatures(root.getQualifiedName(), stmt);\n features.getFieldAccesses().add(fieldAccess);\n putSplitLines(features);\n validLines.add(stmt.getPosition().getLine());\n putFeatures(stmt.getPosition().getLine(), features);\n }\n } else {\n LibraryConstants.put(fieldRef.getQualifiedName(), analysis.getLiteral().getValue());\n }\n }\n\n private void parseLine(CtStatement stmt) {\n if(stmt.getPosition().equals(SourcePosition.NOPOSITION)) {\n return;\n }\n try {\n JavaFeatures features = new JavaFeatures(root.getQualifiedName(), stmt);\n String text = features.getText();\n if(text.equals(\"do\") || text.equals(\"else\") || text.equals(\"try\")) {\n return;\n }\n putSplitLines(features);\n validLines.add(stmt.getPosition().getLine());\n putFeatures(stmt.getPosition().getLine(), features);\n } catch (IllegalStateException e) {\n // comment in a single line\n }\n }\n\n private void putSplitLines(JavaFeatures features) {\n List splitLines = features.getSplitLines();\n int baseLine = splitLines.get(0);\n for (Integer line : splitLines) {\n splitLinesToLogical.put(line, baseLine);\n }\n }\n\n private void putFeatures(int line, JavaFeatures features) {\n if(featuresMap.containsKey(line)) {\n JavaFeatures old = (JavaFeatures) featuresMap.get(line);\n old.merge(features);\n } else {\n featuresMap.put(line, features);\n }\n }\n\n}\n\nframework/src/main/java/ppt4j/util/StringUtils.java\npublic class StringUtils {\n\n @Property(\"user.home\")\n private static String USER_HOME;\n\n @Property(\"ppt4j.database.root\")\n private static String DB_ROOT;\n\n @Property(\"ppt4j.database.prepatch.name\")\n private static String PREPATCH_NAME;\n\n @Property(\"ppt4j.database.postpatch.name\")\n private static String POSTPATCH_NAME;\n\n @Property(\"ppt4j.classpath\")\n private static String CLASSPATH;\n\n public static String printSet(Set set) {\n return printSet(set, false, false);\n }\n\n public static String printSet(Set set, boolean emphasizeString, boolean printType) {\n if(set.isEmpty()) {\n return \"[]\";\n }\n StringBuilder sb = new StringBuilder();\n sb.append(\"[ \");\n Object[] arr = set.toArray();\n for (int i = 0; i < set.size(); i++) {\n Object s = arr[i];\n if(emphasizeString && s instanceof String) {\n sb.append(String.format(\"\\\"%s\\\"\", s));\n } else {\n sb.append(String.format(\"%s\", s));\n }\n if(printType) {\n sb.append(String.format(\":%s\", s.getClass().getSimpleName()));\n }\n if(i != set.size() - 1) {\n sb.append(\", \");\n }\n }\n sb.append(\" ]\");\n return sb.toString();\n }\n\n public static String convertToDescriptor(String type) {\n type = type.replaceAll(\"<.*>\", \"\");\n type = type.trim().replace(\".\", \"/\");\n return switch (type) {\n case \"\" -> \"\";\n case \"\", \"void\" -> \"V\";\n case \"boolean\" -> \"Z\";\n case \"byte\" -> \"B\";\n case \"char\" -> \"C\";\n case \"short\" -> \"S\";\n case \"int\" -> \"I\";\n case \"long\" -> \"J\";\n case \"float\" -> \"F\";\n case \"double\" -> \"D\";\n default -> {\n if(type.endsWith(\"[]\")) {\n String baseType = type.substring(0, type.length() - 2);\n yield String.format(\"[%s\", convertToDescriptor(baseType));\n } else {\n yield String.format(\"L%s;\", type);\n }\n }\n };\n }\n\n public static boolean isPrimitive(String type) {\n if(type.startsWith(\"java.lang.\")) {\n type = type.substring(\"java.lang.\".length());\n }\n return switch (type) {\n case \"Boolean\", \"Byte\", \"Character\", \"Short\",\n \"Integer\", \"Long\", \"Float\", \"Double\",\n \"boolean\", \"byte\", \"char\", \"short\", \"int\", \"long\", \"float\",\n \"double\", \"Z\", \"B\", \"C\", \"S\", \"I\", \"J\", \"F\", \"D\" -> true;\n default -> false;\n };\n }\n\n public static String convertMethodSignature(\n String nameAndArgs, String returnType) {\n String name = nameAndArgs.substring(0, nameAndArgs.indexOf(\"(\"));\n String[] args = nameAndArgs.substring(\n nameAndArgs.indexOf(\"(\") + 1, nameAndArgs.indexOf(\")\")\n ).split(\",\");\n StringBuilder sb = new StringBuilder();\n sb.append(name);\n sb.append(\":(\");\n for (String arg : args) {\n sb.append(convertToDescriptor(arg));\n }\n sb.append(\")\");\n sb.append(convertToDescriptor(returnType));\n return sb.toString();\n }\n\n public static String convertQualifiedName(String name, String className) {\n return convertQualifiedName(name, className, true);\n }\n\n public static String convertQualifiedName(String name,\n String className,\n boolean retainClassName) {\n String _className = name.split(\"#\")[0];\n if((_className.equals(className) || isPrimitive(_className)) && !retainClassName) {\n return name.split(\"#\")[1];\n } else {\n return _className.replace(\".\", \"/\")\n + \".\" + name.split(\"#\")[1];\n }\n }\n\n public static boolean isJavaComment(String line) {\n String trimmed = line.trim();\n return trimmed.matches(\"//.*\") || trimmed.matches(\"/\\\\*.*\\\\*/\");\n }\n\n public static boolean isJavaCode(String line) {\n if(isJavaComment(line)) {\n return false;\n }\n String trimmed = line.trim();\n if(trimmed.isEmpty()) {\n return false;\n }\n String[] patterns = {\n \"\\\\{\",\n \"\\\\}\",\n \"\\\\};\",\n \"else\",\n \"\\\\}\\\\s*else\\\\s*\\\\{\",\n \"else\\\\s*\\\\{\",\n \"\\\\}\\\\s*else\",\n };\n for (String pattern : patterns) {\n if(trimmed.matches(pattern)) {\n return false;\n }\n }\n return true;\n }\n\n public static String trimJavaCodeLine(String codeLine) {\n codeLine = codeLine.replaceAll(\"//.*\", \"\");\n codeLine = codeLine.replaceAll(\"/\\\\*.*\\\\*/\", \"\");\n codeLine = codeLine.replaceAll(\"\\\\s+$\", \"\");\n codeLine = codeLine.replaceAll(\"^\\\\s+\", \"\");\n if (codeLine.endsWith(\"{\")) {\n codeLine = codeLine.substring(0, codeLine.length() - 1);\n }\n return codeLine.trim();\n }\n\n public static @NonNull Main.Command matchPrefix(String prefix) {\n Main.Command matched = null;\n for (Main.Command command : Main.Command.values()) {\n if(command.name.startsWith(prefix.toLowerCase())) {\n if(matched != null) {\n System.err.println(\"Ambiguous command: \" + prefix);\n System.err.println(\"Possible commands:\");\n for (Main.Command c : Main.Command.values()) {\n if(c.name.startsWith(prefix)) {\n System.err.println(c.name);\n }\n }\n System.exit(1);\n }\n matched = command;\n }\n }\n if(matched == null) {\n System.err.println(\"Unknown command: \" + prefix);\n System.exit(1);\n }\n return matched;\n }\n\n public static byte[] toBytes(List lines) {\n return String.join(\"\\n\", lines).getBytes();\n }\n\n @SuppressWarnings(\"HttpUrlsUsage\")\n public static URL toURL(String path) {\n try {\n if(path.startsWith(\"http://\") || path.startsWith(\"https://\")) {\n return new URL(path);\n } else {\n return new File(path).toURI().toURL();\n }\n } catch (MalformedURLException e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static String extractClassName(String filePath,\n String topLevelPrefix) {\n if(topLevelPrefix.endsWith(\"/\")) {\n topLevelPrefix =\n topLevelPrefix.substring(0, topLevelPrefix.length() - 1);\n }\n String className = filePath.substring(\n topLevelPrefix.length() + 1, filePath.length() - 5\n );\n return className.replace(\"/\", \".\");\n }\n\n public static String buildMethodSignature(MethodInsnNode minsn, BasicValue[] args) {\n String returnType = minsn.desc.split(\"\\\\)\")[1];\n StringBuilder argTypes = new StringBuilder();\n for(BasicValue arg : args) {\n argTypes.append(arg.getType().getDescriptor());\n }\n return \"(\" + argTypes + \")\" + returnType;\n }\n\n public static String substringBetween(String str, char c1, char c2) {\n int start = str.indexOf(c1);\n int end = str.lastIndexOf(c2);\n if(start == -1 || end == -1) {\n return null;\n }\n return str.substring(start + 1, end);\n }\n\n public static String toWrapperType(String type) {\n return switch (type) {\n case \"boolean\" -> \"java/lang/Boolean\";\n case \"byte\" -> \"java/lang/Byte\";\n case \"char\" -> \"java/lang/Character\";\n case \"short\" -> \"java/lang/Short\";\n case \"int\" -> \"java/lang/Integer\";\n case \"long\" -> \"java/lang/Long\";\n case \"float\" -> \"java/lang/Float\";\n case \"double\" -> \"java/lang/Double\";\n default -> type;\n };\n }\n\n public static String resolvePath(String path) {\n // if the path begins with ~, replace it with the home directory\n if(path.startsWith(\"~\")) {\n path = USER_HOME + path.substring(1);\n }\n return path;\n }\n\n public static String[] splitArgDesc(String desc) {\n String argDescs = substringBetween(desc, '(', ')');\n if(argDescs == null || argDescs.isEmpty()) {\n return new String[0];\n }\n List args = new ArrayList<>();\n for(int i = 0; i < argDescs.length(); i++) {\n char c = argDescs.charAt(i);\n if(c == 'L') {\n int end = argDescs.indexOf(';', i);\n args.add(argDescs.substring(i, end + 1));\n i = end;\n } else if(c == '[') {\n int end = i;\n while(argDescs.charAt(end) == '[') {\n end++;\n }\n if(argDescs.charAt(end) == 'L') {\n end = argDescs.indexOf(';', end);\n }\n args.add(argDescs.substring(i, end + 1));\n i = end;\n } else {\n args.add(String.valueOf(c));\n }\n }\n return args.toArray(String[]::new);\n }\n\n public static String joinArgDesc(List descList) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"(\");\n for(String desc : descList) {\n sb.append(desc);\n }\n sb.append(\")\");\n return sb.toString();\n }\n\n public static String getDatabasePrepatchSrcPath(Vulnerability vuln) {\n int id = vuln.getDatabaseId();\n String innerPath = \"/\" + vuln.getJavaSrcTopLevelDir();\n return String.format(\"%s/%s/%d%s\",\n DB_ROOT, PREPATCH_NAME, id, innerPath);\n }\n\n public static String getDatabasePostpatchSrcPath(Vulnerability vuln) {\n int id = vuln.getDatabaseId();\n String innerPath = \"/\" + vuln.getJavaSrcTopLevelDir();\n return String.format(\"%s/%s/%d%s\",\n DB_ROOT, POSTPATCH_NAME, id, innerPath);\n }\n\n public static String getDatabasePrepatchClassPath(Vulnerability vuln) {\n int id = vuln.getDatabaseId();\n return resolvePath(String.format(\"%s/%s/%d/%s\",\n DB_ROOT, PREPATCH_NAME, id, vuln.getClassesTopLevelDir()));\n }\n\n public static String getDatabasePostpatchClassPath(Vulnerability vuln) {\n int id = vuln.getDatabaseId();\n return resolvePath(String.format(\"%s/%s/%d/%s\",\n DB_ROOT, POSTPATCH_NAME, id, vuln.getClassesTopLevelDir()));\n }\n\n public static String[] getThirdPartySrcDirsFromPrepatch(\n Vulnerability vuln) {\n int id = vuln.getDatabaseId();\n String[] thirdParties = vuln.getThirdPartySrcDirs().clone();\n for(int i = 0;i < thirdParties.length;i++) {\n thirdParties[i] = String.format(\"%s/%s/%d/%s\",\n DB_ROOT, PREPATCH_NAME, id, thirdParties[i]);\n thirdParties[i] = resolvePath(thirdParties[i]);\n }\n return thirdParties;\n }\n\n public static String[] getThirdPartyLibDirsFromPrepatch(\n Vulnerability vuln) {\n int id = vuln.getDatabaseId();\n String[] thirdParties = vuln.getThirdPartyLibDirs().clone();\n for(int i = 0;i < thirdParties.length;i++) {\n thirdParties[i] = String.format(\"%s/%s/%d/%s\",\n DB_ROOT, PREPATCH_NAME, id, thirdParties[i]);\n thirdParties[i] = resolvePath(thirdParties[i]);\n }\n return thirdParties;\n }\n\n public static int extractDatabaseId(String name) {\n // pattern: VUL4J-%d\n // extract the number and return it\n if(name.matches(\"VUL4J-\\\\d+\")) {\n return Integer.parseInt(name.substring(6));\n } else {\n throw new IllegalStateException(\"Invalid database name: \" + name);\n }\n }\n\n public static String getJavaSrcTopLevelDir(VulnerabilityInfo info) {\n if(info.src_top_level_dir != null) {\n return info.src_top_level_dir;\n }\n if(info.build_system.equals(\"Maven\")) {\n String targetDir = info.src_classes_dir;\n if(targetDir.equals(\"target/classes\")) {\n return \"src/main/java\";\n }\n int index = targetDir.indexOf(\"/target/classes\");\n if(index == -1) {\n throw new IllegalStateException(\"Invalid target directory: \" + targetDir);\n }\n String base = targetDir.substring(0, index);\n return base + \"/src/main/java\";\n }\n if(info.build_system.equals(\"Gradle\")) {\n String targetDir = info.src_classes_dir;\n if(targetDir.equals(\"build/classes/java/main\") ||\n targetDir.equals(\"build/classes/main\")) {\n return \"src/main/java\";\n }\n int index = targetDir.indexOf(\"/build/classes/java/main\");\n if(index == -1) {\n index = targetDir.indexOf(\"/build/classes/main\");\n }\n if(index == -1) {\n throw new IllegalStateException(\"Invalid target directory: \" + targetDir);\n }\n String base = targetDir.substring(0, index);\n return base + \"/src/main/java\";\n }\n throw new IllegalStateException(\"Must specify src_top_level_dir with custom build system\");\n }\n\n public static String buildNewStringArrayCode(String[] arr) {\n if(arr == null || arr.length == 0) {\n return \"new String[0]\";\n }\n StringBuilder sb = new StringBuilder();\n sb.append(\"new String[] {\");\n for(String e : arr) {\n sb.append(\"\\\"\").append(e).append(\"\\\",\");\n }\n sb.deleteCharAt(sb.length() - 1);\n sb.append(\"}\");\n return sb.toString();\n }\n\n public static String getThirdPartySrcDirsString(VulnerabilityInfo info) {\n return buildNewStringArrayCode(info.third_party_src_dirs);\n }\n\n public static String getClassPathToLoad(Vulnerability vuln) {\n\n return String.join(File.pathSeparator,\n CLASSPATH,\n getDatabasePrepatchClassPath(vuln),\n getDatabasePostpatchClassPath(vuln),\n String.join(File.pathSeparator,\n getThirdPartyLibDirsFromPrepatch(vuln)));\n }\n\n public static String getThirdPartyLibDirsString(VulnerabilityInfo info) {\n return buildNewStringArrayCode(info.third_party_lib_dirs);\n }\n}\n\nframework/src/main/java/ppt4j/database/Vulnerability.java\n@SuppressWarnings(\"unused\")\npublic interface Vulnerability extends Serializable {\n\n default int getDatabaseId() {\n return this.getClass().getAnnotation(Database.class).id();\n }\n\n default String getCVEId() {\n return this.getClass().getAnnotation(Database.class).value();\n }\n\n default String getProjectName() {\n return getRepoUrl().substring(getRepoUrl().lastIndexOf('/') + 1);\n }\n\n String getRepoUrl();\n\n String getPatchCommitHash();\n\n default String getDiffUrl() {\n return getRepoUrl() + \"/commit/\" + getPatchCommitHash() + \".diff\";\n }\n\n String getJavaSrcTopLevelDir();\n\n String getClassesTopLevelDir();\n\n default String[] getThirdPartySrcDirs() {\n return new String[0];\n }\n\n default String[] getThirdPartyLibDirs() {\n return new String[0];\n }\n\n default boolean shouldScanAllModules() {\n return false;\n }\n\n default String[] getIgnoredFilePatterns() {\n return new String[]{\n \".*Test.*\", \".*Issue.*\", \".*src/test/.*\", \".*/package-info\\\\.java\",\n };\n }\n\n default String[] getRequiredFilePatterns() {\n return new String[]{\n \".*\\\\.java\"\n };\n }\n\n default void dump(String path) {\n FileUtils.serializeObject(this, path);\n }\n\n static Vulnerability load(String path) {\n return FileUtils.deserializeObject(Vulnerability.class, path);\n }\n\n}\n\nframework/src/main/java/ppt4j/database/DatabaseType.java\npublic enum DatabaseType {\n\n PREPATCH, POSTPATCH;\n\n @Property(\"ppt4j.database.prepatch.name\")\n private static String PREPATCH_DIR;\n\n @Property(\"ppt4j.database.postpatch.name\")\n private static String POSTPATCH_DIR;\n\n @Property(\"ppt4j.database.root\")\n private static String DATABASE_ROOT;\n\n public String getPath() {\n String subDir = this == PREPATCH ? PREPATCH_DIR : POSTPATCH_DIR;\n return Path.of(StringUtils.resolvePath(DATABASE_ROOT), subDir).toString();\n }\n\n public String getPath(int id) {\n return Path.of(getPath(), String.valueOf(id)).toString();\n }\n\n public String toString() {\n return this == PREPATCH ? \"prepatch\" : \"postpatch\";\n }\n\n}\n\nframework/src/main/java/ppt4j/feature/FeatureMatcher.java\n@SuppressWarnings(\"unused\")\npublic interface FeatureMatcher {\n\n String getAlgorithm();\n\n @SuppressWarnings({\"SwitchStatementWithTooFewBranches\", \"EnhancedSwitchMigration\"})\n static FeatureMatcher get(String algorithm) {\n switch (algorithm) {\n case \"jaccard\":\n return new JaccardMatcher();\n default:\n throw new IllegalArgumentException(\n \"Unknown algorithm: \" + algorithm);\n }\n }\n\n static FeatureMatcher get() {\n return get(\"jaccard\");\n }\n\n double match(Features f1, Features f2);\n\n default boolean isMatch(Features f1, Features f2, double threshold) {\n return match(f1, f2) >= threshold;\n }\n\n}\n\nframework/src/main/java/ppt4j/diff/DiffParser.java\n@Log4j\npublic class DiffParser {\n\n private final List diffs;\n\n private final List>>\n diffLines = new ArrayList<>();\n\n private final List fileDiffs = new ArrayList<>();\n\n private boolean downloadIntegrityCheck = false;\n\n @Log4j\n static class SigintHandler extends Thread {\n\n private final DiffParser diff;\n private final File f;\n\n public SigintHandler(DiffParser diff, File f) {\n this.diff = diff;\n this.f = f;\n }\n\n public void register() {\n Runtime.getRuntime().addShutdownHook(this);\n }\n\n @Override\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public void run() {\n if (!diff.downloadIntegrityCheck) {\n log.error(\"Download incomplete\");\n f.delete();\n }\n }\n\n }\n\n public DiffParser(URL url) throws IOException {\n FileUtils.makeLocalDirectory(\".temp\");\n boolean web = url.getProtocol().equals(\"http\")\n || url.getProtocol().equals(\"https\");\n if (web) {\n log.trace(\"Downloading diff file\");\n log.trace(\"URL: \" + url);\n }\n byte[] buf = download(url);\n if(web) {\n log.trace(\"Download complete\");\n }\n UnifiedDiffParser parser = new UnifiedDiffParser();\n diffs = parser.parse(preprocess(buf));\n buildDiffLines();\n for (List> diffLine : diffLines) {\n fileDiffs.add(new FileDiff(diffLine));\n }\n }\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n public byte[] download(URL url) throws IOException {\n byte[] buf = null;\n File f = new File(\".temp/\" + url.toString().hashCode());\n if(f.exists()) {\n FileInputStream fis = new FileInputStream(f);\n buf = fis.readAllBytes();\n fis.close();\n } else {\n f.createNewFile();\n new SigintHandler(this, f).register();\n try {\n URLConnection socketConn = url.openConnection();\n socketConn.setConnectTimeout(10000);\n socketConn.setReadTimeout(20000);\n BufferedInputStream bis = new BufferedInputStream(socketConn.getInputStream());\n FileOutputStream fos = new FileOutputStream(f);\n buf = bis.readAllBytes();\n fos.write(buf);\n fos.close();\n bis.close();\n downloadIntegrityCheck = true;\n } catch (IOException e) {\n log.error(e);\n System.exit(1);\n }\n }\n return buf;\n }\n\n public DiffParser(String patchPath) throws IOException {\n this(StringUtils.toURL(patchPath));\n }\n\n public int getNumOfDiffs() {\n return diffs.size();\n }\n\n public String getFileName(int diffIndex, boolean removePrefix) {\n String file = diffs.get(diffIndex).getFromFileName();\n if(file.equals(\"/dev/null\")) {\n file = diffs.get(diffIndex).getToFileName();\n }\n if(removePrefix) {\n file = file.substring(file.indexOf('/') + 1);\n }\n return file;\n }\n\n public FileDiff getFileDiff(int diffIndex) {\n return fileDiffs.get(diffIndex);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < fileDiffs.size(); i++) {\n FileDiff fileDiff = fileDiffs.get(i);\n sb.append(getFileName(i, true)).append(\"\\n\");\n sb.append(fileDiff.toString()).append(\"\\n\");\n }\n return sb.toString();\n }\n\n private void buildDiffLines() {\n diffs.forEach(diff -> {\n List> lines = new ArrayList<>();\n diff.getHunks().forEach(hunk -> {\n int fromLine = hunk.getFromFileRange().getLineStart() - 1;\n int toLine = hunk.getToFileRange().getLineStart() - 1;\n List hunkLines = hunk.getLines();\n for (Line line : hunkLines) {\n if (line.getLineType() == Line.LineType.FROM) {\n fromLine++;\n lines.add(Pair.of(fromLine, line));\n } else if (line.getLineType() == Line.LineType.TO) {\n toLine++;\n lines.add(Pair.of(toLine, line));\n } else {\n fromLine++;\n toLine++;\n }\n }\n });\n diffLines.add(lines);\n });\n }\n\n // insert '\\n' before the pattern \"diff --git\"\n private byte[] preprocess(byte[] buf) {\n String content = new String(buf);\n String[] lines = content.split(\"\\n\");\n List newLines = new ArrayList<>();\n for(int i = 0;i < lines.length;i++) {\n String line = lines[i];\n if(line.startsWith(\"diff --git\") && i > 0) {\n newLines.add(\"\");\n }\n newLines.add(line);\n }\n return StringUtils.toBytes(newLines);\n }\n\n}\n\nframework/src/main/java/ppt4j/factory/ExtractorFactory.java\n@Log4j\npublic final class ExtractorFactory {\n\n String prepatchPath, postpatchPath;\n String[] thirdPartySrcPath;\n\n @Getter\n String classPath;\n\n boolean isJar = false;\n private JarFile jarFile = null;\n\n @Setter\n Vulnerability vuln = null;\n\n final Map cachedPreExtractors = new HashMap<>();\n final Map cachedPostExtractors = new HashMap<>();\n final Map cachedBytecodeExtractors = new HashMap<>();\n\n final Map cachedPre2Class = new HashMap<>();\n final Map cachedPost2Class = new HashMap<>();\n\n public static ExtractorFactory get(String prepatchPath,\n String postpatchPath,\n String classPath,\n String... thirdPartySrcPath) {\n return new ExtractorFactory(prepatchPath, postpatchPath,\n classPath, thirdPartySrcPath);\n }\n\n public static ExtractorFactory get(Vulnerability vuln,\n DatabaseType type) {\n String prepatchPath = StringUtils.getDatabasePrepatchSrcPath(vuln);\n String postpatchPath = StringUtils.getDatabasePostpatchSrcPath(vuln);\n String classPath = Path.of(\n type.getPath(vuln.getDatabaseId()),\n vuln.getClassesTopLevelDir()\n ).toString();\n VMUtils.checkVMClassPathPresent(classPath);\n String[] thirdPartySrcPath = StringUtils.getThirdPartySrcDirsFromPrepatch(vuln);\n ExtractorFactory factory = get(prepatchPath, postpatchPath,\n classPath, thirdPartySrcPath);\n factory.vuln = vuln;\n return factory;\n }\n\n ExtractorFactory(String prepatchPath,\n String postpatchPath,\n String classPath,\n String... thirdPartySrcPath) {\n this.prepatchPath = StringUtils.resolvePath(prepatchPath);\n this.postpatchPath = StringUtils.resolvePath(postpatchPath);\n this.thirdPartySrcPath = thirdPartySrcPath;\n\n this.classPath = StringUtils.resolvePath(classPath);\n\n if(classPath.endsWith(\"jar\")) {\n isJar = true;\n try {\n jarFile = new JarFile(this.classPath);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n public JavaExtractor getPreJavaClass(String className) {\n return getJavaExtractor(className, cachedPreExtractors, DatabaseType.PREPATCH);\n }\n\n public JavaExtractor getPostJavaClass(String className) {\n return getJavaExtractor(className, cachedPostExtractors, DatabaseType.POSTPATCH);\n }\n\n @SuppressWarnings(\"all\")\n private static class CuFilter implements CompilationUnitFilter {\n\n private final Set includeClasses = new HashSet<>();\n\n private final String moduleName;\n private final String basePath;\n\n public CuFilter(String basePath, String className, Set includeClasses) {\n this.basePath = basePath;\n this.moduleName = className.substring(0, className.lastIndexOf(\".\"));\n this.includeClasses.addAll(includeClasses);\n }\n\n private boolean _exclude(String s) {\n String mod = s.substring(0, s.lastIndexOf(\".\"));\n if(mod.endsWith(moduleName)) {\n return false;\n }\n for (String className : includeClasses) {\n if(s.endsWith(className)) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean exclude(String s) {\n s = s.substring(0, s.length() - 5);\n s = s.replace(\"/\", \".\");\n return _exclude(s);\n }\n }\n\n private JavaExtractor getJavaExtractor(String className,\n Map cachedExtractors, DatabaseType type) {\n if(cachedExtractors.containsKey(className)) {\n return cachedExtractors.get(className);\n }\n if(vuln != null) {\n InputStream is = ResourceUtils.readSerializedFile(vuln.getDatabaseId(), type, className);\n if(is != null) {\n JavaExtractor extractor = FileUtils.deserializeObject(JavaExtractor.class, is);\n assert extractor != null;\n cachedExtractors.put(className, extractor);\n return extractor;\n }\n }\n Launcher temp = new Launcher();\n String basePath = type == DatabaseType.PREPATCH ? prepatchPath : postpatchPath;\n String path = Path.of(basePath, className.replace(\".\", \"/\") + \".java\").toString();\n if(!new File(path).exists()) {\n log.debug(\"File not found: \" + path);\n return JavaExtractor.nil();\n }\n temp.addInputResource(path);\n temp.buildModel();\n ImportScannerImpl importScanner = new ImportScannerImpl();\n importScanner.scan(temp.getFactory().Class().get(className));\n Set includeClasses = new HashSet<>();\n for(CtImport ctImport: importScanner.getAllImports()) {\n if(ctImport.getReference() instanceof CtTypeReference ty) {\n includeClasses.add(ty.getQualifiedName());\n }\n }\n CuFilter filter = new CuFilter(basePath, className, includeClasses);\n Launcher launcher = new Launcher();\n launcher.addInputResource(basePath);\n Arrays.stream(thirdPartySrcPath).forEach(launcher::addInputResource);\n launcher.getEnvironment().setPreserveLineNumbers(true);\n launcher.getEnvironment().setIgnoreDuplicateDeclarations(true);\n try {\n launcher.getModelBuilder().addCompilationUnitFilter(filter);\n launcher.buildModel();\n } catch (Throwable e) {\n launcher = new Launcher();\n launcher.addInputResource(basePath);\n Arrays.stream(thirdPartySrcPath).forEach(launcher::addInputResource);\n launcher.getEnvironment().setPreserveLineNumbers(true);\n launcher.getEnvironment().setIgnoreDuplicateDeclarations(true);\n launcher.buildModel();\n }\n CtClass clazz = launcher.getFactory().Class().get(className);\n if(clazz == null) {\n return JavaExtractor.nil();\n }\n JavaExtractor ex = new JavaExtractor(clazz);\n ex.parse();\n cachedExtractors.put(className, ex);\n return ex;\n }\n\n public BytecodeExtractor getBytecodeClass(String className) throws IOException {\n if(cachedBytecodeExtractors.containsKey(className)) {\n return cachedBytecodeExtractors.get(className);\n }\n BytecodeExtractor ex;\n if(isJar) {\n JarEntry entry = jarFile.getJarEntry(\n className.replace('.', '/') + \".class\");\n try {\n if(entry == null) {\n throw new IOException(\"Entry is null\");\n }\n InputStream is = jarFile.getInputStream(entry);\n ex = new BytecodeExtractor(is);\n } catch (IOException e) {\n log.debug(\"Bytecode of class \" + className + \" not found.\");\n return BytecodeExtractor.nil();\n }\n for (Iterator it = jarFile.entries().asIterator(); it.hasNext(); ) {\n JarEntry entry1 = it.next();\n if(entry1.getName().startsWith(className.replace('.', '/') + \"$\")) {\n log.debug(\"Adding inner class \" + entry1.getName() + \" from jar file.\");\n BytecodeExtractor innerEx = new BytecodeExtractor(jarFile.getInputStream(entry1));\n ex.putInnerClass(innerEx);\n }\n }\n } else {\n String dir = Path.of(classPath,\n className.replace('.', '/') + \".class\").toString();\n try {\n ex = new BytecodeExtractor(dir);\n } catch (IOException e) {\n log.debug(\"Bytecode of class \" + className + \" not found.\");\n return BytecodeExtractor.nil();\n }\n dir = dir.substring(0, dir.lastIndexOf('/'));\n File packageDir = new File(dir);\n assert packageDir.exists() && packageDir.isDirectory();\n File[] files = packageDir.listFiles();\n assert files != null;\n String regex = \".*\" + className.replace('.', '/') + \"\\\\$.*\\\\.class\";\n for (File file : files) {\n if (file.getAbsolutePath().matches(regex)) {\n BytecodeExtractor innerEx = new BytecodeExtractor(file.getAbsolutePath());\n ex.putInnerClass(innerEx);\n }\n }\n }\n ex.parse();\n cachedBytecodeExtractors.put(className, ex);\n return ex;\n }\n\n public CrossMatcher getPre2Class(String className) throws IOException {\n if(cachedPre2Class.containsKey(className)) {\n return cachedPre2Class.get(className);\n }\n CrossMatcher matcher = CrossMatcher.get(getPreJavaClass(className),\n getBytecodeClass(className), false);\n cachedPre2Class.put(className, matcher);\n return matcher;\n }\n\n public CrossMatcher getPost2Class(String className) throws IOException {\n if(cachedPost2Class.containsKey(className)) {\n return cachedPost2Class.get(className);\n }\n CrossMatcher matcher = CrossMatcher.get(getPostJavaClass(className),\n getBytecodeClass(className), true);\n cachedPost2Class.put(className, matcher);\n return matcher;\n }\n\n}", "answers": [" private static double PATCH_PRESENCE_THRESHOLD;"], "length": 3927, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "3bd3d3a2-04b4-4030-89f6-89097909c7c2", "reasoning": "The PatchAnalyzer file starts with a @Property annotation for \"ppt4j.analysis.patch.presence_threshold\". In other classes, such @Property annotations are followed by a private static field of appropriate type (e.g., double for thresholds). Therefore the next line should declare the static field that holds this configuration value.", "reasoning_model_answer": "private static double PRESENCE_THRESHOLD;", "assistant_with_reasoning": "\nThe PatchAnalyzer file starts with a @Property annotation for \"ppt4j.analysis.patch.presence_threshold\". In other classes, such @Property annotations are followed by a private static field of appropriate type (e.g., double for thresholds). Therefore the next line should declare the static field that holds this configuration value.\n\nprivate static double PRESENCE_THRESHOLD;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.389, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36599, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private static double PRESENCE_THRESHOLD;", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "import mdteam.ait.AITMod;\nimport mdteam.ait.core.AITBlockEntityTypes;\nimport mdteam.ait.core.AITBlocks;\nimport mdteam.ait.core.blocks.ConsoleGeneratorBlock;\nimport mdteam.ait.core.blocks.types.HorizontalDirectionalBlock;\nimport mdteam.ait.core.item.SonicItem;\nimport mdteam.ait.registry.ConsoleRegistry;\nimport mdteam.ait.registry.ConsoleVariantRegistry;\nimport mdteam.ait.tardis.Tardis;\nimport mdteam.ait.tardis.TardisDesktop;\nimport mdteam.ait.tardis.console.ConsoleSchema;\nimport mdteam.ait.tardis.util.AbsoluteBlockPos;\nimport mdteam.ait.tardis.util.TardisUtil;\nimport mdteam.ait.tardis.variant.console.ConsoleVariantSchema;\nimport mdteam.ait.tardis.wrapper.client.manager.ClientTardisManager;\nimport mdteam.ait.tardis.wrapper.server.manager.ServerTardisManager;\nimport net.minecraft.block.Block;\nimport net.minecraft.block.BlockState;\nimport net.minecraft.block.entity.BlockEntity;\nimport net.minecraft.block.entity.BlockEntityType;\nimport net.minecraft.entity.ItemEntity;\nimport net.minecraft.entity.player.PlayerEntity;\nimport net.minecraft.item.EndCrystalItem;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.nbt.NbtCompound;\nimport net.minecraft.network.listener.ClientPlayPacketListener;\nimport net.minecraft.network.packet.Packet;\nimport net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket;\nimport net.minecraft.sound.SoundCategory;\nimport net.minecraft.sound.SoundEvents;\nimport net.minecraft.util.Identifier;\nimport net.minecraft.util.math.BlockPos;\nimport net.minecraft.world.World;\nimport org.jetbrains.annotations.Nullable;\nimport java.util.List;\nimport java.util.UUID;\nimport static mdteam.ait.core.blockentities.ConsoleBlockEntity.nextConsole;\nimport static mdteam.ait.core.blockentities.ConsoleBlockEntity.nextVariant;\nimport static mdteam.ait.tardis.util.TardisUtil.isClient;", "context": "src/main/java/mdteam/ait/core/blockentities/ConsoleGeneratorBlockEntity.java\npackage mdteam.ait.core.blockentities;\n\n\n\n\npublic class ConsoleGeneratorBlockEntity extends BlockEntity {\n\n private Identifier type;\n private Identifier variant;\n\n public ConsoleGeneratorBlockEntity(BlockPos pos, BlockState state) {\n super(AITBlockEntityTypes.CONSOLE_GENERATOR_ENTITY_TYPE, pos, state);\n this.type = ConsoleRegistry.HARTNELL.id();\n }\n\n public void useOn(World world, boolean sneaking, PlayerEntity player) {\n //if(world != TardisUtil.getTardisDimension()) return;\n if(player.getMainHandStack().getItem() instanceof SonicItem) {\n\n NbtCompound nbt = player.getMainHandStack().getOrCreateNbt();\n\n if(!nbt.contains(\"tardis\")) return;\n\n ConsoleBlockEntity consoleBlockEntity = new ConsoleBlockEntity(pos,AITBlocks.CONSOLE.getDefaultState());\n\n consoleBlockEntity.setType(this.getConsoleSchema());\n consoleBlockEntity.setVariant(this.getConsoleVariant());\n\n this.getWorld().setBlockState(this.pos, AITBlocks.CONSOLE.getDefaultState());\n this.getWorld().addBlockEntity(consoleBlockEntity);\n\n world.playSound(null, this.pos, SoundEvents.BLOCK_BEACON_POWER_SELECT, SoundCategory.BLOCKS, 0.5f, 1.0f);\n\n /*if(!player.isCreative()) {\n player.getMainHandStack().decrement(1);\n // ItemEntity item = new ItemEntity(player.getWorld(), player.getX(), player.getY(), player.getZ(), new ItemStack(AITBlocks.CONSOLE_GENERATOR));\n // this.getWorld().spawnEntity(item);\n }*/\n return;\n }\n\n world.playSound(null, this.pos, SoundEvents.BLOCK_SCULK_CHARGE, SoundCategory.BLOCKS, 0.5f, 1.0f);\n\n if (sneaking) {\n this.changeConsole(nextVariant(this.getConsoleVariant()));\n } else\n this.changeConsole(nextConsole(this.getConsoleSchema()));\n }\n\n @Override\n public void writeNbt(NbtCompound nbt) {\n super.writeNbt(nbt);\n if(this.type != null)\n nbt.putString(\"console\", this.type.toString());\n if (this.variant != null)\n nbt.putString(\"variant\", this.variant.toString());\n }\n\n public ConsoleSchema getConsoleSchema() {\n if (type == null) {\n this.setConsoleSchema(ConsoleRegistry.HARTNELL.id());\n }\n\n return ConsoleRegistry.REGISTRY.get(type);\n }\n\n private void setConsoleSchema(Identifier type) {\n this.type = type;\n markDirty();\n if(this.getWorld() == null) return;\n this.getWorld().updateListeners(this.pos, this.getCachedState(), this.getCachedState(), Block.NOTIFY_LISTENERS);\n }\n\n public ConsoleVariantSchema getConsoleVariant() {\n\nsrc/main/java/mdteam/ait/core/blocks/types/HorizontalDirectionalBlock.java\npublic class HorizontalDirectionalBlock extends Block {\n\n public static final DirectionProperty FACING = HorizontalFacingBlock.FACING;\n\n public HorizontalDirectionalBlock(Settings settings) {\n super(settings);\n\n this.setDefaultState(this.stateManager.getDefaultState().with(FACING, Direction.NORTH));\n }\n\n @Nullable\n @Override\n public BlockState getPlacementState(ItemPlacementContext ctx) {\n return this.getDefaultState().with(FACING, ctx.getHorizontalPlayerFacing().getOpposite());\n }\n\n @Override\n protected void appendProperties(StateManager.Builder builder) {\n builder.add(FACING);\n }\n}\n\nsrc/main/java/mdteam/ait/registry/ConsoleRegistry.java\npublic class ConsoleRegistry {\n public static final SimpleRegistry REGISTRY = FabricRegistryBuilder.createSimple(RegistryKey.ofRegistry(new Identifier(AITMod.MOD_ID, \"console\"))).buildAndRegister();\n public static ConsoleSchema register(ConsoleSchema schema) {\n return Registry.register(REGISTRY, schema.id(), schema);\n }\n\n //public static ConsoleSchema BOREALIS;\n public static ConsoleSchema CORAL; // @TODO implement the new coral when its made again\n public static ConsoleSchema HARTNELL;\n //public static ConsoleSchema TEMP; // @TODO implement the new hudolin when its made again\n\n public static void init() {\n HARTNELL = register(new HartnellConsole());\n //BOREALIS = register(new BorealisConsole());\n CORAL = register(new CoralConsole());\n //TEMP = register(new TempConsole());\n }\n}\n\nsrc/main/java/mdteam/ait/tardis/wrapper/server/manager/ServerTardisManager.java\npublic class ServerTardisManager extends TardisManager {\n\n public static final Identifier SEND = new Identifier(\"ait\", \"send_tardis\");\n public static final Identifier UPDATE = new Identifier(\"ait\", \"update_tardis\");\n private static final ServerTardisManager instance = new ServerTardisManager();\n // Changed from MultiMap to HashMap to fix some concurrent issues, maybe\n private final ConcurrentHashMap> subscribers = new ConcurrentHashMap<>(); // fixme most of the issues with tardises on client when the world gets reloaded is because the subscribers dont get readded so the client stops getting informed, either save this somehow or make sure the client reasks on load.\n\n public final ConcurrentHashMap> exterior_subscribers = new ConcurrentHashMap<>();\n public final ConcurrentHashMap> interior_subscribers = new ConcurrentHashMap<>();\n\n public ServerTardisManager() {\n ServerPlayNetworking.registerGlobalReceiver(\n ClientTardisManager.ASK, (server, player, handler, buf, responseSender) -> {\n UUID uuid = buf.readUuid();\n if (player == null) return;\n addSubscriberToTardis(player, uuid);\n this.sendTardis(player, uuid);\n\n }\n );\n\n ServerPlayNetworking.registerGlobalReceiver(\n ClientTardisManager.LET_KNOW_UNLOADED, (server, player, handler, buf, responseSender) -> {\n UUID uuid = buf.readUuid();\n if (player == null) return;\n removeSubscriberToTardis(player, uuid);\n }\n );\n\n ServerPlayNetworking.registerGlobalReceiver(\n ClientTardisManager.ASK_POS, (server, player, handler, buf, responseSender) -> {\n BlockPos pos = buf.readBlockPos();\n UUID uuid = null;\n for (Tardis tardis : this.getLookup().values()) {\n if (!tardis.getTravel().getPosition().equals(pos)) continue;\n\n uuid = tardis.getUuid();\n }\n if (uuid == null)\n return;\n addSubscriberToTardis(player, uuid);\n this.sendTardis(player, uuid);\n }\n );\n\n ServerLifecycleEvents.SERVER_STOPPING.register(server -> {\n // force all dematting to go flight and all matting to go land\n for (Tardis tardis : this.getLookup().values()) {\n if (tardis.getTravel().getState() == TardisTravel.State.DEMAT) {\n tardis.getTravel().toFlight();\n } else if (tardis.getTravel().getState() == TardisTravel.State.MAT) {\n tardis.getTravel().forceLand();\n }\n\n tardis.getDoor().closeDoors();\n }\n\n this.reset();\n });\n ServerLifecycleEvents.SERVER_STARTED.register(server -> this.loadTardises());\n ServerTickEvents.END_SERVER_TICK.register(server -> {\n // fixme would this cause lag?\n for (Tardis tardis : ServerTardisManager.getInstance().getLookup().values()) {\n tardis.tick(server);\n }\n });\n ServerTickEvents.END_WORLD_TICK.register(world -> {\n // fixme lag?\n for (Tardis tardis : ServerTardisManager.getInstance().getLookup().values()) {\n tardis.tick(world);\n }\n });\n ServerTickEvents.START_SERVER_TICK.register(server -> {\n for (Tardis tardis : ServerTardisManager.getInstance().getLookup().values()) {\n tardis.startTick(server);\n }\n });\n }\n\n /**\n * Adds a subscriber to the Tardis\n * @param serverPlayerEntity PLAYER\n * @param tardisUUID TARDIS UUID\n */\n public void addSubscriberToTardis(ServerPlayerEntity serverPlayerEntity, UUID tardisUUID) {\n if (this.subscribers.containsKey(tardisUUID)) {\n this.subscribers.get(tardisUUID).add(serverPlayerEntity.getUuid());\n } else {\n List subscriber_list = new CopyOnWriteArrayList<>();\n subscriber_list.add(serverPlayerEntity.getUuid());\n this.subscribers.put(tardisUUID, subscriber_list);\n }\n\n }\n\n /**\n * Adds an exterior subscriber to the Tardis.\n *\n * @param player the server player entity to add as a subscriber\n * @param uuid the UUID of the subscriber\n */\n public void addExteriorSubscriberToTardis(ServerPlayerEntity player, UUID uuid) {\n if (this.exterior_subscribers.containsKey(uuid)) {\n this.exterior_subscribers.get(uuid).add(player.getUuid());\n } else {\n List subscriber_list = new CopyOnWriteArrayList<>();\n subscriber_list.add(player.getUuid());\n this.exterior_subscribers.put(uuid, subscriber_list);\n }\n }\n\n /**\n * Adds an interior subscriber to the Tardis.\n *\n * @param player the ServerPlayerEntity to add as a subscriber\n * @param uuid the UUID of the subscriber\n */\n public void addInteriorSubscriberToTardis(ServerPlayerEntity player, UUID uuid) {\n if (this.interior_subscribers.containsKey(uuid)) {\n this.interior_subscribers.get(uuid).add(player.getUuid());\n } else {\n List subscriber_list = new CopyOnWriteArrayList<>();\n subscriber_list.add(player.getUuid());\n this.interior_subscribers.put(uuid, subscriber_list);\n }\n }\n\n /**\n * Removes the specified player from the exterior subscribers of the Tardis with the given UUID.\n *\n * @param player the player to remove\n * @param uuid the UUID of the Tardis\n */\n public void removeExteriorSubscriberToTardis(ServerPlayerEntity player, UUID uuid) {\n if (!this.exterior_subscribers.containsKey(uuid)) return;\n List old_uuids = this.exterior_subscribers.get(uuid);\n int i_to_remove = -1;\n for (int i = 0; i < old_uuids.size(); i++) {\n if (old_uuids.get(i).equals(player.getUuid())) {\n i_to_remove = i;\n break;\n }\n }\n if (i_to_remove == -1) return;\n old_uuids.remove(i_to_remove);\n if (old_uuids.isEmpty()) {\n this.exterior_subscribers.remove(uuid);\n } else {\n this.exterior_subscribers.put(uuid, old_uuids);\n }\n }\n\n /**\n * Removes the interior subscriber with the specified UUID for the given player.\n *\n * @param player the server player entity\n * @param uuid the UUID of the interior subscriber to be removed\n */\n public void removeInteriorSubscriberToTardis(ServerPlayerEntity player, UUID uuid) {\n if (!this.interior_subscribers.containsKey(uuid)) return;\n List old_uuids = this.interior_subscribers.get(uuid);\n int i_to_remove = -1;\n for (int i = 0; i < old_uuids.size(); i++) {\n if (old_uuids.get(i).equals(player.getUuid())) {\n i_to_remove = i;\n break;\n }\n }\n if (i_to_remove == -1) return;\n old_uuids.remove(i_to_remove);\n if (old_uuids.isEmpty()) {\n this.interior_subscribers.remove(uuid);\n } else {\n this.interior_subscribers.put(uuid, old_uuids);\n }\n }\n\n public void removePlayerFromAllTardis(ServerPlayerEntity serverPlayerEntity) {\n for (Map.Entry> entry : this.exterior_subscribers.entrySet()) {\n removeSubscriberToTardis(serverPlayerEntity, entry.getKey());\n }\n for (Map.Entry> entry : this.interior_subscribers.entrySet()) {\n removeSubscriberToTardis(serverPlayerEntity, entry.getKey());\n }\n for (Map.Entry> entry : this.subscribers.entrySet()) {\n removeSubscriberToTardis(serverPlayerEntity, entry.getKey());\n }\n }\n\n /**\n * Removes a subscriber from the TARDIS\n * @param serverPlayerEntity the player to remove from the subscribers list\n * @param tardisUUID the UUID of the TARDIS\n */\n private void removeSubscriberToTardis(ServerPlayerEntity serverPlayerEntity, UUID tardisUUID) {\n if (!this.subscribers.containsKey(tardisUUID)) return; // If the Tardis does not have any subscribers ignore this\n\n List old_uuids = this.subscribers.get(tardisUUID);\n int i_to_remove = -1;\n\n for (int i = 0; i < old_uuids.size(); i++) {\n if (old_uuids.get(i).equals(serverPlayerEntity.getUuid())) {\n i_to_remove = i;\n break;\n }\n }\n\n if (i_to_remove == -1) return; // If the player is not in the list ignore this\n\n old_uuids.remove(i_to_remove);\n if (old_uuids.isEmpty()) {\n this.subscribers.remove(tardisUUID);\n } else {\n this.subscribers.put(tardisUUID, old_uuids); // update the subscriber list in case any other subscriber was added or removed during this operation\n }\n }\n\n public ServerTardis create(AbsoluteBlockPos.Directed pos, ExteriorSchema exteriorType, ExteriorVariantSchema variantType, TardisDesktopSchema schema, boolean locked) {\n UUID uuid = UUID.randomUUID();\n\n ServerTardis tardis = new ServerTardis(uuid, pos, schema, exteriorType, variantType, locked);\n // tardis.setFuelCount(1000); // Default fuel count is 100 - cant be set here causes issues. set in PropertiesHandler instead\n //this.saveTardis(tardis);\n this.lookup.put(uuid, tardis);\n\n tardis.getTravel().placeExterior();\n tardis.getTravel().runAnimations();\n return tardis;\n }\n\n public Tardis getTardis(UUID uuid) {\n if (this.lookup.containsKey(uuid))\n return this.lookup.get(uuid);\n\n return this.loadTardis(uuid);\n }\n\n @Override\n public void loadTardis(UUID uuid, Consumer consumer) {\n consumer.accept(this.loadTardis(uuid));\n }\n\n private Tardis loadTardis(UUID uuid) {\n File file = ServerTardisManager.getSavePath(uuid);\n file.getParentFile().mkdirs();\n\n try {\n if (!file.exists())\n throw new IOException(\"Tardis file \" + file + \" doesn't exist!\");\n\n String json = Files.readString(file.toPath());\n ServerTardis tardis = this.gson.fromJson(json, ServerTardis.class);\n this.lookup.put(tardis.getUuid(), tardis);\n\n return tardis;\n } catch (IOException e) {\n AITMod.LOGGER.warn(\"Failed to load tardis with uuid {}!\", file);\n AITMod.LOGGER.warn(e.getMessage());\n }\n\n return null;\n }\n\n @Override\n public GsonBuilder init(GsonBuilder builder) {\n builder.registerTypeAdapter(SerialDimension.class, SerialDimension.serializer());\n return builder;\n }\n\n public void saveTardis(Tardis tardis) {\n /*File savePath = ServerTardisManager.getSavePath(tardis);\n savePath.getParentFile().mkdirs();\n\n try {\n Files.writeString(savePath.toPath(), this.gson.toJson(tardis, ServerTardis.class));\n } catch (IOException e) {\n AITMod.LOGGER.warn(\"Couldn't save Tardis {}\", tardis.getUuid());\n AITMod.LOGGER.warn(e.getMessage());\n }*/\n this.saveTardisAsync(tardis);\n }\n\n public void saveTardisAsync(Tardis tardis) {\n CompletableFuture.runAsync(() -> {\n File savePath = ServerTardisManager.getSavePath(tardis);\n savePath.getParentFile().mkdirs();\n\n try {\n Files.writeString(savePath.toPath(),\n this.gson.toJson(tardis, ServerTardis.class));\n } catch (IOException e) {\n AITMod.LOGGER.warn(\"Couldn't save Tardis {}\", tardis.getUuid());\n AITMod.LOGGER.warn(e.getMessage());\n }\n });\n }\n\n public void saveTardises() {\n List tardises = new CopyOnWriteArrayList<>(getLookup().values());\n\n // Split the tardises into multiple groups\n int numThreads = Runtime.getRuntime().availableProcessors();\n int batchSize = (int) Math.ceil((double) tardises.size() / numThreads);\n\n // Create an ExecutorService with a thread pool\n ExecutorService executorService = Executors.newFixedThreadPool(numThreads);\n\n List> tasks = new ArrayList<>();\n\n // Create a Callable for each batch of tardises\n for (int i = 0; i < tardises.size(); i += batchSize) {\n int endIndex = Math.min(i + batchSize, tardises.size());\n List batch = tardises.subList(i, endIndex);\n\n // Create a Callable to save the batch of tardises\n Callable task = () -> {\n for (Tardis tardis : batch) {\n // Save the tardis\n this.saveTardis(tardis);\n }\n return null;\n };\n\n tasks.add(task);\n }\n\n try {\n // Submit all the tasks to the ExecutorService\n List> futures = executorService.invokeAll(tasks);\n\n // Wait for all the tasks to complete\n for (Future future : futures) {\n future.get();\n }\n } catch (InterruptedException | ExecutionException e) {\n // Handle any exceptions that may occur\n AITMod.LOGGER.warn(\"Failed to save tardises []\" + e.getMessage());\n } finally {\n // Shutdown the ExecutorService\n executorService.shutdown();\n }\n }\n\n public void saveTardis() {\n for (Tardis tardis : this.lookup.values()) {\n this.saveTardis(tardis);\n }\n }\n\n\n public void sendToSubscribers(Tardis tardis) {\n if (tardis == null) return;\n if (!this.subscribers.containsKey(tardis.getUuid())) return;\n// if (!this.subscribers.containsKey(tardis.getUuid())) this.subscribeEveryone(tardis);\n MinecraftServer mc = TardisUtil.getServer();\n\n Map> subscribersCopy = new HashMap<>(this.subscribers);\n List tardisSubscribers = new CopyOnWriteArrayList<>(subscribersCopy.getOrDefault(tardis.getUuid(), Collections.emptyList()));\n\n for (UUID uuid : tardisSubscribers) {\n ServerPlayerEntity player = mc.getPlayerManager().getPlayer(uuid);\n this.sendTardis(player, tardis);\n }\n }\n\n\n private void sendTardis(ServerPlayerEntity player, UUID uuid) {\n if (player == null) return;\n this.sendTardis(player, this.getTardis(uuid));\n }\n\n private void sendTardis(ServerPlayerEntity player, Tardis tardis) {\n if (player == null) return;\n this.sendTardis(player, tardis.getUuid(), this.gson.toJson(tardis, ServerTardis.class));\n }\n\n private void sendTardis(ServerPlayerEntity player, UUID uuid, String json) {\n if (player == null) return;\n PacketByteBuf data = PacketByteBufs.create();\n data.writeUuid(uuid);\n data.writeString(json);\n\n ServerPlayNetworking.send(player, SEND, data);\n }\n\n @Override\n public void reset() {\n this.subscribers.clear();\n\n this.saveTardises();\n super.reset();\n }\n\n private static File getSavePath(UUID uuid) {\n // TODO: maybe, make WorldSavePath.AIT?\n return new File(TardisUtil.getServer().getSavePath(WorldSavePath.ROOT) + \"ait/\" + uuid + \".json\");\n }\n\n private static File getSavePath(Tardis tardis) {\n return ServerTardisManager.getSavePath(tardis.getUuid());\n }\n\n public static ServerTardisManager getInstance() {\n //System.out.println(\"getInstance() = \" + instance);\n return instance;\n }\n\n\n public void loadTardises() {\n Path savePath = TardisUtil.getServer().getSavePath(WorldSavePath.ROOT).resolve(\"ait\");\n\n File[] saved = savePath.toFile().listFiles((dir, name) ->\n name.toLowerCase().endsWith(\".json\") && !new File(dir, name).isDirectory());\n\n if (saved == null) {\n return;\n }\n\n for (String name : Stream.of(saved)\n .map(File::getName)\n .collect(Collectors.toSet())) {\n\n UUID uuid = UUID.fromString(name.substring(name.lastIndexOf(\"/\") + 1, name.lastIndexOf(\".\")));\n this.loadTardis(uuid);\n }\n }\n}\n\nsrc/main/java/mdteam/ait/tardis/Tardis.java\npublic class Tardis {\n // this is starting to get a little bloated..\n\n private final TardisTravel travel;\n private final UUID uuid;\n private TardisDesktop desktop;\n private final TardisExterior exterior;\n private TardisHandlersManager handlers;\n private boolean dirty = false;\n\n public Tardis(UUID uuid, AbsoluteBlockPos.Directed pos, TardisDesktopSchema schema, ExteriorSchema exteriorType, ExteriorVariantSchema variant) {\n this(uuid, tardis -> new TardisTravel(tardis, pos), tardis -> new TardisDesktop(tardis, schema), (tardis) -> new TardisExterior(tardis, exteriorType, variant), false);\n }\n\n protected Tardis(UUID uuid, Function travel, Function desktop, Function exterior, boolean locked) {\n this.uuid = uuid;\n this.travel = travel.apply(this);\n this.desktop = desktop.apply(this);\n this.exterior = exterior.apply(this);\n this.handlers = new TardisHandlersManager(uuid);\n }\n\n public UUID getUuid() {\n return uuid;\n }\n\n public void setDesktop(TardisDesktop desktop) {\n this.desktop = desktop;\n }\n\n public TardisDesktop getDesktop() {\n return desktop;\n }\n\n public TardisExterior getExterior() {\n return exterior;\n }\n\n public DoorHandler getDoor() {\n return this.getHandlers().getDoor();\n }\n\n // dont use this\n public void setLockedTardis(boolean bool) {\n this.getDoor().setLocked(bool);\n }\n\n public boolean getLockedTardis() {\n return this.getDoor().locked();\n }\n\n public TardisTravel getTravel() {\n return travel;\n }\n\n /**\n * Retrieves the TardisHandlersManager instance associated with the given UUID.\n *\n * @return TardisHandlersManager instance or null if it doesn't exist\n */\n public TardisHandlersManager getHandlers() {\n if (handlers == null) {\n handlers = new TardisHandlersManager(getUuid());\n }\n\n return handlers;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() == null) return false;\n Tardis tardis = (Tardis) o;\n return uuid.equals(tardis.uuid);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(uuid);\n }\n\n // fuel - because getHandlers() blah blah is annoying me\n public double addFuel(double fuel) {\n return this.getHandlers().getFuel().addFuel(fuel);\n }\n public void removeFuel(double fuel) {\n this.getHandlers().getFuel().removeFuel(fuel);\n }\n public double getFuel() {\n return this.getHandlers().getFuel().getFuel();\n }\n\n public void setFuelCount(double i) {\n this.getHandlers().getFuel().setFuelCount(i);\n }\n public boolean isRefueling() {\n return this.getHandlers().getFuel().isRefueling();\n }\n public void setRefueling(boolean b) {\n this.getHandlers().getFuel().setRefueling(b);\n }\n\n public void setIsInDanger(boolean danger) {\n this.getHandlers().getHADS().setIsInDanger(danger);\n }\n\n // unlock destop stuff\n // kill me.\n public boolean isDesktopUnlocked(TardisDesktopSchema schema) {\n return PropertiesHandler.isSchemaUnlocked(getHandlers().getProperties(), schema);\n }\n public void unlockDesktop(TardisDesktopSchema schema) {\n PropertiesHandler.setSchemaUnlocked(getHandlers().getProperties(), schema, true);\n this.markDirty();\n }\n\n // for now this just checks that the exterior is the coral growth, which is bad. but its fine for first beta\n // this should stop basic features of the tardis from happening\n public boolean isGrowth() {\n return hasGrowthExterior() || hasGrowthDesktop();\n }\n public boolean hasGrowthExterior() {\n return getExterior().getVariant().equals(ExteriorVariantRegistry.CORAL_GROWTH);\n }\n public boolean hasGrowthDesktop() {\n return getDesktop().getSchema().equals(DesktopRegistry.DEFAULT_CAVE);\n }\n\n public boolean hasPower() {\n return PropertiesHandler.getBool(this.getHandlers().getProperties(), PropertiesHandler.HAS_POWER);\n }\n public void disablePower() {\n if (!hasPower()) return;\n\n //PropertiesHandler.set(this.getHandlers().getProperties(), PropertiesHandler.POWER_DELTA, MAX_POWER_DELTA_TICKS);\n PropertiesHandler.setBool(this.getHandlers().getProperties(), PropertiesHandler.HAS_POWER, false);\n TardisEvents.LOSE_POWER.invoker().onLosePower(this);\n this.markDirty();\n }\n public void enablePower() {\n if (getFuel() <= (0.01 * FuelHandler.TARDIS_MAX_FUEL)) return; // cant enable power if not enough fuel\n if (isSiegeBeingHeld()) return; // cant re-enable while being held, this may become OP tho\n if (isSiegeMode()) setSiegeMode(false);\n if (hasPower()) return;\n\n //PropertiesHandler.set(this.getHandlers().getProperties(), PropertiesHandler.POWER_DELTA, 0);\n PropertiesHandler.setBool(this.getHandlers().getProperties(), PropertiesHandler.HAS_POWER, true);\n TardisEvents.REGAIN_POWER.invoker().onRegainPower(this);\n this.markDirty();\n }\n public void togglePower() {\n if (hasPower())\n disablePower();\n else\n enablePower();\n }\n\n\n public boolean isSiegeMode() {\n return this.getHandlers().getSiege().isSiegeMode();\n }\n public void setSiegeMode(boolean b) {\n this.getHandlers().getSiege().setSiegeMode(b);\n }\n public boolean isSiegeBeingHeld() {\n return this.getHandlers().getSiege().isSiegeBeingHeld();\n }\n public void setSiegeBeingHeld(UUID b) {\n this.getHandlers().getSiege().setSiegeBeingHeld(b);\n }\n public int getTimeInSiegeMode() {\n return this.getHandlers().getSiege().getTimeInSiegeMode();\n }\n\n public AbsoluteBlockPos.Directed position() {\n return this.getTravel().getPosition();\n }\n public AbsoluteBlockPos.Directed destination() {\n return this.getTravel().getDestination();\n }\n\n /**\n * Called at the end of a servers tick\n *\n * @param server the server being ticked\n */\n public void tick(MinecraftServer server) {\n // most of the logic is in the handlers, so we can just disable them if we're a growth\n // if (!isGrowth())\n // this.getHandlers().tick(server);\n\n // @TODO if tnt explodes in the interior (near the console), then it should crash\n\n if (isGrowth() && getDoor().isBothClosed() && !getHandlers().getInteriorChanger().isGenerating())\n getDoor().openDoors();\n if (isGrowth() && getDoor().locked() && !getHandlers().getInteriorChanger().isGenerating())\n getDoor().setLocked(false);\n\n if (isSiegeMode() && !getDoor().locked())\n getDoor().setLocked(true);\n\n this.getHandlers().tick(server);\n\n // im sure this is great for your server performace\n if (TardisChunkUtil.shouldExteriorChunkBeForced(this) && !TardisChunkUtil.isExteriorChunkForced(this)) {\n TardisChunkUtil.forceLoadExteriorChunk(this);\n } else if (!TardisChunkUtil.shouldExteriorChunkBeForced(this) && TardisChunkUtil.isExteriorChunkForced(this)) {\n TardisChunkUtil.stopForceExteriorChunk(this);\n }\n\n // autoland stuff\n // if (getTravel().getState() == TardisTravel.State.FLIGHT && PropertiesHandler.getBool(getHandlers().getProperties(), PropertiesHandler.AUTO_LAND)) {\n // getTravel().materialise();\n // }\n\n // fixme nuh uh i dont like it when it locks on land it makes me sadge, instead lock if it was locked - Loqor\n\n /*if (PropertiesHandler.getBool(getHandlers().getProperties(), PropertiesHandler.IS_FALLING) && !getHandlers().getDoor().locked()) {\n DoorHandler.lockTardis(true, this, null, true);\n }*/\n if (PropertiesHandler.getBool(getHandlers().getProperties(), PropertiesHandler.IS_FALLING)) {\n DoorHandler.lockTardis(true, this, null, true);\n }\n this.getTravel().tick(server);\n }\n\n /**\n * Called at the end of a worlds tick\n *\n * @param world the world being ticked\n */\n public void tick(ServerWorld world) {\n }\n\n /**\n * Called at the end of a clients tick, ONLY FOR CLIENT STUFF!!\n *\n * @param client the remote being ticked\n */\n public void tick(MinecraftClient client) { // fixme should likely be in ClientTardis instead, same with other server-only things should be in ServerTardis\n // referencing client stuff where it COULD be server causes problems\n if(client.player != null &&\n ClientTardisUtil.isPlayerInATardis() && ClientTardisUtil.getCurrentTardis().equals(this) &&\n this.getTravel() != null && this.getTravel().getState() != TardisTravel.State.LANDED) {\n /*if (ClientShakeUtil.shouldShake(this)) */\n ClientShakeUtil.shakeFromConsole();\n }\n\n ClientTardisUtil.tickPowerDelta();\n ClientTardisUtil.tickAlarmDelta();\n }\n\n public boolean isDirty() {\n return dirty;\n }\n\n public void markDirty() {\n dirty = true;\n }\n\n /**\n * Called at the START of a servers tick, ONLY to be used for syncing data to avoid comodification errors\n *\n * @param server the current minecraft server\n */\n public void startTick(MinecraftServer server) {\n if (this instanceof ServerTardis && isDirty()) {\n ((ServerTardis) this).sync();\n dirty = false;\n }\n }\n\n public boolean isInDanger() {\n return this.getHandlers().getHADS().isInDanger();\n }\n}\n\nsrc/main/java/mdteam/ait/core/AITBlockEntityTypes.java\npublic class AITBlockEntityTypes implements NeptuneBlockEntityInit {\n\n public static BlockEntityType EXTERIOR_BLOCK_ENTITY_TYPE = FabricBlockEntityTypeBuilder.create(ExteriorBlockEntity::new, AITBlocks.EXTERIOR_BLOCK).build();\n public static BlockEntityType DOOR_BLOCK_ENTITY_TYPE = FabricBlockEntityTypeBuilder.create(DoorBlockEntity::new, AITBlocks.DOOR_BLOCK).build();\n public static BlockEntityType CONSOLE_BLOCK_ENTITY_TYPE = FabricBlockEntityTypeBuilder.create(ConsoleBlockEntity::new, AITBlocks.CONSOLE).build();\n public static BlockEntityType CONSOLE_GENERATOR_ENTITY_TYPE = FabricBlockEntityTypeBuilder.create(ConsoleGeneratorBlockEntity::new, AITBlocks.CONSOLE_GENERATOR).build();\n public static BlockEntityType CORAL_BLOCK_ENTITY_TYPE = FabricBlockEntityTypeBuilder.create(CoralBlockEntity::new, AITBlocks.CORAL_PLANT).build();\n public static BlockEntityType AIT_RADIO_BLOCK_ENTITY_TYPE = FabricBlockEntityTypeBuilder.create(AITRadioBlockEntity::new, AITBlocks.RADIO).build();\n}\n\nsrc/main/java/mdteam/ait/core/blockentities/ConsoleBlockEntity.java\npublic static ConsoleVariantSchema nextVariant(ConsoleVariantSchema current) {\n List list = ConsoleVariantRegistry.withParent(current.parent());\n\n int idx = list.indexOf(current);\n if (idx < 0 || idx+1 == list.size()) return list.get(0);\n return list.get(idx + 1);\n}\n\nsrc/main/java/mdteam/ait/tardis/variant/console/ConsoleVariantSchema.java\npublic abstract class ConsoleVariantSchema {\n private final Identifier parent;\n private final Identifier id;\n\n protected ConsoleVariantSchema(Identifier parent, Identifier id) {\n this.parent = parent;\n this.id = id;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() == null) return false;\n\n ConsoleVariantSchema that = (ConsoleVariantSchema) o;\n\n return id.equals(that.id);\n }\n\n public ConsoleSchema parent() { return ConsoleRegistry.REGISTRY.get(this.parent); }\n public Identifier id() { return id; }\n public Identifier clientId() { return id().withPath(id().getPath() + \"_client\"); }\n\n public static Object serializer() {\n return new Serializer();\n }\n\n private static class Serializer implements JsonSerializer, JsonDeserializer {\n\n @Override\n public ConsoleVariantSchema deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {\n Identifier id;\n\n try {\n id = new Identifier(json.getAsJsonPrimitive().getAsString());\n } catch (InvalidIdentifierException e) {\n id = new Identifier(AITMod.MOD_ID, \"console/borealis\");\n }\n\n return ConsoleVariantRegistry.REGISTRY.get(id);\n }\n\n @Override\n public JsonElement serialize(ConsoleVariantSchema src, Type typeOfSrc, JsonSerializationContext context) {\n return new JsonPrimitive(src.id().toString());\n }\n }\n}\n\nsrc/main/java/mdteam/ait/tardis/util/TardisUtil.java\npublic static boolean isClient() {\n return !TardisUtil.isServer();\n}\n\nsrc/main/java/mdteam/ait/core/blockentities/ConsoleBlockEntity.java\npublic static ConsoleSchema nextConsole(ConsoleSchema current) {\n List list = ConsoleRegistry.REGISTRY.stream().toList();\n\n int idx = list.indexOf(current);\n if (idx < 0 || idx+1 == list.size()) return list.get(0);\n return list.get(idx + 1);\n}\n\nsrc/main/java/mdteam/ait/core/blocks/ConsoleGeneratorBlock.java\npublic class ConsoleGeneratorBlock extends HorizontalDirectionalBlock implements BlockEntityProvider {\n\n public ConsoleGeneratorBlock(Settings settings) {\n super(settings);\n }\n\n @Nullable\n @Override\n public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {\n return new ConsoleGeneratorBlockEntity(pos, state);\n }\n\n @Override\n public BlockState getAppearance(BlockState state, BlockRenderView renderView, BlockPos pos, Direction side, @Nullable BlockState sourceState, @Nullable BlockPos sourcePos) {\n return super.getAppearance(state, renderView, pos, side, sourceState, sourcePos);\n }\n\n @Override\n public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {\n BlockEntity blockEntity = world.getBlockEntity(pos);\n if (blockEntity instanceof ConsoleGeneratorBlockEntity consoleGeneratorBlockEntity)\n consoleGeneratorBlockEntity.useOn(world, player.isSneaking(), player);\n return ActionResult.SUCCESS;\n }\n}\n\nsrc/main/java/mdteam/ait/AITMod.java\npublic class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true;\n\n public static final AITConfig AIT_CONFIG = AITConfig.createAndLoad(); // if this doesnt exist for you run data gen\n public static final NeptuneItemGroup AIT_ITEM_GROUP = new NeptuneItemGroup(new Identifier(AITMod.MOD_ID, \"item_group\"), AITItems.TARDIS_ITEM.getDefaultStack());\n public static final ComponentKey RADIONBT =\n ComponentRegistry.getOrCreate(new Identifier(AITMod.MOD_ID, \"radionbt\"), RadioNBTComponent.class);\n\n @Override\n public void onInitialize() {\n ServerAITNetworkManager.init();\n ConsoleRegistry.init();\n DesktopRegistry.init();\n ExteriorRegistry.init();\n HumsRegistry.init();\n CreakRegistry.init();\n SequenceRegistry.init();\n\n // These 3 have client registries which also need registering to.\n ConsoleVariantRegistry.init();\n ExteriorVariantRegistry.init();\n DoorRegistry.init();\n\n NeptuneInitHandler.register(AITItems.class, MOD_ID);\n NeptuneInitHandler.register(AITBlocks.class, MOD_ID);\n NeptuneInitHandler.register(AITSounds.class, MOD_ID);\n NeptuneInitHandler.register(AITBlockEntityTypes.class, MOD_ID);\n NeptuneInitHandler.register(AITEntityTypes.class, MOD_ID);\n\n\n TardisUtil.init();\n TardisManager.getInstance();\n TardisManager.init();\n RiftChunkManager.init();\n TardisCriterions.init();\n\n entityAttributeRegister();\n\n // ip support\n if (DependencyChecker.hasPortals())\n PortalsHandler.init();\n\n if (DependencyChecker.hasRegeneration())\n RegenHandler.init();\n\n CommandRegistrationCallback.EVENT.register(((dispatcher, registryAccess, environment) -> {\n TeleportInteriorCommand.register(dispatcher);\n UnlockInteriorsCommand.register(dispatcher);\n SummonTardisCommand.register(dispatcher);\n SetLockedCommand.register(dispatcher);\n // SetHumCommand.register(dispatcher);\n SetFuelCommand.register(dispatcher);\n AddFuelCommand.register(dispatcher);\n RemoveFuelCommand.register(dispatcher);\n ToggleHumCommand.register(dispatcher);\n ToggleAlarmCommand.register(dispatcher);\n ToggleSiegeModeCommand.register(dispatcher);\n RiftChunkCommand.register(dispatcher);\n RealWorldCommand.register(dispatcher);\n }));\n\n ServerBlockEntityEvents.BLOCK_ENTITY_LOAD.register(((blockEntity, world) -> {\n // fixme this doesnt seem to run??\n if (blockEntity instanceof ConsoleBlockEntity console) {\n console.markNeedsSyncing();\n }\n }));\n\n TardisEvents.LANDED.register((tardis -> {\n // stuff for resetting the ExteriorAnimation\n if (tardis.getTravel().getPosition().getWorld().getBlockEntity(tardis.getTravel().getExteriorPos()) instanceof ExteriorBlockEntity entity) {\n entity.getAnimation().setupAnimation(tardis.getTravel().getState());\n }\n }));\n\n TardisEvents.DEMAT.register((tardis -> {\n if (tardis.isGrowth() || tardis.getHandlers().getInteriorChanger().isGenerating() || PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.HANDBRAKE) || PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.IS_FALLING) || tardis.isRefueling())\n return true; // cancelled\n\n if (tardis.getDoor().isOpen() /*|| !tardis.getDoor().locked()*/)\n return true;\n\n for (PlayerEntity player : TardisUtil.getPlayersInInterior(tardis)) {\n TardisCriterions.TAKEOFF.trigger((ServerPlayerEntity) player);\n }\n return false;\n }));\n\n TardisEvents.MAT.register((tardis -> {\n // Check that the tardis has finished flight\n boolean flightDone = tardis.getHandlers().getFlight().hasFinishedFlight();\n\n // Check if the Tardis is on cooldown\n boolean isCooldown = FlightUtil.isMaterialiseOnCooldown(tardis);\n\n // Check if the destination is already occupied\n boolean isDestinationOccupied = !tardis.getTravel().getPosition().equals(tardis.getTravel().getDestination()) && !tardis.getTravel().checkDestination();\n\n return /*!flightDone ||*/ isCooldown || isDestinationOccupied;\n }));\n\n TardisEvents.CRASH.register((tardis -> {\n for (PlayerEntity player : TardisUtil.getPlayersInInterior(tardis)) {\n TardisCriterions.CRASH.trigger((ServerPlayerEntity) player);\n }\n }));\n\n TardisEvents.OUT_OF_FUEL.register(Tardis::disablePower);\n TardisEvents.LOSE_POWER.register((tardis -> {\n if (tardis.getDesktop().getConsolePos() != null) {\n TardisUtil.getTardisDimension().playSound(null, tardis.getDesktop().getConsolePos(), AITSounds.SHUTDOWN, SoundCategory.AMBIENT, 10f, 1f);\n }\n\n // disabling protocols\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.AUTO_LAND, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.ANTIGRAVS_ENABLED, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.HAIL_MARY, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.HADS_ENABLED, false);\n }));\n TardisEvents.REGAIN_POWER.register((tardis -> {\n if (tardis.getDesktop().getConsolePos() != null) {\n TardisUtil.getTardisDimension().playSound(null, tardis.getDesktop().getConsolePos(), AITSounds.POWERUP, SoundCategory.AMBIENT, 10f, 1f);\n }\n }));\n\n ServerPlayNetworking.registerGlobalReceiver(ConsoleBlockEntity.ASK, ((server, player, handler, buf, responseSender) -> {\n if (player.getServerWorld().getRegistryKey() != AITDimensions.TARDIS_DIM_WORLD) return;\n\n BlockPos consolePos = buf.readBlockPos();\n // fixme the gotten block entity is always null, shit.\n if (player.getServerWorld().getBlockEntity(consolePos) instanceof ConsoleBlockEntity console)\n console.markNeedsSyncing();\n }));\n\n\n ServerPlayNetworking.registerGlobalReceiver(ServerHumHandler.RECEIVE, ((server, player, handler, buf, responseSender) -> {\n Tardis tardis = ServerTardisManager.getInstance().getTardis(buf.readUuid());\n HumSound hum = HumSound.fromName(buf.readString(), buf.readString());\n\n if (tardis == null || hum == null) return;\n\n tardis.getHandlers().getHum().setHum(hum);\n }));\n\n ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {\n DesktopRegistry.syncToClient(handler.getPlayer());\n });\n\n\n ServerPlayNetworking.registerGlobalReceiver(TardisDesktop.CACHE_CONSOLE, (server, player, handler, buf, responseSender) -> {\n Tardis tardis = ServerTardisManager.getInstance().getTardis(buf.readUuid());\n TardisUtil.getServer().execute(() -> {\n if (tardis == null) return;\n tardis.getDesktop().cacheConsole();\n });\n });\n\n AIT_ITEM_GROUP.initialize();\n }\n\n public void entityAttributeRegister() {\n FabricDefaultAttributeRegistry.register(AITEntityTypes.CONTROL_ENTITY_TYPE, ConsoleControlEntity.createControlAttributes());\n }\n\n public static final Identifier OPEN_SCREEN_TARDIS = new Identifier(AITMod.MOD_ID, \"open_screen_tardis\"); // fixes \"AITModClient in env type SERVER\"\n\n public static void openScreen(ServerPlayerEntity player, int id, UUID tardis) {\n PacketByteBuf buf = PacketByteBufs.create();\n buf.writeInt(id);\n buf.writeUuid(tardis);\n ServerPlayNetworking.send(player, OPEN_SCREEN_TARDIS, buf);\n }\n}\n\nsrc/main/java/mdteam/ait/tardis/console/ConsoleSchema.java\npublic abstract class ConsoleSchema {\n private final Identifier id;\n private final String name;\n\n protected ConsoleSchema(Identifier id, String name) {\n this.id = id;\n this.name = name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() == null) return false;\n\n ConsoleSchema that = (ConsoleSchema) o;\n\n return id.equals(that.id);\n }\n\n public Identifier id() {\n return this.id;\n }\n public String name() { return this.name; }\n\n @Override\n public String toString() {\n return this.name();\n }\n\n //@TODO protocol abstraction with numbered letters\n\n public abstract ControlTypes[] getControlTypes(); // fixme this kinda sucks idk\n\n public static Object serializer() {\n return new Serializer();\n }\n\n private static class Serializer implements JsonSerializer, JsonDeserializer {\n\n @Override\n public ConsoleSchema deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {\n Identifier id;\n\n try {\n id = new Identifier(json.getAsJsonPrimitive().getAsString());\n } catch (InvalidIdentifierException e) {\n id = CapsuleExterior.REFERENCE;\n }\n\n return ConsoleRegistry.REGISTRY.get(id);\n }\n\n @Override\n public JsonElement serialize(ConsoleSchema src, Type typeOfSrc, JsonSerializationContext context) {\n return new JsonPrimitive(src.id().toString());\n }\n }\n}", "answers": [" if (variant == null) {"], "length": 3562, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "70b9a028-5b17-450a-a640-77b9f9e70dc5", "reasoning": "The method getConsoleVariant() is being defined. Following the pattern of getConsoleSchema(), the first line inside the method should check whether the stored variant identifier is null and, if so, initialize it. Therefore the next line after the opening brace is the null‑check condition.", "reasoning_model_answer": "if (variant == null) {", "assistant_with_reasoning": "\nThe method getConsoleVariant() is being defined. Following the pattern of getConsoleSchema(), the first line inside the method should check whether the stored variant identifier is null and, if so, initialize it. Therefore the next line after the opening brace is the null‑check condition.\n\nif (variant == null) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.401, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37845, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "if (variant == null) {", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "import gnu.trove.iterator.TIntObjectIterator;\nimport gnu.trove.iterator.TLongIterator;\nimport gnu.trove.list.array.TIntArrayList;\nimport gnu.trove.list.array.TLongArrayList;\nimport gnu.trove.map.hash.TIntObjectHashMap;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.RandomAccessFile;\nimport java.text.DecimalFormat;\nimport java.text.MessageFormat;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map.Entry;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport net.osmand.ResultMatcher;\nimport net.osmand.binary.BinaryMapAddressReaderAdapter.AddressRegion;\nimport net.osmand.binary.BinaryMapAddressReaderAdapter.CitiesBlock;\nimport net.osmand.binary.BinaryMapIndexReader.MapIndex;\nimport net.osmand.binary.BinaryMapIndexReader.MapObjectStat;\nimport net.osmand.binary.BinaryMapIndexReader.MapRoot;\nimport net.osmand.binary.BinaryMapIndexReader.SearchFilter;\nimport net.osmand.binary.BinaryMapIndexReader.SearchPoiTypeFilter;\nimport net.osmand.binary.BinaryMapIndexReader.SearchRequest;\nimport net.osmand.binary.BinaryMapIndexReader.TagValuePair;\nimport net.osmand.binary.BinaryMapPoiReaderAdapter.PoiRegion;\nimport net.osmand.binary.BinaryMapPoiReaderAdapter.PoiSubType;\nimport net.osmand.binary.BinaryMapRouteReaderAdapter.RouteRegion;\nimport net.osmand.binary.BinaryMapRouteReaderAdapter.RouteSubregion;\nimport net.osmand.binary.BinaryMapRouteReaderAdapter.RouteTypeRule;\nimport net.osmand.binary.BinaryMapTransportReaderAdapter.TransportIndex;\nimport net.osmand.data.Amenity;\nimport net.osmand.data.Building;\nimport net.osmand.data.City;\nimport net.osmand.data.MapObject;\nimport net.osmand.data.Street;\nimport net.osmand.osm.PoiCategory;\nimport net.osmand.util.MapUtils;\nimport com.google.protobuf.CodedOutputStream;\nimport com.google.protobuf.WireFormat;", "context": "src/net/osmand/binary/BinaryInspector.java\n\t\t\t\t} else if (part instanceof RouteRegion) {\n\t\t\t\t\tous.writeTag(OsmandOdb.OsmAndStructure.ROUTINGINDEX_FIELD_NUMBER, WireFormat.WIRETYPE_FIXED32_LENGTH_DELIMITED);\n\t\t\t\t\tmap = \"Routing\";\n\t\t\t\t} else {\n\t\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t\t}\n\t\t\t\twriteInt(ous, part.getLength());\n\t\t\t\tcopyBinaryPart(ous, BUFFER_TO_READ, raf, part.getFilePointer(), part.getLength());\n\t\t\t\tSystem.out.println(MessageFormat.format(\"{2} part {0} is extracted {1} bytes\",\n\t\t\t\t\t\tnew Object[]{part.getName(), part.getLength(), map}));\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tous.writeInt32(OsmandOdb.OsmAndStructure.VERSIONCONFIRM_FIELD_NUMBER, version);\n\t\tous.flush();\n\t\tfout.close();\n\t\t\n\t\t\n\t\treturn list;\n\t}\n\n\n\tpublic static void copyBinaryPart(CodedOutputStream ous, byte[] BUFFER, RandomAccessFile raf, long fp, int length)\n\t\t\tthrows IOException {\n\t\traf.seek(fp);\n\t\tint toRead = length;\n\t\twhile (toRead > 0) {\n\t\t\tint read = raf.read(BUFFER);\n\t\t\tif (read == -1) {\n\t\t\t\tthrow new IllegalArgumentException(\"Unexpected end of file\");\n\t\t\t}\n\t\t\tif (toRead < read) {\n\t\t\t\tread = toRead;\n\t\t\t}\n\t\t\tous.writeRawBytes(BUFFER, 0, read);\n\t\t\ttoRead -= read;\n\t\t}\n\t}\n\t\n\n\tprotected String formatBounds(int left, int right, int top, int bottom){\n\t\tdouble l = MapUtils.get31LongitudeX(left);\n\t\tdouble r = MapUtils.get31LongitudeX(right);\n\t\tdouble t = MapUtils.get31LatitudeY(top);\n\t\tdouble b = MapUtils.get31LatitudeY(bottom);\n\t\treturn formatLatBounds(l, r, t, b); \n\t}\n\t\n\tprotected String formatLatBounds(double l, double r, double t, double b){\n\t\tMessageFormat format = new MessageFormat(\"(left top - right bottom) : {0,number,#.####}, {1,number,#.####} NE - {2,number,#.####}, {3,number,#.####} NE\", new Locale(\"EN\", \"US\"));\n\t\treturn format.format(new Object[]{l, t, r, b}); \n\t}\n\t\n\tpublic void printFileInformation(String fileName) throws IOException {\n\t\tFile file = new File(fileName);\n\t\tif(!file.exists()){\n\t\t\tprintln(\"Binary OsmAnd index \" + fileName + \" was not found.\");\n\t\t\treturn;\n\t\t}\n\t\tprintFileInformation(file);\n\t}\n\t\n\t\n\tpublic void printFileInformation(File file) throws IOException {\n\t\tRandomAccessFile r = new RandomAccessFile(file.getAbsolutePath(), \"r\");\n\t\tprintFileInformation(r, file);\n\t}\n\n\tpublic void printFileInformation(RandomAccessFile r, File file ) throws IOException {\n\t\tString filename = file.getName();\n\t\ttry {\n\t\t\tBinaryMapIndexReader index = new BinaryMapIndexReader(r, file);\n\t\t\tint i = 1;\n\t\t\tprintln(\"Binary index \" + filename + \" version = \" + index.getVersion() +\" edition = \" + new Date(index.getDateCreated()));\n\t\t\tfor(BinaryIndexPart p : index.getIndexes()){\n\t\t\t\tString partname = \"\";\n\t\t\t\tif(p instanceof MapIndex ){\n\t\t\t\t\tpartname = \"Map\";\n\t\t\t\t} else if(p instanceof TransportIndex){\n\t\t\t\t\tpartname = \"Transport\";\n\t\t\t\t} else if(p instanceof RouteRegion){\n\t\t\t\t\tpartname = \"Routing\";\n\t\t\t\t} else if(p instanceof PoiRegion){\n\t\t\t\t\tpartname = \"Poi\";\n\t\t\t\t} else if(p instanceof AddressRegion){\n\t\t\t\t\tpartname = \"Address\";\n\t\t\t\t}\n\t\t\t\tString name = p.getName() == null ? \"\" : p.getName(); \n\t\t\t\tprintln(MessageFormat.format(\"{0} {1} data {3} - {2,number,#} bytes\",\n\t\t\t\t\t\tnew Object[]{i, partname, p.getLength(), name}));\n\t\t\t\tif(p instanceof TransportIndex){\n\t\t\t\t\tTransportIndex ti = ((TransportIndex) p);\n\t\t\t\t\tint sh = (31 - BinaryMapIndexReader.TRANSPORT_STOP_ZOOM);\n\t\t\t\t\tprintln(\"\\tBounds \" + formatBounds(ti.getLeft() << sh, ti.getRight() << sh, \n\t\t\t\t\t\t\tti.getTop() << sh, ti.getBottom() << sh));\n\t\t\t\t} else if(p instanceof RouteRegion){\n\t\t\t\t\tRouteRegion ri = ((RouteRegion) p);\n\t\t\t\t\tprintln(\"\\tBounds \" + formatLatBounds(ri.getLeftLongitude(), ri.getRightLongitude(), \n\t\t\t\t\t\t\tri.getTopLatitude(), ri.getBottomLatitude()));\n\t\t\t\t\tif((vInfo != null && vInfo.isVrouting())){\n\t\t\t\t\t\tprintRouteDetailInfo(index, (RouteRegion) p);\n\t\t\t\t\t}\n\t\t\t\t} else if(p instanceof MapIndex){\n\t\t\t\t\tMapIndex m = ((MapIndex) p);\n\t\t\t\t\tint j = 1;\n\t\t\t\t\tfor(MapRoot mi : m.getRoots()){\n\t\t\t\t\t\tprintln(MessageFormat.format(\"\\t{4}.{5} Map level minZoom = {0}, maxZoom = {1}, size = {2,number,#} bytes \\n\\t\\tBounds {3}\",\n\t\t\t\t\t\t\t\tnew Object[] {\n\t\t\t\t\t\t\t\tmi.getMinZoom(), mi.getMaxZoom(), mi.getLength(), \n\t\t\t\t\t\t\t\tformatBounds(mi.getLeft(), mi.getRight(), mi.getTop(), mi.getBottom()), \n\t\t\t\t\t\t\t\ti, j++}));\n\t\t\t\t\t}\n\t\t\t\t\tif((vInfo != null && vInfo.isVmap())){\n\t\t\t\t\t\tprintMapDetailInfo(index, m);\n\t\t\t\t\t}\n\t\t\t\t} else if(p instanceof PoiRegion && (vInfo != null && vInfo.isVpoi())){\n\t\t\t\t\tprintPOIDetailInfo(vInfo, index, (PoiRegion) p);\n\t\t\t\t} else if (p instanceof AddressRegion) {\n\t\t\t\t\tList cities = ((AddressRegion) p).cities;\n\nsrc/net/osmand/binary/BinaryMapIndexReader.java\npublic static class MapIndex extends BinaryIndexPart {\n\tList roots = new ArrayList();\n\t\t\n\tMap > encodingRules = new HashMap >();\n\tpublic TIntObjectMap decodingRules = new TIntObjectHashMap();\n\tpublic int nameEncodingType = 0;\n\tpublic int nameEnEncodingType = -1;\n\tpublic int refEncodingType = -1;\n\tpublic int coastlineEncodingType = -1;\n\tpublic int coastlineBrokenEncodingType = -1;\n\tpublic int landEncodingType = -1;\n\tpublic int onewayAttribute = -1;\n\tpublic int onewayReverseAttribute = -1;\n\tpublic TIntHashSet positiveLayers = new TIntHashSet(2);\n\tpublic TIntHashSet negativeLayers = new TIntHashSet(2);\n\t\t\n\tpublic Integer getRule(String t, String v){\n\t\tMap m = encodingRules.get(t);\n\t\tif(m != null){\n\t\t\treturn m.get(v);\n\t\t}\n\t\treturn null;\n\t}\n\t\t\n\tpublic List getRoots() {\n\t\treturn roots;\n\t}\n\t\t\n\tpublic TagValuePair decodeType(int type){\n\t\treturn decodingRules.get(type);\n\t}\n\n\tpublic void finishInitializingTags() {\n\t\tint free = decodingRules.size() * 2 + 1;\n\t\tcoastlineBrokenEncodingType = free++;\n\t\tinitMapEncodingRule(0, coastlineBrokenEncodingType, \"natural\", \"coastline_broken\");\n\t\tif(landEncodingType == -1){\n\t\t\tlandEncodingType = free++;\n\t\t\tinitMapEncodingRule(0, landEncodingType, \"natural\", \"land\");\n\t\t}\n\t}\n\t\t\n\tpublic boolean isRegisteredRule(int id) {\n\t\treturn decodingRules.containsKey(id);\n\t}\n\t\t\n\tpublic void initMapEncodingRule(int type, int id, String tag, String val) {\n\t\tif(!encodingRules.containsKey(tag)){\n\t\t\tencodingRules.put(tag, new HashMap());\n\t\t}\n\t\tencodingRules.get(tag).put(val, id);\n\t\tif(!decodingRules.containsKey(id)){\n\t\t\tdecodingRules.put(id, new TagValuePair(tag, val, type));\n\t\t}\n\t\t\t\n\t\tif(\"name\".equals(tag)){\n\t\t\tnameEncodingType = id;\n\t\t} else if(\"natural\".equals(tag) && \"coastline\".equals(val)){\n\t\t\tcoastlineEncodingType = id;\n\t\t} else if(\"natural\".equals(tag) && \"land\".equals(val)){\n\t\t\tlandEncodingType = id;\n\t\t} else if(\"oneway\".equals(tag) && \"yes\".equals(val)){\n\t\t\tonewayAttribute = id;\n\t\t} else if(\"oneway\".equals(tag) && \"-1\".equals(val)){\n\t\t\tonewayReverseAttribute = id;\n\t\t} else if(\"ref\".equals(tag)){\n\t\t\trefEncodingType = id;\n\t\t} else if(\"name:en\".equals(tag)){\n\t\t\tnameEnEncodingType = id;\n\t\t} else if(\"tunnel\".equals(tag)){\n\t\t\tnegativeLayers.add(id);\n\t\t} else if(\"bridge\".equals(tag)){\n\t\t\tpositiveLayers.add(id);\n\t\t} else if(\"layer\".equals(tag)){\n\t\t\tif(val != null && !val.equals(\"0\") && val.length() > 0) {\n\t\t\t\tif(val.startsWith(\"-\")) {\n\t\t\t\t\tnegativeLayers.add(id);\n\t\t\t\t} else {\n\t\t\t\t\tpositiveLayers.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean isBaseMap(){\n\t\treturn name != null && name.toLowerCase().contains(BASEMAP_NAME);\n\t}\n}\n\nsrc/net/osmand/osm/PoiCategory.java\npublic class PoiCategory extends PoiFilter {\n\n\tprivate List poiFilters = new ArrayList();\n\tprivate Set basemapPoi = null;\n\tprivate int regId;\n\tprivate String defaultTag;\n\n\tpublic PoiCategory(MapPoiTypes registry, String keyName, int regId) {\n\t\tsuper(registry, null, keyName);\n\t\tthis.regId = regId;\n\t}\n\n\tpublic void addPoiType(PoiFilter poi) {\n\t\tpoiFilters.add(poi);\n\t}\n\n\tpublic List getPoiFilters() {\n\t\treturn poiFilters;\n\t}\n\t\n\tpublic String getDefaultTag() {\n\t\tif(defaultTag == null) {\n\t\t\treturn keyName;\n\t\t}\n\t\treturn defaultTag;\n\t}\n\t\n\tpublic void setDefaultTag(String defaultTag) {\n\t\tthis.defaultTag = defaultTag;\n\t}\n\t\n\tpublic Map> putTypes(\n\t\t\tMap> acceptedTypes) {\n\t\tacceptedTypes.put(this, null);\n\t\taddReferenceTypes(acceptedTypes);\n\t\treturn acceptedTypes;\n\t}\n\n\t\n\tpublic boolean isWiki() {\n\t\treturn keyName.equals(MapPoiTypes.OSM_WIKI_CATEGORY);\n\t}\n\n\n\tpublic int ordinal() {\n\t\treturn regId;\n\t}\n\n\t\n\tpublic void addBasemapPoi(PoiType pt) {\n\t\tif(basemapPoi == null) {\n\t\t\tbasemapPoi = new HashSet();\n\t\t}\n\t\tbasemapPoi.add(pt);\n\t}\n\n\tpublic boolean containsBasemapPoi(PoiType pt) {\n\t\tif(basemapPoi == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn basemapPoi.contains(pt);\n\t}\n}\n\nsrc/net/osmand/util/MapUtils.java\npublic class MapUtils {\n\t\n // TODO change the hostname back to osm.org once HTTPS works for it\n // https://github.com/openstreetmap/operations/issues/2\n private static final String BASE_SHORT_OSM_URL = \"https://openstreetmap.org/go/\";\n\t\n\t/**\n * This array is a lookup table that translates 6-bit positive integer\n * index values into their \"Base64 Alphabet\" equivalents as specified\n * in Table 1 of RFC 2045.\n */\n private static final char intToBase64[] = {\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',\n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_', '~'\n };\n\n\tpublic static double getDistance(LatLon l, double latitude, double longitude){\n\t\treturn getDistance(l.getLatitude(), l.getLongitude(), latitude, longitude);\n\t}\n\t\n\tprivate static double scalarMultiplication(double xA, double yA, double xB, double yB, double xC, double yC) {\n\t\t// Scalar multiplication between (AB, AC)\n\t\treturn (xB - xA) * (xC - xA) + (yB- yA) * (yC -yA);\n\t}\n\n\tpublic static double getOrthogonalDistance(double lat, double lon, double fromLat, double fromLon, double toLat, double toLon) {\n\t\treturn getDistance(getProjection(lat, lon, fromLat, fromLon, toLat, toLon), lat, lon);\n\t}\n\t\n\tpublic static double getOrthogonalDistance(LatLon latLon, LatLon fromLatLon, LatLon toLatLon){\n\t\treturn getDistance(\n\t\t\t\tgetProjection(latLon.getLatitude(), latLon.getLongitude(), fromLatLon.getLatitude(),\n\t\t\t\t\t\tfromLatLon.getLongitude(), toLatLon.getLatitude(), toLatLon.getLongitude()),\n\t\t\t\tlatLon.getLatitude(), latLon.getLongitude());\n\t}\n\t\n\tpublic static LatLon getProjection(double lat, double lon, double fromLat, double fromLon, double toLat, double toLon) {\n\t\t// not very accurate computation on sphere but for distances < 1000m it is ok\n\t\tdouble mDist = (fromLat - toLat) * (fromLat - toLat) + (fromLon - toLon) * (fromLon - toLon);\n\t\tdouble projection = scalarMultiplication(fromLat, fromLon, toLat, toLon, lat, lon);\n\t\tdouble prlat;\n\t\tdouble prlon;\n\t\tif (projection < 0) {\n\t\t\tprlat = fromLat;\n\t\t\tprlon = fromLon;\n\t\t} else if (projection >= mDist) {\n\t\t\tprlat = toLat;\n\t\t\tprlon = toLon;\n\t\t} else {\n\t\t\tprlat = fromLat + (toLat - fromLat) * (projection / mDist);\n\t\t\tprlon = fromLon + (toLon - fromLon) * (projection / mDist);\n\t\t}\n\t\treturn new LatLon(prlat, prlon);\n\t}\n\t\n\tpublic static double getProjectionCoeff(double lat, double lon, double fromLat, double fromLon, double toLat, double toLon) {\n\t\t// not very accurate computation on sphere but for distances < 1000m it is ok\n\t\tdouble mDist = (fromLat - toLat) * (fromLat - toLat) + (fromLon - toLon) * (fromLon - toLon);\n\t\tdouble projection = scalarMultiplication(fromLat, fromLon, toLat, toLon, lat, lon);\n\t\tdouble prlat;\n\t\tdouble prlon;\n\t\tif (projection < 0) {\n\t\t\treturn 0;\n\t\t} else if (projection >= mDist) {\n\t\t\treturn 1;\n\t\t} else {\n\t\t\treturn (projection / mDist);\n\t\t}\n\t}\n\t\n\tprivate static double toRadians(double angdeg) {\n//\t\treturn Math.toRadians(angdeg);\n\t\treturn angdeg / 180.0 * Math.PI;\n\t}\n\t\n\t/**\n\t * Gets distance in meters\n\t */\n\tpublic static double getDistance(double lat1, double lon1, double lat2, double lon2){\n\t\tdouble R = 6372.8; // for haversine use R = 6372.8 km instead of 6371 km\n\t\tdouble dLat = toRadians(lat2-lat1);\n\t\tdouble dLon = toRadians(lon2-lon1); \n\t\tdouble a = Math.sin(dLat/2) * Math.sin(dLat/2) +\n\t\t Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) * \n\t\t Math.sin(dLon/2) * Math.sin(dLon/2); \n\t\t//double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\t\t//return R * c * 1000;\n\t\t// simplyfy haversine:\n\t\treturn (2 * R * 1000 * Math.asin(Math.sqrt(a)));\n\t}\n\t\n\t\n\t/**\n\t * Gets distance in meters\n\t */\n\tpublic static double getDistance(LatLon l1, LatLon l2){\n\t\treturn getDistance(l1.getLatitude(), l1.getLongitude(), l2.getLatitude(), l2.getLongitude());\n\t}\n\t\n\tpublic static double checkLongitude(double longitude) {\n\t\tif(longitude > -180 && longitude <= 180) {\n\t\t\treturn longitude;\n\t\t}\n\t\twhile (longitude < -180 || longitude > 180) {\n\t\t\tif (longitude < 0) {\n\t\t\t\tlongitude += 360;\n\t\t\t} else {\n\t\t\t\tlongitude -= 360;\n\t\t\t}\n\t\t}\n\t\treturn longitude;\n\t}\n\t\n\tpublic static double checkLatitude(double latitude) {\n\t\tif(latitude > -80 && latitude <= 80) {\n\t\t\treturn latitude;\n\t\t}\n\t\twhile (latitude < -90 || latitude > 90) {\n\t\t\tif (latitude < 0) {\n\t\t\t\tlatitude += 180;\n\t\t\t} else {\n\t\t\t\tlatitude -= 180;\n\t\t\t}\n\t\t}\n\t\tif(latitude < -85.0511) {\n\t\t\treturn -85.0511;\n \t\t} else if(latitude > 85.0511){\n \t\t\treturn 85.0511;\n \t\t}\n\t\treturn latitude;\n\t}\n\t\n\tpublic static int get31TileNumberX(double longitude){\n\t\tlongitude = checkLongitude(longitude);\n\t\tlong l = 1L << 31;\n\t\treturn (int)((longitude + 180d)/360d * l);\n\t}\n\tpublic static int get31TileNumberY( double latitude){\n\t\tlatitude = checkLatitude(latitude);\n\t\tdouble eval = Math.log( Math.tan(toRadians(latitude)) + 1/Math.cos(toRadians(latitude)) );\n\t\tlong l = 1L << 31;\n\t\tif(eval > Math.PI){\n\t\t\teval = Math.PI;\n\t\t}\n\t\treturn (int) ((1 - eval / Math.PI) / 2 * l);\n\t}\n\t\n\tpublic static double get31LongitudeX(int tileX){\n\t\treturn MapUtils.getLongitudeFromTile(21, tileX /1024f);\n\t}\n\t\n\tpublic static double get31LatitudeY(int tileY){\n\t\treturn MapUtils.getLatitudeFromTile(21, tileY / 1024f);\n\t}\n\t\n\t\n\t\n\t/**\n\t * \n\t * Theses methods operate with degrees (evaluating tiles & vice versa) \n\t * degree longitude measurements (-180, 180) [27.56 Minsk]\n\t// degree latitude measurements (90, -90) [53.9]\n\t */\n\t\n\tpublic static double getTileNumberX(float zoom, double longitude){\n\t\tlongitude = checkLongitude(longitude);\n\t\tfinal double powZoom = getPowZoom(zoom);\n\t\tdouble dz = (longitude + 180d)/360d * powZoom;\n\t\tif (dz >= powZoom) {\n\t\t\treturn powZoom - 0.01;\n\t\t}\n\t\treturn dz;\n\t}\n\t\n\tpublic static double getTileNumberY(float zoom, double latitude){\n\t\tlatitude = checkLatitude(latitude);\n\t\tdouble eval = Math.log( Math.tan(toRadians(latitude)) + 1/Math.cos(toRadians(latitude)) );\n\t\tif (Double.isInfinite(eval) || Double.isNaN(eval)) {\n\t\t\tlatitude = latitude < 0 ? - 89.9 : 89.9;\n\t\t\teval = Math.log( Math.tan(toRadians(latitude)) + 1/Math.cos(toRadians(latitude)) );\n\t\t}\n\t\treturn (1 - eval / Math.PI) / 2 * getPowZoom(zoom);\n\t}\n\t\n\tpublic static double getTileEllipsoidNumberY(float zoom, double latitude){\n\t\tfinal double E2 = (double) latitude * Math.PI / 180;\n\t\tfinal long sradiusa = 6378137;\n\t\tfinal long sradiusb = 6356752;\n\t\tfinal double J2 = (double) Math.sqrt(sradiusa * sradiusa - sradiusb * sradiusb)\t/ sradiusa;\n\t\tfinal double M2 = (double) Math.log((1 + Math.sin(E2))\n\t\t\t\t/ (1 - Math.sin(E2)))/ 2- J2\t* Math.log((1 + J2 * Math.sin(E2))/ (1 - J2 * Math.sin(E2))) / 2;\n\t\tfinal double B2 = getPowZoom(zoom);\n\t\treturn B2 / 2 - M2 * B2 / 2 / Math.PI;\n\t}\n\t\n\tpublic static double getLatitudeFromEllipsoidTileY(float zoom, float tileNumberY){\n\t\tfinal double MerkElipsK = 0.0000001;\n\t\tfinal long sradiusa = 6378137;\n\t\tfinal long sradiusb = 6356752;\n\t\tfinal double FExct = (double) Math.sqrt(sradiusa * sradiusa\n\t\t\t\t- sradiusb * sradiusb)\n\t\t\t\t/ sradiusa;\n\t\tfinal double TilesAtZoom = getPowZoom(zoom);\n\t\tdouble result = (tileNumberY - TilesAtZoom / 2)\n\t\t\t\t/ -(TilesAtZoom / (2 * Math.PI));\n\t\tresult = (2 * Math.atan(Math.exp(result)) - Math.PI / 2) * 180\n\t\t\t\t/ Math.PI;\n\t\tdouble Zu = result / (180 / Math.PI);\n\t\tdouble yy = (tileNumberY - TilesAtZoom / 2);\n\n\t\tdouble Zum1 = Zu;\n\t\tZu = Math.asin(1 - ((1 + Math.sin(Zum1)) * Math.pow(1 - FExct * Math.sin(Zum1), FExct))\n\t\t\t\t/ (Math.exp((2 * yy) / -(TilesAtZoom / (2 * Math.PI))) * Math.pow(1 + FExct * Math.sin(Zum1), FExct)));\n\t\twhile (Math.abs(Zum1 - Zu) >= MerkElipsK) {\n\t\t\tZum1 = Zu;\n\t\t\tZu = Math.asin(1 - ((1 + Math.sin(Zum1)) * Math.pow(1 - FExct * Math.sin(Zum1), FExct))\n\t\t\t\t\t/ (Math.exp((2 * yy) / -(TilesAtZoom / (2 * Math.PI))) * Math.pow(1 + FExct * Math.sin(Zum1), FExct)));\n\t\t}\n\n\t\treturn Zu * 180 / Math.PI;\n\t}\n\t\n\t\n\tpublic static double getTileDistanceWidth(float zoom) {\n\t\tLatLon ll = new LatLon(30, MapUtils.getLongitudeFromTile(zoom, 0));\n\t\tLatLon ll2 = new LatLon(30, MapUtils.getLongitudeFromTile(zoom, 1));\n\t\treturn getDistance(ll, ll2) ;\n\t}\n\t\n\tpublic static double getLongitudeFromTile(double zoom, double x) {\n\t\treturn x / getPowZoom(zoom) * 360.0 - 180.0;\n\t}\n\t\n\tpublic static double getPowZoom(double zoom){\n\t\tif(zoom >= 0 && zoom - Math.floor(zoom) < 0.001f){\n\t\t\treturn 1 << ((int)zoom); \n\t\t} else {\n\t\t\treturn Math.pow(2, zoom);\n\t\t}\n\t}\n\t\n\n\t\n\tpublic static float calcDiffPixelX(float rotateSin, float rotateCos, float dTileX, float dTileY, float tileSize){\n\t\treturn (rotateCos * dTileX - rotateSin * dTileY) * tileSize ;\n\t}\n\t\n\tpublic static float calcDiffPixelY(float rotateSin, float rotateCos, float dTileX, float dTileY, float tileSize){\n\t\treturn (rotateSin * dTileX + rotateCos * dTileY) * tileSize ;\n\t}\n\t\n\tpublic static double getLatitudeFromTile(float zoom, double y) {\n\t\tint sign = y < 0 ? -1 : 1;\n\t\treturn Math.atan(sign * Math.sinh(Math.PI * (1 - 2 * y / getPowZoom(zoom)))) * 180d / Math.PI;\n\t}\n\t\n\t\n\tpublic static int getPixelShiftX(float zoom, double long1, double long2, double tileSize){\n\t\treturn (int) ((getTileNumberX(zoom, long1) - getTileNumberX(zoom, long2)) * tileSize);\n\t}\n\t\n\t\n\tpublic static int getPixelShiftY(float zoom, double lat1, double lat2, double tileSize){\n\t\treturn (int) ((getTileNumberY(zoom, lat1) - getTileNumberY(zoom, lat2)) * tileSize);\n\t}\n\t\n\t\n\t\n\tpublic static void sortListOfMapObject(List list, final double lat, final double lon){\n\t\tCollections.sort(list, new Comparator() {\n\t\t\t@Override\n\t\t\tpublic int compare(MapObject o1, MapObject o2) {\n\t\t\t\treturn Double.compare(MapUtils.getDistance(o1.getLocation(), lat, lon), MapUtils.getDistance(o2.getLocation(),\n\t\t\t\t\t\tlat, lon));\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static String buildGeoUrl(double latitude, double longitude, int zoom) {\n return \"geo:\" + ((float) latitude) + \",\" + ((float)longitude) + \"?z=\" + zoom;\n\t}\n\t\n\t// Examples\n//\tSystem.out.println(buildShortOsmUrl(51.51829d, 0.07347d, 16)); // http://osm.org/go/0EEQsyfu\n//\tSystem.out.println(buildShortOsmUrl(52.30103d, 4.862927d, 18)); // http://osm.org/go/0E4_JiVhs\n//\tSystem.out.println(buildShortOsmUrl(40.59d, -115.213d, 9)); // http://osm.org/go/TelHTB--\n\tpublic static String buildShortOsmUrl(double latitude, double longitude, int zoom){\n return BASE_SHORT_OSM_URL + createShortLinkString(latitude, longitude, zoom) + \"?m\";\n\t}\n\n\tpublic static String createShortLinkString(double latitude, double longitude, int zoom) {\n\t\tlong lat = (long) (((latitude + 90d)/180d)*(1L << 32));\n\t\tlong lon = (long) (((longitude + 180d)/360d)*(1L << 32));\n\t\tlong code = interleaveBits(lon, lat);\n\t\tString str = \"\";\n\t // add eight to the zoom level, which approximates an accuracy of one pixel in a tile.\n\t\tfor (int i = 0; i < Math.ceil((zoom + 8) / 3d); i++) {\n\t\t str += intToBase64[(int) ((code >> (58 - 6 * i)) & 0x3f)];\n\t\t}\n\t\t// append characters onto the end of the string to represent\n\t\t// partial zoom levels (characters themselves have a granularity of 3 zoom levels).\n\t\tfor (int j = 0; j < (zoom + 8) % 3; j++) {\n\t\t\tstr += '-';\n\t\t}\n\t\treturn str;\n\t}\n\t\n\tpublic static GeoParsedPoint decodeShortLinkString(String s) {\n\t\t// convert old shortlink format to current one\n\t\ts = s.replaceAll(\"@\", \"~\");\n\t\tint i = 0;\n\t\tlong x = 0;\n\t\tlong y = 0;\n\t\tint z = -8;\n\n\t\tfor (i = 0; i < s.length(); i++) {\n\t\t\tint digit = -1;\n\t\t\tchar c = s.charAt(i);\n\t\t\tfor (int j = 0; j < intToBase64.length; j++)\n\t\t\t\tif (c == intToBase64[j]) {\n\t\t\t\t\tdigit = j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif (digit < 0)\n\t\t\t\tbreak;\n\t\t\tif (digit < 0)\n\t\t\t\tbreak;\n\t\t\t// distribute 6 bits into x and y\n\t\t\tx <<= 3;\n\t\t\ty <<= 3;\n\t\t\tfor (int j = 2; j >= 0; j--) {\n\t\t\t\tx |= ((digit & (1 << (j+j+1))) == 0 ? 0 : (1 << j));\n\t\t\t\ty |= ((digit & (1 << (j+j))) == 0 ? 0 : (1 << j));\n\t\t\t}\n\t\t\tz += 3;\n\t\t}\n\t\tdouble lon = x * Math.pow(2, 2 - 3 * i) * 90. - 180;\n\t\tdouble lat = y * Math.pow(2, 2 - 3 * i) * 45. - 90;\n\t\t// adjust z\n\t\tif(i < s.length() && s.charAt(i) == '-') {\n\t\t\tz -= 2;\n\t\t\tif(i + 1 < s.length() && s.charAt(i + 1) == '-')\n\t\t\t\tz++;\n\t\t}\n\t\treturn new GeoParsedPoint(lat, lon, z);\n\t}\n\t\n\t/**\t\n\t * interleaves the bits of two 32-bit numbers. the result is known as a Morton code.\t \n\t */\n\tprivate static long interleaveBits(long x, long y){\n\t\tlong c = 0;\n\t\tfor(byte b = 31; b>=0; b--){\n\t\t\tc = (c << 1) | ((x >> b) & 1);\n\t\t\tc = (c << 1) | ((y >> b) & 1);\n\t\t}\n\t\treturn c;\n\t}\n\n\t/**\n\t * Calculate rotation diff D, that R (rotate) + D = T (targetRotate)\n\t * D is between -180, 180 \n\t * @param rotate\n\t * @param targetRotate\n\t * @return \n\t */\n\tpublic static float unifyRotationDiff(float rotate, float targetRotate) {\n\t\tfloat d = targetRotate - rotate;\n\t\twhile(d >= 180){\n\t\t\td -= 360;\n\t\t}\n\t\twhile(d < -180){\n\t\t\td += 360;\n\t\t}\n\t\treturn d;\n\t}\n\t\n\t/**\n\t * Calculate rotation diff D, that R (rotate) + D = T (targetRotate)\n\t * D is between -180, 180 \n\t * @param rotate\n\t * @return\n\t */\n\tpublic static float unifyRotationTo360(float rotate) {\n\t\twhile(rotate < -180){\n\t\t\trotate += 360;\n\t\t}\n\t\twhile(rotate > +180){\n\t\t\trotate -= 360;\n\t\t}\n\t\treturn rotate;\n\t}\n\n\t/**\n\t * @param diff align difference between 2 angles ]-PI, PI] \n\t * @return \n\t */\n\tpublic static double alignAngleDifference(double diff) {\n\t\twhile(diff > Math.PI) {\n\t\t\tdiff -= 2 * Math.PI;\n\t\t}\n\t\twhile(diff <=-Math.PI) {\n\t\t\tdiff += 2 * Math.PI;\n\t\t}\n\t\treturn diff;\n\t\t\n\t}\n\t\n\t/**\n\t * diff align difference between 2 angles ]-180, 180]\n\t * @return \n\t */\n\tpublic static double degreesDiff(double a1, double a2) {\n\t\tdouble diff = a1 - a2;\n\t\twhile(diff > 180) {\n\t\t\tdiff -= 360;\n\t\t}\n\t\twhile(diff <=-180) {\n\t\t\tdiff += 360;\n\t\t}\n\t\treturn diff;\n\t\t\n\t}\t\n\n\t\n\tpublic static double convert31YToMeters(double y1, double y2) {\n\t\t// translate into meters \n\t\treturn (y1 - y2) * 0.01863d;\n\t}\n\t\n\tpublic static double convert31XToMeters(double x1, double x2) {\n\t\t// translate into meters \n\t\treturn (x1 - x2) * 0.011d;\n\t}\n \n\t\n\tpublic static QuadPoint getProjectionPoint31(int px, int py, int st31x, int st31y,int end31x, int end31y) {\n\t\tdouble projection = calculateProjection31TileMetric(st31x, st31y, end31x,\n\t\t\t\tend31y, px, py);\n\t\tdouble mDist = squareRootDist31(end31x, end31y, st31x,\n\t\t\t\tst31y);\n\t\tint pry = end31y;\n\t\tint prx = end31x;\n\t\tif (projection < 0) {\n\t\t\tprx = st31x;\n\t\t\tpry = st31y;\n\t\t} else if (projection >= mDist * mDist) {\n\t\t\tprx = end31x;\n\t\t\tpry = end31y;\n\t\t} else {\n\t\t\tprx = (int) (st31x + (end31x - st31x)\n\t\t\t\t\t* (projection / (mDist * mDist)));\n\t\t\tpry = (int) (st31y + (end31y - st31y)\n\t\t\t\t\t* (projection / (mDist * mDist)));\n\t\t}\n\t\treturn new QuadPoint(prx, pry);\n\t}\n\t\n\t\n\t\n\tpublic static double squareRootDist31(int x1, int y1, int x2, int y2) {\n\t\t// translate into meters \n\t\tdouble dy = MapUtils.convert31YToMeters(y1, y2);\n\t\tdouble dx = MapUtils.convert31XToMeters(x1, x2);\n\t\treturn Math.sqrt(dx * dx + dy * dy);\n//\t\treturn measuredDist(x1, y1, x2, y2);\n\t}\n\t\n\tpublic static double measuredDist31(int x1, int y1, int x2, int y2) {\n\t\treturn getDistance(MapUtils.get31LatitudeY(y1), MapUtils.get31LongitudeX(x1), MapUtils.get31LatitudeY(y2), MapUtils.get31LongitudeX(x2));\n\t}\n\t\n\tpublic static double squareDist31TileMetric(int x1, int y1, int x2, int y2) {\n\t\t// translate into meters \n\t\tdouble dy = convert31YToMeters(y1, y2);\n\t\tdouble dx = convert31XToMeters(x1, x2);\n\t\treturn dx * dx + dy * dy;\n\t}\n\t\n\tpublic static double calculateProjection31TileMetric(int xA, int yA, int xB, int yB, int xC, int yC) {\n\t\t// Scalar multiplication between (AB, AC)\n\t\tdouble multiple = MapUtils.convert31XToMeters(xB, xA) * MapUtils.convert31XToMeters(xC, xA) +\n\t\t\t\tMapUtils.convert31YToMeters(yB, yA) * MapUtils.convert31YToMeters(yC, yA);\n\t\treturn multiple;\n\t}\n\n\tpublic static boolean rightSide(double lat, double lon,\n\t\t\t\t\t\t\t\t\t\t\t\t double aLat, double aLon,\n\t\t\t\t\t\t\t\t\t\t\t\t double bLat, double bLon) {\n\t\tdouble ax = aLon - lon;\n\t\tdouble ay = aLat - lat;\n\t\tdouble bx = bLon - lon;\n\t\tdouble by = bLat - lat;\n\t\tdouble sa = ax * by - bx * ay;\n\t\treturn sa < 0;\n\t}\n\n}\n\nsrc/net/osmand/binary/BinaryMapIndexReader.java\npublic static interface SearchPoiTypeFilter {\n\t\t\n\tpublic boolean accept(PoiCategory type, String subcategory);\n\t\t\n\tpublic boolean isEmpty();\n}\n\nsrc/net/osmand/binary/BinaryMapIndexReader.java\npublic static class MapObjectStat {\n\tpublic int lastStringNamesSize;\n\tpublic int lastObjectIdSize;\n\tpublic int lastObjectHeaderInfo;\n\tpublic int lastObjectAdditionalTypes;\n\tpublic int lastObjectTypes;\n\tpublic int lastObjectCoordinates;\n\n\tpublic int lastObjectSize ;\n\tpublic int lastBlockStringTableSize;\n\tpublic int lastBlockHeaderInfo;\n\t\t\n\tpublic void addBlockHeader(int typesFieldNumber, int sizeL) {\n\t\tlastBlockHeaderInfo +=\n\t\t\t\tCodedOutputStream.computeTagSize(typesFieldNumber) +\n\t\t\t\tCodedOutputStream.computeRawVarint32Size(sizeL);\n\t}\n\t\t\n\tpublic void addTagHeader(int typesFieldNumber, int sizeL) {\n\t\tlastObjectHeaderInfo +=\n\t\t\t\tCodedOutputStream.computeTagSize(typesFieldNumber) +\n\t\t\t\tCodedOutputStream.computeRawVarint32Size(sizeL);\n\t}\n\n\tpublic void clearObjectStats() {\n\t\tlastStringNamesSize = 0;\n\t\tlastObjectIdSize = 0;\n\t\tlastObjectHeaderInfo = 0;\n\t\tlastObjectAdditionalTypes = 0;\n\t\tlastObjectTypes = 0;\n\t\tlastObjectCoordinates = 0;\n\t}\n}\n\nsrc/com/google/protobuf/WireFormat.java\npublic final class WireFormat {\n // Do not allow instantiation.\n private WireFormat() {}\n\n static final int WIRETYPE_VARINT = 0;\n static final int WIRETYPE_FIXED64 = 1;\n static final int WIRETYPE_LENGTH_DELIMITED = 2;\n static final int WIRETYPE_START_GROUP = 3;\n static final int WIRETYPE_END_GROUP = 4;\n static final int WIRETYPE_FIXED32 = 5;\n // Osmand Delta change\n public static final int WIRETYPE_FIXED32_LENGTH_DELIMITED = 6;\n\n static final int TAG_TYPE_BITS = 3;\n static final int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1;\n\n /** Given a tag value, determines the wire type (the lower 3 bits). */\n public static int getTagWireType(final int tag) {\n return tag & TAG_TYPE_MASK;\n }\n\n /** Given a tag value, determines the field number (the upper 29 bits). */\n public static int getTagFieldNumber(final int tag) {\n return tag >>> TAG_TYPE_BITS;\n }\n\n /** Makes a tag value given a field number and wire type. */\n static int makeTag(final int fieldNumber, final int wireType) {\n return (fieldNumber << TAG_TYPE_BITS) | wireType;\n }\n\n /**\n * Lite equivalent to {@link Descriptors.FieldDescriptor.JavaType}. This is\n * only here to support the lite runtime and should not be used by users.\n */\n public enum JavaType {\n INT(0),\n LONG(0L),\n FLOAT(0F),\n DOUBLE(0D),\n BOOLEAN(false),\n STRING(\"\"),\n BYTE_STRING(ByteString.EMPTY),\n ENUM(null),\n MESSAGE(null);\n\n JavaType(final Object defaultDefault) {\n this.defaultDefault = defaultDefault;\n }\n\n /**\n * The default default value for fields of this type, if it's a primitive\n * type.\n */\n Object getDefaultDefault() {\n return defaultDefault;\n }\n\n private final Object defaultDefault;\n }\n\n /**\n * Lite equivalent to {@link Descriptors.FieldDescriptor.Type}. This is\n * only here to support the lite runtime and should not be used by users.\n */\n public enum FieldType {\n DOUBLE (JavaType.DOUBLE , WIRETYPE_FIXED64 ),\n FLOAT (JavaType.FLOAT , WIRETYPE_FIXED32 ),\n INT64 (JavaType.LONG , WIRETYPE_VARINT ),\n UINT64 (JavaType.LONG , WIRETYPE_VARINT ),\n INT32 (JavaType.INT , WIRETYPE_VARINT ),\n FIXED64 (JavaType.LONG , WIRETYPE_FIXED64 ),\n FIXED32 (JavaType.INT , WIRETYPE_FIXED32 ),\n BOOL (JavaType.BOOLEAN , WIRETYPE_VARINT ),\n STRING (JavaType.STRING , WIRETYPE_LENGTH_DELIMITED) {\n public boolean isPackable() { return false; }\n },\n GROUP (JavaType.MESSAGE , WIRETYPE_START_GROUP ) {\n public boolean isPackable() { return false; }\n },\n MESSAGE (JavaType.MESSAGE , WIRETYPE_LENGTH_DELIMITED) {\n public boolean isPackable() { return false; }\n },\n BYTES (JavaType.BYTE_STRING, WIRETYPE_LENGTH_DELIMITED) {\n public boolean isPackable() { return false; }\n },\n UINT32 (JavaType.INT , WIRETYPE_VARINT ),\n ENUM (JavaType.ENUM , WIRETYPE_VARINT ),\n SFIXED32(JavaType.INT , WIRETYPE_FIXED32 ),\n SFIXED64(JavaType.LONG , WIRETYPE_FIXED64 ),\n SINT32 (JavaType.INT , WIRETYPE_VARINT ),\n SINT64 (JavaType.LONG , WIRETYPE_VARINT );\n\n FieldType(final JavaType javaType, final int wireType) {\n this.javaType = javaType;\n this.wireType = wireType;\n }\n\n private final JavaType javaType;\n private final int wireType;\n\n public JavaType getJavaType() { return javaType; }\n public int getWireType() { return wireType; }\n\n public boolean isPackable() { return true; }\n }\n\n // Field numbers for feilds in MessageSet wire format.\n static final int MESSAGE_SET_ITEM = 1;\n static final int MESSAGE_SET_TYPE_ID = 2;\n static final int MESSAGE_SET_MESSAGE = 3;\n\n // Tag numbers.\n static final int MESSAGE_SET_ITEM_TAG =\n makeTag(MESSAGE_SET_ITEM, WIRETYPE_START_GROUP);\n static final int MESSAGE_SET_ITEM_END_TAG =\n makeTag(MESSAGE_SET_ITEM, WIRETYPE_END_GROUP);\n static final int MESSAGE_SET_TYPE_ID_TAG =\n makeTag(MESSAGE_SET_TYPE_ID, WIRETYPE_VARINT);\n static final int MESSAGE_SET_MESSAGE_TAG =\n makeTag(MESSAGE_SET_MESSAGE, WIRETYPE_LENGTH_DELIMITED);\n}", "answers": ["\t\t\t\t\tfor (CitiesBlock c : cities) {"], "length": 3881, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "aa4e3678-465d-45d3-b23f-963fcdacc948", "reasoning": "The code is inside the printFileInformation method handling an AddressRegion. After retrieving the list of city blocks, the next logical step is to iterate over them to print details. The typical pattern in this method is a for‑each loop over the collection, so the next line should start that loop: \"for (CitiesBlock cb : cities) {\".", "reasoning_model_answer": "for (CitiesBlock cb : cities) {", "assistant_with_reasoning": "\nThe code is inside the printFileInformation method handling an AddressRegion. After retrieving the list of city blocks, the next logical step is to iterate over them to print details. The typical pattern in this method is a for‑each loop over the collection, so the next line should start that loop: \"for (CitiesBlock cb : cities) {\".\n\nfor (CitiesBlock cb : cities) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.756, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 32326, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "for (CitiesBlock cb : cities) {", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport org.eclipse.jface.text.BadLocationException;\nimport org.eclipse.jface.text.IDocument;\nimport org.eclipse.jface.text.contentassist.CompletionProposal;\nimport org.eclipse.jface.text.contentassist.ICompletionProposal;\nimport org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;\nimport org.eclipse.jface.text.quickassist.IQuickAssistProcessor;\nimport org.eclipse.jface.text.source.Annotation;\nimport org.eclipse.ui.PlatformUI;\nimport com.abap.sql.beautifier.preferences.PreferenceConstants;\nimport com.abap.sql.beautifier.settings.AbstractSqlSetting;\nimport com.abap.sql.beautifier.settings.CommentsAdder;\nimport com.abap.sql.beautifier.settings.ConditionAligner;\nimport com.abap.sql.beautifier.settings.JoinCombiner;\nimport com.abap.sql.beautifier.settings.OperatorUnifier;\nimport com.abap.sql.beautifier.settings.Restructor;\nimport com.abap.sql.beautifier.settings.SelectCombiner;\nimport com.abap.sql.beautifier.settings.SpaceAdder;\nimport com.abap.sql.beautifier.statement.AbapSql;\nimport com.abap.sql.beautifier.utility.BeautifierIcon;\nimport com.abap.sql.beautifier.utility.Utility;\nimport com.sap.adt.tools.abapsource.ui.AbapSourceUi;\nimport com.sap.adt.tools.abapsource.ui.IAbapSourceUi;\nimport com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices;\nimport com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices.Token;\nimport com.sap.adt.tools.abapsource.ui.sources.editors.AbapSourcePage;", "context": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/StatementProcessor.java\npackage com.abap.sql.beautifier;\n\n\n\n\npublic class StatementProcessor implements IQuickAssistProcessor {\n\n\tpublic IDocument document = null;\n\tpublic IAbapSourceScannerServices scannerServices = null;\n\tpublic AbapSourcePage sourcePage;\n\tpublic IAbapSourceUi sourceUi = null;\n\tprivate String sql = \"\";\n\tprivate String code;\n\tprivate int diff;\n\tprivate int end;\n\tprivate int offsetCursor;\n\tprivate int startReplacement;\n\tprivate boolean oldSyntax = true;\n\n\tprivate String beautifyStatement(String inputCode) {\n\t\t// otherwise the whole beautifier would not work\n\t\tinputCode = inputCode.toUpperCase();\n\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java\npublic class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"COMBINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_SELECT = \"COMBINE_SMALL_SELECT\";\n\n\tpublic static final String COMMAS = \"COMMAS\";\n\n\tpublic static final String ESCAPING = \"ESCAPING\";\n\n\tpublic static final String OPERSTYLE = \"OPERSTYLE\";\n\n\tpublic static final String ORDER_OLD_SYNTAX = \"ORDER_OLD_SYNTAX\";\n\t\n\tpublic static final String ORDER_NEW_SYNTAX = \"ORDER_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL = \"TAB_ALL\";\n\n\tpublic static final String TAB_CONDITIONS = \"TAB_CONDITIONS\";\n\n\tpublic static final String LINE_CHAR_LIMIT = \"LINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS_LIMIT = \"COMBINE_SMALL_JOINS_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS = \"COMBINE_SMALL_JOINS\";\n\n\tpublic static final String TAB_CONDITIONS_NEW_SYNTAX = \"TAB_CONDITIONS_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL_NEW_SYNTAX = \"TAB_ALL_NEW_SYNTAX\";\n\n\tpublic static final String COMMENTSTYLE = \"COMMENTSTYLE\";\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/JoinCombiner.java\npublic class JoinCombiner extends AbstractSqlSetting {\n\n\tpublic JoinCombiner() {\n\n\t}\n\n\n\t@Override\n\tpublic void apply() {\n\t\tif (abapSql.isOldSyntax()) {\n\t\t\t// TODO enable also for new syntax\n\t\t\t\n\t\t\tif (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.COMBINE_SMALL_JOINS)) {\n\n\t\t\t\tint limit = Activator.getDefault().getPreferenceStore()\n\t\t\t\t\t\t.getInt(PreferenceConstants.COMBINE_SMALL_JOINS_LIMIT);\n\n\t\t\t\tAbapSqlPart fromPart = abapSql.getPart(Abap.FROM);\n\n\t\t\t\tList fromLines = fromPart.getLines();\n\n\t\t\t\tString fromLine = \"\";\n\n\t\t\t\tfor (String line : fromLines) {\n\t\t\t\t\tif(fromLine.trim().equals(\"\")) {\n\t\t\t\t\t\tfromLine = fromLine + line;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfromLine = fromLine + \" \" + line;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (fromLine.length() > limit) {\n\t\t\t\t\t\t// too big, not possible\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfromLines = new ArrayList();\n\t\t\t\tfromLines.add(fromLine);\n\t\t\t\tfromPart.setLines(fromLines);\n\t\t\t\tabapSql.setPart(Abap.FROM, fromPart);\n\t\t\t}\n\n\t\t}\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/CommentsAdder.java\npublic class CommentsAdder extends AbstractSqlSetting {\n\tprivate String commentStyle = \"\";\n\n\tpublic CommentsAdder() {\n\n\t}\n\n\t@Override\n\tpublic void apply() {\n\n\t\t// apply comments\n\t\tcommentStyle = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.COMMENTSTYLE);\n\n\t\tif (abapSql.getComments().isEmpty()) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (commentStyle.equals(\"UP\") || commentStyle.equals(\"DOWN\")) {\n\n\t\t\tsetCommentsToOrder();\n\n\t\t\taddFirstLineWhite();\n\n\t\t\taddComments();\n\n\t\t}\n\n\t}\n\n\tprivate void addFirstLineWhite() {\n\t\tAbapSqlPart part = abapSql.getPart(Abap.SELECT);\n\t\tString name;\n\t\tif (part == null) {\n\t\t\tpart = abapSql.getPart(Abap.SELECTFROM);\n\t\t\tname = Abap.SELECTFROM;\n\t\t\tif (part == null) {\n\t\t\t\tpart = abapSql.getPart(Abap.SELECT_SINGLE_FROM);\n\t\t\t\tname = Abap.SELECT_SINGLE_FROM;\n\t\t\t}\n\t\t} else {\n\t\t\tname = Abap.SELECT;\n\t\t}\n\n\t\tList lines = part.getLines();\n\n\t\t// add start white and replace it\n\t\tString firstLine = abapSql.getStartWhite() + lines.get(0);\n\t\tlines.set(0, firstLine);\n\t\tpart.setLines(lines);\n\n\t\tabapSql.setPart(name, part);\n\t}\n\n\tprivate void addComments() {\n\t\tList comments = abapSql.getComments();\n\t\tString firstComment = comments.get(0);\n\t\t// check if first comment is full line comment\n\t\tif (firstComment.startsWith(\"*\")) {\n\t\t\t// add new line\n\t\t\tfirstComment = \"\\r\\n\" + firstComment;\n\t\t\tcomments.set(0, firstComment);\n\t\t}\n\n\t\tAbapSqlPart commentPart = Factory.getPartObject(Abap.COMMENT, comments);\n\n\t\tabapSql.setPart(Abap.COMMENT, commentPart);\n\n\t}\n\n\tprivate void setCommentsToOrder() {\n\n\t\tList order = abapSql.getOrder();\n\n\t\t// set comments position\n\t\tif (commentStyle.equals(\"UP\")) {\n\t\t\torder.add(0, Abap.COMMENT);\n\t\t} else if (commentStyle.equals(\"DOWN\")) {\n\t\t\torder.add(order.size() - 1, Abap.COMMENT);\n\t\t}\n\n\t\tabapSql.setOrder(order);\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/ConditionAligner.java\npublic class ConditionAligner extends AbstractSqlSetting {\n\n\tpublic ConditionAligner() {\n\t}\n\n\tprivate List alignOperators(List sqlConditions) {\n\t\tsqlConditions = deleteUnnecessaryEmptyChars(sqlConditions);\n\n\t\tint curIndex = 0;\n\t\tint maxIndex = getMaxIndexOfOperator(sqlConditions);\n\n\t\tStringBuilder sb;\n\n\t\tboolean shouldAlignOneCharOpers = !validateOpersSameLength(sqlConditions);\n\n\t\tList returnLines = new ArrayList<>();\n\n\t\tfor (String line : sqlConditions) {\n\n\t\t\tsb = new StringBuilder(line);\n\n\t\t\tcurIndex = getIndexOfOper(line);\n\n\t\t\t// if no oper found --> curIndex = -1\n\t\t\tif (curIndex >= 0) {\n\n\t\t\t\tcurIndex = 0;\n\t\t\t\twhile (curIndex < maxIndex) {\n\n\t\t\t\t\tcurIndex = getIndexOfOper(line);\n\n\t\t\t\t\t// if still below max index, insert empty char\n\t\t\t\t\tif (curIndex < maxIndex) {\n\t\t\t\t\t\tline = sb.insert(curIndex, \" \").toString();\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (shouldAlignOneCharOpers) {\n\t\t\t\tfor (String oper : Utility.getOneCharOpers()) {\n\t\t\t\t\tif (line.contains(oper)) {\n\t\t\t\t\t\tline = sb.insert(curIndex + 2, \" \").toString();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturnLines.add(line);\n\n\t\t}\n\n\t\treturn returnLines;\n\t}\n\n\t@Override\n\tpublic void apply() {\n\n\t\tboolean shouldAlign = Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.ALLIGN_OPERS);\n\n\t\tif (shouldAlign) {\n\t\t\t\n\t\t\tAbapSqlPart wherePart = abapSql.getPart(Abap.WHERE);\n\n\t\t\tif (wherePart != null) {\n\t\t\t\tList wherePartLines = wherePart.getLines();\n\t\t\t\twherePartLines = alignOperators(wherePartLines);\n\t\t\t\twherePart.setLines(wherePartLines);\n\t\t\t\tabapSql.setPart(Abap.WHERE, wherePart);\n\t\t\t}\n\n\t\t\tAbapSqlPart fromPart = abapSql.getPart(Abap.FROM);\n\n\t\t\tif (fromPart != null) {\n\t\t\t\tList fromPartLines = fromPart.getLines();\n\t\t\t\tfromPartLines = alignOperators(fromPartLines);\n\t\t\t\tfromPart.setLines(fromPartLines);\n\t\t\t\tabapSql.setPart(Abap.FROM, fromPart);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tprivate List deleteUnnecessaryEmptyChars(List sqlConditions) {\n\t\t// delete tabs and unnecessary empty chars\n\t\tfor (int i = 0; i < sqlConditions.size(); i++) {\n\t\t\tString curLine = sqlConditions.get(i);\n\t\t\tcurLine = curLine.replace(\"\\t\", \"\");\n\t\t\tsqlConditions.set(i, curLine);\n\t\t}\n\n\t\treturn sqlConditions;\n\t}\n\n\tprivate int getIndexOfOper(String line) {\n\t\tList opers = Utility.getAllOperators();\n\t\tfor (String oper : opers) {\n\t\t\tint index = line.indexOf(oper);\n\t\t\tindex = line.lastIndexOf(oper);\n\t\t\tif (index != -1) {\n\t\t\t\t// oper found\n\t\t\t\treturn index;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tprivate int getMaxIndexOfOperator(List sqlConditions) {\n\t\tint curIndex = 0;\n\t\tint maxIndex = 0;\n\t\tfor (String line : sqlConditions) {\n\t\t\tcurIndex = getIndexOfOper(line);\n\t\t\tif (curIndex > maxIndex) {\n\t\t\t\tmaxIndex = curIndex;\n\t\t\t}\n\t\t}\n\n\t\treturn maxIndex;\n\n\t}\n\n\t// returns true if all opers are having the same length (2 or 1)\n\tprivate boolean validateOpersSameLength(List sqlConditions) {\n\t\tboolean containsOne = false;\n\t\tboolean containsTwo = false;\n\t\tfor (String line : sqlConditions) {\n\t\t\tfor (String oper : Utility.getOneCharOpers()) {\n\t\t\t\tif (line.contains(oper)) {\n\t\t\t\t\tcontainsOne = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (String oper : Utility.getTwoCharOpers()) {\n\t\t\t\tif (line.contains(oper)) {\n\t\t\t\t\tcontainsTwo = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (containsOne == containsTwo) {\n\t\t\t// contains both\n\t\t\treturn false;\n\t\t}\n\t\t// same length\n\t\treturn true;\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/statement/AbapSql.java\npublic class AbapSql {\n\n\tprivate Map parts;\n\tprivate List order;\n\tprivate boolean isOldSyntax = true;\n\tprivate List comments = new ArrayList();\n\tprivate String startWhite = \"\";\n\n\tpublic AbapSql(String sql, int diff) {\n\t\tstartWhite = Utility.getWhiteChars(diff);\n\n\t\tparts = new HashMap();\n\n\t\t// get order\n\t\tisOldSyntax = checkIfOldSyntax(sql);\n\t\tif (isOldSyntax) {\n\t\t\tsetOrder(buildOrder(PreferenceConstants.ORDER_OLD_SYNTAX));\n\t\t} else {\n\t\t\tsetOrder(buildOrder(PreferenceConstants.ORDER_NEW_SYNTAX));\n\t\t}\n\n\t\tappendSecWords();\n\n\t\tsql = filterComments(sql);\n\n\t\tsql = Utility.cleanString(sql);\n\n\t\tsetFromString(sql);\n\n\t\tresetFormat();\n\n\t}\n\n\tprivate void appendSecWords() {\n\t\t// append keywords, which are introducing the same part\n\t\tint index;\n\n\t\t// INTO ~ APPENDING\n\t\tindex = order.indexOf(Abap.INTO);\n\t\tif (index != -1) {\n\t\t\torder.add(index, Abap.APPENDING);\n\t\t}\n\t\t\n\t\t// UPTO ~ OFFSET\n\t\tindex = order.indexOf(Abap.UPTO);\n\t\tif (index != -1) {\n\t\t\torder.add(index, Abap.OFFSET);\n\t\t}\n\t\t\n\t\t// INTO ~ INTO CORRESPONDING FIELDS OF\n\t\tindex = order.indexOf(Abap.INTO);\n\t\tif (index != -1) {\n\t\t\torder.add(index, Abap.INTO_COR_FI_OF);\n\t\t}\n\n\t}\n\n\tprivate String filterComments(String sql) {\n\t\tString returnSql = \"\";\n\t\tString asterisks = \"*\";\n\t\tString apostrophes = \"\\\"\";\n\n\t\tif (sql.contains(asterisks) || sql.contains(apostrophes)) {\n\t\t\tList lines = Arrays.asList(sql.split(\"\\r\\n\"));\n\n\t\t\tfor (String line : lines) {\n\t\t\t\tif (line.contains(asterisks) || line.contains(apostrophes)) {\n\t\t\t\t\tint pos = line.indexOf(asterisks);\n\n\t\t\t\t\t// check if asterisks is first char --> full line comment\n\t\t\t\t\tif (pos == 0) {\n\t\t\t\t\t\tcomments.add(line.trim());\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// asterisks was not a comment --> check apostrophes\n\t\t\t\t\tpos = line.indexOf(apostrophes);\n\n\t\t\t\t\tif (pos == -1) {\n\t\t\t\t\t\treturnSql = returnSql + line + \"\\r\\n\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcomments.add(line.substring(pos).trim());\n\t\t\t\t\t\treturnSql = returnSql + line.substring(0, pos) + \"\\r\\n\";\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\treturnSql = returnSql + line + \"\\r\\n\";\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn returnSql;\n\n\t\t} else {\n\t\t\t// does not contain any comments, return original\n\t\t\treturn sql;\n\t\t}\n\n\t}\n\n\tprivate List buildOrder(String syntaxType) {\n\t\tList returnOrder = new ArrayList<>();\n\n\t\tString curOrderString = Activator.getDefault().getPreferenceStore().getString(syntaxType);\n\n\t\tList orderSplit = Arrays.asList(curOrderString.split(\",\"));\n\n\t\tfor (String keyword : orderSplit) {\n\n\t\t\tkeyword = keyword.trim();\n\t\t\t\n\t\t\t//add additional select single\n\t\t\tif(this.isOldSyntax == false && keyword.equals(Abap.SELECTFROM)) {\n\t\t\t\treturnOrder.add(Abap.SELECT_SINGLE_FROM);\n\t\t\t}\n\n\t\t\t// ignore empty values\n\t\t\tif (keyword != \"\") {\n\t\t\t\treturnOrder.add(keyword.toUpperCase());\n\t\t\t}\n\t\t}\n\n\t\treturn returnOrder;\n\t}\n\n\tpublic List getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic void setOrder(List order) {\n\t\tthis.order = order;\n\t}\n\n\tpublic AbapSqlPart getPart(String partname) {\n\n\t\tAbapSqlPart part = parts.get(partname);\n\n\t\tif (partname == Abap.FROM && part == null) {\n\t\t\tpart = parts.get(Abap.SELECTFROM);\n\t\t} else if (partname == Abap.INTO && part == null) {\n\t\t\tpart = parts.get(Abap.APPENDING);\n\t\t}\n\n\t\treturn part;\n\n\t}\n\n\tpublic void setPart(String partname, AbapSqlPart part) {\n\n\t\tparts.put(partname, part);\n\n\t}\n\n\tpublic boolean isOldSyntax() {\n//\t\tString firstLine = getPart(Abap.SELECT).getLines().get(0);\n//\t\t\n//\t\n//\t\tList tokens = Arrays.asList(firstLine.trim().split(\" \"));\n//\n//\t\tif (tokens.size() >= 2) {\n//\t\t\tif (tokens.get(0).equals(Abap.FROM) && tokens.get(1).equals(Abap.FROM)) {\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t}\n\t\tAbapSqlPart part = getPart(Abap.FROM);\n\n\t\tif (part == null) {\n\t\t\tpart = getPart(Abap.SELECTFROM);\n\t\t}\n\t\tString firstLine = \"\";\n\t\tList tokens;\n\n\t\ttry {\n\t\t\tfirstLine = part.getLines().get(0);\n\t\t} catch (IndexOutOfBoundsException | NullPointerException ex) {\n\t\t\t// try other method to check syntax\n\t\t\tpart = getPart(Abap.SELECT);\n\t\t\tif (part == null) {\n\t\t\t\tpart = getPart(Abap.SELECTFROM);\n\t\t\t\tif (part == null) {\n\t\t\t\t\tpart = getPart(Abap.SELECT_SINGLE_FROM);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfirstLine = part.getLines().get(0).trim();\n\n\t\t\ttokens = Arrays.asList(firstLine.trim().split(\" \"));\n\n\t\t\tString firstToken = tokens.get(0);\n\t\t\tString secToken = tokens.get(1);\n\t\t\tif (firstToken.equals(Abap.SELECT) && secToken.equals(Abap.FROM)) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t}\n\n\t\ttokens = Arrays.asList(firstLine.trim().split(\" \"));\n\n\t\tif (tokens.get(0).equals(Abap.SELECT)) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\n\t}\n\n\tpublic List splitSql(String sql, List keywords) {\n\t\tList splits = new ArrayList<>();\n\t\tList result = new ArrayList<>();\n\n\t\tString pattern = \"\\\\b(\" + String.join(\"|\", keywords) + \")\\\\b\";\n\n\t\tPattern regex = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);\n\t\tMatcher matcher = regex.matcher(sql);\n\n\t\tint lastIndex = 0;\n\n\t\tString curString = \"\";\n\n\t\twhile (matcher.find()) {\n\t\t\tint mStart = matcher.start();\n\n\t\t\tint mEnd = matcher.end();\n\n\t\t\tString keyword = sql.substring(mStart, mEnd).trim();\n\n\t\t\t// verify no literal\n\t\t\tboolean isLiteral = Utility.isLiteral(sql, mStart, mEnd);\n\n\t\t\tif (isLiteral) {\n\t\t\t\t// save cur statement\n\t\t\t\tcurString = curString + sql.substring(lastIndex, mEnd);\n\t\t\t\tlastIndex = mEnd;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!curString.matches(\"\")) {\n\t\t\t\t// cur statement not empty, add to list\n\t\t\t\tcurString = curString + sql.substring(lastIndex, mStart);\n\t\t\t\tsplits.add(curString.trim());\n\t\t\t\tcurString = \"\";\n\t\t\t}\n\n\t\t\tif (lastIndex < mStart) {\n\t\t\t\tsplits.add(sql.substring(lastIndex, mStart).trim());\n\t\t\t}\n\n\t\t\tsplits.add(sql.substring(mStart, mEnd).trim());\n\n\t\t\tlastIndex = mEnd;\n\t\t}\n\n\t\t// add remaining text after matching last keyword\n\t\tif (lastIndex < sql.length()) {\n\t\t\tsplits.add(sql.substring(lastIndex).trim());\n\t\t}\n\n\t\t// combine keyword + rest\n\t\tString curLine = \"\";\n\t\tfor (int i = 0; i < splits.size(); i++) {\n\t\t\tif (i % 2 == 0) {\n\t\t\t\tcurLine = splits.get(i);\n\n\t\t\t} else {\n\t\t\t\tcurLine += \" \" + splits.get(i);\n\t\t\t\tresult.add(curLine);\n\t\t\t}\n\t\t}\n\n\t\t// sorting\n\t\tresult.sort(Comparator.comparingInt(s -> getFirstMatchKeyIndex(s, keywords)));\n\n\t\treturn result;\n\t}\n\n\tprivate int getFirstMatchKeyIndex(String string, List keywords) {\n\t\tfor (int i = 0; i < keywords.size(); i++) {\n\t\t\tString keyword = keywords.get(i);\n\t\t\tif (string.contains(keyword)) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn keywords.size();\n\t}\n\n\tpublic void resetFormat() {\n//\t\tString sign = \"\\\"\";\n\n\t\t// clean all lines in all parts = reset format\n\t\tfor (String keyword : getOrder()) {\n\n\t\t\tAbapSqlPart curPart = parts.get(keyword);\n\n\t\t\tif (parts.get(keyword) != null) {\n\n\t\t\t\tList curLines = curPart.getLines();\n\n\t\t\t\tList newLines = new ArrayList();\n\n\t\t\t\tfor (String line : curLines) {\n\n//\t\t\t\t\tif (line.contains(sign)) {\n//\t\t\t\t\t\tint pos = line.indexOf(sign);\n//\n//\t\t\t\t\t\tcomments.add(line.substring(pos));\n//\n//\t\t\t\t\t\tline = line.substring(0, pos);\n//\t\t\t\t\t}\n\n\t\t\t\t\tline = Utility.deleteSpaces(line).trim();\n\n\t\t\t\t\tnewLines.add(line);\n\t\t\t\t}\n\n\t\t\t\tsetPart(keyword, curPart);\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void setFromString(String sql) {\n\t\tsql = Utility.cleanString(sql);\n\n\t\tif (sql.endsWith(\".\")) {\n\t\t\t// delete point\n\t\t\tsql = sql.substring(0, sql.length() - 1);\n\t\t}\n\n\t\tList parts = splitSql(sql, getOrder());\n\t\tList remainingParts = new ArrayList<>();\n\n\t\tfor (String keyword : getOrder()) {\n\t\t\tfor (String split : parts) {\n\t\t\t\tif (split.trim().startsWith(keyword)) {\n\t\t\t\t\tList part = Arrays.asList(split.split(\"\\r\\n\"));\n\n\t\t\t\t\t// without starting spaces\n\t\t\t\t\tList finalPartList = new ArrayList<>();\n\t\t\t\t\tfor (String line : part) {\n\t\t\t\t\t\tfinalPartList.add(line.trim());\n\t\t\t\t\t}\n\n\t\t\t\t\tAbapSqlPart finalPart = Factory.getPartObject(keyword, finalPartList);\n\t\t\t\t\tsetPart(keyword, finalPart);\n\t\t\t\t\t\n\t\t\t\t\tparts.remove(split);\n\n\t\t\t\t\tbreak;\n\t\t\t\t} \n\n\t\t\t}\n\t\t}\n\n\t\tverifyOrder();\n\n\t}\n\n\tpublic static boolean checkIfOldSyntax(String sql) {\n\t\tsql = Utility.cleanString(sql);\n\t\tList splits = Arrays.asList(sql.split(\" \"));\n\t\tif (splits.size() > 2) {\n\n\t\t\tString secToken = splits.get(1).toString().toUpperCase();\n\t\t\tString thirdToken = splits.get(2).toString().toUpperCase();\n\t\t\t\n\t\t\tif (secToken.equals(Abap.FROM) || (secToken.equals(Abap.SINGLE) && thirdToken.equals(Abap.FROM))) {\n\t\t\t\t// new syntax\n\t\t\t\treturn false;\n\t\t\t}\n\n\n\t\t}\n\t\t// oldSyntax\n\t\treturn true;\n\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString sqlString = \"\";\n\n\t\tint limit = Activator.getDefault().getPreferenceStore().getInt(PreferenceConstants.LINE_CHAR_LIMIT);\n\n\t\tif (limit == 0) {\n\t\t\t// forbidden\n\t\t\tlimit = 1;\n\t\t}\n\n\t\tif (!isOldSyntax && this.getPart(Abap.FIELDS) == null) {\n\t\t\tconvertToNewSyntax();\n\t\t}\n\n\t\tfor (String keyword : getOrder()) {\n\t\t\tAbapSqlPart curPart = parts.get(keyword);\n\t\t\tif (curPart != null) {\n\t\t\t\tList curLines = curPart.getLines();\n\t\t\t\tfor (String line : curLines) {\n\n\t\t\t\t\tif (line.length() < limit || keyword.equals(Abap.COMMENT)) {\n\t\t\t\t\t\t// no split on comments\n\t\t\t\t\t\tsqlString = sqlString + line + \"\\r\\n\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// line limit reached\n\t\t\t\t\t\tList splittedLines = Utility.splitLine(line, limit);\n\t\t\t\t\t\tfor (String splittedLine : splittedLines) {\n\t\t\t\t\t\t\tsqlString = sqlString + splittedLine + \"\\r\\n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// build return String\n\t\tsqlString = sqlString.substring(0, sqlString.length() - \"\\r\\n\".length());\n\t\t\n\t\treturn sqlString;\n\t}\n\n\tpublic void setPoint() {\n\t\tList reverseOrder = new ArrayList(getOrder());\n\t\tCollections.reverse(reverseOrder);\n\n\t\tfor (String keyword : reverseOrder) {\n\t\t\tif (keyword.equals(Abap.COMMENT)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (containsPart(keyword)) {\n\t\t\t\t// last part found. set point to the end\n\t\t\t\tAbapSqlPart lastPart = getPart(keyword);\n\t\t\t\tList lines = lastPart.getLines();\n\t\t\t\tint pos = lines.size() - 1;\n\t\t\t\tString lastLine = lines.get(pos) + \".\";\n\t\t\t\tlines.set(pos, lastLine);\n\n//\t\t\t\tlastPart.setLines(lines);\n//\t\t\t\tsetPart(keyword, lastPart);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tpublic AbapSql convertToNewSyntax() {\n\t\tif (!isOldSyntax && this.getPart(Abap.FIELDS) == null) {\n\n\t\t\t// transform the from part to 'select' and fields to 'fields'\n\t\t\tAbapSqlPart selectPart = getPart(Abap.SELECT);\n\t\t\tAbapSqlPart fromPart = getPart(Abap.FROM);\n\n\t\t\tList selectLines = selectPart.getLines();\n\t\t\tList fromLines = fromPart.getLines();\n\n\t\t\tList newFromLines = new ArrayList();\n\t\t\tList fieldLines = new ArrayList();\n\n\t\t\t// reset from\n\t\t\tsetPart(Abap.FROM, null);\n\n\t\t\t// build fields\n\t\t\tfor (String line : selectLines) {\n\t\t\t\tif (line.trim().startsWith(Abap.SELECT)) {\n\t\t\t\t\tline = line.replaceFirst(Abap.SELECT, \"\");\n\t\t\t\t}\n\t\t\t\tfieldLines.add(line);\n\t\t\t}\n\n\t\t\tAbapSqlPart fieldsPart = Factory.getPartObject(Abap.FIELDS, fieldLines);\n\t\t\tsetPart(Abap.FIELDS, fieldsPart);\n\n\t\t\t// new select\n\n\t\t\tfor (int i = 0; i < fromLines.size(); i++) {\n\t\t\t\tString curLine = fromLines.get(i);\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tcurLine = Abap.SELECT + curLine;\n\t\t\t\t}\n\t\t\t\tnewFromLines.add(curLine);\n\t\t\t}\n\n\t\t\tAbapSqlPart newSelectPart = Factory.getPartObject(Abap.SELECT, newFromLines);\n\t\t\tsetPart(Abap.SELECT, newSelectPart);\n\n\t\t}\n\n\t\treturn this;\n\n\t}\n\n\tpublic void verifyOrder() {\n\t\t// deactivated --> not necessary?\n\n//\t\t// check if statement contains FOR ALL ENTRIES and if INTO is at the end\n//\t\tif (containsPart(Abap.FORALLENTRIES)) {\n//\t\t\tList curOrder = getOrder();\n//\n//\t\t\tif (!curOrder.get(curOrder.size() - 1).equals(Abap.INTO)) {\n//\t\t\t\tfor (int i = 0; i < curOrder.size(); i++) {\n//\t\t\t\t\tString keyword = curOrder.get(i);\n//\n//\t\t\t\t\tif (keyword.equals(Abap.INTO)) {\n//\t\t\t\t\t\t// remove from current position and add it to the end\n//\t\t\t\t\t\tcurOrder.remove(i);\n//\t\t\t\t\t\tcurOrder.add(keyword);\n//\t\t\t\t\t\treturn;\n//\t\t\t\t\t}\n//\n//\t\t\t\t}\n//\n//\t\t\t}\n//\n//\t\t}\n\t}\n\n\tpublic boolean containsPart(String partname) {\n\t\tAbapSqlPart part = getPart(partname);\n\n\t\tif (part == null) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic String getStartWhite() {\n\t\treturn startWhite;\n\t}\n\n\tpublic List getComments() {\n\t\treturn comments;\n\t}\n\n\tpublic void setComments(List comments) {\n\t\tthis.comments = comments;\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/utility/BeautifierIcon.java\npublic class BeautifierIcon {\n\tprivate static Image icon;\n\n\tpublic static Image get() {\n\t\tif (icon == null) {\n\t\t\tActivator.getDefault();\n\t\t\ticon = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, \"icons/magicwand16.png\").createImage();\n\t\t}\n\t\treturn icon;\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/OperatorUnifier.java\npublic class OperatorUnifier extends AbstractSqlSetting {\n\n\tString operStyle;\n\n\tpublic OperatorUnifier() {\n\t}\n\n\tpublic OperatorUnifier(String operStyle) {\n\t\tthis.operStyle = operStyle;\n\t}\n\n\t@Override\n\tpublic void apply() {\n\t\tString operStyle = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.OPERSTYLE);\n\t\tif (operStyle == \"sign\" || operStyle == \"char\") {\n\t\t\tfor (String keyword : abapSql.getOrder()) {\n\n\t\t\t\tAbapSqlPart curPart = abapSql.getPart(keyword);\n\n\t\t\t\tif (curPart != null) {\n\t\t\t\t\tList curPartLines = curPart.getLines();\n\t\t\t\t\tList newPartLines = new ArrayList<>();\n\t\t\t\t\tfor (String line : curPartLines) {\n\n\t\t\t\t\t\tif (operStyle == \"sign\") {\n\t\t\t\t\t\t\tline = line.replace(\" EQ \", \" = \");\n\t\t\t\t\t\t\tline = line.replace(\" NE \", \" <> \");\n\t\t\t\t\t\t\tline = line.replace(\" LT \", \" < \");\n\t\t\t\t\t\t\tline = line.replace(\" GT \", \" > \");\n\t\t\t\t\t\t\tline = line.replace(\" LE \", \" <= \");\n\t\t\t\t\t\t\tline = line.replace(\" GE \", \" >= \");\n\t\t\t\t\t\t} else if (operStyle == \"char\") {\n\t\t\t\t\t\t\tline = line.replace(\" = \", \" EQ \");\n\t\t\t\t\t\t\tline = line.replace(\" <> \", \" NE \");\n\t\t\t\t\t\t\tline = line.replace(\" < \", \" LT \");\n\t\t\t\t\t\t\tline = line.replace(\" > \", \" GT \");\n\t\t\t\t\t\t\tline = line.replace(\" <= \", \" LE \");\n\t\t\t\t\t\t\tline = line.replace(\" >= \", \" GE \");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tnewPartLines.add(line);\n\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcurPart.setLines(newPartLines);\n\n\t\t\t\t\tabapSql.setPart(keyword, curPart);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void setOperStyleToChar() {\n\t\toperStyle = \"char\";\n\t}\n\n\tpublic void setOperStyleToSign() {\n\t\toperStyle = \"sign\";\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/SpaceAdder.java\npublic class SpaceAdder extends AbstractSqlSetting {\n\n\tString emptySpaces = \"\";\n\n\tpublic SpaceAdder() {\n\n\t}\n\n\t@Override\n\tpublic void apply() {\n\n\t\t// everything\n\t\ttabAllLines();\n\n\t\t// conditions\n\t\tboolean shouldTabCond;\n\t\tboolean oldSyntax = abapSql.isOldSyntax();\n\n\t\tif (oldSyntax) {\n\t\t\tshouldTabCond = Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.TAB_CONDITIONS);\n\t\t} else {\n\t\t\tshouldTabCond = Activator.getDefault().getPreferenceStore()\n\t\t\t\t\t.getBoolean(PreferenceConstants.TAB_CONDITIONS_NEW_SYNTAX);\n\t\t}\n\n\t\tif (shouldTabCond) {\n\n\t\t\taddSpacesFrom();\n\n\t\t\taddSpacesWhere();\n\n\t\t}\n\t}\n\n\tprivate void addSpacesFrom() {\n\t\tAbapSqlPart fromPart = abapSql.getPart(Abap.FROM);\n\n\t\tif (fromPart == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tList fromLines = fromPart.getLines();\n\t\tList newFromLines = new ArrayList<>();\n\n\t\tfor (String line : fromLines) {\n\t\t\tString newLine = tabConditionLine(line);\n\t\t\tnewFromLines.add(newLine);\n\t\t}\n\n\t\tfromPart.setLines(newFromLines);\n\n\t\tabapSql.setPart(Abap.FROM, fromPart);\n\n\t}\n\n\tprivate void addSpacesWhere() {\n\t\tAbapSqlPart wherePart = abapSql.getPart(Abap.WHERE);\n\n\t\t// if no conditions in sql, nothing to do\n\t\tif (wherePart == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tList whereLines = wherePart.getLines();\n\t\tList newWhereLines = new ArrayList<>();\n\n\t\tfor (String line : whereLines) {\n\t\t\tnewWhereLines.add(tabConditionLine(line));\n\t\t}\n\n\t\twherePart.setLines(newWhereLines);\n\n\t\tabapSql.setPart(Abap.WHERE, wherePart);\n\t}\n\n\tprivate void tabAllLines() {\n\t\t// add empty spaces to every line except SELECT depending on preferences\n\t\tint emptySpacesInt;\n\n\t\tif (abapSql.isOldSyntax()) {\n\t\t\temptySpacesInt = Activator.getDefault().getPreferenceStore().getInt(PreferenceConstants.TAB_ALL);\n\t\t} else {\n\t\t\temptySpacesInt = Activator.getDefault().getPreferenceStore().getInt(PreferenceConstants.TAB_ALL_NEW_SYNTAX);\n\t\t}\n\n\t\temptySpaces = Utility.getWhiteChars(emptySpacesInt);\n\n\t\tfor (String keyword : abapSql.getOrder()) {\n\t\t\tif (abapSql.getPart(keyword) != null) {\n\n\t\t\t\tAbapSqlPart curPart = abapSql.getPart(keyword);\n\t\t\t\tList curPartLines = curPart.getLines();\n\t\t\t\tList newLines = new ArrayList<>();\n\n\t\t\t\tif (keyword.equalsIgnoreCase(Abap.SELECT) || keyword.equalsIgnoreCase(Abap.SELECTFROM)\n\t\t\t\t\t\t|| keyword.equalsIgnoreCase(Abap.SELECT_SINGLE_FROM)) {\n\t\t\t\t\t// exclude first line\n\t\t\t\t\tnewLines.add(curPartLines.get(0));\n\t\t\t\t\tcurPartLines.remove(0);\n\t\t\t\t}\n\n\t\t\t\tfor (String line : curPartLines) {\n\t\t\t\t\tString newLine = abapSql.getStartWhite() + emptySpaces + line; // diff = empty spaces in selected\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ABAP Code\n\t\t\t\t\tnewLines.add(newLine);\n\t\t\t\t}\n\t\t\t\tcurPart.setLines(newLines);\n\t\t\t\tabapSql.setPart(keyword, curPart);\n\t\t\t}\n\t\t}\n\n\t}\n\n\tprivate String tabConditionLine(String line) {\n\t\tString newLine;\n\n\t\t// AND --> 1 space less\n\t\tif (line.trim().startsWith(\"AND\")) {\n\t\t\tnewLine = \" \" + line;\n\t\t} else if (line.trim().startsWith(\"OR\") || line.trim().startsWith(\"ON\")) {\n\t\t\tnewLine = \" \" + line;\n\t\t} else {\n\t\t\tnewLine = line;\n\t\t}\n\n\t\treturn newLine;\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/utility/Utility.java\npublic class Utility {\n\n\tpublic final static String placeholder = \"@!%&\";\n\n\tpublic static int countKeyword(String statement, String keyword) {\n\n\t\tkeyword = keyword.toUpperCase();\n\n\t\tint count = 0;\n\n\t\tList cleanTokenList = convertToCleanTokenList(statement);\n\n\t\tfor (int i = 0; i < cleanTokenList.size(); i++) {\n\t\t\tString token = cleanTokenList.get(i).trim();\n\t\t\tif (token.equalsIgnoreCase(keyword)) {\n\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (i < cleanTokenList.size()) {\n\t\t\t\t\tString tokenBefore = cleanTokenList.get(i - 1);\n\t\t\t\t\tString tokenAfter = cleanTokenList.get(i + 1);\n\n\t\t\t\t\tif (!tokenBefore.trim().matches(\"'\") && !tokenAfter.trim().matches(\"'\")) {\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tpublic static boolean isLiteral(String statement, int start, int end) {\n\t\tString statementStart;\n\n\t\tif (start == 0) {\n\t\t\tstatementStart = statement.substring(0, start);\n\t\t} else {\n\t\t\tstatementStart = statement.substring(0, start - 1);\n\t\t}\n\n\t\tString statementMid = statement.substring(statementStart.length(), end + 1) + placeholder + \" \";\n\t\tString statementEnd = statement.substring(end + 1, statement.length());\n\n\t\tstatement = statementStart + statementMid + statementEnd;\n\n\t\tList cleanTokenList = convertToCleanTokenList(statement);\n\n\t\tboolean isLiteral = false;\n\t\tint count = 0;\n\n\t\tfor (int i = 1; i < cleanTokenList.size(); i++) {\n\n\t\t\tString curToken = cleanTokenList.get(i);\n\n\t\t\t// count all \" ' \"\n\t\t\tif (curToken.matches(\"'\")) {\n\t\t\t\tcount++;\n\t\t\t}\n\n\t\t\tif (curToken.contains(placeholder)) {\n\n\t\t\t\tcurToken = curToken.replaceAll(placeholder, \"\");\n\n\t\t\t\tString tokenBefore = cleanTokenList.get(i - 1).trim();\n\t\t\t\tString tokenAfter = cleanTokenList.get(i + 1).trim();\n\n\t\t\t\tboolean startLiteral = (tokenBefore.matches(\"'\") || curToken.startsWith(\"'\"));\n\t\t\t\tboolean endsLiteral = (tokenAfter.matches(\"'\") || curToken.endsWith(\"'\"));\n\n\t\t\t\tif (startLiteral && endsLiteral) {\n\t\t\t\t\tif (count % 2 != 0) {\n\t\t\t\t\t\tisLiteral = true;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\t\t}\n\n\t\treturn isLiteral;\n\t}\n\n\tprivate static List convertToCleanTokenList(String statement) {\n\t\tstatement = statement.toUpperCase();\n\n\t\tList tokenList = Arrays.asList(statement.trim().split(\" \"));\n\n\t\tList cleanTokenList = new ArrayList();\n\n\t\t// clean tokenList\n\t\tfor (String token : tokenList) {\n\t\t\ttoken = token.replaceAll(\"\\r\\n\", \" \");\n\t\t\tif (!token.isBlank()) {\n\t\t\t\tcleanTokenList.add(token);\n\t\t\t}\n\t\t}\n\n\t\treturn cleanTokenList;\n\n\t}\n\n\tpublic static String deleteSpaces(String statement) {\n\t\t// delete mulitple spaces\n\t\twhile (statement.contains(\" \") || statement.contains(\"\t \")) {\n\t\t\tstatement = statement.replace(\" \", \" \");\n\t\t\tstatement = statement.replace(\"\t\", \" \");\n\t\t}\n\n\t\treturn statement;\n\t}\n\n\tpublic static String deleteLines(String statement) {\n\t\t// return statement.replace(\"\\r\\n\", \" \");\n\t\treturn statement.replace(System.lineSeparator(), \" \");\n\t}\n\n\tpublic static String cleanString(String statement) {\n\t\tString cleanedString = deleteLines(statement);\n\t\tcleanedString = deleteSpaces(cleanedString);\n\t\treturn cleanedString;\n\t}\n\n\tpublic static List getAllOperators() {\n\t\tList opers = new ArrayList<>();\n\n\t\topers.addAll(getTwoCharOpers());\n\n\t\topers.addAll(getOneCharOpers());\n\n\t\treturn opers;\n\t}\n\n\tpublic static List getOneCharOpers() {\n\t\tList opers = new ArrayList<>();\n\n\t\topers.add(\" = \");\n\t\topers.add(\" < \");\n\t\topers.add(\" > \");\n\n\t\treturn opers;\n\n\t}\n\n\tpublic static List getTwoCharOpers() {\n\t\tList opers = new ArrayList<>();\n\n\t\topers.add(\" EQ \");\n\t\topers.add(\" NE \");\n\t\topers.add(\" LT \");\n\t\topers.add(\" GT \");\n\t\topers.add(\" LE \");\n\t\topers.add(\" GE \");\n\n\t\topers.add(\" <> \");\n\t\topers.add(\" <= \");\n\t\topers.add(\" >= \");\n\n\t\topers.add(\" IN \");\n\n\t\treturn opers;\n\t}\n\n\tpublic static List splitLine(String statement, int limit) {\n\t\tList lines = new ArrayList();\n\n\t\tint lengthBefore = statement.length();\n\t\tstatement = statement.strip();\n\t\tString whiteChars = Utility.getWhiteChars(lengthBefore - statement.length());\n\t\tString whiteCharsTabLines = whiteChars + \" \";\n\n\t\tif (statement.length() > limit) {\n\n\t\t\tint count = 0;\n\t\t\tint subStrLength = limit;\n\t\t\twhile (statement != null) {\n\n\t\t\t\tif (statement.length() < subStrLength) {\n\t\t\t\t\tsubStrLength = statement.length();\n\t\t\t\t}\n\n\t\t\t\tString curLine = statement.substring(0, subStrLength);\n\n\t\t\t\tString regex = escapeRegex(statement.trim());\n\n\t\t\t\tif (!curLine.matches(regex)) {\n\n\t\t\t\t\t// get index of last space in this line\n\t\t\t\t\tint curIndex = curLine.lastIndexOf(\" \");\n\n\t\t\t\t\tif (curIndex != -1) {\n\t\t\t\t\t\t// index found\n\t\t\t\t\t\tcurLine = curLine.substring(0, curIndex);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// no space found --> find next space\n\t\t\t\t\t\tfor (int i = (subStrLength + 1); i < statement.length(); i++) {\n\t\t\t\t\t\t\tcurLine = statement.substring(0, i);\n\t\t\t\t\t\t\tcurIndex = curLine.lastIndexOf(\" \");\n\t\t\t\t\t\t\tif (curIndex != -1) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// still not found? take whole statement\n\t\t\t\t\t\tif (curIndex == -1) {\n\t\t\t\t\t\t\tcurLine = statement;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (count == 0) {\n\t\t\t\t\tcurLine = whiteChars + curLine;\n\t\t\t\t} else {\n\t\t\t\t\tcurLine = whiteCharsTabLines + curLine;\n\t\t\t\t}\n\n\t\t\t\tlines.add(curLine);\n\n\t\t\t\tregex = escapeRegex(curLine.trim());\n\n\t\t\t\tstatement = statement.replaceFirst(regex, \"\").trim();\n\n\t\t\t\tif (statement.isBlank()) {\n\t\t\t\t\tstatement = null;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcount++;\n\t\t\t}\n\n\t\t} else {\n\t\t\tstatement = whiteChars + statement;\n\t\t\tlines.add(statement);\n\t\t}\n\n\t\treturn lines;\n\n\t}\n\n\tpublic static String getWhiteChars(int amount) {\n\t\tString white = \"\";\n\n\t\tfor (int i = 0; i < amount; i++) {\n\t\t\twhite = white + \" \";\n\t\t}\n\n\t\treturn white;\n\t}\n\n\tpublic static String escapeRegex(String regex) {\n\t\tregex = regex.replace(\"*\", \"\\\\*\");\n\t\tregex = regex.replace(\"(\", \"\\\\(\");\n\t\tregex = regex.replace(\")\", \"\\\\)\");\n\n\t\treturn regex;\n\t}\n\n}\n\nABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/AbstractSqlSetting.java\npublic abstract class AbstractSqlSetting {\n\n\tprotected AbapSql abapSql;\n\n\tpublic AbstractSqlSetting() {\n\t}\n\n\n\tpublic abstract void apply();\n\n\n\tpublic AbapSql getAbapSql() {\n\t\treturn abapSql;\n\t}\n\n\n\tpublic void setAbapSql(AbapSql abapSql) {\n\t\tthis.abapSql = abapSql;\n\t}\n\n}", "answers": ["\t\tAbapSql abapSql = new AbapSql(inputCode, diff);"], "length": 3530, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "bc6350a2-a611-4544-b63c-65f321928006", "reasoning": "In StatementProcessor.beautifyStatement, after converting the input to upper case the next logical step is to create an AbapSql object with the processed code and the diff value, which will be used by the subsequent settings. The next line therefore constructs the AbapSql instance.", "reasoning_model_answer": "AbapSql abapSql = new AbapSql(inputCode, diff);", "assistant_with_reasoning": "\nIn StatementProcessor.beautifyStatement, after converting the input to upper case the next logical step is to create an AbapSql object with the processed code and the diff value, which will be used by the subsequent settings. The next line therefore constructs the AbapSql instance.\n\nAbapSql abapSql = new AbapSql(inputCode, diff);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.68, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33391, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "AbapSql abapSql = new AbapSql(inputCode, diff);", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerBlockEntity;\nimport com.mangomilk.design_decor.blocks.containers.green.GreenContainerBlockEntity;\nimport com.mangomilk.design_decor.blocks.containers.red.RedContainerBlockEntity;\nimport com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelBlockEntity;\nimport com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelControllerBlockEntity;\nimport com.mangomilk.design_decor.blocks.gas_tank.GasTankBlockEntity;\nimport com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearInstance;\nimport com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearRenderer;\nimport com.mangomilk.design_decor.blocks.millstone.DecoMillStoneBlockEntity;\nimport com.mangomilk.design_decor.blocks.millstone.instance.*;\nimport com.mangomilk.design_decor.blocks.millstone.renderer.*;\nimport com.simibubi.create.AllBlocks;\nimport com.simibubi.create.content.kinetics.base.CutoutRotatingInstance;\nimport com.simibubi.create.content.kinetics.base.KineticBlockEntityRenderer;\nimport com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockEntity;\nimport com.tterrag.registrate.util.entry.BlockEntityEntry;\nimport static com.mangomilk.design_decor.CreateMMBuilding.REGISTRATE;", "context": "src/main/java/com/mangomilk/design_decor/registry/MmbBlockEntities.java\n public static final BlockEntityEntry BLUE_CONTAINER = REGISTRATE\n .blockEntity(\"blue_container\", BlueContainerBlockEntity::new)\n .validBlocks(MmbBlocks.RED_CONTAINER)\n .register();\n\n public static final BlockEntityEntry MMB_CRUSHING_WHEEL = REGISTRATE\n .blockEntity(\"mmb_crushing_wheel\", MmbCrushingWheelBlockEntity::new)\n .instance(() -> CutoutRotatingInstance::new, false)\n .validBlocks(\n MmbBlocks.GRANITE_CRUSHING_WHEEL,\n MmbBlocks.DIORITE_CRUSHING_WHEEL,\n MmbBlocks.LIMESTONE_CRUSHING_WHEEL,\n MmbBlocks.SCORCHIA_CRUSHING_WHEEL,\n MmbBlocks.SCORIA_CRUSHING_WHEEL,\n MmbBlocks.TUFF_CRUSHING_WHEEL,\n MmbBlocks.VERIDIUM_CRUSHING_WHEEL,\n MmbBlocks.DRIPSTONE_CRUSHING_WHEEL,\n MmbBlocks.DEEPSLATE_CRUSHING_WHEEL,\n MmbBlocks.CRIMSITE_CRUSHING_WHEEL,\n MmbBlocks.CALCITE_CRUSHING_WHEEL,\n MmbBlocks.ASURINE_CRUSHING_WHEEL,\n MmbBlocks.OCHRUM_CRUSHING_WHEEL,\n AllBlocks.CRUSHING_WHEEL\n )\n .renderer(() -> KineticBlockEntityRenderer::new)\n .register();\n\n public static final BlockEntityEntry GRANITE_MILLSTONE =\n REGISTRATE.blockEntity(\"granite_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> GraniteMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.GRANITE_MILLSTONE)\n .renderer(() -> GraniteMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry DIORITE_MILLSTONE =\n REGISTRATE.blockEntity(\"diorite_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> DioriteMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.DIORITE_MILLSTONE)\n .renderer(() -> DioriteMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry LIMESTONE_MILLSTONE =\n REGISTRATE.blockEntity(\"limestone_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> LimestoneMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.LIMESTONE_MILLSTONE)\n .renderer(() -> LimestoneMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry SCORCHIA_MILLSTONE =\n REGISTRATE.blockEntity(\"scorchia_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> ScorchiaMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.SCORCHIA_MILLSTONE)\n .renderer(() -> ScorchiaMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry SCORIA_MILLSTONE =\n REGISTRATE.blockEntity(\"scoria_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> ScoriaMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.SCORIA_MILLSTONE)\n .renderer(() -> ScoriaMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry TUFF_MILLSTONE =\n REGISTRATE.blockEntity(\"tuff_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> TuffMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.TUFF_MILLSTONE)\n .renderer(() -> TuffMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry VERIDIUM_MILLSTONE =\n REGISTRATE.blockEntity(\"veridium_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> VeridiumMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.VERIDIUM_MILLSTONE)\n .renderer(() -> VeridiumMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry DRIPSTONE_MILLSTONE =\n REGISTRATE.blockEntity(\"dripstone_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> DripstoneMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.DRIPSTONE_MILLSTONE)\n .renderer(() -> DripstoneMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry DEEPSLATE_MILLSTONE =\n REGISTRATE.blockEntity(\"deepslate_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> DeepslateMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.DEEPSLATE_MILLSTONE)\n .renderer(() -> DeepslateMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry CRIMSITE_MILLSTONE =\n REGISTRATE.blockEntity(\"crimsite_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> CrimsiteMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.CRIMSITE_MILLSTONE)\n .renderer(() -> CrimsiteMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry CALCITE_MILLSTONE =\n REGISTRATE.blockEntity(\"calcite_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> CalciteMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.CALCITE_MILLSTONE)\n .renderer(() -> CalciteMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry ASURINE_MILLSTONE =\n REGISTRATE.blockEntity(\"asurine_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> AsurineMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.ASURINE_MILLSTONE)\n .renderer(() -> AsurineMillStoneRenderer::new)\n .register();\n\n public static final BlockEntityEntry OCHRUM_MILLSTONE =\n REGISTRATE.blockEntity(\"ochrum_millstone\", DecoMillStoneBlockEntity::new)\n .instance(() -> OchrumMillStoneCogInstance::new, false)\n .validBlocks(MmbBlocks.OCHRUM_MILLSTONE)\n .renderer(() -> OchrumMillStoneRenderer::new)\n .register();\n\n\n public static final BlockEntityEntry MMB_CRUSHING_WHEEL_CONTROLLER = REGISTRATE\n\nsrc/main/java/com/mangomilk/design_decor/blocks/containers/green/GreenContainerBlockEntity.java\npublic class GreenContainerBlockEntity extends ItemVaultBlockEntity implements IMultiBlockEntityContainer.Inventory {\n\n\tprotected LazyOptional itemCapability;\n\n\tprotected ItemStackHandler inventory;\n\tprotected BlockPos controller;\n\tprotected BlockPos lastKnownPos;\n\tprotected boolean updateConnectivity;\n\tpublic int radius;\n\tpublic int length;\n\tprotected Axis axis;\n\n\tpublic GreenContainerBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) {\n\t\tsuper(type, pos, state);\n\n\t\tinventory = new ItemStackHandler(AllConfigs.server().logistics.vaultCapacity.get()) {\n\t\t\t@Override\n\t\t\tprotected void onContentsChanged(int slot) {\n\t\t\t\tsuper.onContentsChanged(slot);\n\t\t\t\tupdateComparators();\n\t\t\t}\n\t\t};\n\n\t\titemCapability = LazyOptional.empty();\n\t\tradius = 1;\n\t\tlength = 1;\n\t}\n\n\t@Override\n\tpublic void addBehaviours(List behaviours) {}\n\n\tprotected void updateConnectivity() {\n\t\tupdateConnectivity = false;\n\t\tif (level.isClientSide())\n\t\t\treturn;\n\t\tif (!isController())\n\t\t\treturn;\n\t\tConnectivityHandler.formMulti(this);\n\n\t}\n\n\tprotected void updateComparators() {\n\t\tGreenContainerBlockEntity controllerBE = getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tlevel.blockEntityChanged(controllerBE.worldPosition);\n\t\t\n\t\tBlockPos pos = controllerBE.getBlockPos();\n\t\tfor (int y = 0; y < controllerBE.radius; y++) {\n\t\t\tfor (int z = 0; z < (controllerBE.axis == Axis.X ? controllerBE.radius : controllerBE.length); z++) {\n\t\t\t\tfor (int x = 0; x < (controllerBE.axis == Axis.Z ? controllerBE.radius : controllerBE.length); x++) {\n\t\t\t\t\tlevel.updateNeighbourForOutputSignal(pos.offset(x, y, z), getBlockState().getBlock());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void tick() {\n\t\tsuper.tick();\n\n\n\t\tif (lastKnownPos == null)\n\t\t\tlastKnownPos = getBlockPos();\n\t\telse if (!lastKnownPos.equals(worldPosition) && worldPosition != null) {\n\t\t\tonPositionChanged();\n\t\t\treturn;\n\t\t}\n\n\n\t\tif (updateConnectivity)\n\t\t\tupdateConnectivity();\n\t}\n\n\t@Override\n\tpublic BlockPos getLastKnownPos() {\n\t\treturn lastKnownPos;\n\t}\n\n\t@Override\n\tpublic boolean isController() {\n\t\treturn controller == null || worldPosition.getX() == controller.getX()\n\t\t\t&& worldPosition.getY() == controller.getY() && worldPosition.getZ() == controller.getZ();\n\t}\n\n\tprivate void onPositionChanged() {\n\t\tremoveController(true);\n\t\tlastKnownPos = worldPosition;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic GreenContainerBlockEntity getControllerBE() {\n\t\tif (isController())\n\t\t\treturn this;\n\t\tBlockEntity blockEntity = level.getBlockEntity(controller);\n\t\tif (blockEntity instanceof GreenContainerBlockEntity)\n\t\t\treturn (GreenContainerBlockEntity) blockEntity;\n\t\treturn null;\n\t}\n\n\tpublic void removeController(boolean keepContents) {\n\t\tif (level.isClientSide())\n\t\t\treturn;\n\t\tupdateConnectivity = true;\n\t\tcontroller = null;\n\t\tradius = 1;\n\t\tlength = 1;\n\n\t\tBlockState state = getBlockState();\n\n\n\n\t\t\tif (GreenContainerBlock.isContainer(state)) {\n\t\t\t\tstate = state.setValue(GreenContainerBlock.LARGE, false);\n\t\t\t\tgetLevel().setBlock(worldPosition, state, 22);\n\t\t\t}\n\n\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t\tsendData();\n\t}\n\n\t@Override\n\tpublic void setController(BlockPos controller) {\n\t\tif (level.isClientSide && !isVirtual())\n\t\t\treturn;\n\t\tif (controller.equals(this.controller))\n\t\t\treturn;\n\t\tthis.controller = controller;\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t\tsendData();\n\t}\n\n\t@Override\n\tpublic BlockPos getController() {\n\t\treturn isController() ? worldPosition : controller;\n\t}\n\n\t@Override\n\tprotected void read(CompoundTag compound, boolean clientPacket) {\n\t\tsuper.read(compound, clientPacket);\n\n\t\tBlockPos controllerBefore = controller;\n\t\tint prevSize = radius;\n\t\tint prevLength = length;\n\n\t\tupdateConnectivity = compound.contains(\"Uninitialized\");\n\t\tcontroller = null;\n\t\tlastKnownPos = null;\n\n\t\tif (compound.contains(\"LastKnownPos\"))\n\t\t\tlastKnownPos = NbtUtils.readBlockPos(compound.getCompound(\"LastKnownPos\"));\n\t\tif (compound.contains(\"Controller\"))\n\t\t\tcontroller = NbtUtils.readBlockPos(compound.getCompound(\"Controller\"));\n\n\t\tif (isController()) {\n\t\t\tradius = compound.getInt(\"Size\");\n\t\t\tlength = compound.getInt(\"Length\");\n\t\t}\n\n\t\tif (!clientPacket) {\n\t\t\tinventory.deserializeNBT(compound.getCompound(\"Inventory\"));\n\t\t\treturn;\n\t\t}\n\n\t\tboolean changeOfController =\n\t\t\tcontrollerBefore == null ? controller != null : !controllerBefore.equals(controller);\n\t\tif (hasLevel() && (changeOfController || prevSize != radius || prevLength != length))\n\t\t\tlevel.setBlocksDirty(getBlockPos(), Blocks.AIR.defaultBlockState(), getBlockState());\n\t}\n\n\t@Override\n\tprotected void write(CompoundTag compound, boolean clientPacket) {\n\t\tif (updateConnectivity)\n\t\t\tcompound.putBoolean(\"Uninitialized\", true);\n\t\tif (lastKnownPos != null)\n\t\t\tcompound.put(\"LastKnownPos\", NbtUtils.writeBlockPos(lastKnownPos));\n\t\tif (!isController())\n\t\t\tcompound.put(\"Controller\", NbtUtils.writeBlockPos(controller));\n\t\tif (isController()) {\n\t\t\tcompound.putInt(\"Size\", radius);\n\t\t\tcompound.putInt(\"Length\", length);\n\t\t}\n\n\n\t\tif (!clientPacket) {\n\t\t\tcompound.putString(\"StorageType\", \"CombinedInv\");\n\t\t\tcompound.put(\"Inventory\", inventory.serializeNBT());\n\t\t}\n\t}\n\n\tpublic ItemStackHandler getInventoryOfBlock() {\n\t\treturn inventory;\n\t}\n\n\tpublic void applyInventoryToBlock(ItemStackHandler handler) {\n\t\tfor (int i = 0; i < inventory.getSlots(); i++)\n\t\t\tinventory.setStackInSlot(i, i < handler.getSlots() ? handler.getStackInSlot(i) : ItemStack.EMPTY);\n\t}\n\n\t@Override\n\tpublic LazyOptional getCapability(Capability cap, Direction side) {\n\t\tif (isItemHandlerCap(cap)) {\n\t\t\tinitCapability();\n\t\t\treturn itemCapability.cast();\n\t\t}\n\t\treturn super.getCapability(cap, side);\n\t}\n\n\tprivate void initCapability() {\n\t\tif (itemCapability.isPresent())\n\t\t\treturn;\n\t\tif (!isController()) {\n\t\t\tGreenContainerBlockEntity controllerBE = getControllerBE();\n\t\t\tif (controllerBE == null)\n\t\t\t\treturn;\n\t\t\tcontrollerBE.initCapability();\n\t\t\titemCapability = controllerBE.itemCapability;\n\t\t\treturn;\n\t\t}\n\n\t\tboolean\talongZ = GreenContainerBlock.getContainerBlockAxis(getBlockState()) == Axis.Z;\n\n\n\t\tIItemHandlerModifiable[] invs = new IItemHandlerModifiable[length * radius * radius];\n\t\tfor (int yOffset = 0; yOffset < length; yOffset++) {\n\t\t\tfor (int xOffset = 0; xOffset < radius; xOffset++) {\n\t\t\t\tfor (int zOffset = 0; zOffset < radius; zOffset++) {\n\t\t\t\t\tBlockPos containerPos = alongZ ? worldPosition.offset(xOffset, zOffset, yOffset)\n\t\t\t\t\t\t: worldPosition.offset(yOffset, xOffset, zOffset);\n\t\t\t\t\tGreenContainerBlockEntity containerAt =\n\t\t\t\t\t\tConnectivityHandler.partAt(MmbBlockEntities.GREEN_CONTAINER.get(), level, containerPos);\n\t\t\t\t\tinvs[yOffset * radius * radius + xOffset * radius + zOffset] =\n\t\t\t\t\t\tcontainerAt != null ? containerAt.inventory : new ItemStackHandler();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tCombinedInvWrapper combinedInvWrapper = new CombinedInvWrapper(invs);\n\t\titemCapability = LazyOptional.of(() -> combinedInvWrapper);\n\t}\n\n\tpublic static int getMaxLength(int radius) {\n\t\treturn radius * 3;\n\t}\n\n\t@Override\n\tpublic void preventConnectivityUpdate() { updateConnectivity = false; }\n\n\t@Override\n\tpublic void notifyMultiUpdated() {\n\t\tBlockState state = this.getBlockState();\n\n\t\t\tif (GreenContainerBlock.isContainer(state)) { // safety\n\t\t\t\tlevel.setBlock(getBlockPos(), state.setValue(GreenContainerBlock.LARGE, radius > 2), 6);\n\t\t\t}\n\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t}\n\n\t@Override\n\tpublic Axis getMainConnectionAxis() { return getMainAxisOf(this); }\n\n\t@Override\n\tpublic int getMaxLength(Axis longAxis, int width) {\n\t\tif (longAxis == Axis.Y) return getMaxWidth();\n\t\treturn getMaxLength(width);\n\t}\n\n\t@Override\n\tpublic int getMaxWidth() {\n\t\treturn 3;\n\t}\n\n\t@Override\n\tpublic int getHeight() { return length; }\n\n\t@Override\n\tpublic int getWidth() { return radius; }\n\n\t@Override\n\tpublic void setHeight(int height) { this.length = height; }\n\n\t@Override\n\tpublic void setWidth(int width) { this.radius = width; }\n\n\t@Override\n\tpublic boolean hasInventory() { return true; }\n}\n\nsrc/main/java/com/mangomilk/design_decor/blocks/containers/red/RedContainerBlockEntity.java\npublic class RedContainerBlockEntity extends ItemVaultBlockEntity implements IMultiBlockEntityContainer.Inventory {\n\n\tprotected LazyOptional itemCapability;\n\n\tprotected ItemStackHandler inventory;\n\tprotected BlockPos controller;\n\tprotected BlockPos lastKnownPos;\n\tprotected boolean updateConnectivity;\n\tpublic int radius;\n\tpublic int length;\n\tprotected Axis axis;\n\n\tpublic RedContainerBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) {\n\t\tsuper(type, pos, state);\n\n\t\tinventory = new ItemStackHandler(AllConfigs.server().logistics.vaultCapacity.get()) {\n\t\t\t@Override\n\t\t\tprotected void onContentsChanged(int slot) {\n\t\t\t\tsuper.onContentsChanged(slot);\n\t\t\t\tupdateComparators();\n\t\t\t}\n\t\t};\n\n\t\titemCapability = LazyOptional.empty();\n\t\tradius = 1;\n\t\tlength = 1;\n\t}\n\n\t@Override\n\tpublic void addBehaviours(List behaviours) {}\n\n\tprotected void updateConnectivity() {\n\t\tupdateConnectivity = false;\n\t\tif (level.isClientSide())\n\t\t\treturn;\n\t\tif (!isController())\n\t\t\treturn;\n\t\tConnectivityHandler.formMulti(this);\n\n\t}\n\n\tprotected void updateComparators() {\n\t\tRedContainerBlockEntity controllerBE = getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tlevel.blockEntityChanged(controllerBE.worldPosition);\n\t\t\n\t\tBlockPos pos = controllerBE.getBlockPos();\n\t\tfor (int y = 0; y < controllerBE.radius; y++) {\n\t\t\tfor (int z = 0; z < (controllerBE.axis == Axis.X ? controllerBE.radius : controllerBE.length); z++) {\n\t\t\t\tfor (int x = 0; x < (controllerBE.axis == Axis.Z ? controllerBE.radius : controllerBE.length); x++) {\n\t\t\t\t\tlevel.updateNeighbourForOutputSignal(pos.offset(x, y, z), getBlockState().getBlock());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void tick() {\n\t\tsuper.tick();\n\n\n\t\tif (lastKnownPos == null)\n\t\t\tlastKnownPos = getBlockPos();\n\t\telse if (!lastKnownPos.equals(worldPosition) && worldPosition != null) {\n\t\t\tonPositionChanged();\n\t\t\treturn;\n\t\t}\n\n\n\t\tif (updateConnectivity)\n\t\t\tupdateConnectivity();\n\t}\n\n\t@Override\n\tpublic BlockPos getLastKnownPos() {\n\t\treturn lastKnownPos;\n\t}\n\n\t@Override\n\tpublic boolean isController() {\n\t\treturn controller == null || worldPosition.getX() == controller.getX()\n\t\t\t&& worldPosition.getY() == controller.getY() && worldPosition.getZ() == controller.getZ();\n\t}\n\n\tprivate void onPositionChanged() {\n\t\tremoveController(true);\n\t\tlastKnownPos = worldPosition;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic RedContainerBlockEntity getControllerBE() {\n\t\tif (isController())\n\t\t\treturn this;\n\t\tBlockEntity blockEntity = level.getBlockEntity(controller);\n\t\tif (blockEntity instanceof RedContainerBlockEntity)\n\t\t\treturn (RedContainerBlockEntity) blockEntity;\n\t\treturn null;\n\t}\n\n\tpublic void removeController(boolean keepContents) {\n\t\tif (level.isClientSide())\n\t\t\treturn;\n\t\tupdateConnectivity = true;\n\t\tcontroller = null;\n\t\tradius = 1;\n\t\tlength = 1;\n\n\t\tBlockState state = getBlockState();\n\n\n\n\t\t\tif (RedContainerBlock.isContainer(state)) {\n\t\t\t\tstate = state.setValue(RedContainerBlock.LARGE, false);\n\t\t\t\tgetLevel().setBlock(worldPosition, state, 22);\n\t\t\t}\n\n\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t\tsendData();\n\t}\n\n\t@Override\n\tpublic void setController(BlockPos controller) {\n\t\tif (level.isClientSide && !isVirtual())\n\t\t\treturn;\n\t\tif (controller.equals(this.controller))\n\t\t\treturn;\n\t\tthis.controller = controller;\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t\tsendData();\n\t}\n\n\t@Override\n\tpublic BlockPos getController() {\n\t\treturn isController() ? worldPosition : controller;\n\t}\n\n\t@Override\n\tprotected void read(CompoundTag compound, boolean clientPacket) {\n\t\tsuper.read(compound, clientPacket);\n\n\t\tBlockPos controllerBefore = controller;\n\t\tint prevSize = radius;\n\t\tint prevLength = length;\n\n\t\tupdateConnectivity = compound.contains(\"Uninitialized\");\n\t\tcontroller = null;\n\t\tlastKnownPos = null;\n\n\t\tif (compound.contains(\"LastKnownPos\"))\n\t\t\tlastKnownPos = NbtUtils.readBlockPos(compound.getCompound(\"LastKnownPos\"));\n\t\tif (compound.contains(\"Controller\"))\n\t\t\tcontroller = NbtUtils.readBlockPos(compound.getCompound(\"Controller\"));\n\n\t\tif (isController()) {\n\t\t\tradius = compound.getInt(\"Size\");\n\t\t\tlength = compound.getInt(\"Length\");\n\t\t}\n\n\t\tif (!clientPacket) {\n\t\t\tinventory.deserializeNBT(compound.getCompound(\"Inventory\"));\n\t\t\treturn;\n\t\t}\n\n\t\tboolean changeOfController =\n\t\t\tcontrollerBefore == null ? controller != null : !controllerBefore.equals(controller);\n\t\tif (hasLevel() && (changeOfController || prevSize != radius || prevLength != length))\n\t\t\tlevel.setBlocksDirty(getBlockPos(), Blocks.AIR.defaultBlockState(), getBlockState());\n\t}\n\n\t@Override\n\tprotected void write(CompoundTag compound, boolean clientPacket) {\n\t\tif (updateConnectivity)\n\t\t\tcompound.putBoolean(\"Uninitialized\", true);\n\t\tif (lastKnownPos != null)\n\t\t\tcompound.put(\"LastKnownPos\", NbtUtils.writeBlockPos(lastKnownPos));\n\t\tif (!isController())\n\t\t\tcompound.put(\"Controller\", NbtUtils.writeBlockPos(controller));\n\t\tif (isController()) {\n\t\t\tcompound.putInt(\"Size\", radius);\n\t\t\tcompound.putInt(\"Length\", length);\n\t\t}\n\n\n\t\tif (!clientPacket) {\n\t\t\tcompound.putString(\"StorageType\", \"CombinedInv\");\n\t\t\tcompound.put(\"Inventory\", inventory.serializeNBT());\n\t\t}\n\t}\n\n\tpublic ItemStackHandler getInventoryOfBlock() {\n\t\treturn inventory;\n\t}\n\n\tpublic void applyInventoryToBlock(ItemStackHandler handler) {\n\t\tfor (int i = 0; i < inventory.getSlots(); i++)\n\t\t\tinventory.setStackInSlot(i, i < handler.getSlots() ? handler.getStackInSlot(i) : ItemStack.EMPTY);\n\t}\n\n\t@Override\n\tpublic LazyOptional getCapability(Capability cap, Direction side) {\n\t\tif (isItemHandlerCap(cap)) {\n\t\t\tinitCapability();\n\t\t\treturn itemCapability.cast();\n\t\t}\n\t\treturn super.getCapability(cap, side);\n\t}\n\n\tprivate void initCapability() {\n\t\tif (itemCapability.isPresent())\n\t\t\treturn;\n\t\tif (!isController()) {\n\t\t\tRedContainerBlockEntity controllerBE = getControllerBE();\n\t\t\tif (controllerBE == null)\n\t\t\t\treturn;\n\t\t\tcontrollerBE.initCapability();\n\t\t\titemCapability = controllerBE.itemCapability;\n\t\t\treturn;\n\t\t}\n\n\t\tboolean\talongZ = RedContainerBlock.getContainerBlockAxis(getBlockState()) == Axis.Z;\n\n\n\t\tIItemHandlerModifiable[] invs = new IItemHandlerModifiable[length * radius * radius];\n\t\tfor (int yOffset = 0; yOffset < length; yOffset++) {\n\t\t\tfor (int xOffset = 0; xOffset < radius; xOffset++) {\n\t\t\t\tfor (int zOffset = 0; zOffset < radius; zOffset++) {\n\t\t\t\t\tBlockPos containerPos = alongZ ? worldPosition.offset(xOffset, zOffset, yOffset)\n\t\t\t\t\t\t: worldPosition.offset(yOffset, xOffset, zOffset);\n\t\t\t\t\tRedContainerBlockEntity containerAt =\n\t\t\t\t\t\tConnectivityHandler.partAt(MmbBlockEntities.RED_CONTAINER.get(), level, containerPos);\n\t\t\t\t\tinvs[yOffset * radius * radius + xOffset * radius + zOffset] =\n\t\t\t\t\t\tcontainerAt != null ? containerAt.inventory : new ItemStackHandler();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tCombinedInvWrapper combinedInvWrapper = new CombinedInvWrapper(invs);\n\t\titemCapability = LazyOptional.of(() -> combinedInvWrapper);\n\t}\n\n\tpublic static int getMaxLength(int radius) {\n\t\treturn radius * 3;\n\t}\n\n\t@Override\n\tpublic void preventConnectivityUpdate() { updateConnectivity = false; }\n\n\t@Override\n\tpublic void notifyMultiUpdated() {\n\t\tBlockState state = this.getBlockState();\n\n\t\t\tif (RedContainerBlock.isContainer(state)) { // safety\n\t\t\t\tlevel.setBlock(getBlockPos(), state.setValue(RedContainerBlock.LARGE, radius > 2), 6);\n\t\t\t}\n\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t}\n\n\t@Override\n\tpublic Axis getMainConnectionAxis() { return getMainAxisOf(this); }\n\n\t@Override\n\tpublic int getMaxLength(Axis longAxis, int width) {\n\t\tif (longAxis == Axis.Y) return getMaxWidth();\n\t\treturn getMaxLength(width);\n\t}\n\n\t@Override\n\tpublic int getMaxWidth() {\n\t\treturn 3;\n\t}\n\n\t@Override\n\tpublic int getHeight() { return length; }\n\n\t@Override\n\tpublic int getWidth() { return radius; }\n\n\t@Override\n\tpublic void setHeight(int height) { this.length = height; }\n\n\t@Override\n\tpublic void setWidth(int width) { this.radius = width; }\n\n\t@Override\n\tpublic boolean hasInventory() { return true; }\n}\n\nsrc/main/java/com/mangomilk/design_decor/CreateMMBuilding.java\npublic static final CreateRegistrate REGISTRATE = CreateRegistrate.create(CreateMMBuilding.MOD_ID).creativeModeTab(()-> MmbCreativeModeTab.BUILDING);\n\nsrc/main/java/com/mangomilk/design_decor/blocks/millstone/DecoMillStoneBlockEntity.java\npublic class DecoMillStoneBlockEntity extends MillstoneBlockEntity {\n public DecoMillStoneBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) {\n super(type, pos, state);\n capability = LazyOptional.of(DecoMillstoneInventoryHandler::new);\n }\n\n public MillingRecipe lastRecipe;\n\n @Override\n public void tick() {\n super.tick();\n\n if (getSpeed() == 0)\n return;\n for (int i = 0; i < outputInv.getSlots(); i++)\n if (outputInv.getStackInSlot(i)\n .getCount() == outputInv.getSlotLimit(i))\n return;\n\n if (timer > 0) {\n timer -= getProcessingSpeed();\n\n if (level.isClientSide) {\n spawnParticles();\n return;\n }\n if (timer <= 0)\n process();\n return;\n }\n\n if (inputInv.getStackInSlot(0)\n .isEmpty())\n return;\n\n RecipeWrapper inventoryIn = new RecipeWrapper(inputInv);\n if (lastRecipe == null || !lastRecipe.matches(inventoryIn, level)) {\n Optional recipe = AllRecipeTypes.MILLING.find(inventoryIn, level);\n if (!recipe.isPresent()) {\n timer = 100;\n sendData();\n } else {\n lastRecipe = recipe.get();\n timer = lastRecipe.getProcessingDuration();\n sendData();\n }\n return;\n }\n\n timer = lastRecipe.getProcessingDuration();\n sendData();\n }\n\n public void process() {\n RecipeWrapper inventoryIn = new RecipeWrapper(inputInv);\n\n if (lastRecipe == null || !lastRecipe.matches(inventoryIn, level)) {\n Optional recipe = AllRecipeTypes.MILLING.find(inventoryIn, level);\n if (!recipe.isPresent())\n return;\n lastRecipe = recipe.get();\n }\n\n ItemStack stackInSlot = inputInv.getStackInSlot(0);\n stackInSlot.shrink(1);\n inputInv.setStackInSlot(0, stackInSlot);\n lastRecipe.rollResults()\n .forEach(stack -> ItemHandlerHelper.insertItemStacked(outputInv, stack, false));\n award(AllAdvancements.MILLSTONE);\n\n sendData();\n setChanged();\n }\n\n public boolean canProcess(ItemStack stack) {\n ItemStackHandler tester = new ItemStackHandler(1);\n tester.setStackInSlot(0, stack);\n RecipeWrapper inventoryIn = new RecipeWrapper(tester);\n\n if (lastRecipe != null && lastRecipe.matches(inventoryIn, level))\n return true;\n return AllRecipeTypes.MILLING.find(inventoryIn, level)\n .isPresent();\n }\n\n public class DecoMillstoneInventoryHandler extends CombinedInvWrapper {\n\n public DecoMillstoneInventoryHandler() {\n super(inputInv, outputInv);\n }\n\n @Override\n public boolean isItemValid(int slot, ItemStack stack) {\n if (outputInv == getHandlerFromIndex(getIndexForSlot(slot)))\n return false;\n return canProcess(stack) && super.isItemValid(slot, stack);\n }\n\n @Override\n public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) {\n if (outputInv == getHandlerFromIndex(getIndexForSlot(slot)))\n return stack;\n if (!isItemValid(slot, stack))\n return stack;\n return super.insertItem(slot, stack, simulate);\n }\n\n @Override\n public ItemStack extractItem(int slot, int amount, boolean simulate) {\n if (inputInv == getHandlerFromIndex(getIndexForSlot(slot)))\n return ItemStack.EMPTY;\n return super.extractItem(slot, amount, simulate);\n }\n\n }\n}\n\nsrc/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelBlockEntity.java\n@EventBusSubscriber\npublic class MmbCrushingWheelBlockEntity extends CrushingWheelBlockEntity {\n\n\tpublic static final DamageSource DAMAGE_SOURCE = new DamageSource(\"create.crush\").bypassArmor()\n\t\t\t.setScalesWithDifficulty();\n\n\tpublic MmbCrushingWheelBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) {\n\t\tsuper(type, pos, state);\n\t\tsetLazyTickRate(20);\n\t}\n\n\t@Override\n\tprotected AABB createRenderBoundingBox() {\n\t\treturn new AABB(worldPosition).inflate(1);\n\t}\n}\n\nsrc/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerBlockEntity.java\npublic class BlueContainerBlockEntity extends ItemVaultBlockEntity implements IMultiBlockEntityContainer.Inventory {\n\n\tprotected LazyOptional itemCapability;\n\n\tprotected ItemStackHandler inventory;\n\tprotected BlockPos controller;\n\tprotected BlockPos lastKnownPos;\n\tprotected boolean updateConnectivity;\n\tpublic int radius;\n\tpublic int length;\n\tprotected Axis axis;\n\n\tpublic BlueContainerBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) {\n\t\tsuper(type, pos, state);\n\n\t\tinventory = new ItemStackHandler(AllConfigs.server().logistics.vaultCapacity.get()) {\n\t\t\t@Override\n\t\t\tprotected void onContentsChanged(int slot) {\n\t\t\t\tsuper.onContentsChanged(slot);\n\t\t\t\tupdateComparators();\n\t\t\t}\n\t\t};\n\n\t\titemCapability = LazyOptional.empty();\n\t\tradius = 1;\n\t\tlength = 1;\n\t}\n\n\t@Override\n\tpublic void addBehaviours(List behaviours) {}\n\n\tprotected void updateConnectivity() {\n\t\tupdateConnectivity = false;\n\t\tif (level.isClientSide())\n\t\t\treturn;\n\t\tif (!isController())\n\t\t\treturn;\n\t\tConnectivityHandler.formMulti(this);\n\n\t}\n\n\tprotected void updateComparators() {\n\t\tBlueContainerBlockEntity controllerBE = getControllerBE();\n\t\tif (controllerBE == null)\n\t\t\treturn;\n\n\t\tlevel.blockEntityChanged(controllerBE.worldPosition);\n\t\t\n\t\tBlockPos pos = controllerBE.getBlockPos();\n\t\tfor (int y = 0; y < controllerBE.radius; y++) {\n\t\t\tfor (int z = 0; z < (controllerBE.axis == Axis.X ? controllerBE.radius : controllerBE.length); z++) {\n\t\t\t\tfor (int x = 0; x < (controllerBE.axis == Axis.Z ? controllerBE.radius : controllerBE.length); x++) {\n\t\t\t\t\tlevel.updateNeighbourForOutputSignal(pos.offset(x, y, z), getBlockState().getBlock());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void tick() {\n\t\tsuper.tick();\n\n\n\t\tif (lastKnownPos == null)\n\t\t\tlastKnownPos = getBlockPos();\n\t\telse if (!lastKnownPos.equals(worldPosition) && worldPosition != null) {\n\t\t\tonPositionChanged();\n\t\t\treturn;\n\t\t}\n\n\n\t\tif (updateConnectivity)\n\t\t\tupdateConnectivity();\n\t}\n\n\t@Override\n\tpublic BlockPos getLastKnownPos() {\n\t\treturn lastKnownPos;\n\t}\n\n\t@Override\n\tpublic boolean isController() {\n\t\treturn controller == null || worldPosition.getX() == controller.getX()\n\t\t\t&& worldPosition.getY() == controller.getY() && worldPosition.getZ() == controller.getZ();\n\t}\n\n\tprivate void onPositionChanged() {\n\t\tremoveController(true);\n\t\tlastKnownPos = worldPosition;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic BlueContainerBlockEntity getControllerBE() {\n\t\tif (isController())\n\t\t\treturn this;\n\t\tBlockEntity blockEntity = level.getBlockEntity(controller);\n\t\tif (blockEntity instanceof BlueContainerBlockEntity)\n\t\t\treturn (BlueContainerBlockEntity) blockEntity;\n\t\treturn null;\n\t}\n\n\tpublic void removeController(boolean keepContents) {\n\t\tif (level.isClientSide())\n\t\t\treturn;\n\t\tupdateConnectivity = true;\n\t\tcontroller = null;\n\t\tradius = 1;\n\t\tlength = 1;\n\n\t\tBlockState state = getBlockState();\n\n\n\n\t\t\tif (BlueContainerBlock.isContainer(state)) {\n\t\t\t\tstate = state.setValue(BlueContainerBlock.LARGE, false);\n\t\t\t\tgetLevel().setBlock(worldPosition, state, 22);\n\t\t\t}\n\n\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t\tsendData();\n\t}\n\n\t@Override\n\tpublic void setController(BlockPos controller) {\n\t\tif (level.isClientSide && !isVirtual())\n\t\t\treturn;\n\t\tif (controller.equals(this.controller))\n\t\t\treturn;\n\t\tthis.controller = controller;\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t\tsendData();\n\t}\n\n\t@Override\n\tpublic BlockPos getController() {\n\t\treturn isController() ? worldPosition : controller;\n\t}\n\n\t@Override\n\tprotected void read(CompoundTag compound, boolean clientPacket) {\n\t\tsuper.read(compound, clientPacket);\n\n\t\tBlockPos controllerBefore = controller;\n\t\tint prevSize = radius;\n\t\tint prevLength = length;\n\n\t\tupdateConnectivity = compound.contains(\"Uninitialized\");\n\t\tcontroller = null;\n\t\tlastKnownPos = null;\n\n\t\tif (compound.contains(\"LastKnownPos\"))\n\t\t\tlastKnownPos = NbtUtils.readBlockPos(compound.getCompound(\"LastKnownPos\"));\n\t\tif (compound.contains(\"Controller\"))\n\t\t\tcontroller = NbtUtils.readBlockPos(compound.getCompound(\"Controller\"));\n\n\t\tif (isController()) {\n\t\t\tradius = compound.getInt(\"Size\");\n\t\t\tlength = compound.getInt(\"Length\");\n\t\t}\n\n\t\tif (!clientPacket) {\n\t\t\tinventory.deserializeNBT(compound.getCompound(\"Inventory\"));\n\t\t\treturn;\n\t\t}\n\n\t\tboolean changeOfController =\n\t\t\tcontrollerBefore == null ? controller != null : !controllerBefore.equals(controller);\n\t\tif (hasLevel() && (changeOfController || prevSize != radius || prevLength != length))\n\t\t\tlevel.setBlocksDirty(getBlockPos(), Blocks.AIR.defaultBlockState(), getBlockState());\n\t}\n\n\t@Override\n\tprotected void write(CompoundTag compound, boolean clientPacket) {\n\t\tif (updateConnectivity)\n\t\t\tcompound.putBoolean(\"Uninitialized\", true);\n\t\tif (lastKnownPos != null)\n\t\t\tcompound.put(\"LastKnownPos\", NbtUtils.writeBlockPos(lastKnownPos));\n\t\tif (!isController())\n\t\t\tcompound.put(\"Controller\", NbtUtils.writeBlockPos(controller));\n\t\tif (isController()) {\n\t\t\tcompound.putInt(\"Size\", radius);\n\t\t\tcompound.putInt(\"Length\", length);\n\t\t}\n\n\n\t\tif (!clientPacket) {\n\t\t\tcompound.putString(\"StorageType\", \"CombinedInv\");\n\t\t\tcompound.put(\"Inventory\", inventory.serializeNBT());\n\t\t}\n\t}\n\n\tpublic ItemStackHandler getInventoryOfBlock() {\n\t\treturn inventory;\n\t}\n\n\tpublic void applyInventoryToBlock(ItemStackHandler handler) {\n\t\tfor (int i = 0; i < inventory.getSlots(); i++)\n\t\t\tinventory.setStackInSlot(i, i < handler.getSlots() ? handler.getStackInSlot(i) : ItemStack.EMPTY);\n\t}\n\n\t@Override\n\tpublic LazyOptional getCapability(Capability cap, Direction side) {\n\t\tif (isItemHandlerCap(cap)) {\n\t\t\tinitCapability();\n\t\t\treturn itemCapability.cast();\n\t\t}\n\t\treturn super.getCapability(cap, side);\n\t}\n\n\tprivate void initCapability() {\n\t\tif (itemCapability.isPresent())\n\t\t\treturn;\n\t\tif (!isController()) {\n\t\t\tBlueContainerBlockEntity controllerBE = getControllerBE();\n\t\t\tif (controllerBE == null)\n\t\t\t\treturn;\n\t\t\tcontrollerBE.initCapability();\n\t\t\titemCapability = controllerBE.itemCapability;\n\t\t\treturn;\n\t\t}\n\n\t\tboolean\talongZ = BlueContainerBlock.getContainerBlockAxis(getBlockState()) == Axis.Z;\n\n\n\t\tIItemHandlerModifiable[] invs = new IItemHandlerModifiable[length * radius * radius];\n\t\tfor (int yOffset = 0; yOffset < length; yOffset++) {\n\t\t\tfor (int xOffset = 0; xOffset < radius; xOffset++) {\n\t\t\t\tfor (int zOffset = 0; zOffset < radius; zOffset++) {\n\t\t\t\t\tBlockPos containerPos = alongZ ? worldPosition.offset(xOffset, zOffset, yOffset)\n\t\t\t\t\t\t: worldPosition.offset(yOffset, xOffset, zOffset);\n\t\t\t\t\tBlueContainerBlockEntity containerAt =\n\t\t\t\t\t\tConnectivityHandler.partAt(MmbBlockEntities.BLUE_CONTAINER.get(), level, containerPos);\n\t\t\t\t\tinvs[yOffset * radius * radius + xOffset * radius + zOffset] =\n\t\t\t\t\t\tcontainerAt != null ? containerAt.inventory : new ItemStackHandler();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tCombinedInvWrapper combinedInvWrapper = new CombinedInvWrapper(invs);\n\t\titemCapability = LazyOptional.of(() -> combinedInvWrapper);\n\t}\n\n\tpublic static int getMaxLength(int radius) {\n\t\treturn radius * 3;\n\t}\n\n\t@Override\n\tpublic void preventConnectivityUpdate() { updateConnectivity = false; }\n\n\t@Override\n\tpublic void notifyMultiUpdated() {\n\t\tBlockState state = this.getBlockState();\n\n\t\t\tif (BlueContainerBlock.isContainer(state)) { // safety\n\t\t\t\tlevel.setBlock(getBlockPos(), state.setValue(BlueContainerBlock.LARGE, radius > 2), 6);\n\t\t\t}\n\n\t\titemCapability.invalidate();\n\t\tsetChanged();\n\t}\n\n\t@Override\n\tpublic Axis getMainConnectionAxis() { return getMainAxisOf(this); }\n\n\t@Override\n\tpublic int getMaxLength(Axis longAxis, int width) {\n\t\tif (longAxis == Axis.Y) return getMaxWidth();\n\t\treturn getMaxLength(width);\n\t}\n\n\t@Override\n\tpublic int getMaxWidth() {\n\t\treturn 3;\n\t}\n\n\t@Override\n\tpublic int getHeight() { return length; }\n\n\t@Override\n\tpublic int getWidth() { return radius; }\n\n\t@Override\n\tpublic void setHeight(int height) { this.length = height; }\n\n\t@Override\n\tpublic void setWidth(int width) { this.radius = width; }\n\n\t@Override\n\tpublic boolean hasInventory() { return true; }\n}\n\nsrc/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearRenderer.java\npublic class IndustrialGearRenderer extends KineticBlockEntityRenderer {\n public IndustrialGearRenderer(BlockEntityRendererProvider.Context context) {\n super(context);\n }\n\n @Override\n protected void renderSafe(BracketedKineticBlockEntity be, float partialTicks, PoseStack ms,\n MultiBufferSource buffer, int light, int overlay) {\n\n if (Backend.canUseInstancing(be.getLevel()))\n return;\n\n if (!MmbBlocks.LARGE_COGWHEEL.has(be.getBlockState())) {\n super.renderSafe(be, partialTicks, ms, buffer, light, overlay);\n return;\n }\n\n // Large cogs sometimes have to offset their teeth by 11.25 degrees in order to\n // mesh properly\n\n Direction.Axis axis = getRotationAxisOf(be);\n Direction facing = Direction.fromAxisAndDirection(axis, Direction.AxisDirection.POSITIVE);\n renderRotatingBuffer(be,\n CachedBufferer.partialFacingVertical(DecoPartialModels.SHAFTLESS_LARGE_COGWHEEL, be.getBlockState(), facing),\n ms, buffer.getBuffer(RenderType.solid()), light);\n\n float angle = getAngleForLargeCogShaft(be, axis);\n SuperByteBuffer shaft =\n CachedBufferer.partialFacingVertical(DecoPartialModels.EMPTY, be.getBlockState(), facing);\n kineticRotationTransform(shaft, be, axis, angle, light);\n shaft.renderInto(ms, buffer.getBuffer(RenderType.solid()));\n\n }\n\n public static float getAngleForLargeCogShaft(SimpleKineticBlockEntity be, Direction.Axis axis) {\n BlockPos pos = be.getBlockPos();\n float offset = getShaftAngleOffset(axis, pos);\n float time = AnimationTickHolder.getRenderTime(be.getLevel());\n float angle = ((time * be.getSpeed() * 3f / 10 + offset) % 360) / 180 * (float) Math.PI;\n return angle;\n }\n\n public static float getShaftAngleOffset(Direction.Axis axis, BlockPos pos) {\n float offset = 0;\n double d = (((axis == Direction.Axis.X) ? 0 : pos.getX()) + ((axis == Direction.Axis.Y) ? 0 : pos.getY())\n + ((axis == Direction.Axis.Z) ? 0 : pos.getZ())) % 2;\n if (d == 0)\n offset = 22.5f;\n return offset;\n }\n}\n\nsrc/main/java/com/mangomilk/design_decor/blocks/gas_tank/GasTankBlockEntity.java\npublic class GasTankBlockEntity extends SmartBlockEntity implements IHaveGoggleInformation {\n\n\n protected FluidTank tankInventory;\n\n protected LazyOptional fluidCapability;\n\n public GasTankBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) {\n super(type, pos, state);\n\n tankInventory = new SmartFluidTank(5000,this::onFluidStackChanged);\n\n fluidCapability = LazyOptional.of(() -> tankInventory);\n }\n\n @Nonnull\n @Override\n @SuppressWarnings(\"removal\")\n public LazyOptional getCapability(@Nonnull Capability cap, Direction side) {\n\n if (cap == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY)\n return fluidCapability.cast();\n return super.getCapability(cap, side);\n }\n @Override\n public void invalidate() {\n super.invalidate();\n\n fluidCapability.invalidate();\n }\n\n @Override\n protected void read(CompoundTag compound, boolean clientPacket) {\n super.read(compound, clientPacket);\n\n tankInventory.readFromNBT(compound.getCompound(\"TankContent\"));\n\n\n\n }\n protected void onFluidStackChanged(FluidStack newFluidStack) {\n if (!hasLevel())\n return;\n\n\n\n if (!level.isClientSide) {\n setChanged();\n sendData();\n }\n\n\n }\n @Override\n public void write(CompoundTag compound, boolean clientPacket) {\n super.write(compound, clientPacket);\n\n\n compound.put(\"TankContent\", tankInventory.writeToNBT(new CompoundTag()));\n\n\n\n }\n @Override\n public void addBehaviours(List behaviours) {}\n @Override\n @SuppressWarnings(\"removal\")\n public boolean addToGoggleTooltip(List tooltip, boolean isPlayerSneaking) {\n\n //--Fluid Info--//\n LazyOptional handler = this.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY);\n Optional resolve = handler.resolve();\n if (!resolve.isPresent())\n return false;\n\n IFluidHandler tank = resolve.get();\n if (tank.getTanks() == 0)\n return false;\n\n LangBuilder mb = Lang.translate(\"generic.unit.millibuckets\");\n\n\n boolean isEmpty = true;\n for (int i = 0; i < tank.getTanks(); i++) {\n FluidStack fluidStack = tank.getFluidInTank(i);\n if (fluidStack.isEmpty())\n continue;\n\n Lang.fluidName(fluidStack)\n .style(ChatFormatting.GRAY)\n .forGoggles(tooltip, 1);\n\n Lang.builder()\n .add(Lang.number(fluidStack.getAmount())\n .add(mb)\n .style(ChatFormatting.DARK_PURPLE))\n .text(ChatFormatting.GRAY, \" / \")\n .add(Lang.number(tank.getTankCapacity(i))\n .add(mb)\n .style(ChatFormatting.DARK_GRAY))\n .forGoggles(tooltip, 1);\n\n isEmpty = false;\n }\n\n if (tank.getTanks() > 1) {\n if (isEmpty)\n tooltip.remove(tooltip.size() - 1);\n return true;\n }\n\n if (!isEmpty)\n return true;\n\n Lang.translate(\"gui.goggles.fluid_container.capacity\")\n .add(Lang.number(tank.getTankCapacity(0))\n .add(mb)\n .style(ChatFormatting.DARK_PURPLE))\n .style(ChatFormatting.DARK_GRAY)\n .forGoggles(tooltip, 1);\n\n\n return true;\n }\n}\n\nsrc/main/java/com/mangomilk/design_decor/blocks/industrial_gear/IndustrialGearInstance.java\npublic class IndustrialGearInstance extends SingleRotatingInstance {\n\n protected RotatingData additionalShaft;\n\n public IndustrialGearInstance(MaterialManager materialManager, BracketedKineticBlockEntity blockEntity) {\n super(materialManager, blockEntity);\n }\n\n @Override\n public void init() {\n super.init();\n if (!ICogWheel.isLargeCog(blockEntity.getBlockState()))\n return;\n\n // Large cogs sometimes have to offset their teeth by 11.25 degrees in order to\n // mesh properly\n\n float speed = blockEntity.getSpeed();\n Direction.Axis axis = KineticBlockEntityRenderer.getRotationAxisOf(blockEntity);\n BlockPos pos = blockEntity.getBlockPos();\n float offset = BracketedKineticBlockEntityRenderer.getShaftAngleOffset(axis, pos);\n Direction facing = Direction.fromAxisAndDirection(axis, Direction.AxisDirection.POSITIVE);\n Instancer half = getRotatingMaterial().getModel(DecoPartialModels.EMPTY, blockState,\n facing, () -> this.rotateToAxis(axis));\n\n additionalShaft = setup(half.createInstance(), speed);\n additionalShaft.setRotationOffset(offset);\n }\n\n @Override\n protected Instancer getModel() {\n if (!ICogWheel.isLargeCog(blockEntity.getBlockState()))\n return super.getModel();\n\n Direction.Axis axis = KineticBlockEntityRenderer.getRotationAxisOf(blockEntity);\n Direction facing = Direction.fromAxisAndDirection(axis, Direction.AxisDirection.POSITIVE);\n return getRotatingMaterial().getModel(DecoPartialModels.SHAFTLESS_LARGE_COGWHEEL, blockState, facing,\n () -> this.rotateToAxis(axis));\n }\n\n private PoseStack rotateToAxis(Direction.Axis axis) {\n Direction facing = Direction.fromAxisAndDirection(axis, Direction.AxisDirection.POSITIVE);\n PoseStack poseStack = new PoseStack();\n TransformStack.cast(poseStack)\n .centre()\n .rotateToFace(facing)\n .multiply(Vector3f.XN.rotationDegrees(-90))\n .unCentre();\n return poseStack;\n }\n\n @Override\n public void update() {\n super.update();\n if (additionalShaft != null) {\n updateRotation(additionalShaft);\n additionalShaft.setRotationOffset(BracketedKineticBlockEntityRenderer.getShaftAngleOffset(axis, pos));\n }\n }\n\n @Override\n public void updateLight() {\n super.updateLight();\n if (additionalShaft != null)\n relight(pos, additionalShaft);\n }\n\n @Override\n public void remove() {\n super.remove();\n if (additionalShaft != null)\n additionalShaft.delete();\n }\n\n}\n\nsrc/main/java/com/mangomilk/design_decor/blocks/crushing_wheels/MmbCrushingWheelControllerBlockEntity.java\npublic class MmbCrushingWheelControllerBlockEntity extends CrushingWheelControllerBlockEntity {\n\tprivate UUID entityUUID;\n\tprivate RecipeWrapper wrapper;\n\tpublic MmbCrushingWheelControllerBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) {\n\t\tsuper(type, pos, state);\n\t\twrapper = new RecipeWrapper(inventory);\n\t}\n\n\t@Override\n\tpublic void tick() {\n\t\tsuper.tick();\n\t\tif (searchForEntity) {\n\t\t\tsearchForEntity = false;\n\t\t\tList search = level.getEntities((Entity) null, new AABB(getBlockPos()),\n\t\t\t\te -> entityUUID.equals(e.getUUID()));\n\t\t\tif (search.isEmpty())\n\t\t\t\tclear();\n\t\t\telse\n\t\t\t\tprocessingEntity = search.get(0);\n\t\t}\n\n\t\tif (!isOccupied())\n\t\t\treturn;\n\t\tif (crushingspeed == 0)\n\t\t\treturn;\n\n\t\tif (level.isClientSide)\n\t\t\tDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> this.tickAudio());\n\n\t\tfloat speed = crushingspeed * 4;\n\n\t\tVec3 centerPos = VecHelper.getCenterOf(worldPosition);\n\t\tDirection facing = getBlockState().getValue(MmbCrushingWheelControllerBlock.FACING);\n\t\tint offset = facing.getAxisDirection()\n\t\t\t.getStep();\n\t\tVec3 outSpeed = new Vec3((facing.getAxis() == Axis.X ? 0.25D : 0.0D) * offset,\n\t\t\toffset == 1 ? (facing.getAxis() == Axis.Y ? 0.5D : 0.0D) : 0.0D // Increased upwards speed so upwards\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// crushing wheels shoot out the item\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// properly.\n\t\t\t, (facing.getAxis() == Axis.Z ? 0.25D : 0.0D) * offset); // No downwards speed, so downwards crushing wheels\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// drop the items as before.\n\t\tVec3 outPos = centerPos.add((facing.getAxis() == Axis.X ? .55f * offset : 0f),\n\t\t\t(facing.getAxis() == Axis.Y ? .55f * offset : 0f), (facing.getAxis() == Axis.Z ? .55f * offset : 0f));\n\n\t\tif (!hasEntity()) {\n\n\t\t\tfloat processingSpeed =\n\t\t\t\tMth.clamp((speed) / (!inventory.appliedRecipe ? Mth.log2(inventory.getStackInSlot(0)\n\t\t\t\t\t.getCount()) : 1), .25f, 20);\n\t\t\tinventory.remainingTime -= processingSpeed;\n\t\t\tspawnParticles(inventory.getStackInSlot(0));\n\n\t\t\tif (level.isClientSide)\n\t\t\t\treturn;\n\n\t\t\tif (inventory.remainingTime < 20 && !inventory.appliedRecipe) {\n\t\t\t\tapplyRecipe();\n\t\t\t\tinventory.appliedRecipe = true;\n\t\t\t\tlevel.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 2 | 16);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (inventory.remainingTime > 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinventory.remainingTime = 0;\n\n\t\t\t// Output Items\n\t\t\tif (facing != Direction.UP) {\n\t\t\t\tBlockPos nextPos = worldPosition.offset(facing.getAxis() == Axis.X ? 1f * offset : 0f, (-1f),\n\t\t\t\t\tfacing.getAxis() == Axis.Z ? 1f * offset : 0f);\n\t\t\t\tDirectBeltInputBehaviour behaviour =\n\t\t\t\t\tBlockEntityBehaviour.get(level, nextPos, DirectBeltInputBehaviour.TYPE);\n\t\t\t\tif (behaviour != null) {\n\t\t\t\t\tboolean changed = false;\n\t\t\t\t\tif (!behaviour.canInsertFromSide(facing))\n\t\t\t\t\t\treturn;\n\t\t\t\t\tfor (int slot = 0; slot < inventory.getSlots(); slot++) {\n\t\t\t\t\t\tItemStack stack = inventory.getStackInSlot(slot);\n\t\t\t\t\t\tif (stack.isEmpty())\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tItemStack remainder = behaviour.handleInsertion(stack, facing, false);\n\t\t\t\t\t\tif (remainder.equals(stack, false))\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tinventory.setStackInSlot(slot, remainder);\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (changed) {\n\t\t\t\t\t\tsetChanged();\n\t\t\t\t\t\tsendData();\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Eject Items\n\t\t\tfor (int slot = 0; slot < inventory.getSlots(); slot++) {\n\t\t\t\tItemStack stack = inventory.getStackInSlot(slot);\n\t\t\t\tif (stack.isEmpty())\n\t\t\t\t\tcontinue;\n\t\t\t\tItemEntity entityIn = new ItemEntity(level, outPos.x, outPos.y, outPos.z, stack);\n\t\t\t\tentityIn.setDeltaMovement(outSpeed);\n\t\t\t\tentityIn.getPersistentData()\n\t\t\t\t\t.put(\"BypassCrushingWheel\", NbtUtils.writeBlockPos(worldPosition));\n\t\t\t\tlevel.addFreshEntity(entityIn);\n\t\t\t}\n\t\t\tinventory.clear();\n\t\t\tlevel.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 2 | 16);\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (!processingEntity.isAlive() || !processingEntity.getBoundingBox()\n\t\t\t.intersects(new AABB(worldPosition).inflate(.5f))) {\n\t\t\tclear();\n\t\t\treturn;\n\t\t}\n\n\t\tdouble xMotion = ((worldPosition.getX() + .5f) - processingEntity.getX()) / 2f;\n\t\tdouble zMotion = ((worldPosition.getZ() + .5f) - processingEntity.getZ()) / 2f;\n\t\tif (processingEntity.isShiftKeyDown())\n\t\t\txMotion = zMotion = 0;\n\t\tdouble movement = Math.max(-speed / 4f, -.5f) * -offset;\n\t\tprocessingEntity.setDeltaMovement(\n\t\t\tnew Vec3(facing.getAxis() == Axis.X ? movement : xMotion, facing.getAxis() == Axis.Y ? movement : 0f // Do\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// not\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// move\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// entities\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// upwards\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// or\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// downwards\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// for\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// horizontal\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// crushers,\n\t\t\t\t, facing.getAxis() == Axis.Z ? movement : zMotion)); // Or they'll only get their feet crushed.\n\n\t\tif (level.isClientSide)\n\t\t\treturn;\n\n\t\tif (!(processingEntity instanceof ItemEntity)) {\n\t\t\tVec3 entityOutPos = outPos.add(facing.getAxis() == Axis.X ? .5f * offset : 0f,\n\t\t\t\tfacing.getAxis() == Axis.Y ? .5f * offset : 0f, facing.getAxis() == Axis.Z ? .5f * offset : 0f);\n\t\t\tint crusherDamage = AllConfigs.server().kinetics.crushingDamage.get();\n\n\t\t\tif (processingEntity instanceof LivingEntity) {\n\t\t\t\tif ((((LivingEntity) processingEntity).getHealth() - crusherDamage <= 0) // Takes LivingEntity instances\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// as exception, so it can\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// move them before it would\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// kill them.\n\t\t\t\t\t&& (((LivingEntity) processingEntity).hurtTime <= 0)) { // This way it can actually output the items\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// to the right spot.\n\t\t\t\t\tprocessingEntity.setPos(entityOutPos.x, entityOutPos.y, entityOutPos.z);\n\t\t\t\t}\n\t\t\t}\n\t\t\tprocessingEntity.hurt(CrushingWheelBlockEntity.DAMAGE_SOURCE, crusherDamage);\n\t\t\tif (!processingEntity.isAlive()) {\n\t\t\t\tprocessingEntity.setPos(entityOutPos.x, entityOutPos.y, entityOutPos.z);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tItemEntity itemEntity = (ItemEntity) processingEntity;\n\t\titemEntity.setPickUpDelay(20);\n\t\tif (facing.getAxis() == Axis.Y) {\n\t\t\tif (processingEntity.getY() * -offset < (centerPos.y - .25f) * -offset) {\n\t\t\t\tintakeItem(itemEntity);\n\t\t\t}\n\t\t} else if (facing.getAxis() == Axis.Z) {\n\t\t\tif (processingEntity.getZ() * -offset < (centerPos.z - .25f) * -offset) {\n\t\t\t\tintakeItem(itemEntity);\n\t\t\t}\n\t\t} else {\n\t\t\tif (processingEntity.getX() * -offset < (centerPos.x - .25f) * -offset) {\n\t\t\t\tintakeItem(itemEntity);\n\t\t\t}\n\t\t}\n\t}\n\n\t@OnlyIn(Dist.CLIENT)\n\tpublic void tickAudio() {\n\t\tfloat pitch = Mth.clamp((crushingspeed / 256f) + .45f, .85f, 1f);\n\t\tif (entityUUID == null && inventory.getStackInSlot(0)\n\t\t\t.isEmpty())\n\t\t\treturn;\n\t\tSoundScapes.play(AmbienceGroup.CRUSHING, worldPosition, pitch);\n\t}\n\n\tprivate void intakeItem(ItemEntity itemEntity) {\n\t\tinventory.clear();\n\t\tinventory.setStackInSlot(0, itemEntity.getItem()\n\t\t\t.copy());\n\t\titemInserted(inventory.getStackInSlot(0));\n\t\titemEntity.discard();\n\t\tlevel.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 2 | 16);\n\t}\n\n\tprotected void spawnParticles(ItemStack stack) {\n\t\tif (stack == null || stack.isEmpty())\n\t\t\treturn;\n\n\t\tParticleOptions particleData = null;\n\t\tif (stack.getItem() instanceof BlockItem)\n\t\t\tparticleData = new BlockParticleOption(ParticleTypes.BLOCK, ((BlockItem) stack.getItem()).getBlock()\n\t\t\t\t.defaultBlockState());\n\t\telse\n\t\t\tparticleData = new ItemParticleOption(ParticleTypes.ITEM, stack);\n\n\t\tRandomSource r = level.random;\n\t\tfor (int i = 0; i < 4; i++)\n\t\t\tlevel.addParticle(particleData, worldPosition.getX() + r.nextFloat(), worldPosition.getY() + r.nextFloat(),\n\t\t\t\tworldPosition.getZ() + r.nextFloat(), 0, 0, 0);\n\t}\n\n\tprivate void applyRecipe() {\n\t\tOptional> recipe = findRecipe();\n\n\t\tList list = new ArrayList<>();\n\t\tif (recipe.isPresent()) {\n\t\t\tint rolls = inventory.getStackInSlot(0)\n\t\t\t\t.getCount();\n\t\t\tinventory.clear();\n\t\t\tfor (int roll = 0; roll < rolls; roll++) {\n\t\t\t\tList rolledResults = recipe.get()\n\t\t\t\t\t.rollResults();\n\t\t\t\tfor (int i = 0; i < rolledResults.size(); i++) {\n\t\t\t\t\tItemStack stack = rolledResults.get(i);\n\t\t\t\t\tItemHelper.addToList(stack, list);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int slot = 0; slot < list.size() && slot + 1 < inventory.getSlots(); slot++)\n\t\t\t\tinventory.setStackInSlot(slot + 1, list.get(slot));\n\t\t} else {\n\t\t\tinventory.clear();\n\t\t}\n\n\t}\n\n\tpublic Optional> findRecipe() {\n\t\tOptional> crushingRecipe = AllRecipeTypes.CRUSHING.find(wrapper, level);\n\t\tif (!crushingRecipe.isPresent())\n\t\t\tcrushingRecipe = AllRecipeTypes.MILLING.find(wrapper, level);\n\t\treturn crushingRecipe;\n\t}\n\n\t@Override\n\tpublic void write(CompoundTag compound, boolean clientPacket) {\n\t\tif (hasEntity())\n\t\t\tcompound.put(\"Entity\", NbtUtils.createUUID(entityUUID));\n\t\tcompound.put(\"Inventory\", inventory.serializeNBT());\n\t\tcompound.putFloat(\"Speed\", crushingspeed);\n\t}\n\n\t@Override\n\tprotected void read(CompoundTag compound, boolean clientPacket) {\n\t\tsuper.read(compound, clientPacket);\n\t\tif (compound.contains(\"Entity\") && !isOccupied()) {\n\t\t\tentityUUID = NbtUtils.loadUUID(NBTHelper.getINBT(compound, \"Entity\"));\n\t\t\tthis.searchForEntity = true;\n\t\t}\n\t\tcrushingspeed = compound.getFloat(\"Speed\");\n\t\tinventory.deserializeNBT(compound.getCompound(\"Inventory\"));\n\t}\n\n\tpublic void startCrushing(Entity entity) {\n\t\tprocessingEntity = entity;\n\t\tentityUUID = entity.getUUID();\n\t}\n\n\tprivate void itemInserted(ItemStack stack) {\n\t\tOptional> recipe = findRecipe();\n\t\tinventory.remainingTime = recipe.isPresent() ? recipe.get()\n\t\t\t.getProcessingDuration() : 100;\n\t\tinventory.appliedRecipe = false;\n\t}\n\n\t@Override\n\tpublic LazyOptional getCapability(Capability cap, Direction side) {\n\t\tif (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)\n\t\t\treturn handler.cast();\n\t\treturn super.getCapability(cap, side);\n\t}\n\n\tpublic void clear() {\n\t\tprocessingEntity = null;\n\t\tentityUUID = null;\n\t}\n\n\tpublic boolean isOccupied() {\n\t\treturn hasEntity() || !inventory.isEmpty();\n\t}\n\n\tpublic boolean hasEntity() {\n\t\treturn processingEntity != null;\n\t}\n\n}", "answers": [" .blockEntity(\"mmb_crushing_wheel_controller\", MmbCrushingWheelControllerBlockEntity::new)"], "length": 4413, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "f87dfd5f-b06e-4547-807c-07c003196aaf", "reasoning": "The code defines a static BlockEntityEntry for the crushing wheel controller. Following the pattern used for other entries, after the assignment line the builder chain continues with a call to .blockEntity providing the registry name and constructor reference. Therefore the next line should be the .blockEntity call with the appropriate name and class.", "reasoning_model_answer": ".blockEntity(\"mmb_crushing_wheel_controller\", MmbCrushingWheelControllerBlockEntity::new)", "assistant_with_reasoning": "\nThe code defines a static BlockEntityEntry for the crushing wheel controller. Following the pattern used for other entries, after the assignment line the builder chain continues with a call to .blockEntity providing the registry name and constructor reference. Therefore the next line should be the .blockEntity call with the appropriate name and class.\n\n.blockEntity(\"mmb_crushing_wheel_controller\", MmbCrushingWheelControllerBlockEntity::new)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.252, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37295, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": ".blockEntity(\"mmb_crushing_wheel_controller\", MmbCrushingWheelControllerBlockEntity::new)", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import numpy as np\nimport cdl.obj as dlo\nimport cdl.param as dlp\nfrom cdl.config import _\nfrom cdl.core.gui.main import CDLMainWindow\nfrom cdl.core.gui.panel.image import ImagePanel\nfrom cdl.core.gui.panel.signal import SignalPanel\nfrom cdl.tests.data import (\n create_paracetamol_signal,\n create_peak2d_image,\n create_sincos_image,\n)\nfrom cdl.tests.features.common.newobject_unit import (\n iterate_image_creation,\n iterate_signal_creation,\n)\nfrom cdl.widgets import fitdialog", "context": "cdl/tests/scenarios/common.py\n panel.add_label_with_title()\n\n __compute_11_operations(panel, 2)\n\n\ndef run_signal_computations(\n win: CDLMainWindow, data_size: int = 500, all_types: bool = True\n) -> None:\n \"\"\"Testing signal features\"\"\"\n panel = win.signalpanel\n win.set_current_panel(\"signal\")\n\n if all_types:\n for signal in iterate_signal_creation(data_size, non_zero=True):\n panel.add_object(create_paracetamol_signal(data_size))\n panel.add_object(signal)\n compute_common_operations(panel)\n panel.remove_all_objects()\n\n sig1 = create_paracetamol_signal(data_size)\n win.add_object(sig1)\n\n # Add new signal based on s0\n panel.objview.set_current_object(sig1)\n newparam = dlo.new_signal_param(\n _(\"Random function\"), stype=dlo.SignalTypes.UNIFORMRANDOM\n )\n addparam = dlo.UniformRandomParam.create(vmin=0, vmax=sig1.y.max() * 0.2)\n panel.new_object(newparam, addparam=addparam, edit=False)\n\n compute_common_operations(panel)\n\n win.add_object(create_paracetamol_signal(data_size))\n\n param = dlp.NormalizeYParam()\n for _name, method in param.methods:\n param.method = method\n panel.processor.compute_normalize(param)\n\n param = dlp.XYCalibrateParam.create(a=1.2, b=0.1)\n panel.processor.compute_calibration(param)\n\n panel.processor.compute_derivative()\n panel.processor.compute_integral()\n\n param = dlp.PeakDetectionParam()\n panel.processor.compute_peak_detection(param)\n\n panel.processor.compute_multigaussianfit()\n\n panel.objview.select_objects([-3])\n sig = panel.objview.get_sel_objects()[0]\n i1 = data_size // 10\n i2 = len(sig.y) - i1\n panel.processor.compute_roi_extraction(dlp.ROIDataParam.create([[i1, i2]]))\n\n param = dlp.PolynomialFitParam()\n panel.processor.compute_polyfit(param)\n\n panel.processor.compute_fit(_(\"Gaussian fit\"), fitdialog.gaussianfit)\n panel.processor.compute_fit(_(\"Lorentzian fit\"), fitdialog.lorentzianfit)\n panel.processor.compute_fit(_(\"Voigt fit\"), fitdialog.voigtfit)\n\n newparam = dlo.new_signal_param(_(\"Gaussian\"), stype=dlo.SignalTypes.GAUSS)\n sig = dlo.create_signal_from_param(\n newparam, dlo.GaussLorentzVoigtParam(), edit=False\n )\n panel.add_object(sig)\n\n param = dlp.FWHMParam()\n for fittype, _name in param.fittypes:\n param.fittype = fittype\n panel.processor.compute_fwhm(param)\n panel.processor.compute_fw1e2()\n\n # Create a new signal which X values are a subset of sig1\n x = np.linspace(sig1.x.min(), sig1.x.max(), data_size // 2)[: data_size // 4]\n y = x * 0.0\n sig2 = dlo.create_signal(\"X values for interpolation\", x, y)\n panel.add_object(sig2)\n\n # Test interpolation\n for method_choice_tuple in dlp.InterpolationParam._methods:\n method = method_choice_tuple[0]\n for fill_value in (None, 0.0):\n panel.objview.set_current_object(sig1)\n param = dlp.InterpolationParam.create(method=method, fill_value=fill_value)\n panel.processor.compute_interpolation(sig2, param)\n\n # Test resampling\n xmin, xmax = x[0], x[-1]\n for mode, dx, nbpts in ((\"dx\", 0.1, 10), (\"nbpts\", 0.0, 100)):\n panel.objview.set_current_object(sig1)\n param = dlp.ResamplingParam.create(\n xmin=xmin, xmax=xmax, mode=mode, dx=dx, nbpts=nbpts\n )\n panel.processor.compute_resampling(param)\n\n # Test convolution\n panel.objview.set_current_object(sig1)\n panel.processor.compute_derivative()\n panel.processor.compute_convolution(sig1)\n\n # Test detrending\n panel.objview.set_current_object(sig1)\n for method_choice_tuple in dlp.DetrendingParam._methods:\n param = dlp.DetrendingParam.create(method=method_choice_tuple[0])\n panel.processor.compute_detrending(param)\n\n\ndef run_image_computations(\n win: CDLMainWindow, data_size: int = 150, all_types: bool = True\n) -> None:\n \"\"\"Testing signal features\"\"\"\n win.set_current_panel(\"image\")\n panel = win.imagepanel\n\n newparam = dlo.new_image_param(height=data_size, width=data_size)\n\n if all_types:\n\n\ncdl/tests/data.py\ndef create_sincos_image(\n p: cdl.obj.NewImageParam | None = None,\n) -> cdl.obj.ImageObj:\n \"\"\"Creating test image (sin(x)+cos(y))\n\n Args:\n p (cdl.obj.NewImageParam | None): Image parameters. Defaults to None.\n\n Returns:\n cdl.obj.ImageObj: Image object\n \"\"\"\n p = __set_default_size_dtype(p)\n p.title = \"Test image (sin(x)+cos(y))\" if p.title is None else p.title\n dtype = p.dtype.value\n x, y = np.meshgrid(np.linspace(0, 10, p.width), np.linspace(0, 10, p.height))\n raw_data = 0.5 * (np.sin(x) + np.cos(y)) + 0.5\n dmin = np.iinfo(dtype).min * 0.95\n dmax = np.iinfo(dtype).max * 0.95\n obj = cdl.obj.create_image_from_param(p)\n obj.data = np.array(raw_data * (dmax - dmin) + dmin, dtype=dtype)\n return obj\n\ncdl/tests/data.py\ndef create_paracetamol_signal(\n size: int | None = None, title: str | None = None\n) -> cdl.obj.SignalObj:\n \"\"\"Create test signal (Paracetamol molecule spectrum)\n\n Args:\n size (int | None): Size of the data. Defaults to None.\n title (str | None): Title of the signal. Defaults to None.\n\n Returns:\n SignalObj: Signal object\n \"\"\"\n obj = cdl.obj.read_signal(get_test_fnames(\"paracetamol.txt\")[0])\n if title is not None:\n obj.title = title\n if size is not None:\n x0, y0 = obj.xydata\n x1 = np.linspace(x0[0], x0[-1], size)\n y1 = np.interp(x1, x0, y0)\n obj.set_xydata(x1, y1)\n return obj\n\ncdl/tests/features/common/newobject_unit.py\ndef iterate_signal_creation(\n data_size: int = 500, non_zero: bool = False, verbose: bool = True\n) -> Generator[SignalObj, None, None]:\n \"\"\"Iterate over all possible signals created from parameters\"\"\"\n if verbose:\n execenv.print(\n f\" Iterating over signal types (size={data_size}, non_zero={non_zero}):\"\n )\n for stype in SignalTypes:\n if non_zero and stype in (SignalTypes.ZEROS,):\n continue\n if verbose:\n execenv.print(f\" {stype.value}\")\n newparam = new_signal_param(stype=stype, size=data_size)\n if stype == SignalTypes.UNIFORMRANDOM:\n addparam = UniformRandomParam()\n elif stype == SignalTypes.NORMALRANDOM:\n addparam = NormalRandomParam()\n else:\n addparam = None\n signal = create_signal_from_param(newparam, addparam=addparam)\n if stype == SignalTypes.ZEROS:\n assert (signal.y == 0).all()\n yield signal\n\ncdl/widgets/fitdialog.py\ndef guifit(\n x,\n y,\n fitfunc,\n fitparams,\n fitargs=None,\n fitkwargs=None,\n wintitle=None,\n title=None,\n xlabel=None,\n ylabel=None,\n param_cols=1,\n auto_fit=True,\n winsize=None,\n winpos=None,\n parent=None,\n name=None,\n):\ndef polynomialfit(x, y, degree, parent=None, name=None):\n def fitfunc(x, params):\ndef gaussianfit(x, y, parent=None, name=None):\n def fitfunc(x, params):\ndef lorentzianfit(x, y, parent=None, name=None):\n def fitfunc(x, params):\ndef voigtfit(x, y, parent=None, name=None):\n def fitfunc(x, params):\ndef multigaussian(x, *values, **kwargs):\ndef multigaussianfit(x, y, peak_indexes, parent=None, name=None):\n def fitfunc(xi, params):\n\ncdl/tests/features/common/newobject_unit.py\ndef iterate_image_creation(\n data_size: int = 500, non_zero: bool = False, verbose: bool = True\n) -> Generator[ImageObj, None, None]:\n \"\"\"Iterate over all possible images created from parameters\"\"\"\n if verbose:\n execenv.print(\n f\" Iterating over image types (size={data_size}, non_zero={non_zero}):\"\n )\n for itype in ImageTypes:\n if non_zero and itype in (ImageTypes.EMPTY, ImageTypes.ZEROS):\n continue\n if verbose:\n execenv.print(f\" {itype.value}\")\n for dtype in ImageDatatypes:\n if verbose:\n execenv.print(f\" {dtype.value}\")\n newparam = new_image_param(\n itype=itype, dtype=dtype, width=data_size, height=data_size\n )\n if itype == ImageTypes.GAUSS:\n addparam = Gauss2DParam()\n addparam.x0 = addparam.y0 = 3\n addparam.sigma = 5\n elif itype == ImageTypes.UNIFORMRANDOM:\n addparam = UniformRandomParam()\n addparam.set_from_datatype(dtype.value)\n elif itype == ImageTypes.NORMALRANDOM:\n addparam = NormalRandomParam()\n addparam.set_from_datatype(dtype.value)\n else:\n addparam = None\n image = create_image_from_param(newparam, addparam=addparam)\n if itype == ImageTypes.ZEROS:\n assert (image.data == 0).all()\n yield image\n\ncdl/core/gui/panel/image.py\nclass ImagePanel(BaseDataPanel):\n \"\"\"Object handling the item list, the selected item properties and plot,\n specialized for Image objects\"\"\"\n\n PANEL_STR = _(\"Image panel\")\n PARAMCLASS = ImageObj\n DIALOGSIZE = (800, 800)\n ANNOTATION_TOOLS = (\n AnnotatedCircleTool,\n AnnotatedSegmentTool,\n AnnotatedRectangleTool,\n AnnotatedPointTool,\n AnnotatedEllipseTool,\n LabelTool,\n )\n IO_REGISTRY = ImageIORegistry\n H5_PREFIX = \"DataLab_Ima\"\n ROIDIALOGOPTIONS = {\"show_itemlist\": True, \"show_contrast\": False}\n ROIDIALOGCLASS = roieditor.ImageROIEditor\n\n # pylint: disable=duplicate-code\n\n def __init__(self, parent: QW.QWidget, plotwidget: PlotWidget, toolbar) -> None:\n super().__init__(parent, plotwidget, toolbar)\n self.plothandler = ImagePlotHandler(self, plotwidget)\n self.processor = ImageProcessor(self, plotwidget)\n self.acthandler = ImageActionHandler(self, toolbar)\n\n # ------Refreshing GUI--------------------------------------------------------------\n def properties_changed(self) -> None:\n \"\"\"The properties 'Apply' button was clicked: updating signal\"\"\"\n obj = self.objview.get_current_object()\n if obj is not None:\n obj.invalidate_maskdata_cache()\n super().properties_changed()\n\n # ------Creating, adding, removing objects------------------------------------------\n def get_newparam_from_current(\n self, newparam: NewImageParam | None = None\n ) -> NewImageParam | None:\n \"\"\"Get new object parameters from the current object.\n\n Args:\n newparam (guidata.dataset.DataSet): new object parameters.\n If None, create a new one.\n\n Returns:\n New object parameters\n \"\"\"\n curobj: ImageObj = self.objview.get_current_object()\n newparam = new_image_param() if newparam is None else newparam\n if curobj is not None:\n newparam.width, newparam.height = curobj.size\n newparam.dtype = ImageDatatypes.from_dtype(curobj.data.dtype)\n return newparam\n\n def new_object(\n self,\n newparam: NewImageParam | None = None,\n addparam: gds.DataSet | None = None,\n edit: bool = True,\n add_to_panel: bool = True,\n ) -> ImageObj | None:\n \"\"\"Create a new object (image).\n\n Args:\n newparam (Daguidata.dataset.datatypes.DataSettaSet): new object parameters\n addparam (guidata.dataset.DataSet): additional parameters\n edit (bool): Open a dialog box to edit parameters (default: True)\n add_to_panel (bool): Add the object to the panel (default: True)\n\n Returns:\n New object\n \"\"\"\n if not self.mainwindow.confirm_memory_state():\n return None\n newparam = self.get_newparam_from_current(newparam)\n image = create_image_from_param(\n newparam, addparam=addparam, edit=edit, parent=self\n )\n if image is None:\n return None\n if add_to_panel:\n self.add_object(image)\n return image\n\n def delete_metadata(self, refresh_plot: bool = True) -> None:\n \"\"\"Delete metadata of selected objects\n\n Args:\n refresh_plot (bool | None): Refresh plot. Defaults to True.\n \"\"\"\n for obj in self.objview.get_sel_objects(include_groups=True):\n obj.invalidate_maskdata_cache()\n super().delete_metadata(refresh_plot)\n\n def toggle_show_contrast(self, state: bool) -> None:\n \"\"\"Toggle show contrast option\"\"\"\n Conf.view.show_contrast.set(state)\n self.SIG_REFRESH_PLOT.emit(\"selected\", True)\n\ncdl/core/gui/main.py\nclass CDLMainWindow(QW.QMainWindow, AbstractCDLControl, metaclass=CDLMainWindowMeta):\n \"\"\"DataLab main window\n\n Args:\n console: enable internal console\n hide_on_close: True to hide window on close\n \"\"\"\n\n __instance = None\n\n SIG_READY = QC.Signal()\n SIG_SEND_OBJECT = QC.Signal(object)\n SIG_SEND_OBJECTLIST = QC.Signal(object)\n SIG_CLOSING = QC.Signal()\n\n @staticmethod\n def get_instance(console=None, hide_on_close=False):\n \"\"\"Return singleton instance\"\"\"\n if CDLMainWindow.__instance is None:\n return CDLMainWindow(console, hide_on_close)\n return CDLMainWindow.__instance\n\n def __init__(self, console=None, hide_on_close=False):\n \"\"\"Initialize main window\"\"\"\n CDLMainWindow.__instance = self\n super().__init__()\n win32_fix_title_bar_background(self)\n self.setObjectName(APP_NAME)\n self.setWindowIcon(get_icon(\"DataLab.svg\"))\n\n execenv.log(self, \"Starting initialization\")\n\n self.__restore_pos_and_size()\n\n self.ready_flag = True\n\n self.hide_on_close = hide_on_close\n self.__old_size = None\n self.__memory_warning = False\n self.memorystatus = None\n\n self.console = None\n self.macropanel: MacroPanel = None\n\n self.signal_toolbar: QW.QToolBar = None\n self.image_toolbar: QW.QToolBar = None\n self.signalpanel: SignalPanel = None\n self.imagepanel: ImagePanel = None\n self.tabwidget: QW.QTabWidget = None\n self.docks: dict[AbstractPanel, QW.QDockWidget] = None\n self.h5inputoutput = H5InputOutput(self)\n\n self.openh5_action: QW.QAction = None\n self.saveh5_action: QW.QAction = None\n self.browseh5_action: QW.QAction = None\n self.settings_action: QW.QAction = None\n self.quit_action: QW.QAction = None\n self.auto_refresh_action: QW.QAction = None\n self.showlabel_action: QW.QAction = None\n\n self.file_menu: QW.QMenu = None\n self.edit_menu: QW.QMenu = None\n self.operation_menu: QW.QMenu = None\n self.processing_menu: QW.QMenu = None\n self.computing_menu: QW.QMenu = None\n self.plugins_menu: QW.QMenu = None\n self.view_menu: QW.QMenu = None\n self.help_menu: QW.QMenu = None\n\n self.__is_modified = None\n self.set_modified(False)\n\n # Starting XML-RPC server thread\n self.remote_server = RemoteServer(self)\n if Conf.main.rpc_server_enabled.get():\n self.remote_server.SIG_SERVER_PORT.connect(self.xmlrpc_server_started)\n self.remote_server.start()\n\n # Setup actions and menus\n if console is None:\n console = Conf.console.console_enabled.get()\n self.setup(console)\n\n execenv.log(self, \"Initialization done\")\n\n # ------API related to XML-RPC remote control\n @staticmethod\n def xmlrpc_server_started(port):\n \"\"\"XML-RPC server has started, writing comm port in configuration file\"\"\"\n Conf.main.rpc_server_port.set(port)\n\n def __get_current_basedatapanel(self) -> BaseDataPanel:\n \"\"\"Return the current BaseDataPanel,\n or the signal panel if macro panel is active\n\n Returns:\n BaseDataPanel: current panel\n \"\"\"\n panel = self.tabwidget.currentWidget()\n if not isinstance(panel, base.BaseDataPanel):\n panel = self.signalpanel\n return panel\n\n def __get_specific_panel(self, panel: str | None) -> BaseDataPanel:\n \"\"\"Return a specific BaseDataPanel.\n\n Args:\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n\n Returns:\n BaseDataPanel: panel\n\n Raises:\n ValueError: if panel is unknown\n \"\"\"\n if not panel:\n return self.__get_current_basedatapanel()\n if panel == \"signal\":\n return self.signalpanel\n if panel == \"image\":\n return self.imagepanel\n raise ValueError(f\"Unknown panel: {panel}\")\n\n @remote_controlled\n def get_group_titles_with_object_infos(\n self,\n ) -> tuple[list[str], list[list[str]], list[list[str]]]:\n \"\"\"Return groups titles and lists of inner objects uuids and titles.\n\n Returns:\n Tuple: groups titles, lists of inner objects uuids and titles\n \"\"\"\n panel = self.__get_current_basedatapanel()\n return panel.objmodel.get_group_titles_with_object_infos()\n\n @remote_controlled\n def get_object_titles(self, panel: str | None = None) -> list[str]:\n \"\"\"Get object (signal/image) list for current panel.\n Objects are sorted by group number and object index in group.\n\n Args:\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n\n Returns:\n list[str]: list of object titles\n\n Raises:\n ValueError: if panel is unknown\n \"\"\"\n return self.__get_specific_panel(panel).objmodel.get_object_titles()\n\n @remote_controlled\n def get_object(\n self,\n nb_id_title: int | str | None = None,\n panel: str | None = None,\n ) -> SignalObj | ImageObj:\n \"\"\"Get object (signal/image) from index.\n\n Args:\n nb_id_title: Object number, or object id, or object title.\n Defaults to None (current object).\n panel: Panel name. Defaults to None (current panel).\n\n Returns:\n Object\n\n Raises:\n KeyError: if object not found\n TypeError: if index_id_title type is invalid\n \"\"\"\n panelw = self.__get_specific_panel(panel)\n if nb_id_title is None:\n return panelw.objview.get_current_object()\n if isinstance(nb_id_title, int):\n return panelw.objmodel.get_object_from_number(nb_id_title)\n if isinstance(nb_id_title, str):\n try:\n return panelw.objmodel[nb_id_title]\n except KeyError:\n try:\n return panelw.objmodel.get_object_from_title(nb_id_title)\n except KeyError as exc:\n raise KeyError(\n f\"Invalid object index, id or title: {nb_id_title}\"\n ) from exc\n raise TypeError(f\"Invalid index_id_title type: {type(nb_id_title)}\")\n\n @remote_controlled\n def get_object_uuids(self, panel: str | None = None) -> list[str]:\n \"\"\"Get object (signal/image) uuid list for current panel.\n Objects are sorted by group number and object index in group.\n\n Args:\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n\n Returns:\n list[str]: list of object uuids\n\n Raises:\n ValueError: if panel is unknown\n \"\"\"\n return self.__get_specific_panel(panel).objmodel.get_object_ids()\n\n @remote_controlled\n def get_sel_object_uuids(self, include_groups: bool = False) -> list[str]:\n \"\"\"Return selected objects uuids.\n\n Args:\n include_groups: If True, also return objects from selected groups.\n\n Returns:\n List of selected objects uuids.\n \"\"\"\n panel = self.__get_current_basedatapanel()\n return panel.objview.get_sel_object_uuids(include_groups)\n\n @remote_controlled\n def select_objects(\n self,\n selection: list[int | str],\n panel: str | None = None,\n ) -> None:\n \"\"\"Select objects in current panel.\n\n Args:\n selection: List of object numbers (1 to N) or uuids to select\n panel: panel name (valid values: \"signal\", \"image\").\n If None, current panel is used. Defaults to None.\n \"\"\"\n panel = self.__get_specific_panel(panel)\n panel.objview.select_objects(selection)\n\n @remote_controlled\n def select_groups(\n self, selection: list[int | str] | None = None, panel: str | None = None\n ) -> None:\n \"\"\"Select groups in current panel.\n\n Args:\n selection: List of group numbers (1 to N), or list of group uuids,\n or None to select all groups. Defaults to None.\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used. Defaults to None.\n \"\"\"\n panel = self.__get_specific_panel(panel)\n panel.objview.select_groups(selection)\n\n @remote_controlled\n def delete_metadata(self, refresh_plot: bool = True) -> None:\n \"\"\"Delete metadata of selected objects\n\n Args:\n refresh_plot (bool | None): Refresh plot. Defaults to True.\n \"\"\"\n panel = self.__get_current_basedatapanel()\n panel.delete_metadata(refresh_plot)\n\n @remote_controlled\n def get_object_shapes(\n self,\n nb_id_title: int | str | None = None,\n panel: str | None = None,\n ) -> list:\n \"\"\"Get plot item shapes associated to object (signal/image).\n\n Args:\n nb_id_title: Object number, or object id, or object title.\n Defaults to None (current object).\n panel: Panel name. Defaults to None (current panel).\n\n Returns:\n List of plot item shapes\n \"\"\"\n obj = self.get_object(nb_id_title, panel)\n return list(obj.iterate_shape_items(editable=False))\n\n @remote_controlled\n def add_annotations_from_items(\n self, items: list, refresh_plot: bool = True, panel: str | None = None\n ) -> None:\n \"\"\"Add object annotations (annotation plot items).\n\n Args:\n items (list): annotation plot items\n refresh_plot (bool | None): refresh plot. Defaults to True.\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n \"\"\"\n panel = self.__get_specific_panel(panel)\n panel.add_annotations_from_items(items, refresh_plot)\n\n @remote_controlled\n def add_label_with_title(\n self, title: str | None = None, panel: str | None = None\n ) -> None:\n \"\"\"Add a label with object title on the associated plot\n\n Args:\n title (str | None): Label title. Defaults to None.\n If None, the title is the object title.\n panel (str | None): panel name (valid values: \"signal\", \"image\").\n If None, current panel is used.\n \"\"\"\n self.__get_specific_panel(panel).add_label_with_title(title)\n\n # ------Misc.\n @property\n def panels(self) -> tuple[AbstractPanel, ...]:\n \"\"\"Return the tuple of implemented panels (signal, image)\n\n Returns:\n tuple[SignalPanel, ImagePanel, MacroPanel]: tuple of panels\n \"\"\"\n return (self.signalpanel, self.imagepanel, self.macropanel)\n\n def __set_low_memory_state(self, state: bool) -> None:\n \"\"\"Set memory warning state\"\"\"\n self.__memory_warning = state\n\n def confirm_memory_state(self) -> bool: # pragma: no cover\n \"\"\"Check memory warning state and eventually show a warning dialog\n\n Returns:\n bool: True if memory state is ok\n \"\"\"\n if not env.execenv.unattended and self.__memory_warning:\n threshold = Conf.main.available_memory_threshold.get()\n answer = QW.QMessageBox.critical(\n self,\n _(\"Warning\"),\n _(\"Available memory is below %d MB.

Do you want to continue?\")\n % threshold,\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n )\n return answer == QW.QMessageBox.Yes\n return True\n\n def check_stable_release(self) -> None: # pragma: no cover\n \"\"\"Check if this is a stable release\"\"\"\n if __version__.replace(\".\", \"\").isdigit():\n # This is a stable release\n return\n if \"b\" in __version__:\n # This is a beta release\n rel = _(\n \"This software is in the beta stage of its release cycle. \"\n \"The focus of beta testing is providing a feature complete \"\n \"software for users interested in trying new features before \"\n \"the final release. However, beta software may not behave as \"\n \"expected and will probably have more bugs or performance issues \"\n \"than completed software.\"\n )\n else:\n # This is an alpha release\n rel = _(\n \"This software is in the alpha stage of its release cycle. \"\n \"The focus of alpha testing is providing an incomplete software \"\n \"for early testing of specific features by users. \"\n \"Please note that alpha software was not thoroughly tested \"\n \"by the developer before it is released.\"\n )\n txtlist = [\n f\"{APP_NAME} v{__version__}:\",\n \"\",\n _(\"This is not a stable release.\"),\n \"\",\n rel,\n ]\n QW.QMessageBox.warning(self, APP_NAME, \"
\".join(txtlist), QW.QMessageBox.Ok)\n\n def __check_dependencies(self) -> None: # pragma: no cover\n \"\"\"Check dependencies\"\"\"\n if IS_FROZEN or execenv.unattended:\n # No need to check dependencies if DataLab has been frozen, or if\n # the user has chosen to ignore this check, or if we are in unattended mode\n # (i.e. running automated tests)\n\n if IS_FROZEN:\n QW.QMessageBox.information(\n self,\n _(\"Information\"),\n _(\n \"The dependency check feature is not relevant for the \"\n \"standalone version of DataLab.\"\n ),\n QW.QMessageBox.Ok,\n )\n return\n try:\n state = dephash.check_dependencies_hash(DATAPATH)\n bad_deps = [name for name in state if not state[name]]\n if not bad_deps:\n # Everything is OK\n QW.QMessageBox.information(\n self,\n _(\"Information\"),\n _(\n \"All critical dependencies of DataLab have been qualified \"\n \"on this operating system.\"\n ),\n QW.QMessageBox.Ok,\n )\n return\n except IOError:\n bad_deps = None\n txt0 = _(\"Non-compliant dependency:\")\n if bad_deps is None or len(bad_deps) > 1:\n txt0 = _(\"Non-compliant dependencies:\")\n if bad_deps is None:\n txtlist = [\n _(\"DataLab has not yet been qualified on your operating system.\"),\n ]\n else:\n txtlist = [\n \"\" + txt0 + \" \" + \", \".join(bad_deps),\n \"\",\n _(\n \"At least one dependency does not comply with DataLab \"\n \"qualification standard reference (wrong dependency version \"\n \"has been installed, or dependency source code has been \"\n \"modified, or the application has not yet been qualified \"\n \"on your operating system).\"\n ),\n ]\n txtlist += [\n \"\",\n _(\n \"This means that the application has not been officially qualified \"\n \"in this context and may not behave as expected.\"\n ),\n ]\n txt = \"
\".join(txtlist)\n QW.QMessageBox.warning(self, APP_NAME, txt, QW.QMessageBox.Ok)\n\n def check_for_previous_crash(self) -> None: # pragma: no cover\n \"\"\"Check for previous crash\"\"\"\n if execenv.unattended:\n self.__show_logviewer()\n elif Conf.main.faulthandler_log_available.get(\n False\n ) or Conf.main.traceback_log_available.get(False):\n txt = \"
\".join(\n [\n logviewer.get_log_prompt_message(),\n \"\",\n _(\"Do you want to see available log files?\"),\n ]\n )\n btns = QW.QMessageBox.StandardButton.Yes | QW.QMessageBox.StandardButton.No\n choice = QW.QMessageBox.warning(self, APP_NAME, txt, btns)\n if choice == QW.QMessageBox.StandardButton.Yes:\n self.__show_logviewer()\n\n def take_screenshot(self, name: str) -> None: # pragma: no cover\n \"\"\"Take main window screenshot\"\"\"\n self.memorystatus.set_demo_mode(True)\n qth.grab_save_window(self, f\"{name}\")\n self.memorystatus.set_demo_mode(False)\n\n def take_menu_screenshots(self) -> None: # pragma: no cover\n \"\"\"Take menu screenshots\"\"\"\n for panel in self.panels:\n if isinstance(panel, base.BaseDataPanel):\n self.tabwidget.setCurrentWidget(panel)\n for name in (\n \"file\",\n \"edit\",\n \"view\",\n \"operation\",\n \"processing\",\n \"computing\",\n \"help\",\n ):\n menu = getattr(self, f\"{name}_menu\")\n menu.popup(self.pos())\n qth.grab_save_window(menu, f\"{panel.objectName()}_{name}\")\n menu.close()\n\n # ------GUI setup\n def __restore_pos_and_size(self) -> None:\n \"\"\"Restore main window position and size from configuration\"\"\"\n pos = Conf.main.window_position.get(None)\n if pos is not None:\n posx, posy = pos\n self.move(QC.QPoint(posx, posy))\n size = Conf.main.window_size.get(None)\n if size is not None:\n width, height = size\n self.resize(QC.QSize(width, height))\n if pos is not None and size is not None:\n sgeo = self.screen().availableGeometry()\n out_inf = posx < -int(0.9 * width) or posy < -int(0.9 * height)\n out_sup = posx > int(0.9 * sgeo.width()) or posy > int(0.9 * sgeo.height())\n if len(QW.QApplication.screens()) == 1 and (out_inf or out_sup):\n # Main window is offscreen\n posx = min(max(posx, 0), sgeo.width() - width)\n posy = min(max(posy, 0), sgeo.height() - height)\n self.move(QC.QPoint(posx, posy))\n\n def __save_pos_and_size(self) -> None:\n \"\"\"Save main window position and size to configuration\"\"\"\n is_maximized = self.windowState() == QC.Qt.WindowMaximized\n Conf.main.window_maximized.set(is_maximized)\n if not is_maximized:\n size = self.size()\n Conf.main.window_size.set((size.width(), size.height()))\n pos = self.pos()\n Conf.main.window_position.set((pos.x(), pos.y()))\n\n def setup(self, console: bool = False) -> None:\n \"\"\"Setup main window\n\n Args:\n console: True to setup console\n \"\"\"\n self.__register_plugins()\n self.__configure_statusbar()\n self.__setup_global_actions()\n self.__add_signal_image_panels()\n self.__create_plugins_actions()\n self.__setup_central_widget()\n self.__add_menus()\n if console:\n self.__setup_console()\n self.__update_actions()\n self.__add_macro_panel()\n self.__configure_panels()\n\n def __register_plugins(self) -> None:\n \"\"\"Register plugins\"\"\"\n with qth.try_or_log_error(\"Discovering plugins\"):\n # Discovering plugins\n plugin_nb = len(discover_plugins())\n execenv.log(self, f\"{plugin_nb} plugin(s) found\")\n for plugin_class in PluginRegistry.get_plugin_classes():\n with qth.try_or_log_error(f\"Instantiating plugin {plugin_class.__name__}\"):\n # Instantiating plugin\n plugin: PluginBase = plugin_class()\n with qth.try_or_log_error(f\"Registering plugin {plugin.info.name}\"):\n # Registering plugin\n plugin.register(self)\n\n def __create_plugins_actions(self) -> None:\n \"\"\"Create plugins actions\"\"\"\n with self.signalpanel.acthandler.new_category(ActionCategory.PLUGINS):\n with self.imagepanel.acthandler.new_category(ActionCategory.PLUGINS):\n for plugin in PluginRegistry.get_plugins():\n with qth.try_or_log_error(f\"Create actions for {plugin.info.name}\"):\n plugin.create_actions()\n\n @staticmethod\n def __unregister_plugins() -> None:\n \"\"\"Unregister plugins\"\"\"\n while PluginRegistry.get_plugins():\n # Unregistering plugin\n plugin = PluginRegistry.get_plugins()[-1]\n with qth.try_or_log_error(f\"Unregistering plugin {plugin.info.name}\"):\n plugin.unregister()\n\n def __configure_statusbar(self) -> None:\n \"\"\"Configure status bar\"\"\"\n self.statusBar().showMessage(_(\"Welcome to %s!\") % APP_NAME, 5000)\n # Plugin status\n pluginstatus = status.PluginStatus()\n self.statusBar().addPermanentWidget(pluginstatus)\n # XML-RPC server status\n xmlrpcstatus = status.XMLRPCStatus()\n xmlrpcstatus.set_port(self.remote_server.port)\n self.statusBar().addPermanentWidget(xmlrpcstatus)\n # Memory status\n threshold = Conf.main.available_memory_threshold.get()\n self.memorystatus = status.MemoryStatus(threshold)\n self.memorystatus.SIG_MEMORY_ALARM.connect(self.__set_low_memory_state)\n self.statusBar().addPermanentWidget(self.memorystatus)\n\n def __setup_global_actions(self) -> None:\n \"\"\"Setup global actions\"\"\"\n self.openh5_action = create_action(\n self,\n _(\"Open HDF5 files...\"),\n icon=get_icon(\"fileopen_h5.svg\"),\n tip=_(\"Open one or several HDF5 files\"),\n triggered=lambda checked=False: self.open_h5_files(import_all=True),\n )\n self.saveh5_action = create_action(\n self,\n _(\"Save to HDF5 file...\"),\n icon=get_icon(\"filesave_h5.svg\"),\n tip=_(\"Save to HDF5 file\"),\n triggered=self.save_to_h5_file,\n )\n self.browseh5_action = create_action(\n self,\n _(\"Browse HDF5 file...\"),\n icon=get_icon(\"h5browser.svg\"),\n tip=_(\"Browse an HDF5 file\"),\n triggered=lambda checked=False: self.open_h5_files(import_all=None),\n )\n self.settings_action = create_action(\n self,\n _(\"Settings...\"),\n icon=get_icon(\"libre-gui-settings.svg\"),\n tip=_(\"Open settings dialog\"),\n triggered=self.__edit_settings,\n )\n main_toolbar = self.addToolBar(_(\"Main Toolbar\"))\n add_actions(\n main_toolbar,\n [\n self.openh5_action,\n self.saveh5_action,\n self.browseh5_action,\n None,\n self.settings_action,\n ],\n )\n # Quit action for \"File menu\" (added when populating menu on demand)\n if self.hide_on_close:\n quit_text = _(\"Hide window\")\n quit_tip = _(\"Hide DataLab window\")\n else:\n quit_text = _(\"Quit\")\n quit_tip = _(\"Quit application\")\n if sys.platform != \"darwin\":\n # On macOS, the \"Quit\" action is automatically added to the application menu\n self.quit_action = create_action(\n self,\n quit_text,\n shortcut=QG.QKeySequence(QG.QKeySequence.Quit),\n icon=get_icon(\"libre-gui-close.svg\"),\n tip=quit_tip,\n triggered=self.close,\n )\n # View menu actions\n self.auto_refresh_action = create_action(\n self,\n _(\"Auto-refresh\"),\n icon=get_icon(\"refresh-auto.svg\"),\n tip=_(\"Auto-refresh plot when object is modified, added or removed\"),\n toggled=self.toggle_auto_refresh,\n )\n self.showlabel_action = create_action(\n self,\n _(\"Show graphical object titles\"),\n icon=get_icon(\"show_titles.svg\"),\n tip=_(\"Show or hide ROI and other graphical object titles or subtitles\"),\n toggled=self.toggle_show_titles,\n )\n\n def __add_signal_panel(self) -> None:\n \"\"\"Setup signal toolbar, widgets and panel\"\"\"\n self.signal_toolbar = self.addToolBar(_(\"Signal Processing Toolbar\"))\n curvewidget = DockablePlotWidget(self, PlotType.CURVE)\n curveplot = curvewidget.get_plot()\n curveplot.add_item(make.legend(\"TR\"))\n self.signalpanel = signal.SignalPanel(\n self, curvewidget.plotwidget, self.signal_toolbar\n )\n self.signalpanel.SIG_STATUS_MESSAGE.connect(self.statusBar().showMessage)\n return curvewidget\n\n def __add_image_panel(self) -> None:\n \"\"\"Setup image toolbar, widgets and panel\"\"\"\n self.image_toolbar = self.addToolBar(_(\"Image Processing Toolbar\"))\n imagewidget = DockablePlotWidget(self, PlotType.IMAGE)\n self.imagepanel = image.ImagePanel(\n self, imagewidget.plotwidget, self.image_toolbar\n )\n # -----------------------------------------------------------------------------\n # # Before eventually disabling the \"peritem\" mode by default, wait for the\n # # plotpy bug to be fixed (peritem mode is not compatible with multiple image\n # # items):\n # for cspanel in (\n # self.imagepanel.plotwidget.get_xcs_panel(),\n # self.imagepanel.plotwidget.get_ycs_panel(),\n # ):\n # cspanel.peritem_ac.setChecked(False)\n # -----------------------------------------------------------------------------\n self.imagepanel.SIG_STATUS_MESSAGE.connect(self.statusBar().showMessage)\n return imagewidget\n\n def __add_signal_image_panels(self) -> None:\n \"\"\"Add signal and image panels\"\"\"\n self.tabwidget = QW.QTabWidget()\n cdock = self.__add_dockwidget(self.__add_signal_panel(), title=_(\"Curve panel\"))\n idock = self.__add_dockwidget(self.__add_image_panel(), title=_(\"Image panel\"))\n self.tabifyDockWidget(cdock, idock)\n self.docks = {self.signalpanel: cdock, self.imagepanel: idock}\n self.tabwidget.currentChanged.connect(self.__tab_index_changed)\n self.signalpanel.SIG_OBJECT_ADDED.connect(\n lambda: self.set_current_panel(\"signal\")\n )\n self.imagepanel.SIG_OBJECT_ADDED.connect(\n lambda: self.set_current_panel(\"image\")\n )\n for panel in (self.signalpanel, self.imagepanel):\n panel.setup_panel()\n\n def __setup_central_widget(self) -> None:\n \"\"\"Setup central widget (main panel)\"\"\"\n self.tabwidget.setMaximumWidth(500)\n self.tabwidget.addTab(self.signalpanel, get_icon(\"signal.svg\"), _(\"Signals\"))\n self.tabwidget.addTab(self.imagepanel, get_icon(\"image.svg\"), _(\"Images\"))\n self.setCentralWidget(self.tabwidget)\n\n @staticmethod\n def __get_local_doc_path() -> str | None:\n \"\"\"Return local documentation path, if it exists\"\"\"\n locale = QC.QLocale.system().name()\n for suffix in (\"_\" + locale[:2], \"_en\"):\n path = osp.join(DATAPATH, \"doc\", f\"{APP_NAME}{suffix}.pdf\")\n if osp.isfile(path):\n return path\n return None\n\n def __add_menus(self) -> None:\n \"\"\"Adding menus\"\"\"\n self.file_menu = self.menuBar().addMenu(_(\"File\"))\n configure_menu_about_to_show(self.file_menu, self.__update_file_menu)\n self.edit_menu = self.menuBar().addMenu(_(\"&Edit\"))\n self.operation_menu = self.menuBar().addMenu(_(\"Operations\"))\n self.processing_menu = self.menuBar().addMenu(_(\"Processing\"))\n self.computing_menu = self.menuBar().addMenu(_(\"Computing\"))\n self.plugins_menu = self.menuBar().addMenu(_(\"Plugins\"))\n self.view_menu = self.menuBar().addMenu(_(\"&View\"))\n configure_menu_about_to_show(self.view_menu, self.__update_view_menu)\n self.help_menu = self.menuBar().addMenu(\"?\")\n for menu in (\n self.edit_menu,\n self.operation_menu,\n self.processing_menu,\n self.computing_menu,\n self.plugins_menu,\n ):\n configure_menu_about_to_show(menu, self.__update_generic_menu)\n help_menu_actions = [\n create_action(\n self,\n _(\"Online documentation\"),\n icon=get_icon(\"libre-gui-help.svg\"),\n triggered=lambda: webbrowser.open(__docurl__),\n ),\n ]\n localdocpath = self.__get_local_doc_path()\n if localdocpath is not None:\n help_menu_actions += [\n create_action(\n self,\n _(\"PDF documentation\"),\n icon=get_icon(\"help_pdf.svg\"),\n triggered=lambda: webbrowser.open(localdocpath),\n ),\n ]\n help_menu_actions += [None]\n if TEST_SEGFAULT_ERROR:\n help_menu_actions += [\n create_action(\n self,\n _(\"Test segfault/Python error\"),\n triggered=self.test_segfault_error,\n )\n ]\n help_menu_actions += [\n create_action(\n self,\n _(\"Log files\") + \"...\",\n icon=get_icon(\"logs.svg\"),\n triggered=self.__show_logviewer,\n ),\n create_action(\n self,\n _(\"Installation and configuration\") + \"...\",\n icon=get_icon(\"libre-toolbox.svg\"),\n triggered=lambda: instconfviewer.exec_cdl_installconfig_dialog(self),\n ),\n None,\n create_action(\n self,\n _(\"Project home page\"),\n icon=get_icon(\"libre-gui-globe.svg\"),\n triggered=lambda: webbrowser.open(__homeurl__),\n ),\n create_action(\n self,\n _(\"Bug report or feature request\"),\n icon=get_icon(\"libre-gui-globe.svg\"),\n triggered=lambda: webbrowser.open(__supporturl__),\n ),\n create_action(\n self,\n _(\"Check critical dependencies...\"),\n triggered=self.__check_dependencies,\n ),\n create_action(\n self,\n _(\"About...\"),\n icon=get_icon(\"libre-gui-about.svg\"),\n triggered=self.__about,\n ),\n ]\n add_actions(self.help_menu, help_menu_actions)\n\n def __setup_console(self) -> None:\n \"\"\"Add an internal console\"\"\"\n ns = {\n \"cdl\": self,\n \"np\": np,\n \"sps\": sps,\n \"spi\": spi,\n \"os\": os,\n \"sys\": sys,\n \"osp\": osp,\n \"time\": time,\n }\n msg = (\n \"Welcome to DataLab console!\\n\"\n \"---------------------------\\n\"\n \"You can access the main window with the 'cdl' variable.\\n\"\n \"Example:\\n\"\n \" o = cdl.get_object() # returns currently selected object\\n\"\n \" o = cdl[1] # returns object number 1\\n\"\n \" o = cdl['My image'] # returns object which title is 'My image'\\n\"\n \" o.data # returns object data\\n\"\n \"Modules imported at startup: \"\n \"os, sys, os.path as osp, time, \"\n \"numpy as np, scipy.signal as sps, scipy.ndimage as spi\"\n )\n self.console = DockableConsole(self, namespace=ns, message=msg, debug=DEBUG)\n self.console.setMaximumBlockCount(Conf.console.max_line_count.get(5000))\n self.console.go_to_error.connect(go_to_error)\n console_dock = self.__add_dockwidget(self.console, _(\"Console\"))\n console_dock.hide()\n self.console.interpreter.widget_proxy.sig_new_prompt.connect(\n lambda txt: self.repopulate_panel_trees()\n )\n\n def __add_macro_panel(self) -> None:\n \"\"\"Add macro panel\"\"\"\n self.macropanel = macro.MacroPanel()\n mdock = self.__add_dockwidget(self.macropanel, _(\"Macro manager\"))\n self.docks[self.macropanel] = mdock\n self.tabifyDockWidget(self.docks[self.imagepanel], mdock)\n self.docks[self.signalpanel].raise_()\n\n def __configure_panels(self) -> None:\n \"\"\"Configure panels\"\"\"\n # Connectings signals\n for panel in self.panels:\n panel.SIG_OBJECT_ADDED.connect(self.set_modified)\n panel.SIG_OBJECT_REMOVED.connect(self.set_modified)\n self.macropanel.SIG_OBJECT_MODIFIED.connect(self.set_modified)\n # Initializing common panel actions\n self.auto_refresh_action.setChecked(Conf.view.auto_refresh.get(True))\n self.showlabel_action.setChecked(Conf.view.show_label.get(False))\n # Restoring current tab from last session\n tab_idx = Conf.main.current_tab.get(None)\n if tab_idx is not None:\n self.tabwidget.setCurrentIndex(tab_idx)\n # Set focus on current panel, so that keyboard shortcuts work (Fixes #10)\n self.tabwidget.currentWidget().setFocus()\n\n def set_process_isolation_enabled(self, state: bool) -> None:\n \"\"\"Enable/disable process isolation\n\n Args:\n state (bool): True to enable process isolation\n \"\"\"\n for processor in (self.imagepanel.processor, self.signalpanel.processor):\n processor.set_process_isolation_enabled(state)\n\n # ------Remote control\n @remote_controlled\n def get_current_panel(self) -> str:\n \"\"\"Return current panel name\n\n Returns:\n str: panel name (valid values: \"signal\", \"image\", \"macro\")\n \"\"\"\n panel = self.tabwidget.currentWidget()\n dock = self.docks[panel]\n if panel is self.signalpanel and dock.isVisible():\n return \"signal\"\n if panel is self.imagepanel and dock.isVisible():\n return \"image\"\n return \"macro\"\n\n @remote_controlled\n def set_current_panel(self, panel: str) -> None:\n \"\"\"Switch to panel.\n\n Args:\n panel (str): panel name (valid values: \"signal\", \"image\", \"macro\")\n\n Raises:\n ValueError: unknown panel\n \"\"\"\n if self.get_current_panel() == panel:\n if panel in (\"signal\", \"image\"):\n # Force tab index changed event to be sure that the dock associated\n # to the current panel is raised\n self.__tab_index_changed(self.tabwidget.currentIndex())\n return\n if panel == \"signal\":\n self.tabwidget.setCurrentWidget(self.signalpanel)\n elif panel == \"image\":\n self.tabwidget.setCurrentWidget(self.imagepanel)\n elif panel == \"macro\":\n self.docks[self.macropanel].raise_()\n else:\n raise ValueError(f\"Unknown panel {panel}\")\n\n @remote_controlled\n def calc(self, name: str, param: gds.DataSet | None = None) -> None:\n \"\"\"Call compute function `name` in current panel's processor\n\n Args:\n name (str): function name\n param (guidata.dataset.DataSet): optional parameters\n (default: None)\n\n Raises:\n ValueError: unknown function\n \"\"\"\n panel = self.tabwidget.currentWidget()\n if isinstance(panel, base.BaseDataPanel):\n for funcname in (name, f\"compute_{name}\"):\n func = getattr(panel.processor, funcname, None)\n if func is not None:\n break\n else:\n raise ValueError(f\"Unknown function {funcname}\")\n if param is None:\n func()\n else:\n func(param)\n\n # ------GUI refresh\n def has_objects(self) -> bool:\n \"\"\"Return True if sig/ima panels have any object\"\"\"\n return sum(len(panel) for panel in self.panels) > 0\n\n def set_modified(self, state: bool = True) -> None:\n \"\"\"Set mainwindow modified state\"\"\"\n state = state and self.has_objects()\n self.__is_modified = state\n self.setWindowTitle(APP_NAME + (\"*\" if state else \"\"))\n\n def __add_dockwidget(self, child, title: str) -> QW.QDockWidget:\n \"\"\"Add QDockWidget and toggleViewAction\"\"\"\n dockwidget, location = child.create_dockwidget(title)\n self.addDockWidget(location, dockwidget)\n return dockwidget\n\n def repopulate_panel_trees(self) -> None:\n \"\"\"Repopulate all panel trees\"\"\"\n for panel in self.panels:\n if isinstance(panel, base.BaseDataPanel):\n panel.objview.populate_tree()\n\n def __update_actions(self) -> None:\n \"\"\"Update selection dependent actions\"\"\"\n is_signal = self.tabwidget.currentWidget() is self.signalpanel\n panel = self.signalpanel if is_signal else self.imagepanel\n panel.selection_changed()\n self.signal_toolbar.setVisible(is_signal)\n self.image_toolbar.setVisible(not is_signal)\n if self.plugins_menu is not None:\n plugin_actions = panel.get_category_actions(ActionCategory.PLUGINS)\n self.plugins_menu.setEnabled(len(plugin_actions) > 0)\n\n def __tab_index_changed(self, index: int) -> None:\n \"\"\"Switch from signal to image mode, or vice-versa\"\"\"\n dock = self.docks[self.tabwidget.widget(index)]\n dock.raise_()\n self.__update_actions()\n\n def __update_generic_menu(self, menu: QW.QMenu | None = None) -> None:\n \"\"\"Update menu before showing up -- Generic method\"\"\"\n if menu is None:\n menu = self.sender()\n menu.clear()\n panel = self.tabwidget.currentWidget()\n category = {\n self.file_menu: ActionCategory.FILE,\n self.edit_menu: ActionCategory.EDIT,\n self.view_menu: ActionCategory.VIEW,\n self.operation_menu: ActionCategory.OPERATION,\n self.processing_menu: ActionCategory.PROCESSING,\n self.computing_menu: ActionCategory.COMPUTING,\n self.plugins_menu: ActionCategory.PLUGINS,\n }[menu]\n actions = panel.get_category_actions(category)\n add_actions(menu, actions)\n\n def __update_file_menu(self) -> None:\n \"\"\"Update file menu before showing up\"\"\"\n self.saveh5_action.setEnabled(self.has_objects())\n self.__update_generic_menu(self.file_menu)\n add_actions(\n self.file_menu,\n [\n None,\n self.openh5_action,\n self.saveh5_action,\n self.browseh5_action,\n None,\n self.settings_action,\n ],\n )\n if self.quit_action is not None:\n add_actions(self.file_menu, [None, self.quit_action])\n\n def __update_view_menu(self) -> None:\n \"\"\"Update view menu before showing up\"\"\"\n self.__update_generic_menu(self.view_menu)\n add_actions(self.view_menu, [None] + self.createPopupMenu().actions())\n\n @remote_controlled\n def toggle_show_titles(self, state: bool) -> None:\n \"\"\"Toggle show annotations option\n\n Args:\n state: state\n \"\"\"\n Conf.view.show_label.set(state)\n for datapanel in (self.signalpanel, self.imagepanel):\n for obj in datapanel.objmodel:\n obj.set_metadata_option(\"showlabel\", state)\n datapanel.SIG_REFRESH_PLOT.emit(\"selected\", True)\n\n @remote_controlled\n def toggle_auto_refresh(self, state: bool) -> None:\n \"\"\"Toggle auto refresh option\n\n Args:\n state: state\n \"\"\"\n Conf.view.auto_refresh.set(state)\n for datapanel in (self.signalpanel, self.imagepanel):\n datapanel.plothandler.set_auto_refresh(state)\n\n # ------Common features\n @remote_controlled\n def reset_all(self) -> None:\n \"\"\"Reset all application data\"\"\"\n for panel in self.panels:\n if panel is not None:\n panel.remove_all_objects()\n\n @staticmethod\n def __check_h5file(filename: str, operation: str) -> str:\n \"\"\"Check HDF5 filename\"\"\"\n filename = osp.abspath(osp.normpath(filename))\n bname = osp.basename(filename)\n if operation == \"load\" and not osp.isfile(filename):\n raise IOError(f'File not found \"{bname}\"')\n if not filename.endswith(\".h5\"):\n raise IOError(f'Invalid HDF5 file \"{bname}\"')\n Conf.main.base_dir.set(filename)\n return filename\n\n @remote_controlled\n def save_to_h5_file(self, filename=None) -> None:\n \"\"\"Save to a DataLab HDF5 file\n\n Args:\n filename (str): HDF5 filename. If None, a file dialog is opened.\n\n Raises:\n IOError: if filename is invalid or file cannot be saved.\n \"\"\"\n if filename is None:\n basedir = Conf.main.base_dir.get()\n with qth.save_restore_stds():\n filename, _fl = getsavefilename(self, _(\"Save\"), basedir, \"HDF5 (*.h5)\")\n if not filename:\n return\n with qth.qt_try_loadsave_file(self, filename, \"save\"):\n filename = self.__check_h5file(filename, \"save\")\n self.h5inputoutput.save_file(filename)\n self.set_modified(False)\n\n @remote_controlled\n def open_h5_files(\n self,\n h5files: list[str] | None = None,\n import_all: bool | None = None,\n reset_all: bool | None = None,\n ) -> None:\n \"\"\"Open a DataLab HDF5 file or import from any other HDF5 file.\n\n Args:\n h5files: HDF5 filenames (optionally with dataset name, separated by \":\")\n import_all (bool): Import all datasets from HDF5 files\n reset_all (bool): Reset all application data before importing\n\n Returns:\n None\n \"\"\"\n if not self.confirm_memory_state():\n return\n if reset_all is None:\n reset_all = False\n if self.has_objects():\n answer = QW.QMessageBox.question(\n self,\n _(\"Warning\"),\n _(\n \"Do you want to remove all signals and images \"\n \"before importing data from HDF5 files?\"\n ),\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n )\n if answer == QW.QMessageBox.Yes:\n reset_all = True\n if h5files is None:\n basedir = Conf.main.base_dir.get()\n with qth.save_restore_stds():\n h5files, _fl = getopenfilenames(self, _(\"Open\"), basedir, \"HDF5 (*.h5)\")\n for fname_with_dset in h5files:\n if \",\" in fname_with_dset:\n filename, dsetname = fname_with_dset.split(\",\")\n else:\n filename, dsetname = fname_with_dset, None\n if import_all is None and dsetname is None:\n self.import_h5_file(filename, reset_all)\n else:\n with qth.qt_try_loadsave_file(self, filename, \"load\"):\n filename = self.__check_h5file(filename, \"load\")\n if dsetname is None:\n self.h5inputoutput.open_file(filename, import_all, reset_all)\n else:\n self.h5inputoutput.import_dataset_from_file(filename, dsetname)\n reset_all = False\n\n @remote_controlled\n def import_h5_file(self, filename: str, reset_all: bool | None = None) -> None:\n \"\"\"Import HDF5 file into DataLab\n\n Args:\n filename (str): HDF5 filename (optionally with dataset name,\n separated by \":\")\n reset_all (bool): Delete all DataLab signals/images before importing data\n\n Returns:\n None\n \"\"\"\n with qth.qt_try_loadsave_file(self, filename, \"load\"):\n filename = self.__check_h5file(filename, \"load\")\n self.h5inputoutput.import_file(filename, False, reset_all)\n\n # This method is intentionally *not* remote controlled\n # (see TODO regarding RemoteClient.add_object method)\n # @remote_controlled\n def add_object(self, obj: SignalObj | ImageObj) -> None:\n \"\"\"Add object - signal or image\n\n Args:\n obj (SignalObj or ImageObj): object to add (signal or image)\n \"\"\"\n if self.confirm_memory_state():\n if isinstance(obj, SignalObj):\n self.signalpanel.add_object(obj)\n elif isinstance(obj, ImageObj):\n self.imagepanel.add_object(obj)\n else:\n raise TypeError(f\"Unsupported object type {type(obj)}\")\n\n @remote_controlled\n def open_object(self, filename: str) -> None:\n \"\"\"Open object from file in current panel (signal/image)\n\n Args:\n filename (str): HDF5 filename\n\n Returns:\n None\n \"\"\"\n panel = self.tabwidget.currentWidget()\n panel.open_object(filename)\n\n # ------Other methods related to AbstractCDLControl interface\n def get_version(self) -> str:\n \"\"\"Return DataLab version.\n\n Returns:\n str: DataLab version\n \"\"\"\n return __version__\n\n def close_application(self) -> None: # Implementing AbstractCDLControl interface\n \"\"\"Close DataLab application\"\"\"\n self.close()\n\n def raise_window(self) -> None: # Implementing AbstractCDLControl interface\n \"\"\"Raise DataLab window\"\"\"\n bring_to_front(self)\n\n def add_signal(\n self,\n title: str,\n xdata: np.ndarray,\n ydata: np.ndarray,\n xunit: str | None = None,\n yunit: str | None = None,\n xlabel: str | None = None,\n ylabel: str | None = None,\n ) -> bool: # pylint: disable=too-many-arguments\n \"\"\"Add signal data to DataLab.\n\n Args:\n title (str): Signal title\n xdata (numpy.ndarray): X data\n ydata (numpy.ndarray): Y data\n xunit (str | None): X unit. Defaults to None.\n yunit (str | None): Y unit. Defaults to None.\n xlabel (str | None): X label. Defaults to None.\n ylabel (str | None): Y label. Defaults to None.\n\n Returns:\n bool: True if signal was added successfully, False otherwise\n\n Raises:\n ValueError: Invalid xdata dtype\n ValueError: Invalid ydata dtype\n \"\"\"\n obj = create_signal(\n title,\n xdata,\n ydata,\n units=(xunit, yunit),\n labels=(xlabel, ylabel),\n )\n self.add_object(obj)\n return True\n\n def add_image(\n self,\n title: str,\n data: np.ndarray,\n xunit: str | None = None,\n yunit: str | None = None,\n zunit: str | None = None,\n xlabel: str | None = None,\n ylabel: str | None = None,\n zlabel: str | None = None,\n ) -> bool: # pylint: disable=too-many-arguments\n \"\"\"Add image data to DataLab.\n\n Args:\n title (str): Image title\n data (numpy.ndarray): Image data\n xunit (str | None): X unit. Defaults to None.\n yunit (str | None): Y unit. Defaults to None.\n zunit (str | None): Z unit. Defaults to None.\n xlabel (str | None): X label. Defaults to None.\n ylabel (str | None): Y label. Defaults to None.\n zlabel (str | None): Z label. Defaults to None.\n\n Returns:\n bool: True if image was added successfully, False otherwise\n\n Raises:\n ValueError: Invalid data dtype\n \"\"\"\n obj = create_image(\n title,\n data,\n units=(xunit, yunit, zunit),\n labels=(xlabel, ylabel, zlabel),\n )\n self.add_object(obj)\n return True\n\n # ------?\n def __about(self) -> None: # pragma: no cover\n \"\"\"About dialog box\"\"\"\n self.check_stable_release()\n if self.remote_server.port is None:\n xrpcstate = '' + _(\"not started\") + \"\"\n else:\n xrpcstate = _(\"started (port %s)\") % self.remote_server.port\n xrpcstate = f\"{xrpcstate}\"\n if Conf.main.process_isolation_enabled.get():\n pistate = \"\" + _(\"enabled\") + \"\"\n else:\n pistate = \"\" + _(\"disabled\") + \"\"\n adv_conf = \"
\".join(\n [\n \"\" + _(\"Advanced configuration:\") + \"\",\n \"• \" + _(\"XML-RPC server:\") + \" \" + xrpcstate,\n \"• \" + _(\"Process isolation:\") + \" \" + pistate,\n ]\n )\n pinfos = PluginRegistry.get_plugin_infos()\n created_by = _(\"Created by\")\n dev_by = _(\"Developed and maintained by %s open-source project team\") % APP_NAME\n copyrght = \"2023 Codra\"\n QW.QMessageBox.about(\n self,\n _(\"About\") + \" \" + APP_NAME,\n f\"\"\"{APP_NAME} v{__version__}
{APP_DESC}\n

{created_by} Pierre Raybaut
{dev_by}
Copyright © {copyrght}\n

{adv_conf}

{pinfos}\"\"\",\n )\n\n def __edit_settings(self) -> None:\n \"\"\"Edit settings\"\"\"\n changed_options = edit_settings(self)\n for option in changed_options:\n if option == \"plot_toolbar_position\":\n for dock in self.docks.values():\n widget = dock.widget()\n if isinstance(widget, DockablePlotWidget):\n widget.update_toolbar_position()\n if option == \"ima_defaults\" and len(self.imagepanel) > 0:\n answer = QW.QMessageBox.question(\n self,\n _(\"Visualization settings\"),\n _(\n \"Default visualization settings have changed.

\"\n \"Do you want to update all active %s objects?\"\n )\n % _(\"image\"),\n QW.QMessageBox.Yes | QW.QMessageBox.No,\n )\n if answer == QW.QMessageBox.Yes:\n self.imagepanel.update_metadata_view_settings()\n\n def __show_logviewer(self) -> None:\n \"\"\"Show error logs\"\"\"\n logviewer.exec_cdl_logviewer_dialog(self)\n\n @staticmethod\n def test_segfault_error() -> None:\n \"\"\"Generate errors (both fault and traceback)\"\"\"\n import ctypes # pylint: disable=import-outside-toplevel\n\n ctypes.string_at(0)\n raise RuntimeError(\"!!! Testing RuntimeError !!!\")\n\n def show(self) -> None:\n \"\"\"Reimplement QMainWindow method\"\"\"\n super().show()\n if self.__old_size is not None:\n self.resize(self.__old_size)\n\n # ------Close window\n def close_properly(self) -> bool:\n \"\"\"Close properly\n\n Returns:\n bool: True if closed properly, False otherwise\n \"\"\"\n if not env.execenv.unattended and self.__is_modified:\n answer = QW.QMessageBox.warning(\n self,\n _(\"Quit\"),\n _(\n \"Do you want to save all signals and images \"\n \"to an HDF5 file before quitting DataLab?\"\n ),\n QW.QMessageBox.Yes | QW.QMessageBox.No | QW.QMessageBox.Cancel,\n )\n if answer == QW.QMessageBox.Yes:\n self.save_to_h5_file()\n if self.__is_modified:\n return False\n elif answer == QW.QMessageBox.Cancel:\n return False\n for panel in self.panels:\n if panel is not None:\n panel.close()\n if self.console is not None:\n try:\n self.console.close()\n except RuntimeError:\n # TODO: [P3] Investigate further why the following error occurs when\n # restarting the mainwindow (this is *not* a production case):\n # \"RuntimeError: wrapped C/C++ object of type DockableConsole\n # has been deleted\".\n # Another solution to avoid this error would be to really restart\n # the application (run each unit test in a separate process), but\n # it would represent too much effort for an error occuring in test\n # configurations only.\n pass\n self.reset_all()\n self.__save_pos_and_size()\n self.__unregister_plugins()\n\n # Saving current tab for next session\n Conf.main.current_tab.set(self.tabwidget.currentIndex())\n\n execenv.log(self, \"closed properly\")\n return True\n\n def closeEvent(self, event: QG.QCloseEvent) -> None:\n \"\"\"Reimplement QMainWindow method\"\"\"\n if self.hide_on_close:\n self.__old_size = self.size()\n self.hide()\n else:\n if self.close_properly():\n self.SIG_CLOSING.emit()\n event.accept()\n else:\n event.ignore()", "answers": [" for image in iterate_image_creation(data_size, non_zero=True):"], "length": 5469, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "37919f7b-8bf8-45df-9b71-ebd227d713de", "reasoning": "In run_signal_computations, after checking all_types they loop over generated signals with iterate_signal_creation. The image counterpart should similarly loop over images using iterate_image_creation. Therefore the next line after the 'if all_types:' statement is the for-loop header.", "reasoning_model_answer": "for image in iterate_image_creation(data_size, non_zero=True):", "assistant_with_reasoning": "\nIn run_signal_computations, after checking all_types they loop over generated signals with iterate_signal_creation. The image counterpart should similarly loop over images using iterate_image_creation. Therefore the next line after the 'if all_types:' statement is the for-loop header.\n\nfor image in iterate_image_creation(data_size, non_zero=True):", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.504, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36518, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "for image in iterate_image_creation(data_size, non_zero=True):", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import org.bukkit.Location;\nimport org.bukkit.EntityEffect;\nimport org.bukkit.Nameable;\nimport org.bukkit.Server;\nimport org.bukkit.World;\nimport org.bukkit.event.entity.EntityDamageEvent;\nimport org.bukkit.metadata.Metadatable;\nimport org.bukkit.util.Vector;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.UUID;\nimport org.bukkit.block.PistonMoveReaction;\nimport org.bukkit.command.CommandSender;\nimport org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;", "context": "src/main/java/org/bukkit/entity/Entity.java\npackage org.bukkit.entity;\n\n\n\n/**\n * Represents a base entity in the world\n */\npublic interface Entity extends Metadatable, CommandSender, Nameable {\n\n /**\n * Gets the entity's current position\n *\n * @return a new copy of Location containing the position of this entity\n */\n public Location getLocation();\n\n /**\n * Stores the entity's current position in the provided Location object.\n *

\n * If the provided Location is null this method does nothing and returns\n * null.\n *\n * @param loc the location to copy into\n * @return The Location object provided or null\n */\n public Location getLocation(Location loc);\n\n /**\n * Sets this entity's velocity\n *\n * @param velocity New velocity to travel with\n */\n public void setVelocity(Vector velocity);\n\n /**\n * Gets this entity's current velocity\n *\n * @return Current traveling velocity of this entity\n */\n\nsrc/main/java/org/bukkit/event/entity/EntityDamageEvent.java\npublic class EntityDamageEvent extends EntityEvent implements Cancellable {\n private static final HandlerList handlers = new HandlerList();\n private static final DamageModifier[] MODIFIERS = DamageModifier.values();\n private static final Function ZERO = Functions.constant(-0.0);\n private final Map modifiers;\n private final Map> modifierFunctions;\n private final Map originals;\n private boolean cancelled;\n private final DamageCause cause;\n\n @Deprecated\n public EntityDamageEvent(final Entity damagee, final DamageCause cause, final double damage) {\n this(damagee, cause, new EnumMap(ImmutableMap.of(DamageModifier.BASE, damage)), new EnumMap>(ImmutableMap.of(DamageModifier.BASE, ZERO)));\n }\n\n public EntityDamageEvent(final Entity damagee, final DamageCause cause, final Map modifiers, final Map> modifierFunctions) {\n super(damagee);\n Validate.isTrue(modifiers.containsKey(DamageModifier.BASE), \"BASE DamageModifier missing\");\n Validate.isTrue(!modifiers.containsKey(null), \"Cannot have null DamageModifier\");\n Validate.noNullElements(modifiers.values(), \"Cannot have null modifier values\");\n Validate.isTrue(modifiers.keySet().equals(modifierFunctions.keySet()), \"Must have a modifier function for each DamageModifier\");\n Validate.noNullElements(modifierFunctions.values(), \"Cannot have null modifier function\");\n this.originals = new EnumMap(modifiers);\n this.cause = cause;\n this.modifiers = modifiers;\n this.modifierFunctions = modifierFunctions;\n }\n\n public boolean isCancelled() {\n return cancelled;\n }\n\n public void setCancelled(boolean cancel) {\n cancelled = cancel;\n }\n\n /**\n * Gets the original damage for the specified modifier, as defined at this\n * event's construction.\n *\n * @param type the modifier\n * @return the original damage\n * @throws IllegalArgumentException if type is null\n */\n public double getOriginalDamage(DamageModifier type) throws IllegalArgumentException {\n final Double damage = originals.get(type);\n if (damage != null) {\n return damage;\n }\n if (type == null) {\n throw new IllegalArgumentException(\"Cannot have null DamageModifier\");\n }\n return 0;\n }\n\n /**\n * Sets the damage for the specified modifier.\n *\n * @param type the damage modifier\n * @param damage the scalar value of the damage's modifier\n * @see #getFinalDamage()\n * @throws IllegalArgumentException if type is null\n * @throws UnsupportedOperationException if the caller does not support\n * the particular DamageModifier, or to rephrase, when {@link\n * #isApplicable(DamageModifier)} returns false\n */\n public void setDamage(DamageModifier type, double damage) throws IllegalArgumentException, UnsupportedOperationException {\n if (!modifiers.containsKey(type)) {\n throw type == null ? new IllegalArgumentException(\"Cannot have null DamageModifier\") : new UnsupportedOperationException(type + \" is not applicable to \" + getEntity());\n }\n modifiers.put(type, damage);\n }\n\n /**\n * Gets the damage change for some modifier\n *\n * @param type the damage modifier\n * @return The raw amount of damage caused by the event\n * @throws IllegalArgumentException if type is null\n * @see DamageModifier#BASE\n */\n public double getDamage(DamageModifier type) throws IllegalArgumentException {\n Validate.notNull(type, \"Cannot have null DamageModifier\");\n final Double damage = modifiers.get(type);\n return damage == null ? 0 : damage;\n }\n\n /**\n * This checks to see if a particular modifier is valid for this event's\n * caller, such that, {@link #setDamage(DamageModifier, double)} will not\n * throw an {@link UnsupportedOperationException}.\n *

\n * {@link DamageModifier#BASE} is always applicable.\n *\n * @param type the modifier\n * @return true if the modifier is supported by the caller, false otherwise\n * @throws IllegalArgumentException if type is null\n */\n public boolean isApplicable(DamageModifier type) throws IllegalArgumentException {\n Validate.notNull(type, \"Cannot have null DamageModifier\");\n return modifiers.containsKey(type);\n }\n\n /**\n * Gets the raw amount of damage caused by the event\n *\n * @return The raw amount of damage caused by the event\n * @see DamageModifier#BASE\n */\n public double getDamage() {\n return getDamage(DamageModifier.BASE);\n }\n\n /**\n * Gets the amount of damage caused by the event after all damage\n * reduction is applied.\n *\n * @return the amount of damage caused by the event\n */\n public final double getFinalDamage() {\n double damage = 0;\n for (DamageModifier modifier : MODIFIERS) {\n damage += getDamage(modifier);\n }\n return damage;\n }\n\n /**\n * Sets the raw amount of damage caused by the event.\n *

\n * For compatibility this also recalculates the modifiers and scales\n * them by the difference between the modifier for the previous damage\n * value and the new one.\n *\n * @param damage The raw amount of damage caused by the event\n */\n public void setDamage(double damage) {\n // These have to happen in the same order as the server calculates them, keep the enum sorted\n double remaining = damage;\n double oldRemaining = getDamage(DamageModifier.BASE);\n for (DamageModifier modifier : MODIFIERS) {\n if (!isApplicable(modifier)) {\n continue;\n }\n\n Function modifierFunction = modifierFunctions.get(modifier);\n double newVanilla = modifierFunction.apply(remaining);\n double oldVanilla = modifierFunction.apply(oldRemaining);\n double difference = oldVanilla - newVanilla;\n\n // Don't allow value to cross zero, assume zero values should be negative\n double old = getDamage(modifier);\n if (old > 0) {\n setDamage(modifier, Math.max(0, old - difference));\n } else {\n setDamage(modifier, Math.min(0, old - difference));\n }\n remaining += newVanilla;\n oldRemaining += oldVanilla;\n }\n\n setDamage(DamageModifier.BASE, damage);\n }\n\n /**\n * Gets the cause of the damage.\n *\n * @return A DamageCause value detailing the cause of the damage.\n */\n public DamageCause getCause() {\n return cause;\n }\n\n @Override\n public HandlerList getHandlers() {\n return handlers;\n }\n\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n /**\n * An enum to specify the types of modifier\n *\n * @deprecated This API is responsible for a large number of implementation\n * problems and is in general unsustainable to maintain. It is likely to be\n * removed very soon in a subsequent release. Please see\n * https://www.spigotmc.org/threads/194446/ for more information.\n */\n @Deprecated\n public enum DamageModifier {\n /**\n * This represents the amount of damage being done, also known as the\n * raw {@link EntityDamageEvent#getDamage()}.\n */\n BASE,\n /**\n * This represents the damage reduced by a wearing a helmet when hit\n * by a falling block.\n */\n HARD_HAT,\n /**\n * This represents the damage reduction caused by blocking, only present for\n * {@link Player Players}.\n */\n BLOCKING,\n /**\n * This represents the damage reduction caused by wearing armor.\n */\n ARMOR,\n /**\n * This represents the damage reduction caused by the Resistance potion effect.\n */\n RESISTANCE,\n /**\n * This represents the damage reduction caused by the combination of:\n *

    \n *
  • \n * Armor enchantments\n *
  • \n * Witch's potion resistance\n *
  • \n *
\n */\n MAGIC,\n /**\n * This represents the damage reduction caused by the absorption potion\n * effect.\n */\n ABSORPTION,\n ;\n }\n\n /**\n * An enum to specify the cause of the damage\n */\n public enum DamageCause {\n\n /**\n * Damage caused when an entity contacts a block such as a Cactus.\n *

\n * Damage: 1 (Cactus)\n */\n CONTACT,\n /**\n * Damage caused when an entity attacks another entity.\n *

\n * Damage: variable\n */\n ENTITY_ATTACK,\n /**\n * Damage caused when an entity attacks another entity in a sweep attack.\n *

\n * Damage: variable\n */\n ENTITY_SWEEP_ATTACK,\n /**\n * Damage caused when attacked by a projectile.\n *

\n * Damage: variable\n */\n PROJECTILE,\n /**\n * Damage caused by being put in a block\n *

\n * Damage: 1\n */\n SUFFOCATION,\n /**\n * Damage caused when an entity falls a distance greater than 3 blocks\n *

\n * Damage: fall height - 3.0\n */\n FALL,\n /**\n * Damage caused by direct exposure to fire\n *

\n * Damage: 1\n */\n FIRE,\n /**\n * Damage caused due to burns caused by fire\n *

\n * Damage: 1\n */\n FIRE_TICK,\n /**\n * Damage caused due to a snowman melting\n *

\n * Damage: 1\n */\n MELTING,\n /**\n * Damage caused by direct exposure to lava\n *

\n * Damage: 4\n */\n LAVA,\n /**\n * Damage caused by running out of air while in water\n *

\n * Damage: 2\n */\n DROWNING,\n /**\n * Damage caused by being in the area when a block explodes.\n *

\n * Damage: variable\n */\n BLOCK_EXPLOSION,\n /**\n * Damage caused by being in the area when an entity, such as a\n * Creeper, explodes.\n *

\n * Damage: variable\n */\n ENTITY_EXPLOSION,\n /**\n * Damage caused by falling into the void\n *

\n * Damage: 4 for players\n */\n VOID,\n /**\n * Damage caused by being struck by lightning\n *

\n * Damage: 5\n */\n LIGHTNING,\n /**\n * Damage caused by committing suicide using the command \"/kill\"\n *

\n * Damage: 1000\n */\n SUICIDE,\n /**\n * Damage caused by starving due to having an empty hunger bar\n *

\n * Damage: 1\n */\n STARVATION,\n /**\n * Damage caused due to an ongoing poison effect\n *

\n * Damage: 1\n */\n POISON,\n /**\n * Damage caused by being hit by a damage potion or spell\n *

\n * Damage: variable\n */\n MAGIC,\n /**\n * Damage caused by Wither potion effect\n */\n WITHER,\n /**\n * Damage caused by being hit by a falling block which deals damage\n *

\n * Note: Not every block deals damage\n *

\n * Damage: variable\n */\n FALLING_BLOCK,\n /**\n * Damage caused in retaliation to another attack by the Thorns\n * enchantment.\n *

\n * Damage: 1-4 (Thorns)\n */\n THORNS,\n /**\n * Damage caused by a dragon breathing fire.\n *

\n * Damage: variable\n */\n DRAGON_BREATH,\n /**\n * Custom damage.\n *

\n * Damage: variable\n */\n CUSTOM,\n /**\n * Damage caused when an entity runs into a wall.\n *

\n * Damage: variable\n */\n FLY_INTO_WALL,\n /**\n * Damage caused when an entity steps on {@link Material#MAGMA}.\n *

\n * Damage: 1\n */\n HOT_FLOOR,\n /**\n * Damage caused when an entity is colliding with too many entities due\n * to the maxEntityCramming game rule.\n *

\n * Damage: 6\n */\n CRAMMING\n }\n}\n\nsrc/main/java/org/bukkit/Location.java\npublic class Location implements Cloneable, ConfigurationSerializable {\n private World world;\n private double x;\n private double y;\n private double z;\n private float pitch;\n private float yaw;\n\n /**\n * Constructs a new Location with the given coordinates\n *\n * @param world The world in which this location resides\n * @param x The x-coordinate of this new location\n * @param y The y-coordinate of this new location\n * @param z The z-coordinate of this new location\n */\n public Location(final World world, final double x, final double y, final double z) {\n this(world, x, y, z, 0, 0);\n }\n\n /**\n * Constructs a new Location with the given coordinates and direction\n *\n * @param world The world in which this location resides\n * @param x The x-coordinate of this new location\n * @param y The y-coordinate of this new location\n * @param z The z-coordinate of this new location\n * @param yaw The absolute rotation on the x-plane, in degrees\n * @param pitch The absolute rotation on the y-plane, in degrees\n */\n public Location(final World world, final double x, final double y, final double z, final float yaw, final float pitch) {\n this.world = world;\n this.x = x;\n this.y = y;\n this.z = z;\n this.pitch = pitch;\n this.yaw = yaw;\n }\n\n /**\n * Sets the world that this location resides in\n *\n * @param world New world that this location resides in\n */\n public void setWorld(World world) {\n this.world = world;\n }\n\n /**\n * Gets the world that this location resides in\n *\n * @return World that contains this location\n */\n public World getWorld() {\n return world;\n }\n\n /**\n * Gets the chunk at the represented location\n *\n * @return Chunk at the represented location\n */\n public Chunk getChunk() {\n return world.getChunkAt(this);\n }\n\n /**\n * Gets the block at the represented location\n *\n * @return Block at the represented location\n */\n public Block getBlock() {\n return world.getBlockAt(this);\n }\n\n /**\n * Sets the x-coordinate of this location\n *\n * @param x X-coordinate\n */\n public void setX(double x) {\n this.x = x;\n }\n\n /**\n * Gets the x-coordinate of this location\n *\n * @return x-coordinate\n */\n public double getX() {\n return x;\n }\n\n /**\n * Gets the floored value of the X component, indicating the block that\n * this location is contained with.\n *\n * @return block X\n */\n public int getBlockX() {\n return locToBlock(x);\n }\n\n /**\n * Sets the y-coordinate of this location\n *\n * @param y y-coordinate\n */\n public void setY(double y) {\n this.y = y;\n }\n\n /**\n * Gets the y-coordinate of this location\n *\n * @return y-coordinate\n */\n public double getY() {\n return y;\n }\n\n /**\n * Gets the floored value of the Y component, indicating the block that\n * this location is contained with.\n *\n * @return block y\n */\n public int getBlockY() {\n return locToBlock(y);\n }\n\n /**\n * Sets the z-coordinate of this location\n *\n * @param z z-coordinate\n */\n public void setZ(double z) {\n this.z = z;\n }\n\n /**\n * Gets the z-coordinate of this location\n *\n * @return z-coordinate\n */\n public double getZ() {\n return z;\n }\n\n /**\n * Gets the floored value of the Z component, indicating the block that\n * this location is contained with.\n *\n * @return block z\n */\n public int getBlockZ() {\n return locToBlock(z);\n }\n\n /**\n * Sets the yaw of this location, measured in degrees.\n *

    \n *
  • A yaw of 0 or 360 represents the positive z direction.\n *
  • A yaw of 180 represents the negative z direction.\n *
  • A yaw of 90 represents the negative x direction.\n *
  • A yaw of 270 represents the positive x direction.\n *
\n * Increasing yaw values are the equivalent of turning to your\n * right-facing, increasing the scale of the next respective axis, and\n * decreasing the scale of the previous axis.\n *\n * @param yaw new rotation's yaw\n */\n public void setYaw(float yaw) {\n this.yaw = yaw;\n }\n\n /**\n * Gets the yaw of this location, measured in degrees.\n *
    \n *
  • A yaw of 0 or 360 represents the positive z direction.\n *
  • A yaw of 180 represents the negative z direction.\n *
  • A yaw of 90 represents the negative x direction.\n *
  • A yaw of 270 represents the positive x direction.\n *
\n * Increasing yaw values are the equivalent of turning to your\n * right-facing, increasing the scale of the next respective axis, and\n * decreasing the scale of the previous axis.\n *\n * @return the rotation's yaw\n */\n public float getYaw() {\n return yaw;\n }\n\n /**\n * Sets the pitch of this location, measured in degrees.\n *
    \n *
  • A pitch of 0 represents level forward facing.\n *
  • A pitch of 90 represents downward facing, or negative y\n * direction.\n *
  • A pitch of -90 represents upward facing, or positive y direction.\n *
\n * Increasing pitch values the equivalent of looking down.\n *\n * @param pitch new incline's pitch\n */\n public void setPitch(float pitch) {\n this.pitch = pitch;\n }\n\n /**\n * Gets the pitch of this location, measured in degrees.\n *
    \n *
  • A pitch of 0 represents level forward facing.\n *
  • A pitch of 90 represents downward facing, or negative y\n * direction.\n *
  • A pitch of -90 represents upward facing, or positive y direction.\n *
\n * Increasing pitch values the equivalent of looking down.\n *\n * @return the incline's pitch\n */\n public float getPitch() {\n return pitch;\n }\n\n /**\n * Gets a unit-vector pointing in the direction that this Location is\n * facing.\n *\n * @return a vector pointing the direction of this location's {@link\n * #getPitch() pitch} and {@link #getYaw() yaw}\n */\n public Vector getDirection() {\n Vector vector = new Vector();\n\n double rotX = this.getYaw();\n double rotY = this.getPitch();\n\n vector.setY(-Math.sin(Math.toRadians(rotY)));\n\n double xz = Math.cos(Math.toRadians(rotY));\n\n vector.setX(-xz * Math.sin(Math.toRadians(rotX)));\n vector.setZ(xz * Math.cos(Math.toRadians(rotX)));\n\n return vector;\n }\n\n /**\n * Sets the {@link #getYaw() yaw} and {@link #getPitch() pitch} to point\n * in the direction of the vector.\n * \n * @param vector the direction vector\n * @return the same location\n */\n public Location setDirection(Vector vector) {\n /*\n * Sin = Opp / Hyp\n * Cos = Adj / Hyp\n * Tan = Opp / Adj\n *\n * x = -Opp\n * z = Adj\n */\n final double _2PI = 2 * Math.PI;\n final double x = vector.getX();\n final double z = vector.getZ();\n\n if (x == 0 && z == 0) {\n pitch = vector.getY() > 0 ? -90 : 90;\n return this;\n }\n\n double theta = Math.atan2(-x, z);\n yaw = (float) Math.toDegrees((theta + _2PI) % _2PI);\n\n double x2 = NumberConversions.square(x);\n double z2 = NumberConversions.square(z);\n double xz = Math.sqrt(x2 + z2);\n pitch = (float) Math.toDegrees(Math.atan(-vector.getY() / xz));\n\n return this;\n }\n\n /**\n * Adds the location by another.\n *\n * @see Vector\n * @param vec The other location\n * @return the same location\n * @throws IllegalArgumentException for differing worlds\n */\n public Location add(Location vec) {\n if (vec == null || vec.getWorld() != getWorld()) {\n throw new IllegalArgumentException(\"Cannot add Locations of differing worlds\");\n }\n\n x += vec.x;\n y += vec.y;\n z += vec.z;\n return this;\n }\n\n /**\n * Adds the location by a vector.\n *\n * @see Vector\n * @param vec Vector to use\n * @return the same location\n */\n public Location add(Vector vec) {\n this.x += vec.getX();\n this.y += vec.getY();\n this.z += vec.getZ();\n return this;\n }\n\n /**\n * Adds the location by another. Not world-aware.\n *\n * @see Vector\n * @param x X coordinate\n * @param y Y coordinate\n * @param z Z coordinate\n * @return the same location\n */\n public Location add(double x, double y, double z) {\n this.x += x;\n this.y += y;\n this.z += z;\n return this;\n }\n\n /**\n * Subtracts the location by another.\n *\n * @see Vector\n * @param vec The other location\n * @return the same location\n * @throws IllegalArgumentException for differing worlds\n */\n public Location subtract(Location vec) {\n if (vec == null || vec.getWorld() != getWorld()) {\n throw new IllegalArgumentException(\"Cannot add Locations of differing worlds\");\n }\n\n x -= vec.x;\n y -= vec.y;\n z -= vec.z;\n return this;\n }\n\n /**\n * Subtracts the location by a vector.\n *\n * @see Vector\n * @param vec The vector to use\n * @return the same location\n */\n public Location subtract(Vector vec) {\n this.x -= vec.getX();\n this.y -= vec.getY();\n this.z -= vec.getZ();\n return this;\n }\n\n /**\n * Subtracts the location by another. Not world-aware and\n * orientation independent.\n *\n * @see Vector\n * @param x X coordinate\n * @param y Y coordinate\n * @param z Z coordinate\n * @return the same location\n */\n public Location subtract(double x, double y, double z) {\n this.x -= x;\n this.y -= y;\n this.z -= z;\n return this;\n }\n\n /**\n * Gets the magnitude of the location, defined as sqrt(x^2+y^2+z^2). The\n * value of this method is not cached and uses a costly square-root\n * function, so do not repeatedly call this method to get the location's\n * magnitude. NaN will be returned if the inner result of the sqrt()\n * function overflows, which will be caused if the length is too long. Not\n * world-aware and orientation independent.\n *\n * @see Vector\n * @return the magnitude\n */\n public double length() {\n return Math.sqrt(NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z));\n }\n\n /**\n * Gets the magnitude of the location squared. Not world-aware and\n * orientation independent.\n *\n * @see Vector\n * @return the magnitude\n */\n public double lengthSquared() {\n return NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z);\n }\n\n /**\n * Get the distance between this location and another. The value of this\n * method is not cached and uses a costly square-root function, so do not\n * repeatedly call this method to get the location's magnitude. NaN will\n * be returned if the inner result of the sqrt() function overflows, which\n * will be caused if the distance is too long.\n *\n * @see Vector\n * @param o The other location\n * @return the distance\n * @throws IllegalArgumentException for differing worlds\n */\n public double distance(Location o) {\n return Math.sqrt(distanceSquared(o));\n }\n\n /**\n * Get the squared distance between this location and another.\n *\n * @see Vector\n * @param o The other location\n * @return the distance\n * @throws IllegalArgumentException for differing worlds\n */\n public double distanceSquared(Location o) {\n if (o == null) {\n throw new IllegalArgumentException(\"Cannot measure distance to a null location\");\n } else if (o.getWorld() == null || getWorld() == null) {\n throw new IllegalArgumentException(\"Cannot measure distance to a null world\");\n } else if (o.getWorld() != getWorld()) {\n throw new IllegalArgumentException(\"Cannot measure distance between \" + getWorld().getName() + \" and \" + o.getWorld().getName());\n }\n\n return NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z);\n }\n\n /**\n * Performs scalar multiplication, multiplying all components with a\n * scalar. Not world-aware.\n *\n * @param m The factor\n * @see Vector\n * @return the same location\n */\n public Location multiply(double m) {\n x *= m;\n y *= m;\n z *= m;\n return this;\n }\n\n /**\n * Zero this location's components. Not world-aware.\n *\n * @see Vector\n * @return the same location\n */\n public Location zero() {\n x = 0;\n y = 0;\n z = 0;\n return this;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Location other = (Location) obj;\n\n if (this.world != other.world && (this.world == null || !this.world.equals(other.world))) {\n return false;\n }\n if (Double.doubleToLongBits(this.x) != Double.doubleToLongBits(other.x)) {\n return false;\n }\n if (Double.doubleToLongBits(this.y) != Double.doubleToLongBits(other.y)) {\n return false;\n }\n if (Double.doubleToLongBits(this.z) != Double.doubleToLongBits(other.z)) {\n return false;\n }\n if (Float.floatToIntBits(this.pitch) != Float.floatToIntBits(other.pitch)) {\n return false;\n }\n if (Float.floatToIntBits(this.yaw) != Float.floatToIntBits(other.yaw)) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int hash = 3;\n\n hash = 19 * hash + (this.world != null ? this.world.hashCode() : 0);\n hash = 19 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32));\n hash = 19 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32));\n hash = 19 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32));\n hash = 19 * hash + Float.floatToIntBits(this.pitch);\n hash = 19 * hash + Float.floatToIntBits(this.yaw);\n return hash;\n }\n\n @Override\n public String toString() {\n return \"Location{\" + \"world=\" + world + \",x=\" + x + \",y=\" + y + \",z=\" + z + \",pitch=\" + pitch + \",yaw=\" + yaw + '}';\n }\n\n /**\n * Constructs a new {@link Vector} based on this Location\n *\n * @return New Vector containing the coordinates represented by this\n * Location\n */\n public Vector toVector() {\n return new Vector(x, y, z);\n }\n\n @Override\n public Location clone() {\n try {\n return (Location) super.clone();\n } catch (CloneNotSupportedException e) {\n throw new Error(e);\n }\n }\n\n /**\n * Check if each component of this Location is finite.\n *\n * @throws IllegalArgumentException if any component is not finite\n */\n public void checkFinite() throws IllegalArgumentException {\n NumberConversions.checkFinite(x, \"x not finite\");\n NumberConversions.checkFinite(y, \"y not finite\");\n NumberConversions.checkFinite(z, \"z not finite\");\n NumberConversions.checkFinite(pitch, \"pitch not finite\");\n NumberConversions.checkFinite(yaw, \"yaw not finite\");\n }\n\n /**\n * Safely converts a double (location coordinate) to an int (block\n * coordinate)\n *\n * @param loc Precise coordinate\n * @return Block coordinate\n */\n public static int locToBlock(double loc) {\n return NumberConversions.floor(loc);\n }\n\n @Utility\n public Map serialize() {\n Map data = new HashMap();\n data.put(\"world\", this.world.getName());\n\n data.put(\"x\", this.x);\n data.put(\"y\", this.y);\n data.put(\"z\", this.z);\n\n data.put(\"yaw\", this.yaw);\n data.put(\"pitch\", this.pitch);\n\n return data;\n }\n\n /**\n * Required method for deserialization\n *\n * @param args map to deserialize\n * @return deserialized location\n * @throws IllegalArgumentException if the world don't exists\n * @see ConfigurationSerializable\n */\n public static Location deserialize(Map args) {\n World world = Bukkit.getWorld((String) args.get(\"world\"));\n if (world == null) {\n throw new IllegalArgumentException(\"unknown world\");\n }\n\n return new Location(world, NumberConversions.toDouble(args.get(\"x\")), NumberConversions.toDouble(args.get(\"y\")), NumberConversions.toDouble(args.get(\"z\")), NumberConversions.toFloat(args.get(\"yaw\")), NumberConversions.toFloat(args.get(\"pitch\")));\n }\n}", "answers": [" public Vector getVelocity();"], "length": 3916, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ffd3c6aa-0085-403e-8d95-2b8b1b3d8e8b", "reasoning": "In the Entity interface, after the comment describing the getVelocity method, the next line should be the method signature itself. The Bukkit API defines this as returning a Vector. Therefore the appropriate next line is the declaration of getVelocity().", "reasoning_model_answer": "public Vector getVelocity();", "assistant_with_reasoning": "\nIn the Entity interface, after the comment describing the getVelocity method, the next line should be the method signature itself. The Bukkit API defines this as returning a Vector. Therefore the appropriate next line is the declaration of getVelocity().\n\npublic Vector getVelocity();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 9.163, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 31914, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public Vector getVelocity();", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "import random\nimport copy\nimport sys\nimport os\nimport bitsandbytes as bnb\nimport torch.nn as nn\nimport transformers\nimport torch\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import CUDA_VISIBLE_DEVICES, USE_TORCH, CPU_NUMS # from config\nfrom transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES\nfrom peft import (get_peft_model_state_dict, get_peft_model, LoraConfig)\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom transformers.modeling_utils import unwrap_model\nfrom tensorboardX import SummaryWriter\nfrom datasets import load_dataset\nfrom macro_gpt.models.llama.modeling_llama import LlamaForCausalLM as LLMForCausalLM\nfrom macro_gpt.models.llama.tokenization_llama import LlamaTokenizer as LLMTokenizer\nfrom macro_gpt.models.llama.modeling_llama import LlamaConfig as LLMConfig\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_PRETRAIN, DATA_PATH, MODEL_SAVE_DIR, REPO_ID\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MICRO_BATCH_SIZE, BATCH_SIZE, GRADIENT_ACCUMULATION_STEPS\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LEARNING_RATE, EPOCHS, SAVE_STEPS, VAL_SET_SIZE, TARGET_MODULES\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import IS_PARALLELIZABLE, MODEL_PARALLEL, USE_CACHE\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MAX_LENGTH_Q, MAX_LENGTH_A, MAX_LENGTH_QA\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LORA_DROPOUT, LORA_ALPHA, LORA_R\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_CONFIG, PATH_TOKENIZER_PRETRAIN", "context": "macro_gpt/ft_gpt/train.pt.py\n# !/usr/bin/python\n# -*- coding: utf-8 -*-\n# @time : 2023/3/5 21:04\n# @author : Mo\n# @function: macro-gpt\n\n\npath_root = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../..\"))\nsys.path.append(path_root)\nos.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"max_split_size_mb:3072\"\n\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMODEL_PARALLEL = False\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nREPO_ID = \"Macropodus/macrogpt-tokenizer\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMODEL_SAVE_DIR = \"model_macrogpt_1b3_float32\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nDATA_PATH = \"../datasets/tigerbot-train-00001-of-00097.json\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nCPU_NUMS = \"9\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nTARGET_MODULES = [\"query_key_value\"]\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nLORA_ALPHA = 16\n\nmacro_gpt/models/llama/modeling_llama.py\ndef is_flash_attn_available():\n def _is_package_available(pkg_name: str, return_version: bool = False) -> Union[Tuple[bool, str], bool]:\ndef _get_unpad_data(padding_mask):\ndef _make_causal_mask(\n input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0\n):\ndef _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):\n def __init__(self, hidden_size, eps=1e-6):\n def forward(self, hidden_states):\n def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):\n def _set_cos_sin_cache(self, seq_len, device, dtype):\n def forward(self, x, seq_len=None):\n def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):\n def _set_cos_sin_cache(self, seq_len, device, dtype):\n def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):\n def _set_cos_sin_cache(self, seq_len, device, dtype):\ndef rotate_half(x):\ndef apply_rotary_pos_emb(q, k, cos, sin, position_ids):\n def __init__(self, config):\n def forward(self, x):\ndef repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:\n def __init__(self, config: LlamaConfig):\n def _init_rope(self):\n def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_value: Optional[Tuple[torch.Tensor]] = None,\n output_attentions: bool = False,\n use_cache: bool = False,\n padding_mask: Optional[torch.LongTensor] = None,\n ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_value: Optional[Tuple[torch.Tensor]] = None,\n output_attentions: bool = False,\n use_cache: bool = False,\n padding_mask: Optional[torch.LongTensor] = None,\n ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n def _flash_attention_forward(\n self, query_states, key_states, value_states, padding_mask, query_length, dropout=0.0, softmax_scale=None\n ):\n def _upad_input(self, query_layer, key_layer, value_layer, padding_mask, query_length):\n def __init__(self, config: LlamaConfig):\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_value: Optional[Tuple[torch.Tensor]] = None,\n output_attentions: Optional[bool] = False,\n use_cache: Optional[bool] = False,\n padding_mask: Optional[torch.LongTensor] = None,\n ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n def _init_weights(self, module):\n def _set_gradient_checkpointing(self, module, value=False):\n def __init__(self, config: LlamaConfig):\n def get_input_embeddings(self):\n def set_input_embeddings(self, value):\n def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, BaseModelOutputWithPast]:\n def create_custom_forward(module):\n def custom_forward(*inputs):\n def __init__(self, config):\n def get_input_embeddings(self):\n def set_input_embeddings(self, value):\n def get_output_embeddings(self):\n def set_output_embeddings(self, new_embeddings):\n def set_decoder(self, decoder):\n def get_decoder(self):\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithPast]:\n def prepare_inputs_for_generation(\n self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n ):\n def _reorder_cache(past_key_values, beam_idx):\n def __init__(self, config):\n def get_input_embeddings(self):\n def set_input_embeddings(self, value):\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, SequenceClassifierOutputWithPast]:\n_CONFIG_FOR_DOC = \"LlamaConfig\"\nLLAMA_START_DOCSTRING = r\"\"\"\n This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n etc.)\n\n This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n and behavior.\n\n Parameters:\n config ([`LlamaConfig`]):\n Model configuration class with all the parameters of the model. Initializing with a config file does not\n load the weights associated with the model, only the configuration. Check out the\n [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\nLLAMA_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide\n it.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n If `past_key_values` is used, optionally only the last `input_ids` have to be input (see\n `past_key_values`).\n\n If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]\n and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more\n information on the default strategy.\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n config.n_positions - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):\n Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape\n `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape\n `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.\n\n Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention\n blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\n If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't\n have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`\n of shape `(batch_size, sequence_length)`.\n inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n model's internal embedding lookup matrix.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\nclass LlamaRMSNorm(nn.Module):\nclass LlamaRotaryEmbedding(nn.Module):\nclass LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):\nclass LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):\nclass LlamaMLP(nn.Module):\nclass LlamaAttention(nn.Module):\nclass LlamaFlashAttention2(LlamaAttention):\nclass LlamaDecoderLayer(nn.Module):\nclass LlamaPreTrainedModel(PreTrainedModel):\nclass LlamaModel(LlamaPreTrainedModel):\nclass LlamaForCausalLM(LlamaPreTrainedModel):\nclass LlamaForSequenceClassification(LlamaPreTrainedModel):\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nPATH_MODEL_PRETRAIN = \"\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nGRADIENT_ACCUMULATION_STEPS = BATCH_SIZE // MICRO_BATCH_SIZE\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMAX_LENGTH_QA = MAX_LENGTH_Q + MAX_LENGTH_A + 4\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMAX_LENGTH_A = 1024 - 2 # default=128 - 2\n\nmacro_gpt/models/llama/modeling_llama.py\nclass LlamaForCausalLM(LlamaPreTrainedModel):\n _tied_weights_keys = [\"lm_head.weight\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.model = LlamaModel(config)\n self.vocab_size = config.vocab_size\n self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_input_embeddings(self):\n return self.model.embed_tokens\n\n def set_input_embeddings(self, value):\n self.model.embed_tokens = value\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def set_output_embeddings(self, new_embeddings):\n self.lm_head = new_embeddings\n\n def set_decoder(self, decoder):\n self.model = decoder\n\n def get_decoder(self):\n return self.model\n\n @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, LlamaForCausalLM\n\n >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)\n >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)\n\n >>> prompt = \"Hey, are you conscious? Can you talk to me?\"\n >>> inputs = tokenizer(prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"Hey, are you conscious? Can you talk to me?\\nI'm not conscious, but I can talk to you.\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n if self.config.pretraining_tp > 1:\n lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)\n logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]\n logits = torch.cat(logits, dim=-1)\n else:\n # logits = self.lm_head(hidden_states)\n logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype))\n logits = logits.float()\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n shift_logits = shift_logits.view(-1, self.config.vocab_size)\n shift_labels = shift_labels.view(-1)\n # Enable model parallelism\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return CausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def prepare_inputs_for_generation(\n self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n ):\n if past_key_values is not None:\n past_length = past_key_values[0][0].shape[2]\n\n # Some generation methods already pass only the last input ID\n if input_ids.shape[1] > past_length:\n remove_prefix_length = past_length\n else:\n # Default to old behavior: keep only final ID\n remove_prefix_length = input_ids.shape[1] - 1\n\n input_ids = input_ids[:, remove_prefix_length:]\n\n position_ids = kwargs.get(\"position_ids\", None)\n if attention_mask is not None and position_ids is None:\n # create position_ids on the fly for batch generation\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n if past_key_values:\n position_ids = position_ids[:, -input_ids.shape[1] :]\n\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step\n if inputs_embeds is not None and past_key_values is None:\n model_inputs = {\"inputs_embeds\": inputs_embeds}\n else:\n model_inputs = {\"input_ids\": input_ids}\n\n model_inputs.update(\n {\n \"position_ids\": position_ids,\n \"past_key_values\": past_key_values,\n \"use_cache\": kwargs.get(\"use_cache\"),\n \"attention_mask\": attention_mask,\n }\n )\n return model_inputs\n\n @staticmethod\n def _reorder_cache(past_key_values, beam_idx):\n reordered_past = ()\n for layer_past in past_key_values:\n reordered_past += (\n tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),\n )\n return reordered_past\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMICRO_BATCH_SIZE = 4 # default=4 # this could actually be 5 but i like powers of 2\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nPATH_MODEL_CONFIG = \"config_macrogpt_1b3_float32.json\" or MODEL_SAVE_DIR\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nUSE_CACHE = False\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nVAL_SET_SIZE = 0\n\nmacro_gpt/models/llama/tokenization_llama.py\nclass LlamaTokenizer(PreTrainedTokenizer):\n \"\"\"\n Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is\n no padding token in the original model.\n\n Args:\n vocab_file (`str`):\n Path to the vocabulary file.\n unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `\"\"`):\n The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this\n token instead.\n bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `\"\"`):\n The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.\n eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `\"\"`):\n The end of sequence token.\n pad_token (`str` or `tokenizers.AddedToken`, *optional*):\n A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by\n attention mechanisms or loss computation.\n sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):\n Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for\n SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,\n to set:\n\n - `enable_sampling`: Enable subword regularization.\n - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.\n\n - `nbest_size = {0,1}`: No sampling is performed.\n - `nbest_size > 1`: samples from the nbest_size results.\n - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)\n using forward-filtering-and-backward-sampling algorithm.\n\n - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for\n BPE-dropout.\n\n add_bos_token (`bool`, *optional*, defaults to `True`):\n Whether or not to add an `bos_token` at the start of sequences.\n add_eos_token (`bool`, *optional*, defaults to `False`):\n Whether or not to add an `eos_token` at the end of sequences.\n clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):\n Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like\n extra spaces.\n use_default_system_prompt (`bool`, *optional*, defaults to `True`):\n Whether or not the default system prompt for Llama should be used.\n spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to add spaces between special tokens.\n legacy (`bool`, *optional*):\n Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622\n and #25224 which includes fixes to properly handle tokens that appear after special tokens. A simple\n example:\n\n - `legacy=True`:\n ```python\n >>> from transformers import T5Tokenizer\n\n >>> tokenizer = T5Tokenizer.from_pretrained(\"t5-base\", legacy=True)\n >>> tokenizer.encode(\"Hello .\")\n [8774, 32099, 3, 5, 1]\n ```\n - `legacy=False`:\n ```python\n >>> from transformers import T5Tokenizer\n\n >>> tokenizer = T5Tokenizer.from_pretrained(\"t5-base\", legacy=False)\n >>> tokenizer.encode(\"Hello .\") # the extra space `[3]` is no longer here\n [8774, 32099, 5, 1]\n ```\n Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.\n\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n model_input_names = [\"input_ids\", \"attention_mask\"]\n\n def __init__(\n self,\n vocab_file,\n unk_token=\"\",\n bos_token=\"\",\n eos_token=\"\",\n pad_token=None,\n sp_model_kwargs: Optional[Dict[str, Any]] = None,\n add_bos_token=True,\n add_eos_token=False,\n clean_up_tokenization_spaces=False,\n use_default_system_prompt=True,\n spaces_between_special_tokens=False,\n legacy=None,\n **kwargs,\n ):\n self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs\n bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token\n unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token\n\n if legacy is None:\n logger.warning_once(\n f\"You are using the default legacy behaviour of the {self.__class__}. This is\"\n \" expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you.\"\n \" If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it\"\n \" means, and thouroughly read the reason why this was added as explained in\"\n \" https://github.com/huggingface/transformers/pull/24565\"\n )\n legacy = True\n\n self.legacy = legacy\n self.vocab_file = vocab_file\n self.add_bos_token = add_bos_token\n self.add_eos_token = add_eos_token\n self.use_default_system_prompt = use_default_system_prompt\n self.sp_model = self.get_spm_processor(kwargs.pop(\"from_slow\", False))\n\n super().__init__(\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n pad_token=pad_token,\n add_bos_token=add_bos_token,\n add_eos_token=add_eos_token,\n sp_model_kwargs=self.sp_model_kwargs,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n use_default_system_prompt=use_default_system_prompt,\n spaces_between_special_tokens=spaces_between_special_tokens,\n legacy=legacy,\n **kwargs,\n )\n\n @property\n def unk_token_length(self):\n return len(self.sp_model.encode(str(self.unk_token)))\n\n # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor\n def get_spm_processor(self, from_slow=False):\n tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n if self.legacy or from_slow: # no dependency on protobuf\n tokenizer.Load(self.vocab_file)\n return tokenizer\n\n with open(self.vocab_file, \"rb\") as f:\n sp_model = f.read()\n model_pb2 = import_protobuf(f\"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)\")\n model = model_pb2.ModelProto.FromString(sp_model)\n normalizer_spec = model_pb2.NormalizerSpec()\n normalizer_spec.add_dummy_prefix = False\n model.normalizer_spec.MergeFrom(normalizer_spec)\n sp_model = model.SerializeToString()\n tokenizer.LoadFromSerializedProto(sp_model)\n return tokenizer\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state[\"sp_model\"] = None\n state[\"sp_model_proto\"] = self.sp_model.serialized_model_proto()\n return state\n\n def __setstate__(self, d):\n self.__dict__ = d\n self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)\n self.sp_model.LoadFromSerializedProto(self.sp_model_proto)\n\n @property\n def vocab_size(self):\n \"\"\"Returns vocab size\"\"\"\n return self.sp_model.get_piece_size()\n\n def get_vocab(self):\n \"\"\"Returns vocab as a dict\"\"\"\n vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}\n vocab.update(self.added_tokens_encoder)\n return vocab\n\n # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize\n def tokenize(self, text: \"TextInput\", add_special_tokens=False, **kwargs) -> List[str]:\n \"\"\"\n Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the\n first token is special.\n \"\"\"\n if self.legacy or len(text) == 0:\n return super().tokenize(text, **kwargs)\n\n tokens = super().tokenize(SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, \" \"), **kwargs)\n\n if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:\n tokens = tokens[1:]\n return tokens\n\n # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize\n def _tokenize(self, text, **kwargs):\n \"\"\"\n Returns a tokenized string.\n\n We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any\n SPIECE_UNDERLINE. For example: `self.sp_model.encode(f\"{SPIECE_UNDERLINE}Hey\", out_type = str)` will give\n `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f\"{unk_token}text\"` and strip the\n `unk_token`. Here is an example with `unk_token = \"\"` and `unk_token_length = 4`.\n `self.tokenizer.sp_model.encode(\" Hey\", out_type = str)[4:]`.\n \"\"\"\n tokens = self.sp_model.encode(text, out_type=str)\n if self.legacy or not text.startswith((SPIECE_UNDERLINE, \" \")):\n return tokens\n\n # 1. Encode string + prefix ex: \" Hey\"\n tokens = self.sp_model.encode(self.unk_token + text, out_type=str)\n # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']\n return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens\n\n def _convert_token_to_id(self, token):\n \"\"\"Converts a token (str) in an id using the vocab.\"\"\"\n return self.sp_model.piece_to_id(token)\n\n def _convert_id_to_token(self, index):\n \"\"\"Converts an index (integer) in a token (str) using the vocab.\"\"\"\n token = self.sp_model.IdToPiece(index)\n return token\n\n def convert_tokens_to_string(self, tokens):\n \"\"\"Converts a sequence of tokens (string) in a single string.\"\"\"\n # since we manually add the prefix space, we have to remove it when decoding\n if tokens[0].startswith(SPIECE_UNDERLINE):\n tokens[0] = tokens[0][1:]\n\n current_sub_tokens = []\n out_string = \"\"\n prev_is_special = False\n for i, token in enumerate(tokens):\n # make sure that special tokens are not decoded using sentencepiece model\n if token in self.all_special_tokens:\n if not prev_is_special and i != 0 and self.legacy:\n out_string += \" \"\n out_string += self.sp_model.decode(current_sub_tokens) + token\n prev_is_special = True\n current_sub_tokens = []\n else:\n current_sub_tokens.append(token)\n prev_is_special = False\n out_string += self.sp_model.decode(current_sub_tokens)\n return out_string\n\n def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:\n \"\"\"\n Save the vocabulary and special tokens file to a directory.\n\n Args:\n save_directory (`str`):\n The directory in which to save the vocabulary.\n\n Returns:\n `Tuple(str)`: Paths to the files saved.\n \"\"\"\n if not os.path.isdir(save_directory):\n logger.error(f\"Vocabulary path ({save_directory}) should be a directory\")\n return\n out_vocab_file = os.path.join(\n save_directory, (filename_prefix + \"-\" if filename_prefix else \"\") + VOCAB_FILES_NAMES[\"vocab_file\"]\n )\n\n if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):\n copyfile(self.vocab_file, out_vocab_file)\n elif not os.path.isfile(self.vocab_file):\n with open(out_vocab_file, \"wb\") as fi:\n content_spiece_model = self.sp_model.serialized_model_proto()\n fi.write(content_spiece_model)\n\n return (out_vocab_file,)\n\n def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):\n bos_token_id = [self.bos_token_id] if self.add_bos_token else []\n eos_token_id = [self.eos_token_id] if self.add_eos_token else []\n\n output = bos_token_id + token_ids_0 + eos_token_id\n\n if token_ids_1 is not None:\n output = output + bos_token_id + token_ids_1 + eos_token_id\n\n return output\n\n def get_special_tokens_mask(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False\n ) -> List[int]:\n \"\"\"\n Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer `prepare_for_model` method.\n\n Args:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n already_has_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not the token list is already formatted with special tokens for the model.\n\n Returns:\n `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.\n \"\"\"\n if already_has_special_tokens:\n return super().get_special_tokens_mask(\n token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True\n )\n\n bos_token_id = [1] if self.add_bos_token else []\n eos_token_id = [1] if self.add_eos_token else []\n\n if token_ids_1 is None:\n return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id\n return (\n bos_token_id\n + ([0] * len(token_ids_0))\n + eos_token_id\n + bos_token_id\n + ([0] * len(token_ids_1))\n + eos_token_id\n )\n\n def create_token_type_ids_from_sequences(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None\n ) -> List[int]:\n \"\"\"\n Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT\n sequence pair mask has the following format:\n\n ```\n 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1\n | first sequence | second sequence |\n ```\n\n if token_ids_1 is None, only returns the first portion of the mask (0s).\n\n Args:\n token_ids_0 (`List[int]`):\n List of ids.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n\n Returns:\n `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).\n \"\"\"\n bos_token_id = [self.bos_token_id] if self.add_bos_token else []\n eos_token_id = [self.eos_token_id] if self.add_eos_token else []\n\n output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)\n\n if token_ids_1 is not None:\n output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)\n\n return output\n\n @property\n def default_chat_template(self):\n \"\"\"\n LLaMA uses [INST] and [/INST] to indicate user messages, and <> and <> to indicate system messages.\n Assistant messages do not have special tokens, because LLaMA chat models are generally trained with strict\n user/assistant/user/assistant message ordering, and so assistant messages can be identified from the ordering\n rather than needing special tokens. The system message is partly 'embedded' in the first user message, which\n results in an unusual token ordering when it is present. This template should definitely be changed if you wish\n to fine-tune a model with more flexible role ordering!\n\n The output should look something like:\n\n [INST] B_SYS SystemPrompt E_SYS Prompt [/INST] Answer [INST] Prompt [/INST] Answer \n [INST] Prompt [/INST]\n \"\"\"\n\n template = (\n \"{% if messages[0]['role'] == 'system' %}\"\n \"{% set loop_messages = messages[1:] %}\" # Extract system message if it's present\n \"{% set system_message = messages[0]['content'] %}\"\n \"{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}\"\n \"{% set loop_messages = messages %}\" # Or use the default system message if the flag is set\n \"{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}\"\n \"{% else %}\"\n \"{% set loop_messages = messages %}\"\n \"{% set system_message = false %}\"\n \"{% endif %}\"\n \"{% for message in loop_messages %}\" # Loop over all non-system messages\n \"{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}\"\n \"{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}\"\n \"{% endif %}\"\n \"{% if loop.index0 == 0 and system_message != false %}\" # Embed system message in first message\n \"{% set content = '<>\\\\n' + system_message + '\\\\n<>\\\\n\\\\n' + message['content'] %}\"\n \"{% else %}\"\n \"{% set content = message['content'] %}\"\n \"{% endif %}\"\n \"{% if message['role'] == 'user' %}\" # After all of that, handle messages/roles in a fairly normal way\n \"{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}\"\n \"{% elif message['role'] == 'system' %}\"\n \"{{ '<>\\\\n' + content.strip() + '\\\\n<>\\\\n\\\\n' }}\"\n \"{% elif message['role'] == 'assistant' %}\"\n \"{{ ' ' + content.strip() + ' ' + eos_token }}\"\n \"{% endif %}\"\n \"{% endfor %}\"\n )\n template = template.replace(\"USE_DEFAULT_PROMPT\", \"true\" if self.use_default_system_prompt else \"false\")\n default_message = DEFAULT_SYSTEM_PROMPT.replace(\"\\n\", \"\\\\n\").replace(\"'\", \"\\\\'\")\n template = template.replace(\"DEFAULT_SYSTEM_MESSAGE\", default_message)\n\n return template", "answers": ["os.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES"], "length": 3621, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "807be713-0c20-4fc9-85ed-9955a7ee7d05", "reasoning": "After the series of imports, the script typically configures the CUDA devices using the imported CUDA_VISIBLE_DEVICES variable. The next logical line sets the environment variable so that PyTorch respects the desired GPU selection.", "reasoning_model_answer": "os.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES", "assistant_with_reasoning": "\nAfter the series of imports, the script typically configures the CUDA devices using the imported CUDA_VISIBLE_DEVICES variable. The next logical line sets the environment variable so that PyTorch respects the desired GPU selection.\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.672, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37599, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "os.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "import com.fasterxml.jackson.databind.JsonNode;\nimport io.fiber.net.common.async.Maybe;\nimport io.fiber.net.script.ast.Block;\nimport io.fiber.net.script.parse.CompiledScript;\nimport io.fiber.net.script.parse.ParseException;\nimport io.fiber.net.script.parse.Parser;\nimport io.fiber.net.script.std.StdLibrary;", "context": "fiber-gateway-script/src/main/java/io/fiber/net/script/Script.java\npackage io.fiber.net.script;\n\n\npublic interface Script {\n\n static Script compile(String script) throws ParseException {\n return compile(script, StdLibrary.getDefInstance());\n }\n\n static Script compileWithoutAssign(String script) throws ParseException {\n\nfiber-gateway-script/src/main/java/io/fiber/net/script/parse/ParseException.java\npublic class ParseException extends RuntimeException {\n protected String expressionString;\n protected int position; // -1 if not known - but should be known in all reasonable cases\n\n /**\n * Creates a new expression exception.\n *\n * @param expressionString the expression string\n * @param message a descriptive message\n */\n public ParseException(String expressionString, String message) {\n super(message);\n this.position = -1;\n this.expressionString = expressionString;\n }\n\n /**\n * Creates a new expression exception.\n *\n * @param expressionString the expression string\n * @param position the position in the expression string where the problem occurred\n * @param message a descriptive message\n */\n public ParseException(String expressionString, int position, String message) {\n super(message);\n this.position = position;\n this.expressionString = expressionString;\n }\n\n /**\n * Creates a new expression exception.\n *\n * @param position the position in the expression string where the problem occurred\n * @param message a descriptive message\n */\n public ParseException(int position, String message) {\n super(message);\n this.position = position;\n }\n\n /**\n * Creates a new expression exception.\n *\n * @param position the position in the expression string where the problem occurred\n * @param message a descriptive message\n * @param cause the underlying cause of this exception\n */\n public ParseException(int position, String message, Throwable cause) {\n super(message, cause);\n this.position = position;\n }\n\n public ParseException(int position, SpelMessage spelMessage, Object... addition) {\n super(spelMessage.formatMessage(position, addition));\n this.position = position;\n }\n\n public ParseException(Throwable cause, int position, SpelMessage spelMessage, Object... addition) {\n super(spelMessage.formatMessage(position, addition), cause);\n this.position = position;\n }\n\n /**\n * Creates a new expression exception.\n */\n public ParseException(String expressionString, int position, SpelMessage spelMessage, Object... addition) {\n super(toDetailedString(expressionString, position, spelMessage, addition));\n this.expressionString = expressionString;\n this.position = position;\n }\n\n public ParseException(String message) {\n super(message);\n }\n\n public ParseException(String message, Throwable cause) {\n super(message, cause);\n }\n\n private static String toDetailedString(String expressionString, int position, SpelMessage spelMessage, Object... addition) {\n StringBuilder output = new StringBuilder();\n if (expressionString != null) {\n output.append(\"Expression '\");\n output.append(expressionString);\n output.append(\"'\");\n if (position != -1) {\n output.append(\" @ \");\n output.append(position);\n }\n output.append(\": \");\n }\n output.append(spelMessage.formatMessagePos(position, addition));\n return output.toString();\n }\n\n public final String getExpressionString() {\n return this.expressionString;\n }\n\n public final int getPosition() {\n return position;\n }\n}\n\nfiber-gateway-script/src/main/java/io/fiber/net/script/std/StdLibrary.java\npublic class StdLibrary implements Library {\n private static final Map DEF_FUNC_MAP = new HashMap<>();\n\n static {\n DEF_FUNC_MAP.put(\"random\", new RandomFunc());\n DEF_FUNC_MAP.put(\"now\", new NowFunc());\n DEF_FUNC_MAP.put(\"canary\", new CanaryFunc());\n DEF_FUNC_MAP.put(\"crc32\", new Crc32Func());\n DEF_FUNC_MAP.put(\"includes\", new IncludesFunc());\n DEF_FUNC_MAP.putAll(ArrayFuncs.FUNC);\n DEF_FUNC_MAP.putAll(ObjectsFuncs.FUNC);\n DEF_FUNC_MAP.putAll(StringsFuncs.FUNC);\n DEF_FUNC_MAP.putAll(MathFuncs.FUNC);\n DEF_FUNC_MAP.putAll(BinaryFunc.FUNC);\n }\n\n protected static Map getDefFuncMap() {\n return DEF_FUNC_MAP;\n }\n\n private final static StdLibrary DEF_INSTANCE = new StdLibrary(DEF_FUNC_MAP);\n\n public static StdLibrary getDefInstance() {\n return DEF_INSTANCE;\n }\n\n protected final Map functionMap;\n\n public StdLibrary(Map functionMap) {\n this.functionMap = functionMap;\n }\n\n @Override\n public Library.Function findFunc(String name) {\n return functionMap.get(name);\n }\n\n @Override\n public Constant findConstant(String namespace, String key) {\n return null;\n }\n\n @Override\n public DirectiveDef findDirectiveDef(String type, String name, List literals) {\n return null;\n }\n}\n\nfiber-gateway-common/src/main/java/io/fiber/net/common/async/Maybe.java\npublic interface Maybe {\n\n interface Emitter {\n void onSuccess(T t);\n\n void onError(Throwable t);\n\n void onComplete();\n\n boolean isDisposed();\n }\n\n interface Observer {\n void onSubscribe(Disposable d);\n\n void onSuccess(T t);\n\n void onError(Throwable e);\n\n void onComplete();\n\n Scheduler scheduler();\n }\n\n interface OnSubscribe {\n\n void subscribe(Emitter emitter) throws Throwable;\n }\n\n void subscribe(Observer observer);\n\n default Maybe onNotify(BiConsumer onNotify) {\n return new OnNotifyWrapMaybe<>(onNotify, this);\n }\n\n default Maybe map(Function function) {\n return new MappedMaybe<>(function, this);\n }\n\n default Disposable subscribe(java.util.function.BiConsumer consumer) {\n FuncMaybeObserver tFuncMaybeObserver = new FuncMaybeObserver<>(consumer);\n subscribe(tFuncMaybeObserver);\n return tFuncMaybeObserver.getDisposable();\n }\n\n\n static Maybe create(OnSubscribe onSubscribe) {\n return new MaybeCreate<>(onSubscribe);\n }\n\n @SuppressWarnings(\"unchecked\")\n static Maybe ofErr(Throwable err) {\n return (Maybe) new ErrMaybe(err);\n }\n}\n\nfiber-gateway-script/src/main/java/io/fiber/net/script/parse/Parser.java\npublic class Parser {\n static final String[] EMPTY_STR_ARR = Constant.EMPTY_STR_ARR;\n static final ExpressionNode[] EMPTY_NODE_ARR = new ExpressionNode[0];\n private static final Pattern VALID_QUALIFIED_ID_PATTERN = Pattern.compile(\"[\\\\p{L}\\\\p{N}_$]+\");\n\n private final Library library;\n private boolean hasAssign = true;\n\n // The token stream constructed from that expression string\n private List tokenStream;\n\n // length of a populated token stream\n private int tokenStreamLength;\n\n // Current location in the token stream when processing tokens\n private int tokenStreamPointer;\n\n private final Map directiveMap = new HashMap<>();\n\n private static final Keyword[] KW_VALUES = Keyword.values();\n\n private static Keyword tryMatchKeyWords(String name) {\n for (Keyword kw : KW_VALUES) {\n if (kw.idt.equals(name)) {\n return kw;\n }\n }\n return null;\n }\n\n enum Keyword {\n LET, IF, ELSE, FOR, OF, CONTINUE, BREAK, RETURN, DIRECTIVE, FROM, TRY, CATCH, THROW;\n\n final String idt;\n\n\n Keyword() {\n idt = name().toLowerCase();\n }\n\n public String getIdt() {\n return idt;\n }\n\n }\n\n private Parser(Library library) {\n this.library = library;\n }\n\n public Parser(Library library, boolean hasAssign) {\n this.library = library;\n this.hasAssign = hasAssign;\n }\n\n public Block parseScript(String script) throws ParseException {\n Tokenizer tokenizer = new Tokenizer(script);\n tokenizer.process();\n return parseScriptFromTokens(tokenizer.getTokens(), script);\n }\n\n public Block parseScriptFromTokens(List tokens, String originScript) {\n this.tokenStream = tokens;\n this.tokenStreamLength = tokens.size();\n this.tokenStreamPointer = 0;\n Block block;\n try {\n block = eatBlock(false);\n } catch (ParseException e) {\n e.expressionString = originScript;\n throw e;\n }\n if (moreTokens()) {\n throw new ParseException(originScript, peekToken().startpos, SpelMessage.MORE_INPUT, toString(nextToken()));\n }\n return block;\n }\n\n public ExpressionNode parseExpression(String exp) throws ParseException {\n Tokenizer tokenizer = new Tokenizer(exp);\n tokenizer.process();\n return parseExpression(tokenizer.getTokens(), exp);\n }\n\n public ExpressionNode parseExpression(List tokens, String originExp) throws ParseException {\n this.tokenStream = tokens;\n this.tokenStreamLength = tokens.size();\n this.tokenStreamPointer = 0;\n ExpressionNode expressionNode;\n try {\n expressionNode = eatExpression();\n } catch (ParseException e) {\n e.expressionString = originExp;\n throw e;\n }\n if (moreTokens()) {\n throw new ParseException(originExp, peekToken().startpos, SpelMessage.MORE_INPUT, toString(nextToken()));\n }\n return expressionNode;\n }\n\n private Statement eatStatement() throws ParseException {\n Statement statement = tryEatIfStatement();\n if (statement != null) {\n return statement;\n }\n statement = tryEatForeachStatement();\n if (statement != null) {\n return statement;\n }\n\n statement = tryEatBreakStatement();\n if (statement != null) {\n return statement;\n }\n statement = tryEatContinueStatement();\n if (statement != null) {\n return statement;\n }\n statement = tryEatReturnStatement();\n if (statement != null) {\n return statement;\n }\n\n statement = tryEatThrowStatement();\n if (statement != null) {\n return statement;\n }\n\n statement = tryEatTryCatchStatement();\n if (statement != null) {\n return statement;\n }\n\n statement = tryEatVariableDeclareStatement();\n if (statement != null) {\n return statement;\n }\n\n statement = tryEatDirectiveStatement();\n if (statement != null) {\n return statement;\n }\n\n ExpressionNode eatExpression = eatExpression();\n peekToken(TokenKind.SEMICOLON, true);\n return new ExpressionStatement(eatExpression);\n }\n\n private Statement tryEatThrowStatement() {\n if (!moreTokens() || !peekIdentifierToken(Keyword.THROW.idt)) {\n return null;\n }\n Token token = nextToken();\n\n ExpressionNode node = eatExpression();\n peekToken(TokenKind.SEMICOLON, true);\n return new ThrowStatement(toPos(token.startpos, node.getEndPosition()), node);\n }\n\n private Statement tryEatTryCatchStatement() {\n if (!moreTokens() || !peekIdentifierToken(Keyword.TRY.idt)) {\n return null;\n }\n\n Token tryTk = eatKeyWord(Keyword.TRY);\n Block tryBk = eatBlock(true);\n eatKeyWord(Keyword.CATCH);\n eatToken(TokenKind.LPAREN);\n Identifier identifier = eatIdentifier();\n eatToken(TokenKind.RPAREN);\n Block catchBk = eatBlock(true);\n return new TryCatchStatement(toPos(tryTk.startpos, catchBk.getEndPosition()), identifier, tryBk, catchBk);\n }\n\n private ContinueStatement tryEatContinueStatement() {\n if (!moreTokens() || !peekIdentifierToken(Keyword.CONTINUE.idt)) {\n return null;\n }\n\n Token token = nextToken();\n peekToken(TokenKind.SEMICOLON, true);\n return new ContinueStatement(toPos(token));\n }\n\n private BreakStatement tryEatBreakStatement() {\n if (!moreTokens() || !peekIdentifierToken(Keyword.BREAK.idt)) {\n return null;\n }\n\n Token token = nextToken();\n peekToken(TokenKind.SEMICOLON, true);\n return new BreakStatement(toPos(token));\n }\n\n private ReturnStatement tryEatReturnStatement() {\n if (!moreTokens() || !peekIdentifierToken(Keyword.RETURN.idt)) {\n return null;\n }\n Token token = nextToken();\n\n if (peekToken(TokenKind.SEMICOLON, true)) {\n return new ReturnStatement(toPos(token), null);\n }\n\n ExpressionNode node = eatExpression();\n peekToken(TokenKind.SEMICOLON, true);\n return new ReturnStatement(toPos(token.startpos, node.getEndPosition()), node);\n }\n\n private DirectiveStatement tryEatDirectiveStatement() {\n if (!moreTokens() || !peekIdentifierToken(Keyword.DIRECTIVE.idt)) {\n return null;\n }\n int startpos = nextToken().startpos;\n\n Identifier name = eatIdentifier();\n\n if (!peekIdentifierToken(Keyword.FROM.idt)) {\n raiseInternalException(name.getEndPosition() + 1, SpelMessage.KEYWORD_DIRECTIVE_NOT_EXPECTED, \"\");\n }\n nextToken();\n\n Identifier type = eatIdentifier();\n\n List literals = new ArrayList<>();\n for (; ; ) {\n Literal literal = maybeEatLiteral();\n if (literal == null) {\n break;\n }\n literals.add(literal);\n }\n if (directiveMap.containsKey(name.getName())) {\n raiseInternalException(startpos, SpelMessage.DIRECTIVE_EXISTS, name.getName(), type.getName());\n return null;\n }\n\n int endpos = eatToken(TokenKind.SEMICOLON).endpos;\n\n Library.DirectiveDef directiveDef = library.findDirectiveDef(type.getName(), name.getName(), literals);\n if (directiveDef == null) {\n raiseInternalException(startpos, SpelMessage.DIRECTIVE_NOT_FOUND, name.getName(), type.getName());\n }\n return new DirectiveStatement(toPos(startpos, endpos), type, name, directiveDef);\n }\n\n private VariableDeclareStatement tryEatVariableDeclareStatement() throws ParseException {\n if (!moreTokens() || !peekIdentifierToken(Keyword.LET.idt)) {\n return null;\n }\n\n Token let = eatKeyWord(Keyword.LET);\n Identifier identifier = eatIdentifier();\n ExpressionNode initializer = null;\n if (peekToken(TokenKind.ASSIGN, true)) {\n initializer = eatExpression();\n }\n Token token = eatToken(TokenKind.SEMICOLON);\n return new VariableDeclareStatement(toPos(let.startpos, token.endpos), identifier, initializer);\n }\n\n\n private ForeachStatement tryEatForeachStatement() throws ParseException {\n if (!peekIdentifierToken(Keyword.FOR.idt)) {\n return null;\n }\n Token forKW = eatKeyWord(Keyword.FOR);\n eatToken(TokenKind.LPAREN);\n eatKeyWord(Keyword.LET);\n\n Identifier key = eatIdentifier();\n eatToken(TokenKind.COMMA);\n Identifier val = eatIdentifier();\n\n eatKeyWord(Keyword.OF);\n\n ExpressionNode collection = eatExpression();\n eatToken(TokenKind.RPAREN);\n Block block = eatBlock(true);\n\n return new ForeachStatement(toPos(forKW.startpos, block.getEndPosition()), key, val, collection, block);\n }\n\n private IfStatement tryEatIfStatement() throws ParseException {\n if (!peekIdentifierToken(Keyword.IF.idt)) {\n return null;\n }\n\n Token ifKW = eatKeyWord(Keyword.IF);\n eatToken(TokenKind.LPAREN);\n ExpressionNode prediction = eatExpression();\n eatToken(TokenKind.RPAREN);\n Block trueBlock = eatBlock(true);\n int endPos = trueBlock.getEndPosition();\n Statement elseBlock = null;\n\n if (peekIdentifierToken(Keyword.ELSE.idt)) {\n eatToken(TokenKind.IDENTIFIER);\n if (peekIdentifierToken(Keyword.IF.idt)) { // else if\n //\n elseBlock = tryEatIfStatement();\n } else {\n elseBlock = eatBlock(true);\n }\n assert elseBlock != null;\n endPos = elseBlock.getEndPosition();\n }\n\n return new IfStatement(toPos(ifKW.startpos, endPos), prediction, trueBlock, elseBlock);\n }\n\n private Block eatBlock(boolean mustCurly) {\n\n Token s = mustCurly ? eatToken(TokenKind.LCURLY) : null;\n List statements = new ArrayList<>();\n while (moreTokens()) {\n if (s != null && peekToken(TokenKind.RCURLY)) {\n break;\n }\n if (peekToken(TokenKind.SEMICOLON, true)) {\n continue;\n }\n Statement e = eatStatement();\n if (e instanceof DirectiveStatement) {\n DirectiveStatement directiveStatement = (DirectiveStatement) e;\n directiveMap.put(directiveStatement.getName().getName(), directiveStatement);\n } else {\n statements.add(e);\n }\n }\n Token e = s != null ? eatToken(TokenKind.RCURLY) : null;\n int pos;\n if (e != null) {\n pos = toPos(s.startpos, e.endpos);\n } else if (!statements.isEmpty()) {\n pos = toPos(statements.get(0).getStartPosition(), statements.get(statements.size() - 1).getEndPosition());\n } else {\n raiseInternalException(0, SpelMessage.MORE_INPUT);\n // not hit\n return null;\n }\n\n return new Block(pos, statements);\n }\n\n private Identifier eatIdentifier() {\n Token token = eatToken(TokenKind.IDENTIFIER);\n if (tryMatchKeyWords(token.data) != null) {\n raiseInternalException(token.startpos, SpelMessage.KEYWORD_DIRECTIVE_NOT_EXPECTED, token.data);\n }\n return new Identifier(toPos(token), token.data);\n }\n\n //\texpression\n // : logicalOrExpression\n // ( (ASSIGN^ logicalOrExpression)\n //\t | (DEFAULT^ logicalOrExpression)\n //\t | (QMARK^ expression COLON! expression)\n // | (ELVIS^ expression))?;\n private ExpressionNode eatExpression() {\n ExpressionNode expr = eatLogicalOrExpression();\n if (moreTokens()) {\n Token t = peekToken();\n if (hasAssign && t.kind == TokenKind.ASSIGN) { // a=b\n nextToken();\n ExpressionNode assignedValue = eatLogicalOrExpression();\n if (expr instanceof MaybeLValue) {\n MaybeLValue lValue = (MaybeLValue) expr;\n lValue.markLValue();\n return new Assign(toPos(t), lValue, assignedValue);\n } else {\n throw new ParseException(\"需要 LValue:\" + expr.getPos());\n }\n }\n\n if (t.kind == TokenKind.QMARK) { // a?b:c\n if (expr == null) {\n expr = Literal.ofNull(toPos(t.startpos - 1, t.endpos - 1));\n }\n nextToken();\n ExpressionNode ifTrueExprValue = eatExpression();\n eatToken(TokenKind.COLON);\n ExpressionNode ifFalseExprValue = eatExpression();\n return new Ternary(toPos(t), expr, ifTrueExprValue, ifFalseExprValue);\n }\n }\n return expr;\n }\n\n //logicalOrExpression : logicalAndExpression (OR^ logicalAndExpression)*;\n private ExpressionNode eatLogicalOrExpression() {\n ExpressionNode expr = eatLogicalAndExpression();\n while (peekToken(TokenKind.SYMBOLIC_OR)) {\n Token t = nextToken(); //consume OR\n ExpressionNode rhExpr = eatLogicalAndExpression();\n checkOperands(t, expr, rhExpr);\n expr = new LogicRelationalExpression(toPos(t), expr, Operator.OR, rhExpr);\n }\n return expr;\n }\n\n // logicalAndExpression : relationalExpression (AND^ relationalExpression)*;\n private ExpressionNode eatLogicalAndExpression() {\n ExpressionNode expr = eatRelationalExpression();\n while (peekToken(TokenKind.SYMBOLIC_AND)) {\n Token t = nextToken();// consume 'AND'\n ExpressionNode rhExpr = eatRelationalExpression();\n checkOperands(t, expr, rhExpr);\n expr = new LogicRelationalExpression(toPos(t), expr, Operator.AND, rhExpr);\n }\n return expr;\n }\n\n // relationalExpression : sumExpression (relationalOperator^ sumExpression)?;\n private ExpressionNode eatRelationalExpression() {\n ExpressionNode expr = eatSumExpression();\n Token relationalOperatorToken = maybeEatRelationalOperator();\n if (relationalOperatorToken != null) {\n Token t = nextToken(); //consume relational operator token\n ExpressionNode rhExpr = eatSumExpression();\n checkOperands(t, expr, rhExpr);\n TokenKind tk = relationalOperatorToken.kind;\n\n if (relationalOperatorToken.isNumericRelationalOperator()) {\n return new BinaryOperator(toPos(t), expr, Operator.fromToken(t.kind), rhExpr);\n }\n\n if (tk == TokenKind.TILDE) {\n return new BinaryOperator(toPos(t), expr, Operator.MATCH, rhExpr);\n }\n Assert.isTrue(tk == TokenKind.IDENTIFIER);\n if (relationalOperatorToken.data.equals(Operator.IN.getPayload())) {\n return new BinaryOperator(toPos(t), expr, Operator.IN, rhExpr);\n }\n }\n return expr;\n }\n\n //sumExpression: productExpression ( (PLUS^ | MINUS^) productExpression)*;\n private ExpressionNode eatSumExpression() {\n ExpressionNode expr = eatProductExpression();\n while (peekToken(TokenKind.PLUS, TokenKind.MINUS)) {\n Token t = nextToken();//consume PLUS or MINUS\n ExpressionNode rhExpr = eatProductExpression();\n checkRightOperand(t, rhExpr);\n if (t.kind == TokenKind.PLUS || t.kind == TokenKind.MINUS) {\n expr = new BinaryOperator(toPos(t), expr, Operator.fromToken(t.kind), rhExpr);\n }\n }\n return expr;\n }\n\n // productExpression: powerExpr ((STAR^ | DIV^| MOD^) powerExpr)* ;\n private ExpressionNode eatProductExpression() {\n ExpressionNode expr = eatPowerIncDecExpression();\n while (peekToken(TokenKind.STAR, TokenKind.DIV, TokenKind.MOD)) {\n Token t = nextToken(); // consume STAR/DIV/MOD\n ExpressionNode rhExpr = eatPowerIncDecExpression();\n checkOperands(t, expr, rhExpr);\n expr = new BinaryOperator(toPos(t), expr, Operator.fromToken(t.kind), rhExpr);\n }\n return expr;\n }\n\n // powerExpr : unaryExpression (POWER^ unaryExpression)? (INC || DEC) ;\n private ExpressionNode eatPowerIncDecExpression() {\n return eatUnaryExpression();\n }\n\n // unaryExpression: (PLUS^ | MINUS^ | BANG^ | INC^ | DEC^) unaryExpression | primaryExpression ;\n private ExpressionNode eatUnaryExpression() {\n if (peekToken(TokenKind.PLUS, TokenKind.MINUS, TokenKind.NOT)) {\n Token t = nextToken();\n ExpressionNode expr = eatUnaryExpression();\n return new UnaryOperator(toPos(t), Operator.fromToken(t.kind), expr);\n }\n\n if (peekIdentifierToken(\"typeof\")) {\n Token t = nextToken();\n ExpressionNode expr = eatUnaryExpression();\n return new UnaryOperator(toPos(t), Operator.TYPEOF, expr);\n }\n return eatPrimaryExpression();\n }\n\n private FunctionCall maybeEatFuncCall(VariableReference prefix) {\n int tokenIdx = this.tokenStreamPointer;\n int dotSize = 0;\n StringBuilder sb = new StringBuilder(prefix.getName());\n while (peekToken(TokenKind.DOT, true)) {\n if (peekToken(TokenKind.IDENTIFIER)) {\n Token token = nextToken();\n sb.append('.').append(token.data);\n dotSize++;\n if (peekToken(TokenKind.LPAREN)) {\n ExpressionNode[] args = maybeEatMethodArgs();\n if (args != null) {\n String funcName = sb.toString();\n Library.Function func = library.findFunc(funcName);\n\n if (func == null && dotSize == 1 && directiveMap.containsKey(prefix.getName())) {\n DirectiveStatement directiveStatement = directiveMap.get(prefix.getName());\n func = directiveStatement.getDirectiveDef().findFunc(prefix.getName(), token.data);\n }\n\n if (func == null) {\n raiseInternalException(prefix.getStartPosition(), SpelMessage.FUNCTION_NOT_DEFINED, funcName);\n }\n return new FunctionCall(func, funcName, toPos(prefix.getStartPosition(), args.length > 0 ? args[args.length - 1].getEndPosition() + 1 : prefix.getStartPosition() + funcName.length() + 2), args);\n }\n }\n } else {\n break;\n }\n }\n\n this.tokenStreamPointer = tokenIdx;\n return null;\n }\n\n // primaryExpression : startNode (node)? -> ^(EXPRESSION startNode (node)?);\n private ExpressionNode eatPrimaryExpression() {\n ExpressionNode start = eatStartNode(); // always a start node\n\n if ((start instanceof VariableReference) && !((VariableReference) start).isRoot()) {\n FunctionCall functionCall = maybeEatFuncCall((VariableReference) start);\n if (functionCall != null) {\n start = functionCall;\n }\n }\n\n ExpressionNode current;\n while ((current = maybeEatNode(start)) != null) {\n start = current;\n }\n return start;\n }\n\n // node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+;\n private ExpressionNode maybeEatNode(ExpressionNode parent) {\n ExpressionNode expr;\n if (peekToken(TokenKind.DOT)) {\n expr = eatDottedNode(parent);\n } else {\n expr = maybeEatNonDottedNode(parent);\n }\n\n return expr;\n }\n\n // nonDottedNode: indexer;\n private ExpressionNode maybeEatNonDottedNode(ExpressionNode parent) {\n if (peekToken(TokenKind.LSQUARE)) {\n return maybeEatIndexer(parent);\n }\n return null;\n }\n\n private ConstantVal maybeConstant(Token prefix) {\n int tokenIdx = this.tokenStreamPointer;\n if (!peekToken(TokenKind.DOT, true)) {\n return null;\n }\n Token token = peekToken();\n if (token == null || token.kind != TokenKind.IDENTIFIER) {\n this.tokenStreamPointer = tokenIdx;\n return null;\n }\n\n String key = token.data;\n if (\"$\".equals(prefix.data)) {\n library.markRootProp(key);\n this.tokenStreamPointer = tokenIdx;\n return null;\n }\n nextToken();\n Library.Constant constant = library.findConstant(prefix.data, key);\n if (constant == null) {\n raiseInternalException(prefix.startpos, SpelMessage.CONSTANT_NOT_FIND, prefix.data, key);\n return null;\n }\n return new ConstantVal(toPos(prefix.startpos, token.endpos), prefix.data + \".\" + key, constant);\n }\n\n //dottedNode\n // : ((methodOrProperty\n //\t | functionOrVar\n // | projection\n // | selection\n // | firstSelection\n // | lastSelection\n // ))\n //\t;\n private ExpressionNode eatDottedNode(ExpressionNode parent) {\n ExpressionNode result;\n Token t = nextToken();// it was a '.' or a '?.'\n if ((result = maybeEatProperty(parent)) != null) {\n return result;\n }\n if (peekToken() == null) {\n // unexpectedly ran out of data\n raiseInternalException(t.startpos, SpelMessage.OOD);\n } else {\n raiseInternalException(t.startpos, SpelMessage.UNEXPECTED_DATA_AFTER_DOT, toString(peekToken()));\n }\n return null;\n }\n\n // functionOrVar\n // : (POUND ID LPAREN) => function\n // | var\n //\n // function : POUND id=ID methodArgs -> ^(FUNCTIONREF[$id] methodArgs);\n // var : POUND id=ID -> ^(VARIABLEREF[$id]);\n private ExpressionNode maybeEatFunctionOrVar() {\n Token t = eatToken(TokenKind.IDENTIFIER);\n ExpressionNode[] args = maybeEatMethodArgs();\n if (args != null) {\n Library.Function func = library.findFunc(t.data);\n if (func == null) {\n raiseInternalException(t.startpos, SpelMessage.FUNCTION_NOT_DEFINED, t.data);\n }\n return new FunctionCall(func, t.data, toPos(t.startpos, t.endpos), args);\n\n }\n if (t.data.charAt(0) == '$') {\n ConstantVal constantVal = maybeConstant(t);\n if (constantVal != null) {\n return constantVal;\n }\n }\n return new VariableReference(t.data, toPos(t.startpos, t.endpos));\n }\n\n // methodArgs : LPAREN! (argument (COMMA! argument)* (COMMA!)?)? RPAREN!;\n private ExpressionNode[] maybeEatMethodArgs() {\n if (!peekToken(TokenKind.LPAREN)) {\n return null;\n }\n List args = new ArrayList<>();\n consumeArguments(args);\n eatToken(TokenKind.RPAREN);\n return args.toArray(new ExpressionNode[args.size()]);\n }\n\n /**\n * Used for consuming arguments for either a method or a constructor call\n */\n private void consumeArguments(List accumulatedArguments) {\n int pos = peekToken().startpos;\n Token next = null;\n do {\n nextToken();// consume ( (first time through) or comma (subsequent times)\n Token t = peekToken();\n if (t == null) {\n raiseInternalException(pos, SpelMessage.RUN_OUT_OF_ARGUMENTS);\n }\n if (t.kind != TokenKind.RPAREN) {\n ExpressionNode e;\n if (t.kind == TokenKind.EXPAND) {\n nextToken();\n e = new ExpandArrArg(toPos(t), eatExpression());\n } else {\n e = eatExpression();\n }\n accumulatedArguments.add(e);\n }\n next = peekToken();\n } while (next != null && next.kind == TokenKind.COMMA);\n\n if (next == null) {\n raiseInternalException(pos, SpelMessage.RUN_OUT_OF_ARGUMENTS);\n }\n }\n\n //startNode\n // : parenExpr | literal\n //\t | type\n //\t | methodOrProperty\n //\t | functionOrVar\n //\t | projection\n //\t | selection\n //\t | firstSelection\n //\t | lastSelection\n //\t | indexer\n //\t | constructor\n private ExpressionNode eatStartNode() {\n ExpressionNode node;\n if ((node = maybeEatLiteral()) != null) {\n return node;\n } else if ((node = maybeEatInlineList()) != null || (node = maybeEatInlineObject()) != null) {\n return node;\n } else if ((node = maybeEatParenExpression()) != null || (node = maybeEatNullReference()) != null) {\n return node;\n }\n return maybeEatFunctionOrVar();\n }\n\n private InlineObject maybeEatInlineObject() {\n Token t = peekToken();\n if (!peekToken(TokenKind.LCURLY, true)) {\n return null;\n }\n InlineObject expr;\n Token closingCurly = peekToken();\n if (peekToken(TokenKind.RCURLY, true)) {\n // empty object '{}'\n expr = new InlineObject(toPos(t.startpos, closingCurly.endpos), EMPTY_STR_ARR, EMPTY_NODE_ARR);\n } else {\n Map map = new LinkedHashMap<>();\n do {\n Token k = peekToken();\n if (k == null) {\n raiseInternalException(t.startpos, SpelMessage.MISSING_INLINE_OBJECT_ELEMENT);\n }\n if (k.kind == TokenKind.EXPAND) {\n nextToken();\n ExpandArrArg expand = new ExpandArrArg(toPos(t), eatExpression());\n map.put(InlineObject.expandKey(), expand);\n } else {\n String key = null;\n if (k.kind == TokenKind.LITERAL_STRING) {\n nextToken();\n try {\n JsonNode node = JsonUtil.MAPPER.readTree(k.data);\n if (!node.isTextual()) {\n raiseInternalException(t.startpos, SpelMessage.NOT_SUPPORT_INLINE_OBJECT_KEY, k);\n }\n key = node.asText();\n } catch (ParseException e) {\n throw e;\n } catch (Exception e) {\n throw new ParseException(e.getMessage());\n }\n } else if (k.kind == TokenKind.IDENTIFIER) {\n key = k.data;\n nextToken();\n if (peekToken(TokenKind.COMMA) || peekToken(TokenKind.RCURLY)) {\n ExpressionNode old = map.put(key, new VariableReference(key, toPos(k)));\n if (old != null) {\n raiseInternalException(t.startpos, SpelMessage.INLINE_OBJECT_DUPLICATE_KEY, k);\n }\n continue;\n }\n } else if (k.kind == TokenKind.RCURLY) {\n break;\n } else {\n raiseInternalException(t.startpos, SpelMessage.NOT_SUPPORT_INLINE_OBJECT_KEY, k);\n }\n eatToken(TokenKind.COLON);\n ExpressionNode old = map.put(key, eatExpression());\n if (old != null) {\n raiseInternalException(t.startpos, SpelMessage.INLINE_OBJECT_DUPLICATE_KEY, k);\n }\n }\n } while (peekToken(TokenKind.COMMA, true));\n closingCurly = eatToken(TokenKind.RCURLY);\n\n Object[] keys = new Object[map.size()];\n keys = map.keySet().toArray(keys);\n ExpressionNode[] values = new ExpressionNode[map.size()];\n values = map.values().toArray(values);\n expr = new InlineObject(toPos(t.startpos, closingCurly.endpos), keys, values);\n }\n return expr;\n }\n\n private Literal maybeEatNullReference() {\n if (peekToken(TokenKind.IDENTIFIER)) {\n Token nullToken = peekToken();\n if (!nullToken.stringValue().equals(\"null\")) {\n return null;\n }\n nextToken();\n return Literal.ofNull(toPos(nullToken));\n }\n return null;\n }\n\n // list = LCURLY (element (COMMA element)*) RCURLY\n private InlineList maybeEatInlineList() {\n Token t = peekToken();\n if (!peekToken(TokenKind.LSQUARE, true)) {\n return null;\n }\n InlineList expr;\n Token closingCurly = peekToken();\n if (peekToken(TokenKind.RSQUARE, true)) {\n // empty list '[]'\n expr = new InlineList(toPos(t.startpos, closingCurly.endpos));\n } else {\n List listElements = new ArrayList<>();\n do {\n ExpressionNode e;\n Token ct = peekToken();\n if (ct == null) {\n // unexpectedly ran out of data\n raiseInternalException(t.startpos, SpelMessage.OOD);\n }\n if (ct.kind == TokenKind.EXPAND) {\n nextToken();\n e = new ExpandArrArg(toPos(ct), eatExpression());\n } else {\n e = eatExpression();\n }\n listElements.add(e);\n } while (peekToken(TokenKind.COMMA, true));\n\n closingCurly = eatToken(TokenKind.RSQUARE);\n expr = new InlineList(toPos(t.startpos, closingCurly.endpos), listElements.toArray(new ExpressionNode[listElements.size()]));\n }\n return expr;\n }\n\n private Indexer maybeEatIndexer(ExpressionNode parent) {\n Token t = peekToken();\n if (!peekToken(TokenKind.LSQUARE, true)) {\n return null;\n }\n ExpressionNode expr = eatExpression();\n eatToken(TokenKind.RSQUARE);\n return new Indexer(toPos(t), parent, expr);\n }\n\n private boolean isValidQualifiedId(Token node) {\n if (node == null || node.kind == TokenKind.LITERAL_STRING) {\n return false;\n }\n if (node.kind == TokenKind.DOT || node.kind == TokenKind.IDENTIFIER) {\n return true;\n }\n String value = node.stringValue();\n return StringUtils.hasLength(value) && VALID_QUALIFIED_ID_PATTERN.matcher(value).matches();\n }\n\n // This is complicated due to the support for dollars in identifiers. Dollars are normally separate tokens but\n // there we want to combine a series of identifiers and dollars into a single identifier\n private PropertyReference maybeEatProperty(ExpressionNode parent) {\n if (peekToken(TokenKind.IDENTIFIER)) {\n Token methodOrPropertyName = nextToken();\n // property\n return new PropertyReference(methodOrPropertyName.data, toPos(methodOrPropertyName), parent);\n }\n return null;\n }\n\n //\tliteral\n // : INTEGER_LITERAL\n //\t| boolLiteral\n //\t| STRING_LITERAL\n // | HEXADECIMAL_INTEGER_LITERAL\n // | REAL_LITERAL\n //\t| DQ_STRING_LITERAL\n //\t| NULL_LITERAL\n private Literal maybeEatLiteral() {\n Token t = peekToken();\n if (t == null) {\n return null;\n }\n Literal result;\n if (t.kind == TokenKind.LITERAL_INT) {\n result = (Literal.getIntLiteral(t.data, toPos(t), 10));\n } else if (t.kind == TokenKind.LITERAL_LONG) {\n result = (Literal.getLongLiteral(t.data, toPos(t), 10));\n } else if (t.kind == TokenKind.LITERAL_HEXINT) {\n result = (Literal.getIntLiteral(t.data, toPos(t), 16));\n } else if (t.kind == TokenKind.LITERAL_HEXLONG) {\n result = (Literal.getLongLiteral(t.data, toPos(t), 16));\n } else if (t.kind == TokenKind.LITERAL_REAL) {\n result = (Literal.getRealLiteral(t.data, toPos(t), false));\n } else if (t.kind == TokenKind.LITERAL_REAL_FLOAT) {\n result = (Literal.getRealLiteral(t.data, toPos(t), true));\n } else if (peekIdentifierToken(\"true\")) {\n result = (Literal.ofBoolean(toPos(t), true));\n } else if (peekIdentifierToken(\"false\")) {\n result = (Literal.ofBoolean(toPos(t), false));\n } else if (t.kind == TokenKind.LITERAL_STRING) {\n result = (Literal.ofString(toPos(t), t.data));\n } else {\n return null;\n }\n nextToken();\n return result;\n }\n\n //parenExpr : LPAREN! expression RPAREN!;\n private ExpressionNode maybeEatParenExpression() {\n if (peekToken(TokenKind.LPAREN)) {\n nextToken();\n ExpressionNode expr = eatExpression();\n eatToken(TokenKind.RPAREN);\n return expr;\n } else {\n return null;\n }\n }\n\n // relationalOperator\n // : EQUAL | NOT_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL | GREATER_THAN\n // | GREATER_THAN_OR_EQUAL | INSTANCEOF | BETWEEN | MATCHES\n private Token maybeEatRelationalOperator() {\n Token t = peekToken();\n if (t == null) {\n return null;\n }\n if (t.isNumericRelationalOperator()) {\n return t;\n }\n if (t.kind == TokenKind.TILDE) {\n return t;\n }\n if (t.kind == TokenKind.IDENTIFIER && Operator.IN.getPayload().equals(t.data)) {\n return t;\n }\n return null;\n }\n\n private Token eatToken(TokenKind expectedKind) {\n Token t = nextToken();\n if (t == null) {\n raiseInternalException(-1, SpelMessage.OOD);\n }\n if (t.kind != expectedKind) {\n raiseInternalException(t.startpos, SpelMessage.NOT_EXPECTED_TOKEN, expectedKind.toString().toLowerCase(), t.getKind().toString().toLowerCase());\n }\n return t;\n }\n\n private boolean peekToken(TokenKind desiredTokenKind) {\n return peekToken(desiredTokenKind, false);\n }\n\n private boolean peekToken(TokenKind desiredTokenKind, boolean consumeIfMatched) {\n if (!moreTokens()) {\n return false;\n }\n Token t = peekToken();\n if (t.kind == desiredTokenKind) {\n if (consumeIfMatched) {\n this.tokenStreamPointer++;\n }\n return true;\n }\n\n if (desiredTokenKind == TokenKind.IDENTIFIER) {\n // might be one of the textual forms of the operators (e.g. NE for != ) - in which case we can treat it as an identifier\n // The list is represented here: Tokenizer.alternativeOperatorNames and those ones are in order in the TokenKind enum\n if (t.kind.ordinal() >= TokenKind.DIV.ordinal() && t.kind.ordinal() <= TokenKind.NOT.ordinal() && t.data != null) {\n // if t.data were null, we'd know it wasn't the textual form, it was the symbol form\n return true;\n }\n }\n return false;\n }\n\n private boolean peekToken(TokenKind possible1, TokenKind possible2) {\n if (!moreTokens()) {\n return false;\n }\n Token t = peekToken();\n return (t.kind == possible1 || t.kind == possible2);\n }\n\n private boolean peekToken(TokenKind possible1, TokenKind possible2, TokenKind possible3) {\n if (!moreTokens()) {\n return false;\n }\n Token t = peekToken();\n return t.kind == possible1 || t.kind == possible2 || t.kind == possible3;\n }\n\n private boolean peekIdentifierToken(String identifierString) {\n if (!moreTokens()) {\n return false;\n }\n Token t = peekToken();\n return t.kind == TokenKind.IDENTIFIER && t.stringValue().equals(identifierString);\n }\n\n private Token eatKeyWord(Keyword keyword) {\n Token t = eatToken(TokenKind.IDENTIFIER);\n\n if (!t.stringValue().equals(keyword.idt)) {\n raiseInternalException(t.startpos, SpelMessage.KEYWORD_NOT_MATCH, keyword.idt, t.stringValue());\n }\n return t;\n }\n\n private boolean moreTokens() {\n return this.tokenStreamPointer < this.tokenStream.size();\n }\n\n private Token nextToken() {\n if (this.tokenStreamPointer >= this.tokenStreamLength) {\n return null;\n }\n return this.tokenStream.get(this.tokenStreamPointer++);\n }\n\n private Token peekToken() {\n if (this.tokenStreamPointer >= this.tokenStreamLength) {\n return null;\n }\n return this.tokenStream.get(this.tokenStreamPointer);\n }\n\n private void raiseInternalException(int pos, SpelMessage message, Object... inserts) {\n throw new ParseException((String) null, pos, message, inserts);\n }\n\n public String toString(Token t) {\n if (t.getKind().hasPayload()) {\n return t.stringValue();\n }\n return t.kind.toString().toLowerCase();\n }\n\n private void checkOperands(Token token, ExpressionNode left, ExpressionNode right) {\n checkLeftOperand(token, left);\n checkRightOperand(token, right);\n }\n\n private void checkLeftOperand(Token token, ExpressionNode operandExpression) {\n if (operandExpression == null) {\n raiseInternalException(token.startpos, SpelMessage.LEFT_OPERAND_PROBLEM);\n }\n }\n\n private void checkRightOperand(Token token, ExpressionNode operandExpression) {\n if (operandExpression == null) {\n raiseInternalException(token.startpos, SpelMessage.RIGHT_OPERAND_PROBLEM);\n }\n }\n\n /**\n * Compress the start and end of a token into a single int.\n */\n private int toPos(Token t) {\n return (t.startpos << 16) + t.endpos;\n }\n\n private int toPos(int start, int end) {\n return (start << 16) + end;\n }\n\n}", "answers": [" return compile(script, StdLibrary.getDefInstance(), false);"], "length": 3819, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "7d6787e8-19a1-4338-8ef0-b03c0cce26f3", "reasoning": "The interface defines a static compile method that delegates to compile(script, StdLibrary.getDefInstance()). The next method, compileWithoutAssign, should similarly delegate but indicate that assignment statements are not allowed. The Parser constructor accepts a boolean hasAssign flag, so the implementation likely calls a three‑argument compile overload with false. Therefore the next line is the return statement invoking compile with the library instance and false.", "reasoning_model_answer": "return compile(script, StdLibrary.getDefInstance(), false);", "assistant_with_reasoning": "\nThe interface defines a static compile method that delegates to compile(script, StdLibrary.getDefInstance()). The next method, compileWithoutAssign, should similarly delegate but indicate that assignment statements are not allowed. The Parser constructor accepts a boolean hasAssign flag, so the implementation likely calls a three‑argument compile overload with false. Therefore the next line is the return statement invoking compile with the library instance and false.\n\nreturn compile(script, StdLibrary.getDefInstance(), false);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.357, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36334, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return compile(script, StdLibrary.getDefInstance(), false);", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.ObjectStreamException;\nimport java.io.Serializable;\nimport java.util.function.Function;\nimport edu.uky.cs.nil.sabre.Settings;\nimport edu.uky.cs.nil.sabre.State;\nimport edu.uky.cs.nil.sabre.Utilities;\nimport edu.uky.cs.nil.sabre.io.DefaultParser;\nimport edu.uky.cs.nil.sabre.util.ImmutableSet;\nimport edu.uky.cs.nil.sabre.util.Unique;", "context": "src/edu/uky/cs/nil/sabre/logic/Quantified.java\npackage edu.uky.cs.nil.sabre.logic;\n\n\n\n/**\n * A quantified expression is a {@link Proposition proposition} which states\n * that a given {@link #argument} proposition holds for some number of possible\n * values that can be substituted for a {@link #variable}.\n * \n * @author Stephen G. Ware\n */\npublic class Quantified implements Proposition {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\n\t/**\n\t * A quantifier is a singleton object that specifies for how many possible\n\t * values a {@link Quantifier quantifier's} proposition must hold.\n\t * \n\t * @author Stephen G. Ware\n\t */\n\tpublic static abstract class Quantifier implements Comparable, Serializable, Unique {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = Quantified.serialVersionUID;\n\t\t\n\t\tprivate Quantifier() {}\n\t\t\n\t\t@Override\n\t\tpublic int compareTo(Quantifier other) {\n\t\t\treturn hashCode() - other.hashCode();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the quantifier this quantifier would become when {@link\n\t\t * Quantifier#negate() negating a quantified expression}.\n\t\t * \n\t\t * @return the negated quantifier\n\t\t */\n\t\tpublic abstract Quantifier negate();\n\t\t\n\t\t/**\n\t\t * Returns {@link Expression a logical expression} that is logically\n\t\t * equivalent to a {@link Quantified quantified expression} with this\n\t\t * quantifier but which does not contain the quantifier or variable.\n\t\t * \n\t\t * @param variable the quantified variable\n\t\t * @param argument an expression in which the variable appears\n\t\t * @return a logical expression equivalent to a quantified expression\n\t\t * where the variable is quantified with this quantifier but in which\n\t\t * this quantifier and variable do not appear\n\t\t */\n\t\tpublic Expression expand(Variable variable, Expression argument) {\n\t\t\tImmutableSet values = variable.type.universe.getValues(variable.type);\n\t\t\tExpression[] arguments = new Expression[values.size()];\n\t\t\tfor(int i=0; i expand(Expression[] arguments) {\n\t\t\treturn new Conjunction<>(arguments);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn UNIVERSAL;\n\t\t}\n\t};\n\t\n\t/**\n\t * The existential {@link Quantifier quantifier} specifies that a\n\t * quantified expression must hold for at least one possible value its\n\t * variable can have.\n\t */\n\tpublic static final Quantifier EXISTENTIAL = new Quantifier() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\nsrc/edu/uky/cs/nil/sabre/Utilities.java\npublic class Utilities {\n\t\n\t/**\n\t * A default {@link edu.uky.cs.nil.sabre.io.Printer printer} generally used\n\t * for converting objects to strings\n\t */\n\tpublic static final DefaultPrinter DEFAULT_PRINTER = new DefaultPrinter();\n\t\n\t/**\n\t * Checks whether two objects are {@link Object#equals(Object) equal to}\n\t * one another without causing a {@link NullPointerException} if one or\n\t * both of them is null.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return true if they are equal or both null, false otherwise\n\t */\n\tpublic static final boolean equals(Object o1, Object o2) {\n\t\tif(o1 == null)\n\t\t\treturn o2 == null;\n\t\telse if(o2 == null)\n\t\t\treturn false;\n\t\telse\n\t\t\treturn o1.equals(o2);\n\t}\n\t\n\t/**\n\t * Returns an object's {@link Object#hashCode() hash code} or 0 if the\n\t * object is null.\n\t * \n\t * @param object the object or null\n\t * @return the object's hash code or 0 if the object was null\n\t */\n\tpublic static final int hashCode(Object object) {\n\t\tif(object == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn object.hashCode();\n\t}\n\t\n\t/**\n\t * Combines two {@link #hashCode(Object) hash code} values.\n\t * \n\t * @param hc1 the first hash code\n\t * @param hc2 the second hash code\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc1, int hc2) {\n\t\treturn hc1 * 31 + hc2;\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of an object.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1) {\n\t\treturn hashCode(hc, hashCode(o1));\n\t}\n\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of two objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2) {\n\t\treturn hashCode(hashCode(o1), hashCode(o2));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of two objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2) {\n\t\treturn hashCode(hashCode(hc, o1), hashCode(o2));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of three\n\t * objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3) {\n\t\treturn hashCode(hashCode(o1, o2), hashCode(o3));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of three objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3) {\n\t\treturn hashCode(hashCode(hc, o1, o2), hashCode(o3));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of four objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4) {\n\t\treturn hashCode(hashCode(o1, o2, o3), hashCode(o4));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of four objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3, Object o4) {\n\t\treturn hashCode(hashCode(hc, o1, o2, o3), hashCode(o4));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of five objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4, Object o5) {\n\t\treturn hashCode(hashCode(o1, o2, o3, o4), hashCode(o5));\n\t}\n\t\n\t/**\n\t * Combines a {@link #hashCode(Object) hash code} value with the {@link\n\t * #hashCode(Object) hash code} of five objects.\n\t * \n\t * @param hc the hash code value\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(int hc, Object o1, Object o2, Object o3, Object o4, Object o5) {\n\t\treturn hashCode(hashCode(hc, o1, o2, o3, o4), hashCode(o5));\n\t}\n\t\n\t/**\n\t * Combines the {@link #hashCode(Object) hash code} values of six objects.\n\t * \n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @param o3 the third object\n\t * @param o4 the fourth object\n\t * @param o5 the fifth object\n\t * @param o6 the sixth object\n\t * @return the combined hash code\n\t */\n\tpublic static final int hashCode(Object o1, Object o2, Object o3, Object o4, Object o5, Object o6) {\n\t\treturn hashCode(hashCode(o1, o2, o3, o4, o5), hashCode(o6));\n\t}\n\t\n\t/**\n\t * Rounds a {@code double} up to the nearest whole number.\n\t * \n\t * @param value the value to round up\n\t * @return the nearest whole number that is greater than or equal to the\n\t * value\n\t */\n\tpublic static final double roundUp(double value) {\n\t\treturn new BigDecimal(value).setScale(0, RoundingMode.UP).doubleValue();\n\t}\n\t\n\t/**\n\t * Compares a pair of {@link Comparable comparable} objects.\n\t * \n\t * @param the type of the objects\n\t * @param o1 the first object\n\t * @param o2 the second object\n\t * @return a negative integer, zero, or a positive integer as the first\n\t * object is less than, equal to, or greater than the second object\n\t */\n\tpublic static final > int compare(C1 o1, C1 o2) {\n\t\treturn o1.compareTo(o2);\n\t}\n\t\n\t/**\n\t * Compares two pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is\n\t * not 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4) {\n\t\tint comparison = compare(o1, o2);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o3, o4);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares three pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is not\n\t * 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param the type of the third pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @param o5 the first object in the third pair\n\t * @param o6 the second object in the third pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable, C3 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4, C3 o5, C3 o6) {\n\t\tint comparison = compare(o1, o2, o3, o4);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o5, o6);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares four pairs of {@link Comparable comparable} objects. The first\n\t * pair (that is, the first two arguments) is compared. If the result is\n\t * not 0, it is returned, otherwise the second pair (that is, the third and\n\t * fourth arguments) is compared, and so on.\n\t * \n\t * @param the type of the first pair of objects\n\t * @param the type of the second pair of objects\n\t * @param the type of the third pair of objects\n\t * @param the type of the fourth pair of objects\n\t * @param o1 the first object in the first pair\n\t * @param o2 the second object in the first pair\n\t * @param o3 the first object in the second pair\n\t * @param o4 the second object in the second pair\n\t * @param o5 the first object in the third pair\n\t * @param o6 the second object in the third pair\n\t * @param o7 the first object in the fourth pair\n\t * @param o8 the second object in the fourth pair\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * pairs are less than, equal to, or greater than the later pairs\n\t */\n\tpublic static final , C2 extends Comparable, C3 extends Comparable, C4 extends Comparable> int compare(C1 o1, C1 o2, C2 o3, C2 o4, C3 o5, C3 o6, C4 o7, C4 o8) {\n\t\tint comparison = compare(o1, o2, o3, o4, o5, o6);\n\t\tif(comparison == 0)\n\t\t\tcomparison = compare(o7, o8);\n\t\treturn comparison;\n\t}\n\t\n\t/**\n\t * Compares two {@link ImmutableArray arrays} of {@link Logical logical}\n\t * objects. The first elements of both arrays are compared. If the result\n\t * is not 0, it is returned, otherwise the second elements of both arrays\n\t * are compared, and so on.\n\t * \n\t * @param array1 the first array\n\t * @param array2 the second array\n\t * @return a negative integer, zero, or a positive integer as the earlier\n\t * elements are less than, equal to, or greater than the later elements\n\t */\n\tpublic static final int compare(ImmutableArray array1, ImmutableArray array2) {\n\t\tint comparison = 0;\n\t\tint size = Math.min(array1.size(), array2.size());\n\t\tfor(int i=0; i array2.size())\n\t\t\t\treturn 1;\n\t\t\telse if(array2.size() > array1.size())\n\t\t\t\treturn -1;\n\t\t}\n\t\treturn comparison;\n\t}\n\n\t/**\n\t * Iterates through all elements of an {@link Iterable iterable} and places\n\t * them into an array of a given type.\n\t * \n\t * @param the component type of the array\n\t * @param iterable the iterable\n\t * @param type the class of the component type of the array\n\t * @return an array containing all the elements in the iterable\n\t */\n\tpublic static final T[] toArray(Iterable iterable, Class type) {\n\t\treturn toArray(iterable.iterator(), 0, type);\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tprivate static final T[] toArray(Iterator iterator, int index, Class type) {\n\t\tif(iterator.hasNext()) {\n\t\t\tT element = iterator.next();\n\t\t\tT[] array = toArray(iterator, index + 1, type);\n\t\t\tarray[index] = element;\n\t\t\treturn array;\n\t\t}\n\t\telse\n\t\t\treturn (T[]) Array.newInstance(type, index);\n\t}\n\t\n\t/**\n\t * Iterates through all elements of an {@link Iterable iterable} and places\n\t * into a {@link ImmutableSet set} only those items which are of a given\n\t * type.\n\t * \n\t * @param the type of elements to collect\n\t * @param type the class object of the type\n\t * @param iterable the iterable to iterate through\n\t * @return a set of elements from the iterable of the given type\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static final ImmutableSet collect(Class type, Iterable iterable) {\n\t\tLinkedHashSet set = new LinkedHashSet<>();\n\t\tfor(Object element : iterable)\n\t\t\tif(type.isAssignableFrom(element.getClass()))\n\t\t\t\tset.add((T) element);\n\t\treturn new ImmutableSet<>(set);\n\t}\n\t\n\t/**\n\t * Wrap a string in parentheses, unless it is already so wrapped.\n\t * \n\t * @param string the second\n\t * @return the string, wrapped in parentheses\n\t */\n\tpublic static final String wrap(String string) {\n\t\tif(string.startsWith(\"(\") && string.endsWith(\")\"))\n\t\t\treturn string;\n\t\telse\n\t\t\treturn \"(\" + string + \")\";\n\t}\n\t\n\t/**\n\t * Converts a number of milliseconds into a short string representation\n\t * that gives the numbers of days, hours, minutes, seconds, and\n\t * milliseconds. For example, {@code \"2d1h3m45s20ms\"} represents two days,\n\t * 1 hour, 3 minutes, fourty-five seconds, and twenty milliseconds.\n\t * \n\t * @param ms the number of milliseconds\n\t * @return a string representation of that amount of time\n\t */\n\tpublic static final String time(long ms) {\n\t\tlong days = TimeUnit.MILLISECONDS.toDays(ms);\n\t\tms -= TimeUnit.DAYS.toMillis(days);\n\t\tlong hours = TimeUnit.MILLISECONDS.toHours(ms);\n\t\tms -= TimeUnit.HOURS.toMillis(hours);\n\t\tlong minutes = TimeUnit.MILLISECONDS.toMinutes(ms);\n\t\tms -= TimeUnit.MINUTES.toMillis(minutes);\n\t\tlong seconds = TimeUnit.MILLISECONDS.toSeconds(ms);\n\t\tms -= TimeUnit.SECONDS.toMillis(seconds);\n\t\tString string = \"\";\n\t\tif(days > 0)\n\t\t\tstring += days + \"d\";\n\t\tif(hours > 0)\n\t\t\tstring += hours + \"h\";\n\t\tif(minutes > 0)\n\t\t\tstring += minutes + \"m\";\n\t\tif(seconds > 0)\n\t\t\tstring += seconds + \"s\";\n\t\tif(ms > 0)\n\t\t\tstring += ms + \"ms\";\n\t\tif(string.isEmpty())\n\t\t\treturn \"0ms\";\n\t\treturn string;\n\t}\n}", "answers": ["\t\t\treturn DefaultParser.EXISTENTIAL_QUANTIFICATION_KEYWORD;"], "length": 2753, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "f912ac1a-2f0c-4a5c-a140-0b0f87314330", "reasoning": "The code is defining the existential Quantifier anonymous subclass. After overriding hashCode, the next method is toString, which should return the keyword for existential quantification, mirroring the universal quantifier's toString implementation that returns DefaultParser.UNIVERSAL_QUANTIFICATION_KEYWORD. Therefore the next line should return the corresponding constant for existential quantification.", "reasoning_model_answer": "return DefaultParser.EXISTENTIAL_QUANTIFICATION_KEYWORD;", "assistant_with_reasoning": "\nThe code is defining the existential Quantifier anonymous subclass. After overriding hashCode, the next method is toString, which should return the keyword for existential quantification, mirroring the universal quantifier's toString implementation that returns DefaultParser.UNIVERSAL_QUANTIFICATION_KEYWORD. Therefore the next line should return the corresponding constant for existential quantification.\n\nreturn DefaultParser.EXISTENTIAL_QUANTIFICATION_KEYWORD;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.694, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 18364, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return DefaultParser.EXISTENTIAL_QUANTIFICATION_KEYWORD;", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import unittest\nfrom reinvent.chemistry import Conversions\nfrom reinvent.chemistry.library_design import (\n FragmentReactionSliceEnumerator,\n BondMaker,\n AttachmentPoints,\n)\nfrom reinvent.chemistry.library_design.dtos import FilteringConditionDTO\nfrom reinvent.chemistry.library_design.enums import MolecularDescriptorsEnum\nfrom reinvent.chemistry.library_design.fragment_reactions import FragmentReactions\nfrom tests.chemistry.library_design.fixtures import FRAGMENT_REACTION_SUZUKI, FRAGMENT_REACTIONS\nfrom tests.chemistry.fixtures.test_data import CELECOXIB", "context": "tests/chemistry/library_design/test_fragment_reactions_slice_enumerator.py\n\n scaffold_conditions = []\n decoration_conditions = []\n self._slice_enumerator = FragmentReactionSliceEnumerator(\n self._suzuki_reaction_dto_list, scaffold_conditions, decoration_conditions\n )\n\n def test_enumeration_slcing_1(self):\n result = self._slice_enumerator.enumerate(self.suzuki_positive_molecule, 1)\n\n self.assertEqual(2, len(result))\n\n def test_enumeration_slicing_2(self):\n result = self._slice_enumerator.enumerate(self.suzuki_positive_molecule, 4)\n\n self.assertEqual(2, len(result))\n\n complete_molecules = []\n for sliced in result:\n values = [\n self.chemistry.mol_to_smiles(smi) for num, smi in sorted(sliced.decorations.items())\n ]\n decorations = \"|\".join(values)\n labeled_scaffold = self._attachment_points.add_attachment_point_numbers(sliced.scaffold)\n molecule = self._bond_maker.join_scaffolds_and_decorations(\n labeled_scaffold, decorations\n )\n complete_smile = self.chemistry.mol_to_smiles(molecule)\n complete_molecules.append(complete_smile)\n self.assertEqual(\n self.chemistry.mol_to_smiles(self.suzuki_positive_molecule),\n list(set(complete_molecules))[0],\n )\n\n\nclass TestMultipleFragmentReactionsSliceEnumerator(unittest.TestCase):\n def setUp(self):\n self._bond_maker = BondMaker()\n self._attachment_points = AttachmentPoints()\n self.chemistry = Conversions()\n self.reactions = FragmentReactions()\n self._fragment_reactions = self.reactions.create_reactions_from_smirks(FRAGMENT_REACTIONS)\n self.positive_smile = CELECOXIB\n\n self.positive_molecule = self.chemistry.smile_to_mol(self.positive_smile)\n\n scaffold_conditions = []\n decoartion_conditions = []\n self._slice_enumerator = FragmentReactionSliceEnumerator(\n self._fragment_reactions, scaffold_conditions, decoartion_conditions\n )\n\n def test_enumeration_slicing_1(self):\n result = self._slice_enumerator.enumerate(self.positive_molecule, 1)\n\n complete_molecules = []\n for sliced in result:\n values = [\n self.chemistry.mol_to_smiles(smi) for num, smi in sorted(sliced.decorations.items())\n ]\n decorations = \"|\".join(values)\n labeled_scaffold = self._attachment_points.add_attachment_point_numbers(sliced.scaffold)\n molecule = self._bond_maker.join_scaffolds_and_decorations(\n labeled_scaffold, decorations\n )\n complete_smile = self.chemistry.mol_to_smiles(molecule)\n complete_molecules.append(complete_smile)\n reference = self.chemistry.mol_to_smiles(self.chemistry.smile_to_mol(self.positive_smile))\n self.assertEqual(reference, list(set(complete_molecules))[0])\n\n self.assertEqual(6, len(result))\n\n def test_enumeration_slicing_2(self):\n result = self._slice_enumerator.enumerate(self.positive_molecule, 2)\n self.assertEqual(12, len(result))\n\n def test_enumeration_slicing_3(self):\n result = self._slice_enumerator.enumerate(self.positive_molecule, 3)\n\n complete_molecules = []\n for sliced in result:\n values = [self.chemistry.mol_to_smiles(smi) for num, smi in sliced.decorations.items()]\n decorations = \"|\".join(values)\n labeled_scaffold = self._attachment_points.add_attachment_point_numbers(sliced.scaffold)\n molecule = self._bond_maker.join_scaffolds_and_decorations(\n labeled_scaffold, decorations\n )\n complete_smile = self.chemistry.mol_to_smiles(molecule)\n complete_molecules.append(complete_smile)\n reference = self.chemistry.mol_to_smiles(self.chemistry.smile_to_mol(self.positive_smile))\n self.assertEqual(reference, list(set(complete_molecules))[0])\n self.assertEqual(1, len(list(set(complete_molecules))))\n self.assertEqual(12, len(result))\n\n\nclass TestReactionsSliceEnumeratorWithFilters(unittest.TestCase):\n def setUp(self):\n self.chemistry = Conversions()\n self.reactions = FragmentReactions()\n self._suzuki_reactions = self.reactions.create_reactions_from_smirks(\n FRAGMENT_REACTION_SUZUKI\n )\n self.positive_smile = CELECOXIB\n\n self.positive_molecule = self.chemistry.smile_to_mol(self.positive_smile)\n descriptors_enum = MolecularDescriptorsEnum()\n\n scaffold_condition_1 = FilteringConditionDTO(descriptors_enum.RING_COUNT, min=1)\n scaffold_condition_2 = FilteringConditionDTO(descriptors_enum.MOLECULAR_WEIGHT, max=600)\n decoartion_condition_1 = FilteringConditionDTO(\n descriptors_enum.HYDROGEN_BOND_ACCEPTORS, max=3\n )\n decoartion_condition_2 = FilteringConditionDTO(descriptors_enum.HYDROGEN_BOND_DONORS, max=3)\n scaffold_conditions = [scaffold_condition_1, scaffold_condition_2]\n decoartion_conditions = [decoartion_condition_1, decoartion_condition_2]\n self._slice_enumerator = FragmentReactionSliceEnumerator(\n self._suzuki_reactions, scaffold_conditions, decoartion_conditions\n )\n\n def test_enumeration_slicing_1(self):\n\n\nreinvent/chemistry/library_design/fragment_reactions.py\nclass FragmentReactions:\n def __init__(self):\n self._conversions = Conversions()\n self._tokens = TransformationTokens()\n self._bond_mapper = BondMapper()\n\n def create_reactions_from_smarts(self, smarts: List[str]) -> List[ChemicalReaction]:\n reactions = [AllChem.ReactionFromSmarts(smirks) for smirks in smarts]\n return reactions\n\n def create_reaction_from_smirk(self, smirks: str) -> ReactionDTO:\n reaction = ReactionDTO(smirks, AllChem.ReactionFromSmarts(smirks))\n return reaction\n\n def create_reactions_from_smirks(self, smirks: List[str]) -> List[ReactionDTO]:\n reactions = [self.create_reaction_from_smirk(smirk) for smirk in smirks]\n return reactions\n\n def slice_molecule_to_fragments(\n self, molecule: Mol, reaction_dtos: List[ReactionDTO]\n ) -> List[Tuple[Mol]]:\n \"\"\"\n This method applies a list of chemical reactions on a molecule and\n decomposes the input molecule to complementary fragments.\n :param molecule:\n :param reaction_dtos:\n :return: Different slicing combinations are returned.\n \"\"\"\n list_of_outcomes = self.apply_reactions_on_molecule(molecule, reaction_dtos)\n all_outcomes = []\n\n for outcome in list_of_outcomes:\n all_outcomes.extend(outcome.reaction_outcomes)\n # TODO: the overall data processing is extremely slow. consider reducing redundancy here.\n return all_outcomes\n\n def apply_reactions_on_molecule(\n self, molecule: Mol, reaction_dtos: List[ReactionDTO]\n ) -> List[ReactionOutcomeDTO]:\n \"\"\"Build list of possible splits of a molecule given multiple reactions.\"\"\"\n list_of_outcomes = []\n for reaction_dto in reaction_dtos:\n outcome_dto = self.apply_reaction_on_molecule(molecule, reaction_dto)\n purged_outcome_dto = self._filter_pairs_with_no_ring_count_change(outcome_dto)\n list_of_outcomes.append(purged_outcome_dto)\n return list_of_outcomes\n\n def apply_reaction_on_molecule(\n self, molecule: Mol, reaction_dto: ReactionDTO\n ) -> ReactionOutcomeDTO:\n \"\"\"Build list of possible splits of a molecule given a single reaction.\"\"\"\n molecule = self._conversions.copy_mol(molecule)\n outcomes = reaction_dto.chemical_reaction.RunReactant(molecule, 0)\n outcome_dto = ReactionOutcomeDTO(reaction_dto.reaction_smarts, list(outcomes), molecule)\n return outcome_dto\n\n def _filter_pairs_with_no_ring_count_change(\n self, outcome_dto: ReactionOutcomeDTO\n ) -> ReactionOutcomeDTO:\n molecule_rings = RingCount(outcome_dto.targeted_molecule)\n acceptable_pairs = []\n for pair in outcome_dto.reaction_outcomes:\n if not self._detect_ring_break(molecule_rings, pair) and len(pair) == 2:\n acceptable_pairs.append(pair)\n outcome_dto.reaction_outcomes = acceptable_pairs\n return outcome_dto\n\n def _detect_ring_break(self, molecule_ring_count: int, pair: Tuple[Mol]) -> bool:\n reagent_rings = 0\n for reagent in pair:\n reagent_smiles = self._conversions.mol_to_smiles(reagent)\n reagent_mol = self._conversions.smile_to_mol(reagent_smiles)\n try:\n reagent_rings = reagent_rings + RingCount(reagent_mol)\n except:\n return True\n return molecule_ring_count != reagent_rings\n\ntests/chemistry/fixtures/test_data.py\nCELECOXIB = 'O=S(=O)(c3ccc(n1nc(cc1c2ccc(cc2)C)C(F)(F)F)cc3)N'\n\nreinvent/chemistry/library_design/attachment_points.py\nclass AttachmentPoints:\n def __init__(self):\n self._conversions = Conversions()\n self._tokens = TransformationTokens()\n\n def add_attachment_point_numbers(self, mol_or_smi, canonicalize=True):\n \"\"\"\n Adds the numbers for the attachment points throughout the molecule.\n :param mol_or_smi: SMILES string to convert.\n :param canonicalize: Canonicalize the SMILES so that the attachment points are always in the same order.\n :return : A converted SMILES string.\n \"\"\"\n if isinstance(mol_or_smi, str):\n smi = mol_or_smi\n if canonicalize:\n smi = self._conversions.mol_to_smiles(self._conversions.smile_to_mol(mol_or_smi))\n # only add numbers ordered by the SMILES ordering\n num = -1\n\n def _ap_callback(_):\n nonlocal num\n num += 1\n return \"[{}:{}]\".format(self._tokens.ATTACHMENT_POINT_TOKEN, num)\n\n return re.sub(self._tokens.ATTACHMENT_POINT_REGEXP, _ap_callback, smi)\n else:\n mol = mol_or_smi\n if canonicalize:\n mol = self._conversions.smile_to_mol(self._conversions.mol_to_smiles(mol))\n idx = 0\n for atom in mol.GetAtoms():\n if atom.GetSymbol() == self._tokens.ATTACHMENT_POINT_TOKEN:\n atom.SetProp(\"molAtomMapNumber\", str(idx))\n idx += 1\n return self._conversions.mol_to_smiles(mol)\n\n def get_attachment_points(self, smile: str) -> List:\n \"\"\"\n Gets all attachment points from SMILES string.\n :param smile: A SMILES string\n :return : A list with the numbers ordered by appearance.\n \"\"\"\n return [\n int(match.group(1))\n for match in re.finditer(self._tokens.ATTACHMENT_POINT_NUM_REGEXP, smile)\n ]\n\n def get_attachment_points_for_molecule(self, molecule: Mol) -> List:\n \"\"\"\n Gets all attachment points from RDKit Mol.\n :param molecule: A Mol object.\n :return : A list with the numbers ordered by appearance.\n \"\"\"\n if isinstance(molecule, Mol):\n return [\n int(atom.GetProp(\"molAtomMapNumber\"))\n for atom in molecule.GetAtoms()\n if atom.GetSymbol() == self._tokens.ATTACHMENT_POINT_TOKEN\n and atom.HasProp(\"molAtomMapNumber\")\n ]\n\n def add_first_attachment_point_number(self, smi, num):\n \"\"\"\n Changes/adds a number to the first attachment point.\n :param smi: SMILES string with the molecule.\n :param num: Number to add.\n :return: A SMILES string with the number added.\n \"\"\"\n return re.sub(\n self._tokens.ATTACHMENT_POINT_REGEXP,\n \"[{}:{}]\".format(self._tokens.ATTACHMENT_POINT_TOKEN, num),\n smi,\n count=1,\n )\n\n def remove_attachment_point_numbers(self, smile: str) -> str:\n \"\"\"\n Removes the numbers for the attachment points throughout the molecule.\n :param smile: SMILES string.\n :return : A converted SMILES string.\n \"\"\"\n result = re.sub(\n self._tokens.ATTACHMENT_POINT_NUM_REGEXP,\n \"[{}]\".format(self._tokens.ATTACHMENT_POINT_TOKEN),\n smile,\n )\n return result\n\n def remove_attachment_point_numbers_from_mol(self, molecule: Mol) -> Mol:\n \"\"\"\n Removes the numbers for the attachment points throughout the molecule.\n :param molecule: RDKit molecule.\n :return : A molecule.\n \"\"\"\n if isinstance(molecule, Mol):\n for atom in molecule.GetAtoms():\n atom.ClearProp(\"molAtomMapNumber\")\n return molecule\n\n def add_brackets_to_attachment_points(self, scaffold: str):\n \"\"\"\n Adds brackets to the attachment points (if they don't have them).\n :param scaffold: SMILES string.\n :return: A SMILES string with attachments in brackets.\n \"\"\"\n return re.sub(\n self._tokens.ATTACHMENT_POINT_NO_BRACKETS_REGEXP,\n \"[{}]\".format(self._tokens.ATTACHMENT_POINT_TOKEN),\n scaffold,\n )\n\nreinvent/chemistry/conversions.py\nclass Conversions:\n @staticmethod\n def smiles_to_mols_and_indices(query_smiles: List[str]) -> Tuple[List[Mol], List[int]]:\n mols = [MolFromSmiles(smile) for smile in query_smiles]\n valid_mask = [mol is not None for mol in mols]\n valid_idxs = [idx for idx, is_valid in enumerate(valid_mask) if is_valid]\n valid_mols = [mols[idx] for idx in valid_idxs]\n return valid_mols, valid_idxs\n\n @staticmethod\n def mols_to_fingerprints(\n molecules: List[Mol], radius: int = 3, use_counts: bool = True, use_features: bool = True\n ) -> List[UIntSparseIntVect]:\n fingerprints = [\n AllChem.GetMorganFingerprint(\n mol, radius, useCounts=use_counts, useFeatures=use_features\n )\n for mol in molecules\n ]\n return fingerprints\n\n @staticmethod\n def smiles_to_mols(query_smiles: List[str]) -> List[Mol]:\n mols = [MolFromSmiles(smile) for smile in query_smiles]\n valid_mask = [mol is not None for mol in mols]\n valid_idxs = [idx for idx, is_valid in enumerate(valid_mask) if is_valid]\n valid_mols = [mols[idx] for idx in valid_idxs]\n return valid_mols\n\n def smiles_to_fingerprints(\n self, query_smiles: List[str], radius=3, use_counts=True, use_features=True\n ) -> List[UIntSparseIntVect]:\n mols = self.smiles_to_mols(query_smiles)\n fingerprints = self.mols_to_fingerprints(\n mols, radius=radius, use_counts=use_counts, use_features=use_features\n )\n return fingerprints\n\n def smile_to_mol(self, smile: str) -> Mol:\n \"\"\"\n Creates a Mol object from a SMILES string.\n :param smile: SMILES string.\n :return: A Mol object or None if it's not valid.\n \"\"\"\n if smile:\n return MolFromSmiles(smile)\n\n def mols_to_smiles(\n self, molecules: List[Mol], isomericSmiles=False, canonical=True\n ) -> List[str]:\n \"\"\"This method assumes that all molecules are valid.\"\"\"\n valid_smiles = [\n MolToSmiles(mol, isomericSmiles=isomericSmiles, canonical=canonical)\n for mol in molecules\n ]\n return valid_smiles\n\n def mol_to_smiles(self, molecule: Mol, isomericSmiles=False, canonical=True) -> str:\n \"\"\"\n Converts a Mol object into a canonical SMILES string.\n :param molecule: Mol object.\n :return: A SMILES string.\n \"\"\"\n if molecule:\n return MolToSmiles(molecule, isomericSmiles=isomericSmiles, canonical=canonical)\n\n def mol_to_random_smiles(self, molecule: Mol) -> str:\n \"\"\"\n Converts a Mol object into a random SMILES string.\n :return: A SMILES string.\n \"\"\"\n if molecule:\n new_atom_order = list(range(molecule.GetNumAtoms()))\n random.shuffle(new_atom_order)\n random_mol = RenumberAtoms(molecule, newOrder=new_atom_order)\n return MolToSmiles(random_mol, canonical=False, isomericSmiles=False)\n\n def convert_to_rdkit_smiles(\n self, smiles: str, allowTautomers=True, sanitize=False, isomericSmiles=False\n ) -> str:\n \"\"\"\n :param smiles: Converts a smiles string into a canonical SMILES string.\n :type allowTautomers: allows having same molecule represented in different tautomeric forms\n \"\"\"\n if allowTautomers:\n return MolToSmiles(\n MolFromSmiles(smiles, sanitize=sanitize), isomericSmiles=isomericSmiles\n )\n else:\n return MolStandardize.canonicalize_tautomer_smiles(smiles)\n\n def convert_to_standardized_smiles(self, smiles: str) -> Optional[str]:\n \"\"\"Standardize SMILES for Mol2Mol\n\n This should only be used to validate and transform user input\n because the code will abort execution on any error it finds.\n\n param smiles: single SMILES string\n return: single SMILES string\n \"\"\"\n\n mol = MolFromSmiles(smiles, sanitize=True)\n\n if not mol: # RDKit fails silently\n raise RuntimeError(f\"RDKit does not accept SMILES: {smiles}\")\n\n standardizer = Standardizer() # MolVS\n\n try:\n smol = standardizer(mol) # runs SanitizeMol() first\n smol = standardizer.charge_parent(smol) # largest fragment uncharged\n smi = MolToSmiles(smol, isomericSmiles=True)\n except Exception as error: # RDKit may raise multiple exceptions\n raise RuntimeError(f\"RDKit does not accept SMILES: {smiles} {error}\")\n\n # Sometimes when standardizing ChEMBL [H] are not removed so try a\n # second call\n if \"[H]\" in smi:\n return self.convert_to_standardized_smiles(smi)\n else:\n return smi\n\n def copy_mol(self, molecule: Mol) -> Mol:\n \"\"\"\n Copies, sanitizes, canonicalizes and cleans a molecule.\n :param molecule: A Mol object to copy.\n :return : Another Mol object copied, sanitized, canonicalized and cleaned.\n \"\"\"\n return self.smile_to_mol(self.mol_to_smiles(molecule))\n\n def randomize_smiles(self, smiles: str) -> str:\n \"\"\"\n Returns a random SMILES given a SMILES of a molecule.\n :param smiles: A smiles string\n :returns: A random SMILES string of the same molecule or None if the molecule is invalid.\n \"\"\"\n mol = MolFromSmiles(smiles)\n if mol:\n new_atom_order = list(range(mol.GetNumHeavyAtoms()))\n random.shuffle(new_atom_order)\n random_mol = RenumberAtoms(mol, newOrder=new_atom_order)\n return MolToSmiles(random_mol, canonical=False, isomericSmiles=False)\n\n def mol_to_inchi_key(self, molecule: Mol) -> str:\n \"\"\"Returns the standard InChI key for a molecule\"\"\"\n if molecule:\n inchi_key = MolToInchiKey(molecule)\n return inchi_key\n\n def mol_to_sdf(self, molecules: List, input_sdf_path: str):\n \"\"\"Write a set of molecules to sdf file\"\"\"\n writer = SDWriter(input_sdf_path)\n for mol in molecules:\n writer.write(mol)\n\nreinvent/chemistry/library_design/fragment_reaction_slice_enumerator.py\nclass FragmentReactionSliceEnumerator:\n def __init__(\n self,\n chemical_reactions: List[ReactionDTO],\n scaffold_conditions: List[FilteringConditionDTO],\n decoration_conditions: List[FilteringConditionDTO],\n ):\n \"\"\"\n Class to enumerate slicings given certain conditions.\n :param chemical_reactions: A list of ChemicalReaction objects.\n :param scaffold_conditions: Conditions to use when filtering scaffolds obtained from slicing molecules (see FragmentFilter).\n :param decoration_conditions: Conditions to use when filtering decorations obtained from slicing molecules.\n \"\"\"\n self._tockens = TransformationTokens()\n self._chemical_reactions = chemical_reactions\n self._scaffold_filter = FragmentFilter(scaffold_conditions)\n self._decoration_filter = FragmentFilter(decoration_conditions)\n self._reactions = FragmentReactions()\n self._conversions = Conversions()\n\n def enumerate(self, molecule: Mol, cuts: int) -> List[FragmentedMolecule]:\n \"\"\"\n Enumerates all possible combination of slicings of a molecule given a number of cuts.\n :param molecule: A mol object with the molecule to slice.\n :param cuts: The number of cuts to perform.\n :return : A list with all the possible (scaffold, decorations) pairs as SlicedMol objects.\n \"\"\"\n original_smiles = self._conversions.mol_to_smiles(molecule)\n sliced_mols = set()\n for cut in range(1, cuts + 1):\n if cut == 1:\n fragment_pairs = self._reactions.slice_molecule_to_fragments(\n molecule, self._chemical_reactions\n )\n\n for pair in fragment_pairs:\n for indx, _ in enumerate(pair):\n decorations = self._select_all_except(pair, indx)\n decoration = self._conversions.copy_mol(decorations[0])\n labeled_decoration = OrderedDict()\n labeled_decoration[0] = decoration # [ for decoration in decorations]\n\n scaffold = self._conversions.copy_mol(pair[indx])\n labeled_scaffold = self._label_scaffold(scaffold)\n\n # TODO: filtering should take place after scaffold is generated\n sliced_mol = FragmentedMolecule(\n labeled_scaffold, labeled_decoration, original_smiles\n )\n if sliced_mol.original_smiles == sliced_mol.reassembled_smiles:\n sliced_mols.add(sliced_mol)\n else:\n for slice in sliced_mols:\n to_add = self._scaffold_slicing(slice, cut)\n sliced_mols = sliced_mols.union(to_add)\n\n return list(filter(self._filter, sliced_mols))\n\n def _scaffold_slicing(self, slice: FragmentedMolecule, cut: int) -> Set[FragmentedMolecule]:\n to_add = set()\n if slice.decorations_count() == cut - 1:\n fragment_pairs = self._reactions.slice_molecule_to_fragments(\n slice.scaffold, self._chemical_reactions\n )\n\n for pair in fragment_pairs:\n scaffold, decoration = self._split_scaffold_from_decorations(pair, cut)\n if scaffold:\n labeled_scaffold = self._label_scaffold(scaffold)\n labeled_scaffold = self._conversions.copy_mol(labeled_scaffold)\n decoration = self._conversions.copy_mol(decoration)\n sliced_mol = self._create_sliced_molecule(slice, labeled_scaffold, decoration)\n\n if sliced_mol.original_smiles == sliced_mol.reassembled_smiles:\n to_add.add(sliced_mol)\n return to_add\n\n def _select_all_except(self, fragments: Tuple[Mol], to_exclude: int) -> List[Mol]:\n return [fragment for indx, fragment in enumerate(fragments) if indx != to_exclude]\n\n def _filter(self, sliced_mol: FragmentedMolecule) -> bool:\n return self._scaffold_filter.filter(sliced_mol.scaffold) and all(\n self._decoration_filter.filter(dec) for dec in sliced_mol.decorations.values()\n )\n\n def _split_scaffold_from_decorations(self, pair: Tuple[Mol], cuts: int) -> Tuple[Mol, Mol]:\n decoration = None\n scaffold = None\n for frag in pair:\n num_att = len(\n [\n atom\n for atom in frag.GetAtoms()\n if atom.GetSymbol() == self._tockens.ATTACHMENT_POINT_TOKEN\n ]\n )\n # detect whether there is one fragment with as many attachment points as cuts (scaffold)\n # the rest are decorations\n if num_att == cuts and not scaffold:\n scaffold = frag\n if num_att == 1:\n decoration = frag\n if decoration and scaffold:\n return scaffold, decoration\n else:\n return (None, None)\n\n def _label_scaffold(self, scaffold: Mol) -> Mol:\n highest_number = self._find_highest_number(scaffold)\n\n for atom in scaffold.GetAtoms():\n if atom.GetSymbol() == self._tockens.ATTACHMENT_POINT_TOKEN:\n try:\n atom_number = int(atom.GetProp(\"molAtomMapNumber\"))\n except:\n highest_number += 1\n num = atom.GetIsotope()\n atom.SetIsotope(0)\n atom.SetProp(\"molAtomMapNumber\", str(highest_number))\n scaffold.UpdatePropertyCache()\n\n return scaffold\n\n def _find_highest_number(self, cut_mol: Mol) -> int:\n highest_number = -1\n\n for atom in cut_mol.GetAtoms():\n if atom.GetSymbol() == self._tockens.ATTACHMENT_POINT_TOKEN:\n try:\n atom_number = int(atom.GetProp(\"molAtomMapNumber\"))\n if highest_number < atom_number:\n highest_number = atom_number\n except:\n pass\n return highest_number\n\n def _create_sliced_molecule(\n self, original_sliced_mol: FragmentedMolecule, scaffold: Mol, decoration: Mol\n ) -> FragmentedMolecule:\n old_decorations = OrderedDict()\n for k, v in original_sliced_mol.decorations.items():\n old_decorations[k] = v\n old_decorations[original_sliced_mol.decorations_count()] = decoration\n sliced_mol = FragmentedMolecule(\n scaffold, old_decorations, original_sliced_mol.original_smiles\n )\n return sliced_mol\n\nreinvent/chemistry/library_design/bond_maker.py\nclass BondMaker:\n def __init__(self):\n self._conversions = Conversions()\n self._tokens = TransformationTokens()\n self._attachment_points = AttachmentPoints()\n\n def join_scaffolds_and_decorations(\n self, scaffold_smi: str, decorations_smi, keep_labels_on_atoms=False\n ) -> Optional[Mol]:\n decorations_smi = [\n self._attachment_points.add_first_attachment_point_number(dec, i)\n for i, dec in enumerate(decorations_smi.split(self._tokens.ATTACHMENT_SEPARATOR_TOKEN))\n ]\n num_attachment_points = len(self._attachment_points.get_attachment_points(scaffold_smi))\n if len(decorations_smi) != num_attachment_points:\n return None\n\n mol = self._conversions.smile_to_mol(scaffold_smi)\n for decoration in decorations_smi:\n mol = self.join_molecule_fragments(\n mol,\n self._conversions.smile_to_mol(decoration),\n keep_label_on_atoms=keep_labels_on_atoms,\n )\n if not mol:\n return None\n return mol\n\n def join_molecule_fragments(self, scaffold: Mol, decoration: Mol, keep_label_on_atoms=False):\n \"\"\"\n Joins a RDKit MOL scaffold with a decoration. They must be labelled.\n :param scaffold: RDKit MOL of the scaffold.\n :param decoration: RDKit MOL of the decoration.\n :param keep_label_on_atoms: Add the labels to the atoms after attaching the molecule.\n This is useful when debugging, but it can give problems.\n :return: A Mol object of the joined scaffold.\n \"\"\"\n\n if scaffold and decoration:\n # obtain id in the decoration\n try:\n attachment_points = [\n atom.GetProp(\"molAtomMapNumber\")\n for atom in decoration.GetAtoms()\n if atom.GetSymbol() == self._tokens.ATTACHMENT_POINT_TOKEN\n ]\n if len(attachment_points) != 1:\n return None # more than one attachment point...\n attachment_point = attachment_points[0]\n except KeyError:\n return None\n\n combined_scaffold = RWMol(CombineMols(decoration, scaffold))\n attachments = [\n atom\n for atom in combined_scaffold.GetAtoms()\n if atom.GetSymbol() == self._tokens.ATTACHMENT_POINT_TOKEN\n and atom.HasProp(\"molAtomMapNumber\")\n and atom.GetProp(\"molAtomMapNumber\") == attachment_point\n ]\n if len(attachments) != 2:\n return None # something weird\n\n neighbors = []\n for atom in attachments:\n if atom.GetDegree() != 1:\n return None # the attachment is wrongly generated\n neighbors.append(atom.GetNeighbors()[0])\n\n bonds = [atom.GetBonds()[0] for atom in attachments]\n bond_type = BondType.SINGLE\n if any(bond for bond in bonds if bond.GetBondType() == BondType.DOUBLE):\n bond_type = BondType.DOUBLE\n\n combined_scaffold.AddBond(neighbors[0].GetIdx(), neighbors[1].GetIdx(), bond_type)\n combined_scaffold.RemoveAtom(attachments[0].GetIdx())\n combined_scaffold.RemoveAtom(attachments[1].GetIdx())\n\n if keep_label_on_atoms:\n for neigh in neighbors:\n self._add_attachment_point_num(neigh, attachment_point)\n\n # Label the atoms in the bond\n bondNumbers = [\n int(atom.GetProp(\"bondNum\"))\n for atom in combined_scaffold.GetAtoms()\n if atom.HasProp(\"bondNum\")\n ]\n\n if bondNumbers:\n bondNum = max(bondNumbers) + 1\n else:\n bondNum = 0\n\n for neighbor in neighbors:\n idx = neighbor.GetIdx()\n atom = combined_scaffold.GetAtomWithIdx(idx)\n atom.SetIntProp(\"bondNum\", bondNum)\n ##########################################\n\n scaffold = combined_scaffold.GetMol()\n try:\n SanitizeMol(scaffold)\n except ValueError: # sanitization error\n return None\n else:\n return None\n\n return scaffold\n\n def _add_attachment_point_num(self, atom, idx):\n idxs = []\n if atom.HasProp(\"molAtomMapNumber\"):\n idxs = atom.GetProp(\"molAtomMapNumber\").split(\",\")\n idxs.append(str(idx))\n idxs = sorted(list(set(idxs)))\n atom.SetProp(\"molAtomMapNumber\", \",\".join(idxs))\n # Fixme: This way of annotating fails in case of several attachment points when the mol is converted back to a\n # SMILES string (RuntimeError: boost::bad_any_cast: failed conversion using boost::any_cast)\n # For example combining scaffold '*C(*)CC' and warhead pair '*OC|*C' would result in\n # C[O:0][CH:0,1]([CH3:1])CC, which results in an error due to the '0,1'\n\n def randomize_scaffold(self, scaffold: Mol):\n smi = self._conversions.mol_to_random_smiles(scaffold)\n conv_smi = None\n if smi:\n conv_smi = self._attachment_points.add_brackets_to_attachment_points(smi)\n return conv_smi", "answers": [" result = self._slice_enumerator.enumerate(self.positive_molecule, 1)"], "length": 2418, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "881c844f-dd3c-4746-8c12-9fe016ba0bfb", "reasoning": "In the TestReactionsSliceEnumeratorWithFilters class, after defining the test method 'def test_enumeration_slicing_1(self):' the next logical line is to invoke the slice enumerator on the positive molecule with a single cut, mirroring other test methods. This starts the test body.\nThe appropriate line, respecting indentation, is:\n result = self._slice_enumerator.enumerate(self.positive_molecule, 1)", "reasoning_model_answer": "result = self._slice_enumerator.enumerate(self.positive_molecule, 1)", "assistant_with_reasoning": "\nIn the TestReactionsSliceEnumeratorWithFilters class, after defining the test method 'def test_enumeration_slicing_1(self):' the next logical line is to invoke the slice enumerator on the positive molecule with a single cut, mirroring other test methods. This starts the test body.\nThe appropriate line, respecting indentation, is:\n result = self._slice_enumerator.enumerate(self.positive_molecule, 1)\n\nresult = self._slice_enumerator.enumerate(self.positive_molecule, 1)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.376, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 32244, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "result = self._slice_enumerator.enumerate(self.positive_molecule, 1)", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import edu.wpi.first.math.Matrix;\nimport edu.wpi.first.math.geometry.Pose2d;\nimport edu.wpi.first.math.geometry.Rotation2d;\nimport edu.wpi.first.math.kinematics.ChassisSpeeds;\nimport edu.wpi.first.math.kinematics.SwerveModuleState;\nimport edu.wpi.first.math.numbers.N1;\nimport edu.wpi.first.math.numbers.N3;\nimport edu.wpi.first.wpilibj.DriverStation;\nimport edu.wpi.first.wpilibj2.command.Command;\nimport edu.wpi.first.wpilibj2.command.Subsystem;\nimport frc.robot.Robot;\nimport frc.robot.RobotTelemetry;\nimport frc.robot.swerve.configs.MUSICDISC2023;\nimport frc.robot.swerve.configs.NOTEBLOCK2023;\nimport frc.spectrumLib.swerve.Drivetrain;\nimport frc.spectrumLib.swerve.Drivetrain.DriveState;\nimport frc.spectrumLib.swerve.Request;\nimport frc.spectrumLib.swerve.config.SwerveConfig;\nimport java.util.concurrent.locks.ReadWriteLock;\nimport java.util.concurrent.locks.ReentrantReadWriteLock;\nimport java.util.function.Consumer;\nimport java.util.function.DoubleSupplier;\nimport java.util.function.Supplier;\nimport org.littletonrobotics.junction.Logger;", "context": "src/main/java/frc/robot/swerve/Swerve.java\npackage frc.robot.swerve;\n\n\npublic class Swerve implements Subsystem {\n public final SwerveConfig config;\n private final Drivetrain drivetrain;\n private final RotationController rotationController;\n private double OdometryUpdateFrequency = 250;\n private double targetHeading = 0;\n private ReadWriteLock m_stateLock = new ReentrantReadWriteLock();\n private SwerveModuleState[] Setpoints = new SwerveModuleState[] {};\n\n public Swerve() {\n RobotTelemetry.print(\"Swerve Subsystem Starting: \");\n\n // Choose the correct swerve configuration\n switch (Robot.config.getRobotType()) {\n case NOTEBLOCK:\n config = NOTEBLOCK2023.config;\n break;\n case MUSICDISC:\n config = MUSICDISC2023.config;\n break;\n case SIM: // runs in simulation\n OdometryUpdateFrequency = 50;\n config = NOTEBLOCK2023.config;\n break;\n default:\n config = NOTEBLOCK2023.config;\n break;\n }\n\nsrc/main/java/frc/robot/swerve/configs/MUSICDISC2023.java\npublic class MUSICDISC2023 {\n // Angle Offsets\n private static final double kFrontLeftCANcoderOffset = 20;\n private static final double kFrontRightCANncoderOffset = 20;\n private static final double kBackLeftCANcoderOffset = 20;\n private static final double kBackRightCANcoderOffset = 20;\n\n // Device Setup\n private static final String kCANbusName = \"rio\";\n private static final boolean supportsPro = false;\n private static final SwerveModuleSteerFeedbackType steerFeedbackType =\n SwerveModuleSteerFeedbackType.RemoteCANcoder;\n\n public static final ModuleConfig FrontLeft =\n NOTEBLOCK2023.FrontLeft.withCANcoderOffset(kFrontLeftCANcoderOffset)\n .withFeedbackSource(steerFeedbackType);\n public static final ModuleConfig FrontRight =\n NOTEBLOCK2023.FrontRight.withCANcoderOffset(kFrontRightCANncoderOffset)\n .withFeedbackSource(steerFeedbackType);\n public static final ModuleConfig BackLeft =\n NOTEBLOCK2023.BackLeft.withCANcoderOffset(kBackLeftCANcoderOffset)\n .withFeedbackSource(steerFeedbackType);\n public static final ModuleConfig BackRight =\n NOTEBLOCK2023.BackRight.withCANcoderOffset(kBackRightCANcoderOffset)\n .withFeedbackSource(steerFeedbackType);\n\n public static final ModuleConfig[] ModuleConfigs = {FrontLeft, FrontRight, BackLeft, BackRight};\n\n public static final SwerveConfig config =\n DefaultConfig.DrivetrainConstants.withCANbusName(kCANbusName)\n .withSupportsPro(supportsPro)\n .withModules(ModuleConfigs);\n}\n\nsrc/main/java/frc/robot/RobotTelemetry.java\npublic class RobotTelemetry extends Telemetry {\n\n /* What to publish over networktables for telemetry */\n NetworkTableInstance inst = NetworkTableInstance.getDefault();\n\n /* Robot pose for field positioning */\n NetworkTable table = inst.getTable(\"Pose\");\n DoubleArrayPublisher fieldPub = table.getDoubleArrayTopic(\"robotPose\").publish();\n StringPublisher fieldTypePub = table.getStringTopic(\".type\").publish();\n\n /* Robot speeds for general checking */\n NetworkTable driveStats = inst.getTable(\"Drive\");\n DoublePublisher velocityX = driveStats.getDoubleTopic(\"Velocity X\").publish();\n DoublePublisher velocityY = driveStats.getDoubleTopic(\"Velocity Y\").publish();\n DoublePublisher speed = driveStats.getDoubleTopic(\"Speed\").publish();\n DoublePublisher odomPeriod = driveStats.getDoubleTopic(\"Odometry Period\").publish();\n\n /* Keep a reference of the last pose to calculate the speeds */\n Pose2d m_lastPose = new Pose2d();\n double lastTime = Utils.getCurrentTimeSeconds();\n\n /* Mechanisms to represent the swerve module states */\n Mechanism2d[] m_moduleMechanisms =\n new Mechanism2d[] {\n new Mechanism2d(1, 1),\n new Mechanism2d(1, 1),\n new Mechanism2d(1, 1),\n new Mechanism2d(1, 1),\n };\n /* A direction and length changing ligament for speed representation */\n MechanismLigament2d[] m_moduleSpeeds =\n new MechanismLigament2d[] {\n m_moduleMechanisms[0]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n m_moduleMechanisms[1]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n m_moduleMechanisms[2]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n m_moduleMechanisms[3]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n };\n /* A direction changing and length constant ligament for module direction */\n MechanismLigament2d[] m_moduleDirections =\n new MechanismLigament2d[] {\n m_moduleMechanisms[0]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n m_moduleMechanisms[1]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n m_moduleMechanisms[2]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n m_moduleMechanisms[3]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n };\n\n public RobotTelemetry() {\n super();\n Logger.recordMetadata(\"RobotType\", Robot.config.getRobotType().name());\n\n Robot.swerve.registerTelemetry((b) -> telemeterize(b));\n }\n\n /* Accept the swerve drive state and telemeterize it to smartdashboard */\n public void telemeterize(DriveState state) {\n /* Telemeterize the pose */\n Pose2d pose = state.Pose;\n fieldTypePub.set(\"Field2d\");\n fieldPub.set(new double[] {pose.getX(), pose.getY(), pose.getRotation().getDegrees()});\n\n /* Telemeterize the robot's general speeds */\n double currentTime = Utils.getCurrentTimeSeconds();\n double diffTime = currentTime - lastTime;\n lastTime = currentTime;\n Translation2d distanceDiff = pose.minus(m_lastPose).getTranslation();\n m_lastPose = pose;\n\n Translation2d velocities = distanceDiff.div(diffTime);\n\n speed.set(velocities.getNorm());\n velocityX.set(velocities.getX());\n velocityY.set(velocities.getY());\n odomPeriod.set(state.OdometryPeriod);\n\n /* Telemeterize the module's states */\n for (int i = 0; i < 4; ++i) {\n m_moduleSpeeds[i].setAngle(state.ModuleStates[i].angle);\n m_moduleDirections[i].setAngle(state.ModuleStates[i].angle);\n m_moduleSpeeds[i].setLength(state.ModuleStates[i].speedMetersPerSecond / (2 * 6));\n\n SmartDashboard.putData(\"Module \" + i, m_moduleMechanisms[i]);\n }\n }\n}\n\nsrc/main/java/frc/robot/swerve/configs/NOTEBLOCK2023.java\npublic class NOTEBLOCK2023 {\n\n // Angle Offsets\n private static final double kFrontLeftCANcoderOffset = -0.407958984375;\n private static final double kFrontRightCANncoderOffset = -0.181396484375;\n private static final double kBackLeftCANcoderOffset = -0.8779296875;\n private static final double kBackRightCANcoderOffset = -0.84130859375;\n\n // Physical Config\n private static final double wheelBaseInches = 21.5;\n private static final double trackWidthInches = 18.5;\n private static final double kDriveGearRatio = 6.746;\n private static final double kSteerGearRatio = 21.428;\n\n // Tuning Config\n // Estimated at first, then fudge-factored to make odom match record\n private static final double kWheelRadiusInches = 2;\n private static final double speedAt12VoltsMps = 6;\n private static final double slipCurrent = 800;\n private static final SlotGains steerGains = new SlotGains(100, 0, 0.05, 0, 0);\n private static final SlotGains driveGains = new SlotGains(0.4, 0, 0, 0, 0);\n\n /*Rotation Controller*/\n private static final double kPRotationController = 0.0;\n private static final double kIRotationController = 0.0;\n private static final double kDRotationController = 0.0;\n\n /*Profiling Configs*/\n private static final double maxVelocity = speedAt12VoltsMps;\n private static final double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed.\n private static final double maxAngularVelocity =\n maxVelocity\n / Units.inchesToMeters(\n Math.hypot(wheelBaseInches / 2.0, trackWidthInches / 2.0));\n private static final double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2);\n\n // Device Setup\n private static final String kCANbusName = \"3847\";\n private static final boolean supportsPro = true;\n private static final SwerveModuleSteerFeedbackType steerFeedbackType =\n SwerveModuleSteerFeedbackType.FusedCANcoder;\n\n // Wheel Positions\n private static final double kFrontLeftXPos = Units.inchesToMeters(wheelBaseInches / 2.0);\n private static final double kFrontLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0);\n private static final double kFrontRightXPos = Units.inchesToMeters(wheelBaseInches / 2.0);\n private static final double kFrontRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);\n private static final double kBackLeftXPos = Units.inchesToMeters(-wheelBaseInches / 2.0);\n private static final double kBackLeftYPos = Units.inchesToMeters(trackWidthInches / 2.0);\n private static final double kBackRightXPos = Units.inchesToMeters(-wheelBaseInches / 2.0);\n private static final double kBackRightYPos = Units.inchesToMeters(-trackWidthInches / 2.0);\n\n public static final ModuleConfig FrontLeft =\n DefaultConfig.FrontLeft.withCANcoderOffset(kFrontLeftCANcoderOffset)\n .withLocationX(kFrontLeftXPos)\n .withLocationY(kFrontLeftYPos)\n .withSlipCurrent(slipCurrent)\n .withSpeedAt12VoltsMps(speedAt12VoltsMps)\n .withDriveMotorGearRatio(kDriveGearRatio)\n .withSteerMotorGearRatio(kSteerGearRatio)\n .withDriveMotorGains(driveGains)\n .withSteerMotorGains(steerGains)\n .withWheelRadius(kWheelRadiusInches)\n .withFeedbackSource(steerFeedbackType);\n\n public static final ModuleConfig FrontRight =\n DefaultConfig.FrontRight.withCANcoderOffset(kFrontRightCANncoderOffset)\n .withLocationX(kFrontRightXPos)\n .withLocationY(kFrontRightYPos)\n .withSlipCurrent(slipCurrent)\n .withSpeedAt12VoltsMps(speedAt12VoltsMps)\n .withDriveMotorGearRatio(kDriveGearRatio)\n .withSteerMotorGearRatio(kSteerGearRatio)\n .withDriveMotorGains(driveGains)\n .withSteerMotorGains(steerGains)\n .withWheelRadius(kWheelRadiusInches)\n .withFeedbackSource(steerFeedbackType);\n\n public static final ModuleConfig BackLeft =\n DefaultConfig.BackLeft.withCANcoderOffset(kBackLeftCANcoderOffset)\n .withLocationX(kBackLeftXPos)\n .withLocationY(kBackLeftYPos)\n .withSlipCurrent(slipCurrent)\n .withSpeedAt12VoltsMps(speedAt12VoltsMps)\n .withDriveMotorGearRatio(kDriveGearRatio)\n .withSteerMotorGearRatio(kSteerGearRatio)\n .withDriveMotorGains(driveGains)\n .withSteerMotorGains(steerGains)\n .withWheelRadius(kWheelRadiusInches)\n .withFeedbackSource(steerFeedbackType);\n\n public static final ModuleConfig BackRight =\n DefaultConfig.BackRight.withCANcoderOffset(kBackRightCANcoderOffset)\n .withLocationX(kBackRightXPos)\n .withLocationY(kBackRightYPos)\n .withSlipCurrent(slipCurrent)\n .withSpeedAt12VoltsMps(speedAt12VoltsMps)\n .withDriveMotorGearRatio(kDriveGearRatio)\n .withSteerMotorGearRatio(kSteerGearRatio)\n .withDriveMotorGains(driveGains)\n .withSteerMotorGains(steerGains)\n .withWheelRadius(kWheelRadiusInches)\n .withFeedbackSource(steerFeedbackType);\n\n public static final ModuleConfig[] ModuleConfigs = {FrontLeft, FrontRight, BackLeft, BackRight};\n\n public static final SwerveConfig config =\n DefaultConfig.DrivetrainConstants.withCANbusName(kCANbusName)\n .withSupportsPro(supportsPro)\n .withModules(ModuleConfigs)\n .withRotationGains(\n kPRotationController, kIRotationController, kDRotationController)\n .withProfilingConfigs(\n maxVelocity, maxAccel, maxAngularVelocity, maxAngularAcceleration);\n}\n\nsrc/main/java/frc/spectrumLib/swerve/config/SwerveConfig.java\npublic class SwerveConfig {\n /** CAN ID of the Pigeon2 on the drivetrain */\n public int Pigeon2Id = 0;\n /** Name of CANivore the swerve drive is on */\n public String CANbusName = \"rio\";\n\n /** If using Pro, specify this as true to make use of all the Pro features */\n public boolean SupportsPro = false;\n\n public ModuleConfig[] modules = new ModuleConfig[0];\n\n /*Rotation Controller*/\n public double kPRotationController = 0.0;\n public double kIRotationController = 0.0;\n public double kDRotationController = 0.0;\n\n /*Profiling Configs*/\n public double maxVelocity = 0;\n public double maxAccel = maxVelocity * 1.5; // take 1/2 sec to get to max speed.\n public double maxAngularVelocity = Math.PI * 2;\n public double maxAngularAcceleration = Math.pow(maxAngularVelocity, 2);\n\n public SwerveConfig withPigeon2Id(int id) {\n this.Pigeon2Id = id;\n return this;\n }\n\n public SwerveConfig withCANbusName(String name) {\n this.CANbusName = name;\n return this;\n }\n\n public SwerveConfig withSupportsPro(boolean supportsPro) {\n this.SupportsPro = supportsPro;\n return this;\n }\n\n public SwerveConfig withModules(ModuleConfig[] modules) {\n this.modules = modules;\n return this;\n }\n\n public SwerveConfig withRotationGains(double kP, double kI, double kD) {\n this.kPRotationController = kP;\n this.kIRotationController = kI;\n this.kDRotationController = kD;\n return this;\n }\n\n public SwerveConfig withProfilingConfigs(\n double maxVelocity,\n double maxAccel,\n double maxAngularVelocity,\n double maxAngularAcceleration) {\n this.maxVelocity = maxVelocity;\n this.maxAccel = maxAccel;\n this.maxAngularVelocity = maxAngularVelocity;\n this.maxAngularAcceleration = maxAngularAcceleration;\n return this;\n }\n}\n\nsrc/main/java/frc/spectrumLib/swerve/Drivetrain.java\npublic class DriveState {\n public int SuccessfulDaqs;\n public int FailedDaqs;\n public Pose2d Pose = new Pose2d();\n public SwerveModuleState[] ModuleStates = new SwerveModuleState[] {};\n public double OdometryPeriod;\n}\n\nsrc/main/java/frc/spectrumLib/swerve/Request.java\npublic interface Request {\n\n /*\n * Contains everything the control requests need to calculate the module state\n */\n public class ControlRequestParameters {\n public SwerveDriveKinematics kinematics;\n public Pose2d currentPose;\n public double timestamp;\n public Translation2d[] swervePositions;\n public double updatePeriod;\n }\n\n public StatusCode apply(ControlRequestParameters parameters, Module... modulesToApply);\n\n /**\n * Does nothing to the swerve module state. This is the default state of a newly created swerve\n * drive mechanism.\n */\n public class Idle implements Request {\n\n /** True to use open-loop control while stopped. */\n public boolean IsOpenLoop = false;\n\n public StatusCode apply(ControlRequestParameters parameters, Module... modulesToApply) {\n\n return StatusCode.OK;\n }\n\n public Idle withIsOpenLoop(boolean isOpenLoop) {\n this.IsOpenLoop = isOpenLoop;\n return this;\n }\n }\n}\n\nsrc/main/java/frc/spectrumLib/swerve/Drivetrain.java\npublic class Drivetrain {\n protected final int ModuleCount;\n protected final double UpdateFrequency;\n protected final Module[] Modules;\n\n protected Pigeon2 m_pigeon2;\n protected SwerveDriveKinematics m_kinematics;\n protected SwerveDrivePoseEstimator m_odometry;\n protected SwerveModulePosition[] m_modulePositions;\n protected Translation2d[] m_moduleLocations;\n protected OdometryThread m_odometryThread;\n protected Rotation2d m_fieldRelativeOffset;\n protected StatusSignal m_yawGetter;\n protected StatusSignal m_angularZGetter;\n\n protected Request m_requestToApply = new Request.Idle();\n protected ControlRequestParameters m_requestParameters = new ControlRequestParameters();\n\n protected ReadWriteLock m_stateLock = new ReentrantReadWriteLock();\n\n protected final SimDrivetrain m_simDrive;\n protected final boolean IsOnCANFD;\n\n /**\n * Plain-Old-Data class holding the state of the swerve drivetrain. This encapsulates most data\n * that is relevant for telemetry or decision-making from the Swerve Drive.\n */\n public class DriveState {\n public int SuccessfulDaqs;\n public int FailedDaqs;\n public Pose2d Pose = new Pose2d();\n public SwerveModuleState[] ModuleStates = new SwerveModuleState[] {};\n public double OdometryPeriod;\n }\n\n protected Consumer m_telemetryFunction = null;\n protected DriveState m_cachedState = new DriveState();\n\n /* Perform swerve module updates in a separate thread to minimize latency */\n public class OdometryThread extends Thread {\n private final int START_THREAD_PRIORITY =\n 1; // Testing shows 1 (minimum realtime) is sufficient for tighter\n // odometry loops.\n // If the odometry period is far away from the desired frequency,\n // increasing this may help\n\n private BaseStatusSignal[] m_allSignals;\n public int SuccessfulDaqs = 0;\n public int FailedDaqs = 0;\n MedianFilter peakRemover = new MedianFilter(3);\n LinearFilter lowPass = LinearFilter.movingAverage(50);\n double lastTime = 0;\n double currentTime = 0;\n double averageLoopTime = 0;\n\n int lastThreadPriority = START_THREAD_PRIORITY;\n int threadPriorityToSet = START_THREAD_PRIORITY;\n\n public OdometryThread() {\n super();\n // 4 signals for each module + 2 for Pigeon2\n m_allSignals = new BaseStatusSignal[(ModuleCount * 4) + 2];\n for (int i = 0; i < ModuleCount; ++i) {\n BaseStatusSignal[] signals = Modules[i].getSignals();\n m_allSignals[(i * 4) + 0] = signals[0];\n m_allSignals[(i * 4) + 1] = signals[1];\n m_allSignals[(i * 4) + 2] = signals[2];\n m_allSignals[(i * 4) + 3] = signals[3];\n }\n m_allSignals[m_allSignals.length - 2] = m_yawGetter;\n m_allSignals[m_allSignals.length - 1] = m_angularZGetter;\n }\n\n @Override\n public void run() {\n /* Make sure all signals update at around 250hz */\n for (BaseStatusSignal sig : m_allSignals) {\n sig.setUpdateFrequency(UpdateFrequency);\n }\n Threads.setCurrentThreadPriority(true, START_THREAD_PRIORITY);\n\n /* Run as fast as possible, our signals will control the timing */\n while (true) {\n /* Synchronously wait for all signals in drivetrain */\n /* Wait up to twice the period of the update frequency */\n StatusCode status;\n if (IsOnCANFD) {\n status = BaseStatusSignal.waitForAll(2.0 / UpdateFrequency, m_allSignals);\n } else {\n try {\n /* Wait for the signals to update */\n Thread.sleep((long) ((1.0 / UpdateFrequency) * 1000.0));\n } catch (InterruptedException ex) {\n }\n status = BaseStatusSignal.refreshAll(m_allSignals);\n }\n m_stateLock.writeLock().lock();\n\n lastTime = currentTime;\n currentTime = Utils.getCurrentTimeSeconds();\n /* We don't care about the peaks, as they correspond to GC events, and we want the period generally low passed */\n averageLoopTime = lowPass.calculate(peakRemover.calculate(currentTime - lastTime));\n\n /* Get status of first element */\n if (status.isOK()) {\n SuccessfulDaqs++;\n } else {\n FailedDaqs++;\n }\n\n /* Now update odometry */\n /* Keep track of the change in azimuth rotations */\n for (int i = 0; i < ModuleCount; ++i) {\n m_modulePositions[i] = Modules[i].getPosition(false);\n }\n // Assume Pigeon2 is flat-and-level so latency compensation can be performed\n double yawDegrees =\n BaseStatusSignal.getLatencyCompensatedValue(m_yawGetter, m_angularZGetter);\n\n /* Keep track of previous and current pose to account for the carpet vector */\n m_odometry.update(Rotation2d.fromDegrees(yawDegrees), m_modulePositions);\n\n /* And now that we've got the new odometry, update the controls */\n m_requestParameters.currentPose =\n m_odometry\n .getEstimatedPosition()\n .relativeTo(new Pose2d(0, 0, m_fieldRelativeOffset));\n m_requestParameters.kinematics = m_kinematics;\n m_requestParameters.swervePositions = m_moduleLocations;\n m_requestParameters.timestamp = currentTime;\n m_requestParameters.updatePeriod = 1.0 / UpdateFrequency;\n\n m_requestToApply.apply(m_requestParameters, Modules);\n\n /* Update our cached state with the newly updated data */\n m_cachedState.FailedDaqs = FailedDaqs;\n m_cachedState.SuccessfulDaqs = SuccessfulDaqs;\n m_cachedState.ModuleStates = new SwerveModuleState[Modules.length];\n for (int i = 0; i < Modules.length; ++i) {\n m_cachedState.ModuleStates[i] = Modules[i].getCurrentState();\n }\n m_cachedState.Pose = m_odometry.getEstimatedPosition();\n m_cachedState.OdometryPeriod = averageLoopTime;\n\n if (m_telemetryFunction != null) {\n /* Log our state */\n m_telemetryFunction.accept(m_cachedState);\n }\n\n m_stateLock.writeLock().unlock();\n /**\n * This is inherently synchronous, since lastThreadPriority is only written here and\n * threadPriorityToSet is only read here\n */\n if (threadPriorityToSet != lastThreadPriority) {\n Threads.setCurrentThreadPriority(true, threadPriorityToSet);\n lastThreadPriority = threadPriorityToSet;\n }\n }\n }\n\n public boolean odometryIsValid() {\n return SuccessfulDaqs > 2; // Wait at least 3 daqs before saying the odometry is valid\n }\n\n /**\n * Sets the DAQ thread priority to a real time priority under the specified priority level\n *\n * @param priority Priority level to set the DAQ thread to. This is a value between 0 and\n * 99, with 99 indicating higher priority and 0 indicating lower priority.\n */\n public void setThreadPriority(int priority) {\n threadPriorityToSet = priority;\n }\n }\n\n protected boolean checkIsOnCanFD(String canbusName) {\n return Unmanaged.isNetworkFD(canbusName);\n }\n\n /**\n * Constructs a CTRSwerveDrivetrain using the specified constants.\n *\n *

This constructs the underlying hardware devices, so user should not construct the devices\n * themselves. If they need the devices, they can access them through getters in the classes.\n *\n * @param swerveConfig Drivetrain-wide constants for the swerve drive\n * @param modules Constants for each specific module\n */\n public Drivetrain(SwerveConfig swerveConfig) {\n this(swerveConfig, 250);\n }\n\n /**\n * Constructs a CTRSwerveDrivetrain using the specified constants.\n *\n *

This constructs the underlying hardware devices, so user should not construct the devices\n * themselves. If they need the devices, they can access them through getters in the classes.\n *\n * @param swerveConfig Drivetrain-wide constants for the swerve drive\n * @param OdometryUpdateFrequency The frequency to run the odometry loop. If unspecified, this\n * is 250 hz.\n * @param modules Constants for each specific module\n */\n public Drivetrain(SwerveConfig swerveConfig, double OdometryUpdateFrequency) {\n ModuleConfig[] moduleConfigs = swerveConfig.modules;\n UpdateFrequency = OdometryUpdateFrequency;\n ModuleCount = moduleConfigs.length;\n\n IsOnCANFD = checkIsOnCanFD(swerveConfig.CANbusName);\n\n m_pigeon2 = new Pigeon2(swerveConfig.Pigeon2Id, swerveConfig.CANbusName);\n m_yawGetter = m_pigeon2.getYaw().clone();\n m_angularZGetter = m_pigeon2.getAngularVelocityZ().clone();\n\n Modules = new Module[ModuleCount];\n m_modulePositions = new SwerveModulePosition[ModuleCount];\n m_moduleLocations = new Translation2d[ModuleCount];\n\n int iteration = 0;\n for (ModuleConfig module : moduleConfigs) {\n Modules[iteration] =\n new Module(module, swerveConfig.CANbusName, swerveConfig.SupportsPro);\n m_moduleLocations[iteration] = new Translation2d(module.LocationX, module.LocationY);\n m_modulePositions[iteration] = Modules[iteration].getPosition(true);\n\n iteration++;\n }\n m_kinematics = new SwerveDriveKinematics(m_moduleLocations);\n m_odometry =\n new SwerveDrivePoseEstimator(\n m_kinematics, new Rotation2d(), m_modulePositions, new Pose2d());\n\n m_fieldRelativeOffset = new Rotation2d();\n\n m_simDrive = new SimDrivetrain(m_moduleLocations, m_pigeon2, swerveConfig, moduleConfigs);\n\n m_odometryThread = new OdometryThread();\n RobotTelemetry.print(\"Starting Odometry Thread: \");\n m_odometryThread.start();\n }\n\n /**\n * Gets a reference to the data acquisition thread.\n *\n * @return DAQ thread\n */\n public OdometryThread getDaqThread() {\n return m_odometryThread;\n }\n\n /**\n * Applies the specified control request to this swerve drivetrain.\n *\n * @param request Request to apply\n */\n public void setControl(Request request) {\n try {\n m_stateLock.writeLock().lock();\n\n m_requestToApply = request;\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Zero's this swerve drive's odometry entirely.\n *\n *

This will zero the entire odometry, and place the robot at 0,0\n */\n public void tareEverything() {\n try {\n m_stateLock.writeLock().lock();\n\n for (int i = 0; i < ModuleCount; ++i) {\n Modules[i].resetPosition();\n m_modulePositions[i] = Modules[i].getPosition(true);\n }\n m_odometry.resetPosition(m_pigeon2.getRotation2d(), m_modulePositions, new Pose2d());\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Takes the current orientation of the robot and makes it X forward for field-relative\n * maneuvers.\n */\n public void seedFieldRelative() {\n try {\n m_stateLock.writeLock().lock();\n\n m_fieldRelativeOffset = getState().Pose.getRotation();\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Takes the current orientation of the robot plus an angle offset and makes it X forward for\n * field-relative maneuvers.\n */\n public void seedFieldRelative(double offsetDegrees) {\n try {\n m_stateLock.writeLock().lock();\n\n m_fieldRelativeOffset =\n getState().Pose.getRotation().plus(Rotation2d.fromDegrees(offsetDegrees));\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Takes the specified location and makes it the current pose for field-relative maneuvers\n *\n * @param location Pose to make the current pose at.\n */\n public void seedFieldRelative(Pose2d location) {\n try {\n m_stateLock.writeLock().lock();\n\n m_odometry.resetPosition(\n Rotation2d.fromDegrees(m_yawGetter.getValue()), m_modulePositions, location);\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Check if the odometry is currently valid\n *\n * @return True if odometry is valid\n */\n public boolean odometryIsValid() {\n try {\n m_stateLock.readLock().lock();\n\n return m_odometryThread.odometryIsValid();\n } finally {\n m_stateLock.readLock().unlock();\n }\n }\n\n /**\n * Get a reference to the module at the specified index. The index corresponds to the module\n * described in the constructor\n *\n * @param index Which module to get\n * @return Reference to SwerveModule\n */\n public Module getModule(int index) {\n if (index >= Modules.length) return null;\n return Modules[index];\n }\n\n /**\n * Gets the current state of the swerve drivetrain.\n *\n * @return Current state of the drivetrain\n */\n public DriveState getState() {\n try {\n m_stateLock.readLock().lock();\n\n return m_cachedState;\n } finally {\n m_stateLock.readLock().unlock();\n }\n }\n\n /**\n * Get the current module states from the cached state\n *\n * @return\n */\n public SwerveModuleState[] getModuleStates() {\n return getState().ModuleStates;\n }\n\n /**\n * Get the current chassis speeds from the cached state\n *\n * @return\n */\n public ChassisSpeeds getChassisSpeeds() {\n return m_kinematics.toChassisSpeeds(getModuleStates());\n }\n\n /**\n * Adds a vision measurement to the Kalman Filter. This will correct the odometry pose estimate\n * while still accounting for measurement noise.\n *\n *

This method can be called as infrequently as you want, as long as you are calling {@link\n * SwerveDrivePoseEstimator#update} every loop.\n *\n *

To promote stability of the pose estimate and make it robust to bad vision data, we\n * recommend only adding vision measurements that are already within one meter or so of the\n * current pose estimate.\n *\n *

Note that the vision measurement standard deviations passed into this method will continue\n * to apply to future measurements until a subsequent call to {@link\n * SwerveDrivePoseEstimator#setVisionMeasurementStdDevs(Matrix)} or this method.\n *\n * @param visionRobotPoseMeters The pose of the robot as measured by the vision camera.\n * @param timestampSeconds The timestamp of the vision measurement in seconds. Note that if you\n * don't use your own time source by calling {@link\n * SwerveDrivePoseEstimator#updateWithTime(double,Rotation2d,SwerveModulePosition[])}, then\n * you must use a timestamp with an epoch since FPGA startup (i.e., the epoch of this\n * timestamp is the same epoch as {@link edu.wpi.first.wpilibj.Timer#getFPGATimestamp()}).\n * This means that you should use {@link edu.wpi.first.wpilibj.Timer#getFPGATimestamp()} as\n * your time source in this case.\n * @param visionMeasurementStdDevs Standard deviations of the vision pose measurement (x\n * position in meters, y position in meters, and heading in radians). Increase these numbers\n * to trust the vision pose measurement less.\n */\n public void addVisionMeasurement(\n Pose2d visionRobotPoseMeters,\n double timestampSeconds,\n Matrix visionMeasurementStdDevs) {\n try {\n m_stateLock.writeLock().lock();\n m_odometry.addVisionMeasurement(\n visionRobotPoseMeters, timestampSeconds, visionMeasurementStdDevs);\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Adds a vision measurement to the Kalman Filter. This will correct the odometry pose estimate\n * while still accounting for measurement noise.\n *\n *

This method can be called as infrequently as you want, as long as you are calling {@link\n * SwerveDrivePoseEstimator#update} every loop.\n *\n *

To promote stability of the pose estimate and make it robust to bad vision data, we\n * recommend only adding vision measurements that are already within one meter or so of the\n * current pose estimate.\n *\n * @param visionRobotPoseMeters The pose of the robot as measured by the vision camera.\n * @param timestampSeconds The timestamp of the vision measurement in seconds. Note that if you\n * don't use your own time source by calling {@link\n * SwerveDrivePoseEstimator#updateWithTime(double,Rotation2d,SwerveModulePosition[])} then\n * you must use a timestamp with an epoch since FPGA startup (i.e., the epoch of this\n * timestamp is the same epoch as {@link edu.wpi.first.wpilibj.Timer#getFPGATimestamp()}.)\n * This means that you should use {@link edu.wpi.first.wpilibj.Timer#getFPGATimestamp()} as\n * your time source or sync the epochs.\n */\n public void addVisionMeasurement(Pose2d visionRobotPoseMeters, double timestampSeconds) {\n try {\n m_stateLock.writeLock().lock();\n m_odometry.addVisionMeasurement(visionRobotPoseMeters, timestampSeconds);\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Sets the pose estimator's trust of global measurements. This might be used to change trust in\n * vision measurements after the autonomous period, or to change trust as distance to a vision\n * target increases.\n *\n * @param visionMeasurementStdDevs Standard deviations of the vision measurements. Increase\n * these numbers to trust global measurements from vision less. This matrix is in the form\n * [x, y, theta]ᵀ, with units in meters and radians.\n */\n public void setVisionMeasurementStdDevs(Matrix visionMeasurementStdDevs) {\n try {\n m_stateLock.writeLock().lock();\n m_odometry.setVisionMeasurementStdDevs(visionMeasurementStdDevs);\n } finally {\n m_stateLock.writeLock().unlock();\n }\n }\n\n /**\n * Updates all the simulation state variables for this drivetrain class. User provides the\n * update variables for the simulation.\n *\n * @param dtSeconds time since last update call\n * @param supplyVoltage voltage as seen at the motor controllers\n */\n public void updateSimState(double dtSeconds, double supplyVoltage) {\n m_simDrive.update(dtSeconds, supplyVoltage, Modules);\n }\n\n /**\n * Register the specified lambda to be executed whenever our SwerveDriveState function is\n * updated in our odometry thread.\n *\n *

It is imperative that this function is cheap, as it will be executed along with the\n * odometry call, and if this takes a long time, it may negatively impact the odometry of this\n * stack.\n *\n *

This can also be used for logging data if the function performs logging instead of\n * telemetry\n *\n * @param telemetryFunction Function to call for telemetry or logging\n */\n public void registerTelemetry(Consumer telemetryFunction) {\n m_telemetryFunction = telemetryFunction;\n }\n}", "answers": [" drivetrain = new Drivetrain(config, OdometryUpdateFrequency);"], "length": 3417, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "9a62bf0d-4f32-480c-9e97-e6e30801bf8d", "reasoning": "After the switch that selects the appropriate SwerveConfig and possibly adjusts OdometryUpdateFrequency, the constructor needs to create the drivetrain using those values. The Drivetrain class has a constructor taking a SwerveConfig and an update frequency, so the next line should instantiate it and assign to the drivetrain field.", "reasoning_model_answer": "drivetrain = new Drivetrain(config, OdometryUpdateFrequency);", "assistant_with_reasoning": "\nAfter the switch that selects the appropriate SwerveConfig and possibly adjusts OdometryUpdateFrequency, the constructor needs to create the drivetrain using those values. The Drivetrain class has a constructor taking a SwerveConfig and an update frequency, so the next line should instantiate it and assign to the drivetrain field.\n\ndrivetrain = new Drivetrain(config, OdometryUpdateFrequency);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.032, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 37077, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "drivetrain = new Drivetrain(config, OdometryUpdateFrequency);", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import org.garret.perst.Persistent;\r\nimport org.slf4j.Logger;\r\nimport frost.fileTransfer.FreenetPriority;\r\nimport frost.fileTransfer.FrostFileListFileObject;\r\nimport frost.fileTransfer.download.FrostDownloadItem;\r\nimport frost.storage.perst.filelist.FileListStorage;\r", "context": "src/main/java/frost/storage/perst/PerstFrostDownloadItem.java\n/*\r\n PerstFrostDownloadItem.java / Frost\r\n Copyright (C) 2007 Frost Project \r\n\r\n This program is free software; you can redistribute it and/or\r\n modify it under the terms of the GNU General Public License as\r\n published by the Free Software Foundation; either version 2 of\r\n the License, or (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program; if not, write to the Free Software\r\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r\n*/\r\npackage frost.storage.perst;\r\n\r\n\r\n\r\n/**\r\n * Class to make FrostDownloadItem persistent.\r\n * FrostDownloadItem itself extends ModelItem and cannot extend Persistent.\r\n */\r\npublic class PerstFrostDownloadItem extends Persistent {\r\n\r\n public String fileName;\r\n public String prefix;\r\n public String downloadDir;\r\n public long fileSize;\r\n public String key;\r\n\r\n public boolean enabled;\r\n public int state;\r\n public long downloadAddedTime;\r\n public long downloadStartedTime;\r\n public long downloadFinishedTime;\r\n public int retries;\r\n public long lastDownloadStopTime;\r\n public String gqIdentifier;\r\n\r\n public String fileListFileSha;\r\n\r\n public boolean isLoggedToFile;\r\n public boolean isTracked;\r\n public boolean isCompletionProgRun;\r\n\r\n public int runtimeSecondsWithoutProgress;\r\n public int oldDoneBlocks;\r\n private FreenetPriority priority;\r\n\r\n public String associatedBoardName;\r\n public String associatedMessageId;\r\n \r\n public PerstFrostDownloadItem() {}\r\n\r\n public PerstFrostDownloadItem(final FrostDownloadItem dlItem) {\r\n fileName = dlItem.getUnprefixedFilename();\r\n prefix = dlItem.getFilenamePrefix();\r\n downloadDir = dlItem.getDownloadDir();\r\n fileSize = dlItem.getFileSize();\r\n key = dlItem.getKey();\r\n enabled = (dlItem.isEnabled()==null?true:dlItem.isEnabled().booleanValue());\r\n state = dlItem.getState();\r\n downloadAddedTime = dlItem.getDownloadAddedMillis();\r\n downloadStartedTime = dlItem.getDownloadStartedMillis();\r\n downloadFinishedTime = dlItem.getDownloadFinishedMillis();\r\n retries = dlItem.getRetries();\r\n lastDownloadStopTime = dlItem.getLastDownloadStopTime();\r\n gqIdentifier = dlItem.getGqIdentifier();\r\n fileListFileSha = (dlItem.getFileListFileObject()==null?null:dlItem.getFileListFileObject().getSha());\r\n isLoggedToFile = dlItem.isLoggedToFile();\r\n isTracked = dlItem.isTracked();\r\n isCompletionProgRun = dlItem.isCompletionProgRun();\r\n runtimeSecondsWithoutProgress = dlItem.getRuntimeSecondsWithoutProgress();\r\n oldDoneBlocks = dlItem.getOldDoneBlocks();\r\n associatedBoardName = dlItem.getAssociatedBoardName();\r\n associatedMessageId = dlItem.getAssociatedMessageId();\r\n priority = dlItem.getPriority();\r\n }\r\n\r\n public FrostDownloadItem toFrostDownloadItem(final Logger logger) {\r\n\r\n FrostFileListFileObject sharedFileObject = null;\r\n if( fileListFileSha != null && fileListFileSha.length() > 0 ) {\r\n\nsrc/main/java/frost/fileTransfer/FrostFileListFileObject.java\npublic class FrostFileListFileObject extends Persistent {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(FrostFileListFileObject.class);\r\n\r\n private String sha = null; // SHA of the file\r\n private long size = 0; // Filesize\r\n private String key = null; // CHK key\r\n\r\n private long lastDownloaded = 0;\r\n private long lastUploaded = 0;\r\n private long firstReceived = 0;\r\n private long lastReceived = 0;\r\n\r\n private long requestLastReceived = 0; // time when we received the last request for this sha\r\n private int requestsReceivedCount = 0; // received requests count\r\n\r\n private long requestLastSent = 0; // time when we sent the last request for this file\r\n private int requestsSentCount = 0; // sent requests count\r\n\r\n private boolean isHidden = false; // user can hide files in search panel\r\n\r\n private IPersistentList frostFileListFileObjectOwnerList;\r\n\r\n // non-persistent fields\r\n private transient String displayName = null;\r\n private transient String displayComment = null;\r\n private transient String displayKeywords = null;\r\n private transient int displayRating = -1;\r\n private transient Boolean hasInfosFromMultipleSources = null;\r\n\r\n private transient List listeners;\r\n\r\n /**\r\n * Used if item is loaded from database.\r\n */\r\n public FrostFileListFileObject(\r\n final String newSha1,\r\n final long newSize,\r\n final String newKey,\r\n final long newLastDownloaded,\r\n final long newLastUploaded,\r\n final long newFirstReceived,\r\n final long newLastReceived,\r\n final long newRequestLastReceived,\r\n final int newRequestsReceivedCount,\r\n final long newRequestLastSent,\r\n final int newRequestSentCount)\r\n {\r\n sha = newSha1;\r\n size = newSize;\r\n key = newKey;\r\n lastDownloaded = newLastDownloaded;\r\n lastUploaded = newLastUploaded;\r\n firstReceived = newFirstReceived;\r\n lastReceived = newLastReceived;\r\n requestLastReceived = newRequestLastReceived;\r\n requestsReceivedCount = newRequestsReceivedCount;\r\n requestLastSent = newRequestLastSent;\r\n requestsSentCount = newRequestSentCount;\r\n }\r\n\r\n /**\r\n * Create instance with data from SharedFilesXmlFile.\r\n * After creation this item should only be saved to database,\r\n * this merges the data from this item in case this files is\r\n * already in the filelist (adds new owner/board).\r\n */\r\n public FrostFileListFileObject(final SharedFileXmlFile sfo, final Identity owner, final long timestamp) {\r\n\r\n sha = sfo.getSha();\r\n size = sfo.getSize().longValue();\r\n key = sfo.getKey();\r\n lastDownloaded = 0;\r\n firstReceived = timestamp;\r\n lastReceived = timestamp; // set or updated after add\r\n\r\n long lastUploadDate = 0;\r\n if( sfo.getKey() != null ) {\r\n if( sfo.getLastUploaded() != null ) {\r\n try {\r\n\t\t\t\t\tfinal OffsetDateTime dt = DateFun.parseDate(sfo.getLastUploaded(), DateFun.FORMAT_DATE,\r\n\t\t\t\t\t\t\tDateFun.getTimeZone());\r\n\t\t\t\t\tlastUploadDate = DateFun.toMilli(dt);\r\n } catch(final Throwable t) {\r\n logger.error(\"error parsing file last uploaded date\", t);\r\n }\r\n }\r\n }\r\n lastUploaded = lastUploadDate;\r\n\r\n final FrostFileListFileObjectOwner ob = new FrostFileListFileObjectOwner(\r\n sfo.getFilename(),\r\n owner.getUniqueName(),\r\n sfo.getComment(),\r\n sfo.getKeywords(),\r\n sfo.getRating(),\r\n timestamp,\r\n lastUploadDate,\r\n sfo.getKey());\r\n\r\n addFrostFileListFileObjectOwner(ob);\r\n }\r\n\r\n private IPersistentList getFrostFileListFileObjectOwnerList() {\r\n if( frostFileListFileObjectOwnerList == null ) {\r\n frostFileListFileObjectOwnerList = FileListStorage.inst().createList(); // ATTN: is used without store also!\r\n }\r\n return frostFileListFileObjectOwnerList;\r\n }\r\n \r\n public void addFrostFileListFileObjectOwner(final FrostFileListFileObjectOwner v) {\r\n v.setFileListFileObject(this);\r\n getFrostFileListFileObjectOwnerList().add(v);\r\n }\r\n \r\n public void deleteFrostFileListFileObjectOwner(final FrostFileListFileObjectOwner v) {\r\n getFrostFileListFileObjectOwnerList().remove(v);\r\n }\r\n \r\n public Iterator getFrostFileListFileObjectOwnerIterator() {\r\n return getFrostFileListFileObjectOwnerList().iterator();\r\n }\r\n \r\n public int getFrostFileListFileObjectOwnerListSize() {\r\n return getFrostFileListFileObjectOwnerList().size();\r\n }\r\n\r\n public String getKey() {\r\n return key;\r\n }\r\n\r\n public void setKey(final String key) {\r\n this.key = key;\r\n notifyListeners();\r\n }\r\n\r\n public long getLastDownloaded() {\r\n return lastDownloaded;\r\n }\r\n\r\n public void setLastDownloaded(final long lastDownloaded) {\r\n this.lastDownloaded = lastDownloaded;\r\n }\r\n\r\n public long getLastUploaded() {\r\n return lastUploaded;\r\n }\r\n\r\n public void setLastUploaded(final long lastUploaded) {\r\n this.lastUploaded = lastUploaded;\r\n notifyListeners();\r\n }\r\n\r\n public long getLastReceived() {\r\n return lastReceived;\r\n }\r\n\r\n public void setLastReceived(final long lastReceived) {\r\n this.lastReceived = lastReceived;\r\n notifyListeners();\r\n }\r\n\r\n public String getSha() {\r\n return sha;\r\n }\r\n\r\n public long getSize() {\r\n return size;\r\n }\r\n\r\n public long getRequestLastReceived() {\r\n return requestLastReceived;\r\n }\r\n\r\n public void setRequestLastReceived(final long requestLastReceived) {\r\n this.requestLastReceived = requestLastReceived;\r\n notifyListeners();\r\n }\r\n\r\n public long getRequestLastSent() {\r\n return requestLastSent;\r\n }\r\n\r\n public void setRequestLastSent(final long requestLastSent) {\r\n this.requestLastSent = requestLastSent;\r\n notifyListeners();\r\n }\r\n\r\n public int getRequestsReceivedCount() {\r\n return requestsReceivedCount;\r\n }\r\n\r\n public void setRequestsReceivedCount(final int requestsReceivedCount) {\r\n this.requestsReceivedCount = requestsReceivedCount;\r\n }\r\n\r\n public int getRequestsSentCount() {\r\n return requestsSentCount;\r\n }\r\n\r\n public void setRequestsSentCount(final int requestsSentCount) {\r\n this.requestsSentCount = requestsSentCount;\r\n }\r\n\r\n public long getFirstReceived() {\r\n return firstReceived;\r\n }\r\n public void setFirstReceived(final long v) {\r\n firstReceived = v;\r\n }\r\n\r\n public boolean isHidden() {\r\n return isHidden;\r\n }\r\n public void setHidden(final boolean isHidden) {\r\n this.isHidden = isHidden;\r\n }\r\n\r\n static class MutableInt {\r\n public int i = 0;\r\n public String name = \"\";\r\n public int rating = 0;\r\n }\r\n\r\n private static MutableInt defaultMutableInt = new MutableInt();\r\n\r\n public String getDisplayName() {\r\n if( displayName == null ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n displayName = \"(no sources)\";\r\n } else {\r\n // choose most often used name\r\n final Hashtable ht = new Hashtable();\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n MutableInt mi = ht.get( e.getName() );\r\n if( mi == null ) {\r\n mi = new MutableInt();\r\n mi.name = e.getName();\r\n mi.i = 1;\r\n ht.put(e.getName(), mi);\r\n } else {\r\n mi.i++;\r\n }\r\n }\r\n MutableInt bestMi = defaultMutableInt;\r\n for( final MutableInt mi : ht.values() ) {\r\n if( mi.i > bestMi.i ) {\r\n bestMi = mi;\r\n }\r\n }\r\n displayName = bestMi.name;\r\n }\r\n }\r\n return displayName;\r\n }\r\n\r\n /**\r\n * @return true if this file has infos from multiple sources (comments, ratings, keywords)\r\n */\r\n public Boolean hasInfosFromMultipleSources() {\r\n if( hasInfosFromMultipleSources == null ) {\r\n if( getFrostFileListFileObjectOwnerList().size() > 1 ) {\r\n int valuesCount = 0;\r\n for( final FrostFileListFileObjectOwner o : getFrostFileListFileObjectOwnerList() ) {\r\n // valuesCount is increased by 1 per FrostFileListFileObjectOwner\r\n if( o.getComment() != null && o.getComment().length() > 0 ) {\r\n valuesCount++;\r\n } else if( o.getKeywords() != null && o.getKeywords().length() > 0 ) {\r\n valuesCount++;\r\n } else if( o.getRating() > 0 ) {\r\n valuesCount++;\r\n }\r\n // if valuesCount is greater 1 we have at least 2 sources that provide informations\r\n if( valuesCount > 1 ) {\r\n hasInfosFromMultipleSources = Boolean.TRUE;\r\n break;\r\n }\r\n }\r\n if( hasInfosFromMultipleSources == null ) {\r\n hasInfosFromMultipleSources = Boolean.FALSE;\r\n }\r\n } else {\r\n hasInfosFromMultipleSources = Boolean.FALSE;\r\n }\r\n }\r\n return hasInfosFromMultipleSources;\r\n }\r\n\r\n public String getDisplayComment() {\r\n if( displayComment == null ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n displayComment = \"(no sources)\";\r\n } else {\r\n // choose most often used name\r\n final Hashtable ht = new Hashtable();\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n final String c = e.getComment();\r\n if( c == null || c.length() == 0 ) {\r\n continue;\r\n }\r\n MutableInt mi = ht.get( c );\r\n if( mi == null ) {\r\n mi = new MutableInt();\r\n mi.name = c;\r\n mi.i = 1;\r\n ht.put(c, mi);\r\n } else {\r\n mi.i++;\r\n }\r\n }\r\n MutableInt bestMi = defaultMutableInt;\r\n for( final MutableInt mi : ht.values() ) {\r\n if( mi.i > bestMi.i ) {\r\n bestMi = mi;\r\n }\r\n }\r\n displayComment = bestMi.name;\r\n }\r\n }\r\n return displayComment;\r\n }\r\n\r\n public String getDisplayKeywords() {\r\n if( displayKeywords == null ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n displayKeywords = \"(no sources)\";\r\n } else {\r\n // choose most often used name\r\n final Hashtable ht = new Hashtable();\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n final String c = e.getKeywords();\r\n if( c == null || c.length() == 0 ) {\r\n continue;\r\n }\r\n MutableInt mi = ht.get( c );\r\n if( mi == null ) {\r\n mi = new MutableInt();\r\n mi.name = c;\r\n mi.i = 1;\r\n ht.put(c, mi);\r\n } else {\r\n mi.i++;\r\n }\r\n }\r\n MutableInt bestMi = defaultMutableInt;\r\n for( final MutableInt mi : ht.values() ) {\r\n if( mi.i > bestMi.i ) {\r\n bestMi = mi;\r\n }\r\n }\r\n displayKeywords = bestMi.name;\r\n }\r\n }\r\n return displayKeywords;\r\n }\r\n\r\n public int getDisplayRating() {\r\n if( displayRating < 0 ) {\r\n final List lst = getFrostFileListFileObjectOwnerList();\r\n if( lst == null || lst.size() == 0 ) {\r\n return 0;\r\n }\r\n // choose most often used rating\r\n // choose most often used name\r\n final int ratings[] = new int[6];\r\n for( final FrostFileListFileObjectOwner e : lst ) {\r\n final int r = e.getRating();\r\n if( r < 1 || r > 5 ) {\r\n continue;\r\n }\r\n ratings[r]++;\r\n }\r\n int bestRating = 0;\r\n for(int x=1; x < ratings.length; x++ ) {\r\n if( ratings[x] > bestRating ) {\r\n bestRating = x;\r\n }\r\n }\r\n displayRating = bestRating;\r\n }\r\n return displayRating;\r\n }\r\n\r\n public void addListener(final FrostDownloadItem d) {\r\n if( !getListeners().contains(d) ) {\r\n getListeners().add(d);\r\n }\r\n }\r\n public void removeListener(final FrostDownloadItem d) {\r\n if( getListeners().contains(d) ) {\r\n getListeners().remove(d);\r\n }\r\n }\r\n public List getListeners() {\r\n if( listeners == null ) {\r\n listeners = new ArrayList();\r\n }\r\n return listeners;\r\n }\r\n private void notifyListeners() {\r\n for( final FrostDownloadItem dl : getListeners() ) {\r\n dl.fireValueChanged();\r\n }\r\n }\r\n}\r\n\nsrc/main/java/frost/fileTransfer/download/FrostDownloadItem.java\npublic class FrostDownloadItem extends ModelItem implements CopyToClipboardItem {\r\n\r\n // the constants representing download states\r\n public transient final static int STATE_WAITING = 1; // wait for start\r\n public transient final static int STATE_TRYING = 2; // download running\r\n public transient final static int STATE_DONE = 3;\r\n public transient final static int STATE_FAILED = 4;\r\n public transient final static int STATE_PROGRESS = 5; // download runs\r\n public transient final static int STATE_DECODING = 6; // decoding runs\r\n\r\n\tprivate String fileName = null;\r\n\tprivate String prefix = null;\r\n private String downloadDir = null;\r\n\tprivate long fileSize = -1;\r\n\tprivate String key = null;\r\n\tprivate String associatedMessageId = null;\r\n\tprivate String associatedBoardName = null;\r\n\r\n private Boolean enabled = Boolean.TRUE;\r\n private int state = STATE_WAITING;\r\n private long downloadAddedTime = 0;\r\n private long downloadStartedTime = 0;\r\n private long downloadFinishedTime = 0;\r\n\tprivate int retries = 0;\r\n private long lastDownloadStopTime = 0;\r\n private String gqIdentifier = null;\r\n\r\n private boolean isLoggedToFile = false;\r\n private boolean isTracked = false;\r\n private boolean isCompletionProgRun = false;\r\n\r\n private int runtimeSecondsWithoutProgress = 0;\r\n private int oldDoneBlocks = 0;\r\n\r\n // if this downloadfile is a shared file then this object is set\r\n private transient FrostFileListFileObject fileListFileObject = null;\r\n\r\n private FreenetPriority priority = FreenetPriority.getPriority(Core.frostSettings.getIntValue(SettingsClass.FCP2_DEFAULT_PRIO_FILE_DOWNLOAD));\r\n\r\n // non persistent fields\r\n\tprivate transient int doneBlocks = 0;\r\n\tprivate transient int requiredBlocks = 0;\r\n\tprivate transient int totalBlocks = 0;\r\n private transient Boolean isFinalized = null;\r\n private transient String errorCodeDescription = null;\r\n\r\n private transient boolean isDirect = false;\r\n private transient boolean isExternal = false;\r\n\r\n private transient boolean internalRemoveExpected = false;\r\n private transient boolean stateShouldBeProgress = false;\r\n\r\n /**\r\n * Add a file from download text box.\r\n */\r\n\tpublic FrostDownloadItem(String fileName, final String key) {\r\n\r\n fileName = FileTransferManager.inst().getDownloadManager().ensureUniqueFilename(fileName);\r\n\r\n this.fileName = Mixed.makeFilename(fileName);\r\n\t\tthis.key = key;\r\n\r\n gqIdentifier = buildGqIdentifier(fileName);\r\n\r\n downloadAddedTime = System.currentTimeMillis();\r\n\r\n\t\tstate = STATE_WAITING;\r\n\t}\r\n\r\n /**\r\n * Add a file attachment.\r\n */\r\n public FrostDownloadItem(final String fileName, final String key, final long s) {\r\n this(fileName, key);\r\n this.fileSize = s;\r\n }\r\n\r\n /**\r\n * Add a shared file from filelist (user searched file and choosed one of the names).\r\n */\r\n public FrostDownloadItem(final FrostFileListFileObject newSfo, String newName) {\r\n\r\n newName = FileTransferManager.inst().getDownloadManager().ensureUniqueFilename(newName);\r\n\r\n FrostFileListFileObject sfo = null;\r\n\r\n // update the shared file object from database (key, owner, sources, ... may have changed)\r\n final FrostFileListFileObject updatedSfo = FileListStorage.inst().getFileBySha(newSfo.getSha());\r\n if( updatedSfo != null ) {\r\n sfo = updatedSfo;\r\n } else {\r\n // paranoia fallback\r\n sfo = newSfo;\r\n }\r\n\r\n fileName = newName;\r\n fileSize = sfo.getSize();\r\n key = sfo.getKey();\r\n\r\n gqIdentifier = buildGqIdentifier(fileName);\r\n\r\n setFileListFileObject(sfo);\r\n\r\n downloadAddedTime = System.currentTimeMillis();\r\n\r\n state = STATE_WAITING;\r\n }\r\n\r\n /**\r\n * Add a saved file from database.\r\n */\r\n\tpublic FrostDownloadItem(\r\n final String newFilename,\r\n final String newFilenamePrefix,\r\n final String newDownloadDir,\r\n final long newSize,\r\n final String newKey,\r\n final Boolean newEnabledownload,\r\n final int newState,\r\n final long newDownloadAddedTime,\r\n final long newDownloadStartedTime,\r\n final long newDownloadFinishedTime,\r\n final int newRetries,\r\n final long newLastDownloadStopTime,\r\n final String newGqId,\r\n final boolean newIsLoggedToFile,\r\n final boolean newIsTracked,\r\n final boolean newIsCompletionProgRun,\r\n final int newRuntimeSecondsWithoutProgress,\r\n final int newOldDoneBlocks,\r\n final String newAssociatedBoardName,\r\n final String newAssociatedMessageId,\r\n final FreenetPriority newPriority\r\n \r\n ) {\r\n fileName = newFilename;\r\n prefix = newFilenamePrefix;\r\n downloadDir = FileAccess.appendSeparator(newDownloadDir);\r\n fileSize = newSize;\r\n key = newKey;\r\n enabled = newEnabledownload;\r\n state = newState;\r\n downloadAddedTime = newDownloadAddedTime;\r\n downloadStartedTime = newDownloadStartedTime;\r\n downloadFinishedTime = newDownloadFinishedTime;\r\n retries = newRetries;\r\n lastDownloadStopTime = newLastDownloadStopTime;\r\n gqIdentifier = newGqId;\r\n isLoggedToFile= newIsLoggedToFile;\r\n isTracked= newIsTracked;\r\n isCompletionProgRun= newIsCompletionProgRun;\r\n runtimeSecondsWithoutProgress = newRuntimeSecondsWithoutProgress;\r\n oldDoneBlocks = newOldDoneBlocks;\r\n associatedBoardName = newAssociatedBoardName;\r\n associatedMessageId = newAssociatedMessageId;\r\n if( newPriority == null ) {\r\n \t\tpriority = FreenetPriority.getPriority(Core.frostSettings.getIntValue(SettingsClass.FCP2_DEFAULT_PRIO_FILE_DOWNLOAD));\r\n \t} else {\r\n \t\tpriority = newPriority;\r\n \t}\r\n \r\n\r\n if( this.state == FrostDownloadItem.STATE_PROGRESS ) {\r\n // download was running at end of last shutdown\r\n stateShouldBeProgress = true;\r\n }\r\n\r\n if (this.state != FrostDownloadItem.STATE_DONE && this.state != FrostDownloadItem.STATE_FAILED) {\r\n this.state = FrostDownloadItem.STATE_WAITING;\r\n }\r\n\t}\r\n\r\n public boolean isSharedFile() {\r\n return getFileListFileObject() != null;\r\n }\r\n\r\n /**\r\n * Used only to set a new name if an item with same name is already in download table.\r\n */\r\n public void setFileName(final String s) {\r\n fileName = s;\r\n }\r\n\tpublic String getFileName() {\r\n\t\tif (prefix == null || prefix.length() == 0) {\r\n\t\t\treturn fileName;\r\n\t\t}\r\n\t\treturn prefix + \"_\" + fileName;\r\n\t}\r\n\tpublic String getUnprefixedFilename() {\r\n\t\treturn fileName;\r\n\t}\r\n\r\n public long getFileSize() {\r\n\t\treturn fileSize;\r\n\t}\r\n\tpublic void setFileSize(final Long newFileSize) {\r\n\t\tfileSize = newFileSize;\r\n fireChange();\r\n\t}\r\n\r\n\tpublic String getKey() {\r\n\t\treturn key;\r\n\t}\r\n\tpublic void setKey(final String newKey) {\r\n\t setKey(newKey, true);\r\n\t}\r\n\tpublic void setKey(final String newKey, final boolean fireChange) {\r\n\t key = newKey;\r\n\t if (fireChange) {\r\n\t fireChange();\r\n\t }\r\n\t}\r\n\r\n\tpublic int getState() {\r\n\t\treturn state;\r\n\t}\r\n\tpublic void setState(final int newState) {\r\n\t\tstate = newState;\r\n fireChange();\r\n\t}\r\n\r\n\tpublic long getLastDownloadStopTime() {\r\n\t\treturn lastDownloadStopTime;\r\n\t}\r\n\tpublic void setLastDownloadStopTime(final long val) {\r\n lastDownloadStopTime = val;\r\n\t}\r\n\r\n\tpublic int getRetries() {\r\n\t\treturn retries;\r\n\t}\r\n\tpublic void setRetries(final int newRetries) {\r\n\t\tretries = newRetries;\r\n fireChange();\r\n\t}\r\n\r\n\tpublic Boolean isEnabled() {\r\n\t\treturn enabled;\r\n\t}\r\n\t/**\r\n\t * @param enabled new enable status of the item. If null, the current status is inverted\r\n\t */\r\n\tpublic void setEnabled(Boolean newEnabled) {\r\n\t\tif (newEnabled == null && enabled != null) {\r\n\t\t\t//Invert the enable status\r\n\t\t\tnewEnabled = !enabled;\r\n\t\t}\r\n\t\tenabled = newEnabled;\r\n fireChange();\r\n\t}\r\n\r\n\tpublic int getDoneBlocks() {\r\n\t\treturn doneBlocks;\r\n\t}\r\n\tpublic void setDoneBlocks(final int newDoneBlocks) {\r\n\t doneBlocks = newDoneBlocks;\r\n\t}\r\n\r\n\tpublic int getRequiredBlocks() {\r\n\t\treturn requiredBlocks;\r\n\t}\r\n\tpublic void setRequiredBlocks(final int newRequiredBlocks) {\r\n\t requiredBlocks = newRequiredBlocks;\r\n\t}\r\n\r\n\tpublic int getTotalBlocks() {\r\n\t\treturn totalBlocks;\r\n\t}\r\n\tpublic void setTotalBlocks(final int newTotalBlocks) {\r\n\t\ttotalBlocks = newTotalBlocks;\r\n\t}\r\n\r\n public Boolean isFinalized() {\r\n return isFinalized;\r\n }\r\n public void setFinalized(final boolean finalized) {\r\n if( finalized ) {\r\n isFinalized = Boolean.TRUE;\r\n } else {\r\n isFinalized = Boolean.FALSE;\r\n }\r\n }\r\n\r\n public long getDownloadAddedMillis() {\r\n return downloadAddedTime;\r\n }\r\n\r\n public long getDownloadFinishedMillis() {\r\n return downloadFinishedTime;\r\n }\r\n\r\n public void setDownloadFinishedTime(final long downloadFinishedTime) {\r\n this.downloadFinishedTime = downloadFinishedTime;\r\n }\r\n\r\n public long getDownloadStartedMillis() {\r\n return downloadStartedTime;\r\n }\r\n\r\n public void setDownloadStartedTime(final long downloadStartedTime) {\r\n this.downloadStartedTime = downloadStartedTime;\r\n }\r\n\r\n public String getGqIdentifier() {\r\n return gqIdentifier;\r\n }\r\n\r\n public void setGqIdentifier(final String gqId) {\r\n this.gqIdentifier = gqId;\r\n }\r\n\r\n public String getDownloadFilename() {\r\n return getDownloadDir() + getFileName();\r\n }\r\n\r\n public String getDownloadDir() {\r\n if (downloadDir == null) {\r\n return FileAccess.appendSeparator(Core.frostSettings.getValue(SettingsClass.DIR_DOWNLOAD));\r\n\t\t}\r\n return downloadDir;\r\n }\r\n\r\n public boolean setDownloadDir(final String dir) {\r\n \tString dirName = FileAccess.appendSeparator(dir);\r\n \tif( FileAccess.createDir(new java.io.File(dirName)) ) {\r\n \t\tdownloadDir = dirName;\r\n \t\treturn true;\r\n \t}\r\n \treturn false;\r\n }\r\n\r\n public void setFilenamePrefix(final String newPrefix) {\r\n \tprefix = newPrefix;\r\n }\r\n\r\n\tpublic final String getFilenamePrefix() {\r\n\t\treturn prefix;\r\n }\r\n\r\n public long getLastReceived() {\r\n if( getFileListFileObject() == null ) {\r\n return 0;\r\n } else {\r\n return getFileListFileObject().getLastReceived();\r\n }\r\n }\r\n\r\n public long getLastUploaded() {\r\n if( getFileListFileObject() == null ) {\r\n return 0;\r\n } else {\r\n return getFileListFileObject().getLastUploaded();\r\n }\r\n }\r\n\r\n public FrostFileListFileObject getFileListFileObject() {\r\n return fileListFileObject;\r\n }\r\n\r\n public void setFileListFileObject(final FrostFileListFileObject sharedFileObject) {\r\n if( this.fileListFileObject != null ) {\r\n this.fileListFileObject.removeListener(this);\r\n }\r\n\r\n int newState = -1;\r\n\r\n // if lastUploaded value changed, maybe restart failed download\r\n if( sharedFileObject != null && this.fileListFileObject != null ) {\r\n// if( sharedFileObject.getLastUploaded() > this.fileListFileObject.getLastUploaded() ) {\r\n if( getState() == STATE_FAILED ) {\r\n newState = STATE_WAITING;\r\n }\r\n// }\r\n }\r\n\r\n this.fileListFileObject = sharedFileObject;\r\n\r\n if( this.fileListFileObject != null ) {\r\n this.fileListFileObject.addListener(this);\r\n }\r\n // take over key and update gui\r\n fireValueChanged();\r\n\r\n if( newState > -1 ) {\r\n setState(newState);\r\n }\r\n }\r\n\r\n /**\r\n * Called by a FrostFileListFileObject if a value interesting for FrostDownloadItem was set.\r\n */\r\n public void fireValueChanged() {\r\n // maybe take over the key, or set new key\r\n // NOTE: once a key is set, the ticker will allow to start this item!\r\n\r\n if( this.fileListFileObject != null ) {\r\n if( this.fileListFileObject.getKey() != null && this.fileListFileObject.getKey().length() > 0 ) {\r\n setKey( this.fileListFileObject.getKey(), false );\r\n }\r\n }\r\n\r\n // if progress increased, reset runtimeSecondsWithoutProgress\r\n if( isSharedFile() && getState() == STATE_PROGRESS ) {\r\n // check if progress changed, maybe reset\r\n if( oldDoneBlocks != getDoneBlocks() ) {\r\n // progress changed\r\n oldDoneBlocks = getDoneBlocks();\r\n resetRuntimeSecondsWithoutProgress();\r\n }\r\n }\r\n\r\n // remaining values are dynamically fetched from FrostFileListFileObject\r\n super.fireChange();\r\n }\r\n\r\n /**\r\n * Builds a global queue identifier.\r\n */\r\n private String buildGqIdentifier(final String filename) {\r\n return new StringBuilder()\r\n .append(\"Frost-\")\r\n .append(filename.replace(' ', '_'))\r\n .append(\"-\")\r\n .append(System.currentTimeMillis())\r\n .append(Core.getCrypto().getSecureRandom().nextInt(10)) // 0-9\r\n .toString();\r\n }\r\n\r\n public String getErrorCodeDescription() {\r\n return errorCodeDescription;\r\n }\r\n public void setErrorCodeDescription(final String errorCodeDescription) {\r\n this.errorCodeDescription = errorCodeDescription;\r\n }\r\n\r\n /**\r\n * @return true if this item is an external global queue item\r\n */\r\n public boolean isExternal() {\r\n return isExternal;\r\n }\r\n public void setExternal(final boolean e) {\r\n isExternal = e;\r\n }\r\n\r\n public boolean isDirect() {\r\n return isDirect;\r\n }\r\n public void setDirect(final boolean d) {\r\n isDirect = d;\r\n super.fireChange();\r\n }\r\n\r\n public FreenetPriority getPriority() {\r\n return priority;\r\n }\r\n \r\n public void setPriority(final FreenetPriority priority) {\r\n this.priority = priority;\r\n super.fireChange();\r\n }\r\n\r\n /**\r\n * @return true if the remove of this request was expected and item should not be removed from the table\r\n */\r\n public boolean isInternalRemoveExpected() {\r\n return internalRemoveExpected;\r\n }\r\n /**\r\n * Set to true if we restart a download (code=11 or 27).\r\n * onPersistentRequestRemoved method checks this and does not remove the request\r\n * from the table if the remove was expected.\r\n */\r\n public void setInternalRemoveExpected(final boolean internalRemoveExpected) {\r\n this.internalRemoveExpected = internalRemoveExpected;\r\n if( isSharedFile() && internalRemoveExpected ) {\r\n resetRuntimeSecondsWithoutProgress();\r\n }\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return getFileName();\r\n }\r\n\r\n public boolean isLoggedToFile() {\r\n return isLoggedToFile;\r\n }\r\n \r\n public boolean isTracked() {\r\n return isTracked;\r\n }\r\n\r\n public void setLoggedToFile(final boolean isLoggedToFile) {\r\n this.isLoggedToFile = isLoggedToFile;\r\n }\r\n \r\n public void setTracked(final boolean isTracked) {\r\n this.isTracked = isTracked;\r\n }\r\n\r\n /**\r\n * @return the runtime of this download item in seconds\r\n */\r\n public synchronized int getRuntimeSecondsWithoutProgress() {\r\n return runtimeSecondsWithoutProgress;\r\n }\r\n\r\n /**\r\n * Sets runtimeSeconds to 0.\r\n */\r\n public synchronized void resetRuntimeSecondsWithoutProgress() {\r\n runtimeSecondsWithoutProgress = 0;\r\n // FIXME: called when download made progress, maybe remember last progress time\r\n }\r\n\r\n /**\r\n * Adds the specified amount of seconds to the value\r\n */\r\n public synchronized void addToRuntimeSecondsWithoutProgress(final int s) {\r\n runtimeSecondsWithoutProgress += s;\r\n }\r\n\r\n public int getOldDoneBlocks() {\r\n return oldDoneBlocks;\r\n }\r\n\r\n public boolean isStateShouldBeProgress() {\r\n return stateShouldBeProgress;\r\n }\r\n\r\n public String getAssociatedMessageId() {\r\n\t\treturn associatedMessageId;\r\n\t}\r\n\r\n public void setAssociatedMessageId(final String messageId) {\r\n\t\tassociatedMessageId = messageId;\r\n\t}\r\n\r\n\tpublic String getAssociatedBoardName() {\r\n\t\treturn associatedBoardName;\r\n\t}\r\n\r\n\tpublic void setAssociatedBoardName(final String boardName) {\r\n\t\tassociatedBoardName = boardName;\r\n\t}\r\n\r\n public void associateWithFrostMessageObject(FrostMessageObject associatedFrostMessageObject) {\r\n \tassociatedBoardName = associatedFrostMessageObject.getBoard().getName();\r\n \tassociatedMessageId = associatedFrostMessageObject.getMessageId();\r\n }\r\n\r\n public boolean isCompletionProgRun() {\r\n return isCompletionProgRun;\r\n }\r\n\r\n public void setCompletionProgRun(final boolean isCompletionProgRun) {\r\n this.isCompletionProgRun = isCompletionProgRun;\r\n }\r\n}\r", "answers": [" sharedFileObject = FileListStorage.inst().getFileBySha(fileListFileSha);\r"], "length": 3293, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "0b9e95e7-0ec6-416d-ab35-75d910773d72", "reasoning": "The method toFrostDownloadItem begins by declaring a variable sharedFileObject and then checks if fileListFileSha is non‑null and non‑empty. The logical next step is to retrieve the corresponding FrostFileListFileObject from the storage using that SHA. In the codebase the storage singleton is accessed via FileListStorage.inst() and provides a getFileBySha method. Therefore the next line should assign the result of that call to sharedFileObject.", "reasoning_model_answer": "sharedFileObject = FileListStorage.inst().getFileBySha(fileListFileSha);", "assistant_with_reasoning": "\nThe method toFrostDownloadItem begins by declaring a variable sharedFileObject and then checks if fileListFileSha is non‑null and non‑empty. The logical next step is to retrieve the corresponding FrostFileListFileObject from the storage using that SHA. In the codebase the storage singleton is accessed via FileListStorage.inst() and provides a getFileBySha method. Therefore the next line should assign the result of that call to sharedFileObject.\n\nsharedFileObject = FileListStorage.inst().getFileBySha(fileListFileSha);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.409, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 35560, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "sharedFileObject = FileListStorage.inst().getFileBySha(fileListFileSha);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport app.controller.deserializer.CampDeserializer;\nimport app.controller.deserializer.EnquiryDeserializer;\nimport app.controller.deserializer.SuggestionDeserializer;\nimport app.controller.deserializer.UserDeserializer;\nimport app.entity.camp.CampList;\nimport app.entity.enquiry.EnquiryList;\nimport app.entity.suggestion.SuggestionList;\nimport app.entity.user.UserList;\nimport app.utils.CSV;\nimport app.consts.Config;", "context": "src/app/entity/RepositoryCollection.java\npackage app.entity;\n\n\n\n/**\n * The {@code RepositoryCollection} class provides a central collection of\n * repositories for users, camps, enquiries, and suggestions.\n * It handles loading and saving data to CSV files using deserializers and CSV\n * utilities.\n */\npublic class RepositoryCollection {\n\n /**\n * The repository for user objects.\n */\n private static UserList userRepository;\n\n /**\n * The repository for camp objects.\n */\n private static CampList campRepository;\n\n /**\n * The repository for enquiry objects.\n */\n private static EnquiryList enquiryRepository;\n\n /**\n * The repository for suggestion objects.\n */\n private static SuggestionList suggestionRepository;\n\n /**\n * Private constructor to prevent instantiation.\n */\n private RepositoryCollection() {\n }\n\n /**\n * Loads data from CSV files into the repositories using deserializers.\n */\n public static void load() {\n ArrayList> userData = CSV.importFromCSV(Config.USER_REPOSITORY_PATH);\n ArrayList> campData = CSV.importFromCSV(Config.CAMP_REPOSITORY_PATH);\n ArrayList> enquiryData = CSV.importFromCSV(Config.ENQUIRY_REPOSITORY_PATH);\n ArrayList> suggestionData = CSV.importFromCSV(Config.SUGGESTION_REPOSITORY_PATH);\n\n userRepository = UserDeserializer.deserialize(userData);\n campRepository = CampDeserializer.deserialize(campData, userRepository);\n enquiryRepository = EnquiryDeserializer.deserialize(enquiryData, userRepository, campRepository);\n suggestionRepository = SuggestionDeserializer.deserialize(suggestionData, userRepository, campRepository);\n }\n\n /**\n * Saves data from the repositories to CSV files.\n */\n public static void save() {\n CSV.exportToCSV(Config.USER_REPOSITORY_PATH, userRepository);\n\nsrc/app/controller/deserializer/UserDeserializer.java\npublic class UserDeserializer {\n\n /**\n * Private constructor to prevent instantiation.\n */\n private UserDeserializer() {\n }\n\n /**\n * Deserializes the provided data into a UserList object containing User\n * entities.\n *\n * @param data The data to deserialize, represented as an ArrayList of\n * ArrayLists of Strings.\n * @return A UserList object populated with deserialized user data.\n */\n public static UserList deserialize(ArrayList> data) {\n UserList cur = new UserList();\n data.forEach(record -> {\n // Extracting data from the record to create a User object\n // id, name, password, faculty, type, points\n String id = record.get(0);\n String name = record.get(1);\n String password = record.get(2);\n String faculty = record.get(3);\n int type = Integer.parseInt(record.get(4));\n\n String typeName = (type == 1) ? \"Staff\" : \"Student\";\n\n String pointsRaw = record.get(5);\n\n // Creating a User object based on the extracted data\n User user = UserFactory.getUser(typeName, id, name, faculty);\n\n // Checking if the user is an instance of Student to set points\n if (user instanceof Student) {\n ((Student) user).setPoints(Integer.parseInt(pointsRaw));\n }\n\n // Adding the user to the UserList if it's not null\n if (user != null) {\n user.setPassword(password);\n cur.add(user);\n // add to UserList which extends Repository List\n }\n\n cur.add(user);\n });\n\n return cur;\n\n }\n}\n\nsrc/app/controller/deserializer/SuggestionDeserializer.java\npublic class SuggestionDeserializer {\n\n /**\n * Private constructor to prevent instantiation.\n */\n private SuggestionDeserializer() {\n }\n\n /**\n * Deserializes the provided data into a SuggestionList object.\n *\n * @param data The data to deserialize, represented as an ArrayList of\n * ArrayLists of Strings.\n * @param userList The UserList containing user information to associate with\n * suggestions.\n * @param campList The CampList containing camp information to associate with\n * suggestions.\n * @return A SuggestionList object populated with deserialized suggestion data.\n */\n\n public static SuggestionList deserialize(ArrayList> data, UserList userList, CampList campList) {\n\n SuggestionList cur = new SuggestionList();\n\n data.forEach(record -> {\n // id, senderID, campSuggestionString, reviewedByID, status 0/1/2\n String id = record.get(0);\n String senderID = record.get(1);\n UserList senderTmp = userList.filterByID(senderID);\n Student sender = null;\n if (senderTmp.size() > 0 && senderTmp.get(0) instanceof Student) {\n sender = (Student) senderTmp.get(0);\n }\n\n String campSuggestionRaw = record.get(2);\n\n // id;name;desc;visibility\n // 0/1;startDate;endDate;closeRegDate;school;location\n\n String[] campSuggestionArr = campSuggestionRaw.split(\";\", -1);\n\n String campSuggestionID = campSuggestionArr[0];\n String name = campSuggestionArr[1] != \"\" ? campSuggestionArr[1] : null;\n String desc = campSuggestionArr[2] != \"\" ? campSuggestionArr[2] : null;\n String visibilityRaw = campSuggestionArr[3];\n Boolean visibility = campSuggestionArr[3] != \"\" ? (visibilityRaw == \"0\" ? false : true) : null;\n Date startDate = campSuggestionArr[4] != \"\" ? new Date(Long.parseLong(campSuggestionArr[4])) : null;\n Date endDate = campSuggestionArr[5] != \"\" ? new Date(Long.parseLong(campSuggestionArr[5])) : null;\n Date closeRegDate = campSuggestionArr[6] != \"\" ? new Date(Long.parseLong(campSuggestionArr[6])) : null;\n String school = campSuggestionArr[7] != \"\" ? campSuggestionArr[7] : null;\n String location = campSuggestionArr[8] != \"\" ? campSuggestionArr[8] : null;\n Integer totalSlots = campSuggestionArr[9] != \"\" ? Integer.parseInt(campSuggestionArr[9]) : null;\n Integer totalCommitteeSlots = campSuggestionArr[10] != \"\" ? Integer.parseInt(campSuggestionArr[10]) : null;\n\n CampDetails campDetails = new CampDetails(campSuggestionID, name, desc,\n visibility, startDate, endDate, closeRegDate, school,\n location, totalSlots, totalCommitteeSlots);\n\n String reviewedByID = record.get(3);\n UserList reviewedByTmp = userList.filterByID(reviewedByID);\n Staff reviewedBy = null;\n if (reviewedByTmp.size() > 0) {\n reviewedBy = (Staff) reviewedByTmp.get(0);\n }\n\n String statusRaw = record.get(4);\n SuggestionStatus status = statusRaw.equals(\"0\") ? SuggestionStatus.PENDING\n : statusRaw.equals(\"1\") ? SuggestionStatus.APPROVED : SuggestionStatus.REJECTED;\n\n Camp originalCamp = campList.filterByID(campSuggestionID).get(0);\n Suggestion suggestion = new Suggestion(id, sender, campDetails, originalCamp, reviewedBy, status);\n\n cur.add(suggestion);\n });\n\n // Creates references to other app.entity\n cur.forEach(suggestion -> {\n if (suggestion.getSender() != null) {\n suggestion.getSender().addSuggestion(suggestion);\n }\n\n if (suggestion.getOriginalCamp() != null) {\n suggestion.getOriginalCamp().addSuggestion(suggestion);\n }\n });\n\n return cur;\n }\n}\n\nsrc/app/entity/enquiry/EnquiryList.java\npublic class EnquiryList extends RepositoryList implements IFilterableByID,\n IFilterableByCamp, IFilterableByStatus, IFilterableBySender,\n IFilterableByAnsweredBy {\n /**\n * Constructs a new EnquiryList with the specified list of enquiries.\n *\n * @param all A list of Enquiry objects to be managed.\n */\n public EnquiryList(List all) {\n super(all);\n }\n\n /**\n * Constructs an empty EnquiryList.\n */\n public EnquiryList() {\n super();\n }\n\n /**\n * Filters the list of enquiries by a specific ID.\n *\n * @param id The ID to filter by.\n * @return A new EnquiryList containing enquiries that match the given ID.\n */\n public EnquiryList filterByID(String id) {\n EnquiryList result = new EnquiryList();\n for (Enquiry enquiry : super.all) {\n if (enquiry.getID().equals(id)) {\n result.add(enquiry);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of enquiries by a specific camp.\n *\n * @param camp The camp to filter by.\n * @return A new EnquiryList containing enquiries that match the given camp.\n */\n public EnquiryList filterByCamp(Camp camp) {\n EnquiryList result = new EnquiryList();\n for (Enquiry enquiry : super.all) {\n if (enquiry.getCamp().equals(camp)) {\n result.add(enquiry);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of enquiries by a specific status.\n *\n * @param status The status to filter by.\n * @return A new EnquiryList containing enquiries that match the given status.\n */\n public EnquiryList filterByStatus(Boolean status) {\n EnquiryList result = new EnquiryList();\n for (Enquiry enquiry : super.all) {\n if ((enquiry.getAnsweredBy() == null) != status) {\n result.add(enquiry);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of enquiries by a specific sender.\n *\n * @param sender The sender to filter by.\n * @return A new EnquiryList containing enquiries that match the given sender.\n */\n public EnquiryList filterBySender(User sender) {\n EnquiryList result = new EnquiryList();\n for (Enquiry enquiry : super.all) {\n if (enquiry.getSender().equals(sender)) {\n result.add(enquiry);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of enquiries by a specific user who answered the enquiry.\n *\n * @param answeredBy The user who answered the enquiry to filter by.\n * @return A new EnquiryList containing enquiries that match the given user who\n * answered the enquiry.\n */\n public EnquiryList filterByAnsweredBy(User answeredBy) {\n EnquiryList result = new EnquiryList();\n for (Enquiry enquiry : super.all) {\n if (enquiry.getAnsweredBy() != null && enquiry.getAnsweredBy().equals(answeredBy)) {\n result.add(enquiry);\n }\n }\n return result;\n }\n\n /**\n * Converts the EnquiryList to an array of Enquiry objects.\n *\n * @return An array of Enquiry objects.\n */\n public Enquiry[] toArray() {\n return super.all.toArray(new Enquiry[super.all.size()]);\n }\n\n public ArrayList> serialize() {\n ArrayList> result = new ArrayList>();\n\n super.all.forEach(enquiryRaw -> {\n Enquiry camp = enquiryRaw;\n ArrayList record = new ArrayList();\n // id, senderID, question, answer, campID, answeredByID\n String senderID = camp.getSender().getID();\n String answeredByID = (camp.getAnsweredBy() == null) ? \"\" : camp.getAnsweredBy().getID();\n String campID = camp.getCamp().getID();\n\n record.add(camp.getID());\n record.add(senderID);\n record.add(camp.getQuestion());\n record.add(camp.getAnswer());\n record.add(campID);\n record.add(answeredByID);\n\n result.add(record);\n\n });\n\n return result;\n }\n\n}\n\nsrc/app/entity/user/UserList.java\npublic class UserList extends RepositoryList implements IFilterableByID, IFilterableBySchool {\n\n /**\n * Constructs a UserList object with the specified list of users.\n *\n * @param all The list of users to be included in the user list.\n */\n public UserList(List all) {\n super(all);\n }\n\n /**\n * Constructs an empty UserList object.\n */\n public UserList() {\n super();\n }\n\n /**\n * Filters the user list by the specified user ID.\n *\n * @param id The user ID to filter by.\n * @return A UserList containing users with the specified ID.\n */\n public UserList filterByID(String id) {\n UserList result = new UserList();\n for (User user : super.all) {\n if (user.getID().equals(id)) {\n result.add(user);\n }\n }\n return result;\n }\n\n public UserList filterBySchool(String school){\n UserList result = new UserList();\n for(User user: super.all){\n if(Objects.equals(user.getSchool(), school)){\n result.add(user);\n }\n }\n return result;\n }\n\n /**\n * Converts the user list to an array of users.\n *\n * @return An array of users.\n */\n public User[] toArray() {\n return super.all.toArray(new User[super.all.size()]);\n }\n\n /**\n * Checks if the user list is empty.\n *\n * @return {@code true} if the user list is empty, {@code false} otherwise.\n */\n public boolean isEmpty() {\n return super.all.isEmpty();\n }\n\n /**\n * Serializes the user list and represents its data as an ArrayList of ArrayList of Strings.\n *\n * @return An {@code ArrayList>} representing the serialized data of the user list.\n */\n public ArrayList> serialize() {\n ArrayList> result = new ArrayList>();\n all.forEach(userRaw -> {\n User user = userRaw;\n ArrayList record = new ArrayList();\n String userType = (user instanceof Staff) ? \"1\" : \"0\";\n String pointString = (user instanceof Student) ? Integer.toString(((Student) user).getPoints()) : \"0\";\n record.add(user.getID());\n record.add(user.getName());\n record.add(user.getPassword());\n record.add(user.getSchool());\n record.add(userType);\n record.add(pointString);\n\n result.add(record);\n });\n\n return result;\n }\n}\n\nsrc/app/entity/camp/CampList.java\npublic class CampList extends RepositoryList implements IFilterableByID, IFilterableByDateRange,\n IFilterableBySchool, IFilterableByVisibility, ISortableByEndDate, ISortableByID,\n ISortableByLocation, ISortableByName, ISortableByRegistrationCloseDate,\n ISortableByStartingDate, IFilterableByAttendee, IFilterableByCampCommittee,\n IFilterableByStudent {\n /**\n * Constructs a new CampList with the specified list of camps.\n *\n * @param all A list of Camp objects to be managed.\n */\n public CampList(List all) {\n super(all);\n }\n\n /**\n * Constructs an empty CampList.\n */\n public CampList() {\n super();\n }\n\n /**\n * Filters the list of camps by the specified ID.\n *\n * @param id The ID to filter by.\n * @return A new CampList containing camps that match the given ID.\n */\n public CampList filterByID(String id) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getID().equals(id)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by the specified school.\n *\n * @param school The school to filter by.\n * @return A new CampList containing camps associated with the given school.\n */\n public CampList filterBySchool(String school) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getSchool().equals(school)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by their visibility status.\n *\n * @param visible The visibility status to filter by.\n * @return A new CampList containing camps with the specified visibility status.\n */\n public CampList filterByVisibility(boolean visible) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.isVisible() == visible) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps within a specific date range.\n *\n * @param startDate The start date of the range.\n * @param endDate The end date of the range.\n * @return A new CampList containing camps within the specified date range.\n */\n public CampList filterByDateRange(Date startDate, Date endDate) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getStartDate().compareTo(startDate) >= 0 && camp.getEndDate().compareTo(endDate) <= 0) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by registration date.\n *\n * @param currentDate The date to compare registration dates against.\n * @return A new CampList containing camps whose registration date is on or\n * after the specified date.\n */\n public CampList filterByRegistrationDate(Date currentDate) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getCloseRegistrationDate().compareTo(currentDate) >= 0) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by a specific student attendee.\n *\n * @param student The student to filter by.\n * @return A new CampList containing camps that the given student is attending.\n */\n public CampList filterByStudent(Student student) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getAttendees().contains(student)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by a specific staff member in charge.\n *\n * @param staff The staff member to filter\n * by.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffsssssssssssssssssssssssssssssssssssssssssssss\n * @return A new CampList containing camps managed by the given staff member.\n */\n public CampList filterByStaff(Staff staff) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getStaffInCharge().equals(staff)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n public CampList filterByCampCommittee(Student student) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getCommittees().contains(student)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n public CampList filterByAttendee(Student attendee) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getAttendees().contains(attendee)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Sorts the list of camps by their names.\n *\n * @return A new CampList sorted by camp names.\n */\n public CampList sortByName() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator comparator = new Comparator() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getName().compareTo(o2.getName());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their registration close dates.\n *\n * @return A new CampList sorted by camp registration close dates.\n */\n public CampList sortByRegistrationCloseDate() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator comparator = new Comparator() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getCloseRegistrationDate().compareTo(o2.getCloseRegistrationDate());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their starting dates.\n *\n * @return A new CampList sorted by camp starting dates.\n */\n public CampList sortByStartingDate() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator comparator = new Comparator() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getStartDate().compareTo(o2.getStartDate());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their end dates.\n *\n * @return A new CampList sorted by camp end dates.\n */\n public CampList sortByEndDate() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator comparator = new Comparator() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getEndDate().compareTo(o2.getEndDate());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their locations.\n *\n * @return A new CampList sorted by camp locations.\n */\n public CampList sortByLocation() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator comparator = new Comparator() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getLocation().compareTo(o2.getLocation());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their IDs.\n *\n * @return A new CampList sorted by camp IDs.\n */\n public CampList sortByID() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator comparator = new Comparator() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getID().compareTo(o2.getID());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Returns all camps in the list.\n *\n * @return This CampList.\n */\n public CampList getAll() {\n return this;\n }\n\n /**\n * Converts the CampList to an array of Camp objects.\n *\n * @return An array of Camp objects.\n */\n public Camp[] toArray() {\n return super.all.toArray(new Camp[super.all.size()]);\n }\n\n public ArrayList> serialize() {\n\n ArrayList> result = new ArrayList>();\n super.all.forEach(campRaw -> {\n Camp camp = (Camp) campRaw;\n // id, name, desc, visibility (0/1), startDate, endDate, closeRegDate, school,\n ArrayList record = new ArrayList();\n String visibility = (camp.isVisible()) ? \"1\" : \"0\";\n String startDate = Long.toString(camp.getStartDate().getTime());\n String endDate = Long.toString(camp.getEndDate().getTime());\n String closeRegDate = Long.toString(camp.getCloseRegistrationDate().getTime());\n\n String staffID = camp.getStaffInCharge().getID();\n\n List attendeeIDsTemp = new ArrayList();\n for (Student attendee : camp.getAttendees()) {\n attendeeIDsTemp.add(attendee.getID());\n }\n String attendeeIDs = String.join(\";\", attendeeIDsTemp);\n\n List committeeIDsTemp = new ArrayList();\n for (Student committee : camp.getCommittees()) {\n committeeIDsTemp.add(committee.getID());\n }\n String committeeIDs = String.join(\";\", committeeIDsTemp);\n\n List registeredIDsTemp = new ArrayList();\n for (Student registered : camp.getRegisteredStudents()) {\n registeredIDsTemp.add(registered.getID());\n }\n String registeredIDs = String.join(\";\", registeredIDsTemp);\n\n record.add(camp.getID());\n record.add(camp.getName());\n record.add(camp.getDescription());\n record.add(visibility);\n record.add(startDate);\n record.add(endDate);\n record.add(closeRegDate);\n record.add(camp.getSchool());\n record.add(camp.getLocation());\n record.add(staffID);\n record.add(attendeeIDs);\n record.add(committeeIDs);\n record.add(registeredIDs);\n record.add(Integer.toString(camp.getTotalSlots()));\n record.add(Integer.toString(camp.getTotalCommitteeSlots()));\n\n result.add(record);\n\n });\n\n return result;\n }\n\n}", "answers": [" CSV.exportToCSV(Config.CAMP_REPOSITORY_PATH, campRepository);"], "length": 2597, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "7e63be69-c541-4968-b180-7a3a2211090d", "reasoning": "In RepositoryCollection.save(), after exporting the user repository, the method should continue exporting the remaining repositories (camp, enquiry, suggestion) to their respective CSV files, mirroring the load() method. The next logical line is the export of the camp repository.", "reasoning_model_answer": "CSV.exportToCSV(Config.CAMP_REPOSITORY_PATH, campRepository);", "assistant_with_reasoning": "\nIn RepositoryCollection.save(), after exporting the user repository, the method should continue exporting the remaining repositories (camp, enquiry, suggestion) to their respective CSV files, mirroring the load() method. The next logical line is the export of the camp repository.\n\nCSV.exportToCSV(Config.CAMP_REPOSITORY_PATH, campRepository);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.92, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 26672, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "CSV.exportToCSV(Config.CAMP_REPOSITORY_PATH, campRepository);", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import app.controller.camp.CampSuggestionController;\nimport app.entity.RepositoryCollection;\nimport app.entity.camp.Camp;\nimport app.entity.camp.CampDetails;\nimport app.entity.suggestion.Suggestion;\nimport app.entity.user.Student;\nimport app.ui.camp.infomationview.OverlayCampInfoDisplayWithParticipantsView;\nimport app.ui.widgets.WidgetButton;\nimport app.ui.windows.ICallBack;\nimport app.ui.windows.Window;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;", "context": "src/app/ui/camp/suggestionview/OverlayCampInfoDisplayWithParticipantsViewSuggestion.java\npackage app.ui.camp.suggestionview;\n\n\n\n/**\n * Represents an overlay view displaying camp details with the ability to suggest modifications.\n * Extends the OverlayCampInfoDisplayWithParticipantsView class.\n */\npublic class OverlayCampInfoDisplayWithParticipantsViewSuggestion extends OverlayCampInfoDisplayWithParticipantsView {\n\n protected Camp camp;\n protected Student student;\n protected Window mainWindow;\n protected WidgetButton submitButton;\n protected Suggestion editSuggestion;\n\n /**\n * Constructs an OverlayCampInfoDisplayWithParticipantsViewSuggestion object.\n * @param x The x-coordinate position of the view.\n * @param y The y-coordinate position of the view.\n * @param offsetY The offset value for the y-coordinate.\n * @param offsetX The offset value for the x-coordinate.\n * @param windowName The name of the window.\n * @param camp The camp for which suggestions are displayed.\n * @param student The student user making the suggestion.\n * @param mainWindow The main window where this overlay view is displayed.\n * @param suggestion The suggestion object containing modification details.\n */\n public OverlayCampInfoDisplayWithParticipantsViewSuggestion(int x, int y, int offsetY, int offsetX, String windowName, Camp camp,\n Student student, Window mainWindow, Suggestion suggestion) {\n super(x, y, offsetY, offsetX, windowName, camp);\n this.student = student;\n this.mainWindow = mainWindow;\n this.camp = camp;\n this.editSuggestion = suggestion;\n submitButton = new WidgetButton(3, 20 + getLenY() / 2, getLenX() - 10, \"Submit Suggestion\");\n addWidget(submitButton);\n removeWidget(exitButton);\n addWidget(exitButton);\n textBoxVis.setHide(true);\n textBoxVis.setSkipSelection(true);\n if (suggestion != null && suggestion.getSuggestion() != null) {\n SimpleDateFormat ft = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");\n\n // Name\n if (suggestion.getSuggestion().getName() != null) {\n textBoxCName.setText(suggestion.getSuggestion().getName());\n }\n\n // Description\n if (suggestion.getSuggestion().getDescription() != null) {\n textBoxDescription.setText(suggestion.getSuggestion().getDescription());\n }\n\n // Start Date\n if (suggestion.getSuggestion().getStartDate() != null) {\n textBoxDStart.setText(ft.format(suggestion.getSuggestion().getStartDate()));\n }\n\n // End Date\n if (suggestion.getSuggestion().getEndDate() != null) {\n textBoxDEnd.setText(ft.format(suggestion.getSuggestion().getEndDate()));\n }\n\n // Registration Close\n if (suggestion.getSuggestion().getCloseRegistrationDate() != null) {\n textBoxDClose.setText(ft.format(suggestion.getSuggestion().getCloseRegistrationDate()));\n }\n\n // Faculty (School)\n if (suggestion.getSuggestion().getSchool() != null) {\n textBoxSchool.setText(suggestion.getSuggestion().getSchool());\n }\n\n // Location\n if (suggestion.getSuggestion().getLocation() != null) {\n textBoxLocation.setText(suggestion.getSuggestion().getLocation());\n }\n\n // Slots\n if (suggestion.getSuggestion().getTotalSlots() != null) {\n textBoxSlots.setText(suggestion.getSuggestion().getTotalSlots().toString());\n }\n\n }\n\n }\n\n /**\n * Handles the message loop for suggesting camp details modifications.\n */\n\nsrc/app/entity/camp/Camp.java\npublic class Camp extends CampDetails implements ITaggedItem {\n\n protected Staff staffInCharge;\n protected Set attendees;\n protected Set committees;\n protected Set registeredStudents;\n private ArrayList suggestionList;\n private ArrayList enquiryList;\n\n public static final int MAX_COMMITTEE = 10;\n\n /**\n * Constructs a new Camp instance with specified details.\n * \n * @param ID Unique identifier for the camp.\n * @param name Name of the camp.\n * @param description Description of the camp.\n * @param visibility Visibility status of the camp.\n * @param startDate Start date of the camp.\n * @param endDate End date of the camp.\n * @param closeRegistrationDate Closing date for registration.\n * @param school School associated with the camp.\n * @param location Location of the camp.\n * @param staffInCharge Staff member in charge of the camp.\n * @param totalSlots Total number of slots available in the camp.\n * @param totalCommitteeSlots Total number of committee slots available in the camp.\n */\n public Camp(String ID, String name, String description, Boolean visibility, Date startDate, Date endDate,\n Date closeRegistrationDate,\n String school, String location, Staff staffInCharge, int totalSlots, int totalCommitteeSlots) {\n super(ID, name, description, visibility, startDate, endDate, closeRegistrationDate, school, location,\n totalSlots, totalCommitteeSlots);\n this.staffInCharge = staffInCharge;\n this.attendees = new HashSet();\n this.committees = new HashSet();\n this.registeredStudents = new HashSet();\n this.suggestionList = new ArrayList();\n this.enquiryList = new ArrayList();\n }\n\n // Example for one getter and one setter\n /**\n * Retrieves the staff member in charge of the camp.\n * \n * @return Staff The staff member in charge.\n */\n public Staff getStaffInCharge() {\n return staffInCharge;\n }\n\n public Set getAttendees() {\n return attendees;\n }\n\n public Set getAttendeesAndCommittees(){\n Set res = new HashSet<>();\n res.addAll(attendees);\n res.addAll(committees);\n return res;\n }\n\n public Set getCommittees() {\n return committees;\n }\n\n /**\n * Sets the staff member in charge of the camp.\n * \n * @param staffInCharge The staff member to be set as in charge.\n */\n public void setStaffInCharge(Staff staffInCharge) {\n this.staffInCharge = staffInCharge;\n }\n\n public void setAttendees(Set attendees) {\n this.attendees = attendees;\n }\n\n public void setCommittees(Set committees) {\n this.committees = committees;\n }\n\n /**\n * Adds a student as an attendee of the camp.\n * \n * @param attendee The student to be added as an attendee.\n * @return boolean True if the student is successfully added.\n */\n public boolean addAttendee(Student attendee) {\n if (this.attendees.size() >= this.totalSlots - MAX_COMMITTEE) {\n return false;\n }\n attendees.add(attendee);\n registeredStudents.add(attendee);\n return true;\n }\n\n /**\n * Adds a student as a committee member of the camp.\n *\n * @param committee The student to be added as a committee member.\n * @return boolean True if the student is successfully added.\n */\n public boolean addCommittee(Student committee) {\n if (this.committees.size() >= MAX_COMMITTEE) {\n return false;\n }\n committees.add(committee);\n registeredStudents.add(committee);\n return true;\n }\n\n /**\n * Removes a student from the list of attendees.\n *\n * @param attendee The student to be removed.\n * @return boolean True if the student is successfully removed.\n */\n public boolean removeAttendee(Student attendee) {\n return attendees.remove(attendee);\n }\n\n public boolean removeCommittee(Student committee) {\n return committees.remove(committee);\n }\n\n /**\n * Creates a suggestion plan based on the current state of the camp.\n * This plan can be used to suggest modifications or improvements to the camp.\n * \n * @return CampDetails A new {@code CampDetails} object representing the\n * suggestion plan.\n */\n public CampDetails createSuggestionPlan() {\n CampDetails suggestionPlan = new CampDetails();\n suggestionPlan.setID(this.ID);\n return suggestionPlan;\n }\n\n /**\n * Retrieves the list of suggestions for the camp.\n *\n * @return The list of suggestions.\n */\n public ArrayList getSuggestionList() {\n return suggestionList;\n }\n\n /**\n * Retrieves the list of enquiries for the camp.\n *\n * @return The list of enquiries.\n */\n public ArrayList getEnquiryList() {\n return enquiryList;\n }\n\n /**\n * Adds a suggestion to the list of suggestions.\n *\n * @param suggestion The suggestion to be added.\n */\n public void addSuggestion(Suggestion suggestion) {\n suggestionList.add(suggestion);\n }\n\n /**\n * Adds an enquiry to the list of enquiries.\n *\n * @param enquiry The enquiry to be added.\n */\n public void addEnquiry(Enquiry enquiry) {\n enquiryList.add(enquiry);\n }\n\n /**\n * Removes a suggestion from the list of suggestions.\n *\n * @param suggestion The suggestion to be removed.\n */\n public void removeSuggestion(Suggestion suggestion) {\n suggestionList.remove(suggestion);\n }\n\n /**\n * Removes an enquiry from the list of enquiries.\n *\n * @param enquiry The enquiry to be removed.\n */\n public void removeEnquiry(Enquiry enquiry) {\n enquiryList.remove(enquiry);\n }\n\n /**\n * Checks if a student is registered in the camp.\n *\n * @param student The student to check for registration.\n * @return True if the student is registered, false otherwise.\n */\n public boolean isStudentRegistered(Student student) {\n return registeredStudents.contains(student);\n }\n\n /**\n * Adds a student to the list of registered students (used for deserialize\n * only).\n *\n * @param student The student to be added.\n */\n public void addRegisteredStudent(Student student) {\n registeredStudents.add(student);\n }\n\n /**\n * Retrieves the list of previously registered students.\n */\n public Set getRegisteredStudents() {\n return registeredStudents;\n }\n}\n\nsrc/app/entity/camp/CampDetails.java\npublic class CampDetails extends CampList implements ITaggedItem {\n protected String ID;\n protected String name;\n protected String description;\n protected Boolean visibility;\n protected Date startDate;\n protected Date endDate;\n protected Date closeRegistrationDate;\n protected String school;\n protected String location;\n protected Integer totalSlots;\n protected Integer totalCommitteeSlots;\n\n /**\n * Constructs a new CampDetails object with specified details.\n *\n * @param ID The unique identifier of the camp.\n * @param name The name of the camp.\n * @param description A description of the camp.\n * @param visibility The visibility status of the camp.\n * @param startDate The start date of the camp.\n * @param endDate The end date of the camp.\n * @param closeRegistrationDate The last date to register for the camp.\n * @param school The school associated with the camp.\n * @param location The location of the camp.\n * @param totalSlots The total number of slots available in the camp.\n * @param totalCommitteeSlots The total number of committee slots available in the camp.\n */\n public CampDetails(String ID, String name, String description, boolean visibility, Date startDate, Date endDate,\n Date closeRegistrationDate,\n String school, String location, Integer totalSlots, Integer totalCommitteeSlots) {\n this.ID = ID;\n this.name = name;\n this.description = description;\n this.visibility = visibility;\n this.startDate = startDate;\n this.endDate = endDate;\n this.closeRegistrationDate = closeRegistrationDate;\n this.school = school;\n this.location = location;\n this.totalSlots = totalSlots;\n this.totalCommitteeSlots = totalCommitteeSlots;\n }\n\n /**\n * Constructs a new CampDetails object with default values.\n */\n public CampDetails() {\n this.ID = null;\n this.name = null;\n this.description = null;\n this.visibility = false;\n this.startDate = null;\n this.endDate = null;\n this.closeRegistrationDate = null;\n this.school = null;\n this.location = null;\n this.totalCommitteeSlots = null;\n }\n\n // Getters and setters for each property with appropriate Javadoc comments.\n // For example:\n\n /**\n * Returns the ID of the camp.\n *\n * @return The camp's unique identifier.\n */\n public String getID() {\n return ID;\n }\n\n /**\n * Returns the name of the camp.\n *\n * @return The camp's name.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Returns the description of the camp.\n *\n * @return The camp's description.\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * Returns the visibility status of the camp.\n *\n * @return The camp's visibility status.\n */\n public Boolean isVisible() {\n return visibility;\n }\n\n /**\n * Returns the start date of the camp.\n *\n * @return The camp's start date.\n */\n public Date getStartDate() {\n return startDate;\n }\n\n /**\n * Returns the end date of the camp.\n *\n * @return The camp's end date.\n */\n public Date getEndDate() {\n return endDate;\n }\n\n /**\n * Returns the registration closure date of the camp.\n *\n * @return The camp's registration closure date.\n */\n public Date getCloseRegistrationDate() {\n return closeRegistrationDate;\n }\n\n /**\n * Returns the school associated with the camp.\n *\n * @return The camp's associated school.\n */\n public String getSchool() {\n return school;\n }\n\n /**\n * Returns the location of the camp.\n *\n * @return The camp's location.\n */\n public String getLocation() {\n return location;\n }\n\n /**\n * Returns the total number of slots available in the camp.\n *\n * @return The camp's total number of slots.\n */\n public Integer getTotalSlots() {\n return totalSlots;\n }\n\n /**\n * Returns the total number of committee slots available in the camp.\n *\n * @return The camp's total number of committee slots.\n */\n public Integer getTotalCommitteeSlots(){\n return totalCommitteeSlots;\n }\n\n /**\n * Set the total number of committee slots available in the camp.\n *\n * @param slots The camp's total number of committee slots.\n */\n public void setTotalCommitteeSlots(int slots){\n this.totalCommitteeSlots = slots;\n }\n\n\n /**\n * Sets the ID of the camp.\n *\n * @param ID The camp's unique identifier.\n */\n public void setID(String ID) {\n this.ID = ID;\n }\n\n /**\n * Sets the name of the camp.\n *\n * @param name The camp's name.\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Sets the description of the camp.\n *\n * @param description The camp's description.\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * Sets the visibility status of the camp.\n *\n * @param visibility The camp's visibility status.\n */\n public void setVisibility(boolean visibility) {\n this.visibility = visibility;\n }\n\n /**\n * Sets the start date of the camp.\n *\n * @param startDate The camp's start date.\n */\n public void setStartDate(Date startDate) {\n this.startDate = startDate;\n }\n\n /**\n * Sets the end date of the camp.\n *\n * @param endDate The camp's end date.\n */\n public void setEndDate(Date endDate) {\n this.endDate = endDate;\n }\n\n /**\n * Sets the registration closure date of the camp.\n *\n * @param closeRegistrationDate The camp's registration closure date.\n */\n public void setCloseRegistrationDate(Date closeRegistrationDate) {\n this.closeRegistrationDate = closeRegistrationDate;\n }\n\n /**\n * Sets the school associated with the camp.\n *\n * @param school The camp's associated school.\n */\n public void setSchool(String school) {\n this.school = school;\n }\n\n /**\n * Sets the location of the camp.\n *\n * @param location The camp's location.\n */\n public void setLocation(String location) {\n this.location = location;\n }\n\n /**\n * Sets the total number of slots available in the camp.\n *\n * @param totalSlots The camp's total number of slots.\n */\n public void setTotalSlots(int totalSlots) {\n this.totalSlots = totalSlots;\n }\n\n}\n\nsrc/app/entity/suggestion/Suggestion.java\npublic class Suggestion implements ITaggedItem {\n protected String ID;\n protected Student sender;\n protected CampDetails suggestion;\n protected Camp originalCamp;\n protected Staff reviewedBy;\n protected SuggestionStatus status;\n\n /**\n * Creates a new suggestion with the given details.\n *\n * @param sender The student who made the suggestion.\n * @param suggsetion The details of the suggestion.\n * @param originalCamp The camp that the suggestion is for.\n */\n public Suggestion(Student sender, CampDetails suggsetion, Camp originalCamp) {\n // id is current timestamp in string\n this.ID = Long.toString(System.currentTimeMillis());\n this.sender = sender;\n this.suggestion = suggsetion;\n this.originalCamp = originalCamp;\n this.status = SuggestionStatus.PENDING;\n }\n\n /**\n * Creates a new suggestion with the given details.\n *\n * @param ID The unique identifier of the suggestion.\n * @param sender The student who made the suggestion.\n * @param suggestion The details of the suggestion.\n * @param originalCamp The camp that the suggestion is for.\n */\n public Suggestion(String ID, Student sender, CampDetails suggestion, Camp originalCamp) {\n // id is current timestamp in string\n this.ID = ID;\n this.sender = sender;\n this.suggestion = suggestion;\n this.originalCamp = originalCamp;\n this.status = SuggestionStatus.PENDING;\n }\n\n /**\n * Creates a new suggestion with the given details.\n *\n * @param sender The student who made the suggestion.\n * @param suggestion The details of the suggestion.\n * @param originalCamp The camp that the suggestion is for.\n * @param reviewedBy The staff member who reviewed the suggestion.\n * @param status The status of the suggestion.\n */\n public Suggestion(String ID, Student sender, CampDetails suggestion, Camp originalCamp, Staff reviewedBy,\n SuggestionStatus status) {\n this.ID = ID;\n this.sender = sender;\n this.suggestion = suggestion;\n this.originalCamp = originalCamp;\n this.reviewedBy = reviewedBy;\n this.status = status;\n }\n\n /**\n * Returns the unique identifier of the suggestion.\n *\n * @return A string representing the ID of the suggestion.\n */\n public String getID() {\n return ID;\n }\n\n /**\n * Returns the student who made the suggestion.\n *\n * @return The student who made the suggestion.\n */\n public Student getSender() {\n return sender;\n }\n\n /**\n * Returns the details of the suggestion.\n *\n * @return The details of the suggestion.\n */\n public CampDetails getSuggestion() {\n return suggestion;\n }\n\n /**\n * Returns the camp that the suggestion is for.\n *\n * @return The camp that the suggestion is for.\n */\n public Camp getOriginalCamp() {\n return originalCamp;\n }\n\n /**\n * Returns the staff member who reviewed the suggestion.\n *\n * @return The staff member who reviewed the suggestion.\n */\n public Staff getReviewedBy() {\n return reviewedBy;\n }\n\n /**\n * Returns the status of the suggestion.\n *\n * @return The status of the suggestion.\n */\n public SuggestionStatus getStatus() {\n return status;\n }\n\n /**\n * Returns the tag of the suggestion.\n *\n */\n public void setID(String ID) {\n this.ID = ID;\n }\n\n /**\n * Returns the tag of the suggestion.\n *\n */\n public void setSender(Student sender) {\n this.sender = sender;\n }\n\n /**\n * Returns the tag of the suggestion.\n *\n */\n public void setSuggestion(CampDetails suggestion) {\n this.suggestion = suggestion;\n }\n\n /**\n * Returns the tag of the suggestion.\n *\n */\n public void setOriginalCamp(Camp originalCamp) {\n this.originalCamp = originalCamp;\n }\n\n /**\n * Returns the tag of the suggestion.\n *\n */\n public void setReviewedBy(Staff reviewedBy) {\n this.reviewedBy = reviewedBy;\n }\n\n /**\n * Returns the tag of the suggestion.\n *\n */\n public void setStatus(SuggestionStatus status) {\n this.status = status;\n }\n\n /**\n * Returns the tag of the suggestion.\n *\n */\n public void setReviewedBy(Staff reviewedBy, SuggestionStatus status) {\n this.reviewedBy = reviewedBy;\n this.status = status;\n }\n}", "answers": [" public void messageLoop() {"], "length": 2521, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "56cd2825-2130-4304-8a98-1c920c09266c", "reasoning": "The class ends after the constructor and includes a comment indicating the next piece should be the method that handles the message loop for suggestions. The typical pattern is to declare a method (often overriding a parent method) named messageLoop. Therefore the next line is the method signature.", "reasoning_model_answer": "public void messageLoop() {", "assistant_with_reasoning": "\nThe class ends after the constructor and includes a comment indicating the next piece should be the method that handles the message loop for suggestions. The typical pattern is to declare a method (often overriding a parent method) named messageLoop. Therefore the next line is the method signature.\n\npublic void messageLoop() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.693, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22878, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public void messageLoop() {", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.badlogic.gdx.graphics.g2d.TextureAtlas;\nimport com.csse3200.game.components.inventory.InventoryDisplayManager;\nimport com.csse3200.game.components.placeables.FenceComponent;\nimport com.csse3200.game.components.placeables.PlaceableEvents;\nimport com.csse3200.game.components.placeables.SprinklerComponent;\nimport com.csse3200.game.entities.Entity;\nimport com.csse3200.game.entities.EntityService;\nimport com.csse3200.game.entities.EntityType;\nimport com.csse3200.game.extensions.GameExtension;\nimport com.csse3200.game.physics.PhysicsService;\nimport com.csse3200.game.physics.components.ColliderComponent;\nimport com.csse3200.game.physics.components.HitboxComponent;\nimport com.csse3200.game.physics.components.PhysicsComponent;\nimport com.csse3200.game.rendering.RenderService;\nimport com.csse3200.game.services.ResourceService;\nimport com.csse3200.game.services.ServiceLocator;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\nimport static org.junit.jupiter.api.Assertions.assertSame;\nimport static org.mockito.ArgumentMatchers.*;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;", "context": "source/core/src/test/com/csse3200/game/entities/factories/PlaceableFactoryTest.java\npackage com.csse3200.game.entities.factories;\n\n\n\n@ExtendWith(GameExtension.class)\nclass PlaceableFactoryTest {\n\n\t@BeforeEach\n\tvoid beforeEach() {\n\t\tServiceLocator.registerPhysicsService(new PhysicsService());\n\t\tServiceLocator.registerEntityService(new EntityService());\n\t\tServiceLocator.registerRenderService(new RenderService());\n\t\tServiceLocator.registerInventoryDisplayManager(new InventoryDisplayManager(null));\n\n\t\t/* Mock our ResourceService for the textures */\n\n\n\t\tResourceService mockResourceService = mock(ResourceService.class);\n\t\twhen(mockResourceService.getAsset(anyString(), any())).thenReturn(null);\n\t\tTextureAtlas mockTextureAtlas = mock(TextureAtlas.class);\n\t\twhen(mockTextureAtlas.findRegion(anyString())).thenReturn(null);\n\t\twhen(mockResourceService.getAsset(anyString(), eq(TextureAtlas.class))).thenReturn(mockTextureAtlas);\n\t\tServiceLocator.registerResourceService(mockResourceService);\n\n\t}\n\n\tvoid baseComponentsAssertion(Entity e) {\n\t\tassertNotNull(e.getComponent(PlaceableEvents.class));\n\t\tassertNotNull(e.getComponent(PhysicsComponent.class));\n\t\tassertNotNull(e.getComponent(HitboxComponent.class));\n\t\tassertNotNull(e.getComponent(ColliderComponent.class));\n\t}\n\n\t@Test\n\tvoid shouldCreateBase() {\n\t\tEntity e = PlaceableFactory.createBasePlaceable(EntityType.TRACTOR);\n\t\tthis.baseComponentsAssertion(e);\n\t}\n\n\t@Test\n\tvoid shouldCreateFence() {\n\t\tEntity e = PlaceableFactory.createFence();\n\n\t\tassertSame(EntityType.FENCE, e.getType());\n\t\tassertNotNull(e.getComponent(FenceComponent.class));\n\t\tthis.baseComponentsAssertion(e);\n\t}\n\n\t@Test\n\tvoid shouldCreateGate() {\n\t\tEntity e = PlaceableFactory.createGate();\n\n\t\tassertSame(EntityType.GATE, e.getType());\n\nsource/core/src/main/com/csse3200/game/physics/components/ColliderComponent.java\npublic class ColliderComponent extends Component {\n\tprivate static final Logger logger = LoggerFactory.getLogger(ColliderComponent.class);\n\n\tprivate final FixtureDef fixtureDef;\n\tprivate Fixture fixture;\n\n\tpublic ColliderComponent() {\n\t\tfixtureDef = new FixtureDef();\n\t}\n\n\t@Override\n\tpublic void create() {\n\t\tif (fixtureDef.shape == null) {\n\t\t\tlogger.trace(\"{} Setting default bounding box\", this);\n\t\t\tfixtureDef.shape = makeBoundingBox();\n\t\t}\n\n\t\tBody physBody = entity.getComponent(PhysicsComponent.class).getBody();\n\t\tfixture = physBody.createFixture(fixtureDef);\n\t}\n\n\t/**\n\t * Set physics as a box with a given size. Box is centered around the entity.\n\t *\n\t * @param size size of the box\n\t * @return self\n\t */\n\tpublic ColliderComponent setAsBox(Vector2 size) {\n\t\treturn setAsBox(size, entity.getCenterPosition());\n\t}\n\n\t/**\n\t * Set physics as a box with a given size. Box is aligned based on alignment.\n\t *\n\t * @param size size of the box\n\t * @param alignX how to align x relative to entity\n\t * @param alignY how to align y relative to entity\n\t * @return self\n\t */\n\tpublic ColliderComponent setAsBoxAligned(Vector2 size, AlignX alignX, AlignY alignY) {\n\t\tVector2 position = new Vector2();\n\t\tswitch (alignX) {\n\t\t\tcase LEFT:\n\t\t\t\tposition.x = size.x / 2;\n\t\t\t\tbreak;\n\t\t\tcase CENTER:\n\t\t\t\tposition.x = entity.getCenterPosition().x;\n\t\t\t\tbreak;\n\t\t\tcase RIGHT:\n\t\t\t\tposition.x = entity.getScale().x - (size.x / 2);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tswitch (alignY) {\n\t\t\tcase BOTTOM:\n\t\t\t\tposition.y = size.y / 2;\n\t\t\t\tbreak;\n\t\t\tcase CENTER:\n\t\t\t\tposition.y = entity.getCenterPosition().y;\n\t\t\t\tbreak;\n\t\t\tcase TOP:\n\t\t\t\tposition.y = entity.getScale().y - (size.y / 2);\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn setAsBox(size, position);\n\t}\n\n\t/**\n\t * Set physics as a box with a given size and local position. Box is centered around the position.\n\t *\n\t * @param size size of the box\n\t * @param position position of the box center relative to the entity.\n\t * @return self\n\t */\n\tpublic ColliderComponent setAsBox(Vector2 size, Vector2 position) {\n\t\tPolygonShape bbox = new PolygonShape();\n\t\tbbox.setAsBox(size.x / 2, size.y / 2, position, 0f);\n\t\tsetShape(bbox);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set friction. This affects the object when touching other objects, but does not affect friction\n\t * with the ground.\n\t *\n\t * @param friction friction, default = 0\n\t * @return self\n\t */\n\tpublic ColliderComponent setFriction(float friction) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.friction = friction;\n\t\t} else {\n\t\t\tfixture.setFriction(friction);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set whether this physics component is a sensor. Sensors don't collide with other objects but\n\t * still trigger collision events. See: https://www.iforce2d.net/b2dtut/sensors\n\t *\n\t * @param isSensor true if sensor, false if not. default = false.\n\t * @return self\n\t */\n\tpublic ColliderComponent setSensor(boolean isSensor) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.isSensor = isSensor;\n\t\t} else {\n\t\t\tfixture.setSensor(isSensor);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set density\n\t *\n\t * @param density Density and size of the physics component determine the object's mass. default =\n\t * 0\n\t * @return self\n\t */\n\tpublic ColliderComponent setDensity(float density) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.density = density;\n\t\t} else {\n\t\t\tfixture.setDensity(density);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set restitution\n\t *\n\t * @param restitution restitution is the 'bounciness' of an object, default = 0\n\t * @return self\n\t */\n\tpublic ColliderComponent setRestitution(float restitution) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.restitution = restitution;\n\t\t} else {\n\t\t\tfixture.setRestitution(restitution);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set shape\n\t *\n\t * @param shape shape, default = bounding box the same size as the entity\n\t * @return self\n\t */\n\tpublic ColliderComponent setShape(Shape shape) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.shape = shape;\n\t\t} else {\n\t\t\tlogger.error(\"{} Cannot set Collider shape after create(), ignoring.\", this);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return Physics fixture of this collider. Null before created()\n\t */\n\tpublic Fixture getFixture() {\n\t\treturn fixture;\n\t}\n\n\t/**\n\t * Set the collider layer, used in collision logic\n\t *\n\t * @param layerMask Bitmask of {@link PhysicsLayer} this collider belongs to\n\t * @return self\n\t */\n\tpublic ColliderComponent setLayer(short layerMask) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.filter.categoryBits = layerMask;\n\t\t} else {\n\t\t\tFilter filter = fixture.getFilterData();\n\t\t\tfilter.categoryBits = layerMask;\n\t\t\tfixture.setFilterData(filter);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return The {@link PhysicsLayer} this collider belongs to\n\t */\n\tpublic short getLayer() {\n\t\tif (fixture == null) {\n\t\t\treturn fixtureDef.filter.categoryBits;\n\t\t}\n\t\treturn fixture.getFilterData().categoryBits;\n\t}\n\n\t@Override\n\tpublic void dispose() {\n\t\tsuper.dispose();\n\t\tBody physBody = entity.getComponent(PhysicsComponent.class).getBody();\n\t\tif (physBody.getFixtureList().contains(fixture, true)) {\n\t\t\tphysBody.destroyFixture(fixture);\n\t\t}\n\t}\n\n\tprivate Shape makeBoundingBox() {\n\t\tPolygonShape bbox = new PolygonShape();\n\t\tVector2 center = entity.getScale().scl(0.5f);\n\t\tbbox.setAsBox(center.x, center.y, center, 0f);\n\t\treturn bbox;\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/services/ResourceService.java\npublic class ResourceService implements Disposable {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(ResourceService.class);\n\tprivate final AssetManager assetManager;\n\n\tpublic ResourceService() {\n\t\tthis(new AssetManager());\n\t}\n\n\t/**\n\t * Initialise this ResourceService to use the provided AssetManager.\n\t *\n\t * @param assetManager AssetManager to use in this service.\n\t * @requires assetManager != null\n\t */\n\tpublic ResourceService(AssetManager assetManager) {\n\t\tthis.assetManager = assetManager;\n\t}\n\n\t/**\n\t * Load an asset from a file.\n\t *\n\t * @param filename Asset path\n\t * @param type Class to load into\n\t * @param Type of class to load into\n\t * @return Instance of class loaded from path\n\t * @see AssetManager#get(String, Class)\n\t */\n\tpublic T getAsset(String filename, Class type) {\n\t\treturn assetManager.get(filename, type);\n\t}\n\n\t/**\n\t * Check if an asset has been loaded already\n\t *\n\t * @param resourceName path of the asset\n\t * @param type Class type of the asset\n\t * @param Type of the asset\n\t * @return true if asset has been loaded, false otherwise\n\t * @see AssetManager#contains(String)\n\t */\n\tpublic boolean containsAsset(String resourceName, Class type) {\n\t\treturn assetManager.contains(resourceName, type);\n\t}\n\n\t/**\n\t * Returns the loading completion progress as a percentage.\n\t *\n\t * @return progress\n\t */\n\tpublic int getProgress() {\n\t\treturn (int) (assetManager.getProgress() * 100);\n\t}\n\n\t/**\n\t * Blocking call to load all assets.\n\t *\n\t * @see AssetManager#finishLoading()\n\t */\n\tpublic void loadAll() {\n\t\tlogger.debug(\"Loading all assets\");\n\t\ttry {\n\t\t\tassetManager.finishLoading();\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Loads assets for the specified duration in milliseconds.\n\t *\n\t * @param duration duration to load for\n\t * @return finished loading\n\t * @see AssetManager#update(int)\n\t */\n\tpublic boolean loadForMillis(int duration) {\n\t\tlogger.debug(\"Loading assets for {} ms\", duration);\n\t\ttry {\n\t\t\treturn assetManager.update(duration);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage());\n\t\t}\n\t\treturn assetManager.isFinished();\n\t}\n\n\t/**\n\t * Clears all loaded assets and assets in the preloading queue.\n\t *\n\t * @see AssetManager#clear()\n\t */\n\tpublic void clearAllAssets() {\n\t\tlogger.debug(\"Clearing all assets\");\n\t\tassetManager.clear();\n\t}\n\n\t/**\n\t * Loads a single asset into the asset manager.\n\t *\n\t * @param assetName asset name\n\t * @param type asset type\n\t * @param type\n\t */\n\tprivate void loadAsset(String assetName, Class type) {\n\t\tlogger.debug(\"Loading {}: {}\", type.getSimpleName(), assetName);\n\t\ttry {\n\t\t\tassetManager.load(assetName, type);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"Could not load {}: {}\", type.getSimpleName(), assetName);\n\t\t}\n\t}\n\n\t/**\n\t * Loads multiple assets into the asset manager.\n\t *\n\t * @param assetNames list of asset names\n\t * @param type asset type\n\t * @param type\n\t */\n\tprivate void loadAssets(String[] assetNames, Class type) {\n\t\tfor (String resource : assetNames) {\n\t\t\tloadAsset(resource, type);\n\t\t}\n\t}\n\n\t/**\n\t * Loads a list of texture assets into the asset manager.\n\t *\n\t * @param textureNames texture filenames\n\t */\n\tpublic void loadTextures(String[] textureNames) {\n\t\tloadAssets(textureNames, Texture.class);\n\t}\n\n\t/**\n\t * Loads a list of texture atlas assets into the asset manager.\n\t *\n\t * @param textureAtlasNames texture atlas filenames\n\t */\n\tpublic void loadTextureAtlases(String[] textureAtlasNames) {\n\t\tloadAssets(textureAtlasNames, TextureAtlas.class);\n\t}\n\n\t/**\n\t * Loads a list of sounds into the asset manager.\n\t *\n\t * @param soundNames sound filenames\n\t */\n\tpublic void loadSounds(String[] soundNames) {\n\t\tloadAssets(soundNames, Sound.class);\n\t}\n\n\t/**\n\t * Loads a list of music assets into the asset manager.\n\t *\n\t * @param musicNames music filenames\n\t */\n\tpublic void loadMusic(String[] musicNames) {\n\t\tloadAssets(musicNames, Music.class);\n\t}\n\n\t/**\n\t * Loads a list of particle effect assets into the asset manager\n\t *\n\t * @param particleNames particle effect filenames\n\t */\n\tpublic void loadParticleEffects(String[] particleNames) {\n\t\tloadAssets(particleNames, ParticleEffect.class);\n\t}\n\n\tpublic void loadSkins(String[] skinNames) {\n\t\tloadAssets(skinNames, Skin.class);\n\t}\n\n\t/**\n\t * Disposes of assets and all of their dependencies from the resource manager\n\t *\n\t * @param assetNames list of asset names to dispose of\n\t */\n\tpublic void unloadAssets(String[] assetNames) {\n\t\tfor (String assetName : assetNames) {\n\t\t\tlogger.debug(\"Unloading {}\", assetName);\n\t\t\ttry {\n\t\t\t\tassetManager.unload(assetName);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\"Could not unload {}\", assetName);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Disposes of the resource service, clearing the asset manager which clears and disposes of all assets and clears\n\t * the preloading queue\n\t */\n\t@Override\n\tpublic void dispose() {\n\t\tassetManager.clear();\n\t}\n}\n\nsource/core/src/test/com/csse3200/game/extensions/GameExtension.java\npublic class GameExtension implements AfterEachCallback, BeforeAllCallback {\n\tprivate Application game;\n\n\t@Override\n\tpublic void beforeAll(ExtensionContext context) {\n\t\t// 'Headless' back-end, so no rendering happens\n\t\tgame = new HeadlessApplication(new ApplicationAdapter() {\n\t\t});\n\n\t\t// Mock any calls to OpenGL\n\t\tGdx.gl20 = Mockito.mock(GL20.class);\n\t\tGdx.gl = Gdx.gl20;\n\t}\n\n\t@Override\n\tpublic void afterEach(ExtensionContext context) {\n\t\t// Clear the global state from the service locator\n\t\tServiceLocator.clear();\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/rendering/RenderService.java\npublic class RenderService implements Disposable {\n\tprivate static final int INITIAL_LAYER_CAPACITY = 4;\n\tprivate static final int INITIAL_CAPACITY = 4;\n\tprivate Stage stage;\n\tprivate DebugRenderer debugRenderer;\n\n\t/**\n\t * Map from layer to list of renderables, allows us to render each layer in the correct order\n\t */\n\tprivate final SortedIntMap> renderables =\n\t\t\tnew SortedIntMap<>(INITIAL_LAYER_CAPACITY);\n\n\t/**\n\t * Register a new renderable.\n\t *\n\t * @param renderable new renderable.\n\t */\n\tpublic void register(Renderable renderable) {\n\t\tint layerIndex = renderable.getLayer();\n\t\tif (!renderables.containsKey(layerIndex)) {\n\t\t\trenderables.put(layerIndex, new Array<>(INITIAL_CAPACITY));\n\t\t}\n\t\tArray layer = renderables.get(layerIndex);\n\t\tlayer.add(renderable);\n\t}\n\n\t/**\n\t * Unregister a renderable.\n\t *\n\t * @param renderable renderable to unregister.\n\t */\n\tpublic void unregister(Renderable renderable) {\n\t\tArray layer = renderables.get(renderable.getLayer());\n\t\tif (layer != null) {\n\t\t\tlayer.removeValue(renderable, true);\n\t\t}\n\t}\n\n\t/**\n\t * Trigger rendering on the given batch. This should be called only from the main renderer.\n\t *\n\t * @param batch batch to render to.\n\t */\n\tpublic void render(SpriteBatch batch) {\n\t\tfor (Array layer : renderables) {\n\t\t\t// Sort into rendering order\n\t\t\tlayer.sort();\n\n\t\t\tfor (Renderable renderable : layer) {\n\t\t\t\trenderable.render(batch);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setStage(Stage stage) {\n\t\tthis.stage = stage;\n\t}\n\n\tpublic Stage getStage() {\n\t\treturn stage;\n\t}\n\n\tpublic void setDebug(DebugRenderer debugRenderer) {\n\t\tthis.debugRenderer = debugRenderer;\n\t}\n\n\tpublic DebugRenderer getDebug() {\n\t\treturn debugRenderer;\n\t}\n\n\t@Override\n\tpublic void dispose() {\n\t\trenderables.clear();\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/physics/PhysicsService.java\npublic class PhysicsService {\n\tprivate final PhysicsEngine engine;\n\n\tpublic PhysicsService() {\n\t\tthis(new PhysicsEngine());\n\t}\n\n\tpublic PhysicsService(PhysicsEngine engine) {\n\t\tthis.engine = engine;\n\t}\n\n\tpublic PhysicsEngine getPhysics() {\n\t\treturn engine;\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/physics/components/HitboxComponent.java\npublic class HitboxComponent extends ColliderComponent {\n\t@Override\n\tpublic void create() {\n\t\tsetSensor(true);\n\t\tsuper.create();\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/entities/EntityType.java\npublic enum EntityType {\n\tPLAYER(0),\n\tTRACTOR(0),\n\tPLANT(10),\n\tDECAYING_PLANT(-10),\n\tTILE(0), // This is team 7 stuff\n\tCOW(0),\n\tCHICKEN(0),\n\tASTROLOTL(0),\n\tOXYGEN_EATER(-10),\n\tDRAGONFLY(0),\n\tBAT(0),\n\tITEM(0),\n\tQUESTGIVER(0),\n\tQUESTGIVER_INDICATOR(0),\n\tCHEST(0),\n\tFENCE(0),\n\tGATE(0),\n\tSPRINKLER(0),\n\tPUMP(0),\n\tLIGHT(0),\n\tSHIP(0),\n\tSHIP_DEBRIS(0),\n\tSHIP_PART_TILE(0),\n\tSHIP_EATER(0),\n\tDUMMY(0), // Used for testing\n\tFIRE_FLIES(0),\n\tGOLDEN_STATUE(0);\n\n\n\t// Negative rate for consumption, positive for production of oxygen\n\tprivate final float hourlyOxygenRate;\n\n\t/**\n\t * A parent like category for Placeable types.\n\t * Allows other Placeable entities to query if this is of the same placeable category.\n\t */\n\tprivate PlaceableCategory placeableCategory;\n\n\tEntityType(float hourlyOxygenRate) {\n\t\tthis.hourlyOxygenRate = hourlyOxygenRate;\n\t}\n\n\t/**\n\t * Getter method for the oxygen consumption/production rate\n\t * of a given entity type.\n\t *\n\t * @return the hourly oxygen rate of the entity type.\n\t */\n\tpublic float getOxygenRate() {\n\t\treturn hourlyOxygenRate;\n\t}\n\n\t/**\n\t * Getter for the placeableCategory\n\t *\n\t * @return this placeableCategory\n\t */\n\tpublic PlaceableCategory getPlaceableCategory() {\n\t\treturn placeableCategory;\n\t}\n\n\t/**\n\t * Setter for the placeableCategory\n\t *\n\t * @param placeableCategory A category that encompasses the Placeable type.\n\t */\n\tpublic void setPlaceableCategory(PlaceableCategory placeableCategory) {\n\t\tthis.placeableCategory = placeableCategory;\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/components/placeables/FenceComponent.java\npublic class FenceComponent extends Component {\n\n\tprivate ConnectedEntityUtility connectedEntityUtility;\n\n\t/**\n\t * Texture paths for different fence orientation.\n\t * The order of this array is very important, correct order ensures a fence gets the correct texture.\n\t */\n\tprivate static final String[] textures_fence = {\n\t\t\t\"images/placeable/fences/f.png\",\n\t\t\t\"images/placeable/fences/f_l.png\",\n\t\t\t\"images/placeable/fences/f_r.png\",\n\t\t\t\"images/placeable/fences/f_r_l.png\",\n\t\t\t\"images/placeable/fences/f_d.png\",\n\t\t\t\"images/placeable/fences/f_d_l.png\",\n\t\t\t\"images/placeable/fences/f_r_d.png\",\n\t\t\t\"images/placeable/fences/f_r_d_l.png\",\n\t\t\t\"images/placeable/fences/f_u.png\",\n\t\t\t\"images/placeable/fences/f_l_u.png\",\n\t\t\t\"images/placeable/fences/f_r_u.png\",\n\t\t\t\"images/placeable/fences/f_r_l_u.png\",\n\t\t\t\"images/placeable/fences/f_d_u.png\",\n\t\t\t\"images/placeable/fences/f_d_l_u.png\",\n\t\t\t\"images/placeable/fences/f_r_d_u.png\",\n\t\t\t\"images/placeable/fences/f_r_d_l_u.png\",\n\t};\n\n\tprivate static final String IMAGE_GATE_OPEN = \"images/placeable/fences/g_r_l_o.png\";\n\tprivate static final String IMAGE_GATE_DUPLICATE = \"images/placeable/fences/g_d_u_o.png\";\n\n\tprivate static final String[] textures_gate_open = {\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_DUPLICATE,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_DUPLICATE,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_DUPLICATE,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t\t\tIMAGE_GATE_OPEN,\n\t};\n\n\tprivate static final String GATE_RIGHT_LEFT_CLOSED = \"images/placeable/fences/g_r_l.png\";\n\tprivate static final String GATE_DOWN_UP_CLOSED = \"images/placeable/fences/g_d_u.png\";\n\n\tprivate static final String[] textures_gate_closed = {\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_DOWN_UP_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_DOWN_UP_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_DOWN_UP_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t\t\tGATE_RIGHT_LEFT_CLOSED,\n\t};\n\n\n\tprivate boolean isGate = false;\n\tprivate boolean isOpen = false;\n\n\tpublic FenceComponent(boolean isGate) {\n\t\tthis.isGate = isGate;\n\t}\n\n\tpublic FenceComponent() {\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic void create() {\n\t\tthis.connectedEntityUtility = new ConnectedEntityUtility(entity);\n\t\tentity.getEvents().addListener(\"onDestroy\", this::onDestroy);\n\n\t\tif (isGate) {\n\t\t\tconfigGate();\n\t\t\tentity.getEvents().addListener(\"interact\", this::toggleGate);\n\t\t\tentity.getEvents().addListener(\"reconfigure\", this::configGate);\n\t\t\tthis.connectedEntityUtility.notifyAdjacent();\n\t\t\treturn;\n\t\t}\n\n\t\tconfigFence();\n\t\tentity.getEvents().addListener(\"reconfigure\", this::configFence);\n\n\t\t// Notify all adjacent of this placement\n\t\tthis.connectedEntityUtility.notifyAdjacent();\n\t}\n\n\t/**\n\t * Sets this fence's texture orientation based off the adjacent fences.\n\t */\n\tpublic void configFence() {\n\t\t// get index into texture array based on surrounding sprinklers\n\t\tbyte orientation = this.connectedEntityUtility.getAdjacentBitmap();\n\t\t// now set the texture.\n\t\tentity.getComponent(DynamicTextureRenderComponent.class).setTexture(textures_fence[orientation]);\n\t}\n\n\t/**\n\t * Sets this gate's texture orientation based off the adjacent fences.\n\t */\n\tpublic void configGate() {\n\t\t// get index into texture array based on surrounding sprinklers\n\t\tbyte orientation = this.connectedEntityUtility.getAdjacentBitmap();\n\t\t// now set the texture.\n\t\tif (isOpen) {\n\t\t\tentity.getComponent(DynamicTextureRenderComponent.class).setTexture(textures_gate_open[orientation]);\n\t\t\treturn;\n\t\t}\n\t\tentity.getComponent(DynamicTextureRenderComponent.class).setTexture(textures_gate_closed[orientation]);\n\t}\n\n\tprivate void toggleGate() {\n\n\t\t/* Play the interact sound */\n\t\ttry {\n\t\t\tServiceLocator.getSoundService().getEffectsMusicService().play(EffectSoundFile.GATE_INTERACT);\n\t\t} catch (Exception e) {\n\t\t\t/* Catch exception when sound service not available */\n\t\t}\n\n\t\tisOpen = !isOpen;\n\n\t\tif (isOpen) {\n\t\t\tthis.entity.getComponent(ColliderComponent.class).setSensor(true);\n\t\t\tconfigGate();\n\t\t\treturn;\n\t\t}\n\t\tthis.entity.getComponent(ColliderComponent.class).setSensor(false);\n\t\t// Update our texture accordingly\n\t\tconfigGate();\n\t}\n\n\t/**\n\t * Destroys the connections to neighbouring fences or gates\n\t */\n\tprivate void onDestroy() {\n\t\tentity.getEvents().trigger(\"destroyConnections\");\n\t}\n}", "answers": ["\t\tassertNotNull(e.getComponent(FenceComponent.class));"], "length": 2302, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "d3518591-13f4-41b6-a216-7c51a4340200", "reasoning": "The test method shouldCreateGate mirrors shouldCreateFence: after checking the entity type, it verifies that the gate entity has a FenceComponent (used for gates) and then checks base components. Therefore the next line is the assertion that the FenceComponent is present.", "reasoning_model_answer": "assertNotNull(e.getComponent(FenceComponent.class));", "assistant_with_reasoning": "\nThe test method shouldCreateGate mirrors shouldCreateFence: after checking the entity type, it verifies that the gate entity has a FenceComponent (used for gates) and then checks base components. Therefore the next line is the assertion that the FenceComponent is present.\n\nassertNotNull(e.getComponent(FenceComponent.class));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.807, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22569, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "assertNotNull(e.getComponent(FenceComponent.class));", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.exc.MismatchedInputException;\nimport de.gtarc.opaca.api.RuntimePlatformApi;\nimport de.gtarc.opaca.platform.auth.JwtUtil;\nimport de.gtarc.opaca.platform.auth.TokenUserDetailsService;\nimport de.gtarc.opaca.platform.containerclient.ContainerClient;\nimport de.gtarc.opaca.platform.containerclient.DockerClient;\nimport de.gtarc.opaca.platform.containerclient.KubernetesClient;\nimport de.gtarc.opaca.platform.session.SessionData;\nimport de.gtarc.opaca.model.*;\nimport de.gtarc.opaca.util.ApiProxy;\nimport lombok.extern.java.Log;\nimport de.gtarc.opaca.util.EventHistory;\nimport org.apache.commons.lang3.RandomStringUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport jakarta.annotation.PostConstruct;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;", "context": "opaca-platform/src/main/java/de/gtarc/opaca/platform/PlatformImpl.java\npackage de.gtarc.opaca.platform;\n\n\n\n\n\n/**\n * This class provides the actual implementation of the API routes. Might also be split up\n * further, e.g. for agent-forwarding, container-management, and linking to other platforms.\n */\n@Log\n@Component\n\nopaca-model/src/main/java/de/gtarc/opaca/util/EventHistory.java\npublic class EventHistory {\n private static final EventHistory INSTANCE = new EventHistory();\n private final List events = Collections.synchronizedList(new LinkedList<>());\n\n private EventHistory() {\n }\n\n public static EventHistory getInstance() {\n return INSTANCE;\n }\n\n public void addEvent(Event entry) {\n if (entry != null) {\n events.add(entry);\n }\n }\n\n public List getEvents() {\n return List.copyOf(events);\n }\n}\n\nopaca-model/src/main/java/de/gtarc/opaca/api/RuntimePlatformApi.java\npublic interface RuntimePlatformApi extends CommonApi {\n\n /**\n * Get full information on the Runtime Platform, including all running Agent Containers and\n * Agents, connected other platforms, etc.\n *\n * REST Route: GET /info\n *\n * @return Extensive information on the platform and its containers and agents.\n */\n RuntimePlatform getPlatformInfo() throws IOException;\n\n /**\n * Get history of \"events\" that occurred in this runtime platform\n *\n * REST: GET /history\n *\n * @return list of recent events, most-recent last\n */\n List getHistory() throws IOException;\n\n /*\n * AUTHENTICATION\n */\n\n /**\n * Retrieve Access Token for given user to be passed as header for secured routes.\n *\n * REST: GET /login\n *\n * @param loginParams Bundles the username and password in the request body\n * @return JWT access token\n */\n String login(Login loginParams) throws IOException;\n\n /*\n * AGENT CONTAINER ROUTES\n */\n\n // see CommonApi.java\n\n /*\n * CONTAINER MANAGEMENT\n */\n\n /**\n * Deploy a container to the runtime Platform. Check requirements, get actual docker image, and\n * deploy to Docker/Kubernetes, then return the ID of the running Agent Container.\n *\n * REST: POST /containers\n *\n * @param container The container to start\n * @return ID of the started container\n */\n String addContainer(PostAgentContainer container) throws IOException;\n\n /**\n * Get descriptions of all currently running Agent Containers.\n *\n * REST: GET /containers\n *\n * @return List of all running containers\n */\n List getContainers() throws IOException;\n\n /**\n * Get description of a single Agent Container\n *\n * REST: GET /containers/{id}\n *\n * @param containerId ID of the container\n * @return Description of the container\n */\n AgentContainer getContainer(String containerId) throws IOException;\n\n /**\n * Remove an Agent Container from the platform.\n *\n * REST: DELETE /containers/{id}\n *\n * @param containerId ID of the container\n * @return Removal successful?\n */\n boolean removeContainer(String containerId) throws IOException;\n\n /**\n * Notify Platform of changes in one of its own containers, triggering an update by calling the /info route.\n * Can be called by the container itself, or by some other entity or the user.\n *\n * REST: POST /containers/notify\n *\n * @param containerId The ID of the container to update.\n * @return true/false depending on whether the update was successful (false = container not reachable, removed)\n */\n boolean notifyUpdateContainer(String containerId) throws IOException;\n\n /*\n * CONNECTIONS MANAGEMENT\n */\n\n /**\n * Connect this platform to another platform, running on a different host.\n * The connection will be bi-directional.\n *\n * REST: POST /connections\n *\n * @param loginConnection Stores the username, password, and url to connect to\n * @return Connection successful?\n */\n boolean connectPlatform(LoginConnection loginConnection) throws IOException;\n\n /**\n * Get list uf base-URLs of connected other Runtime Platforms\n *\n * REST: GET /connections\n *\n * @return List of base-URLs of connected Platforms\n */\n List getConnections() throws IOException;\n\n /**\n * Disconnect a previously connected Platform, in both directions.\n *\n * REST: DELETE /connections\n *\n * @param url The base-URL of the platform to disconnect.\n * @return Disconnect successful?\n */\n boolean disconnectPlatform(String url) throws IOException;\n\n /**\n * Notify Platform of changes in a connected Platform, triggering an update by calling the /info route.\n * Can be called by the platform itself, or by some other entity or the user.\n *\n * REST: POST /connections/notify\n *\n * @param platformUrl The URL of the platform to update.\n * @return true/false depending on whether the update was successful (false = platform not reachable, removed)\n */\n boolean notifyUpdatePlatform(String platformUrl) throws IOException;\n\n}\n\nopaca-platform/src/main/java/de/gtarc/opaca/platform/containerclient/ContainerClient.java\npublic interface ContainerClient {\n\n /**\n * Initialize the client using properties in the given configuration file. Different clients may\n * require different attributes.\n */\n void initialize(PlatformConfig config, SessionData SessionData);\n\n /**\n * Test connection to the Backend, e.g. Docker or Kubernetes. This is called right after initialize,\n * but made this a separate method to make it more explicit. This should raise an Exception (with\n * some details, if possible) that will then crash the Service right after the start.\n */\n void testConnectivity();\n\n /**\n * Start a container with the given container ID (for later reference) and image name. If all goes well,\n * return nothing, otherwise raise an appropriate exception.\n *\n * @return Port Mappings\n */\n AgentContainer.Connectivity startContainer(String containerId, String token, PostAgentContainer container) throws IOException, NoSuchElementException;\n\n /**\n * Stop the agent container with the given ID.\n */\n void stopContainer(String containerId) throws IOException;\n\n /**\n * Get the URL where the container can be reached for forwarding requests.\n */\n String getUrl(String containerId);\n\n}\n\nopaca-platform/src/main/java/de/gtarc/opaca/platform/auth/TokenUserDetailsService.java\n@Service\npublic class TokenUserDetailsService implements UserDetailsService {\n\n @Autowired\n private SessionData sessionData;\n\n @Autowired\n private PlatformConfig config;\n\n\n private Map userCredentials;\n\n @PostConstruct\n\tpublic void postConstruct() {\n\t\tuserCredentials = sessionData.userCredentials;\n if (userCredentials.isEmpty()) {\n addUser(config.usernamePlatform, config.passwordPlatform);\n }\n\t}\n\n /** Returns the user as a standardized 'User' object */\n @Override\n public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n if (userCredentials.containsKey(username)) {\n return new User(username, userCredentials.get(username), List.of());\n } else {\n throw new UsernameNotFoundException(\"User not found: \" + username);\n }\n }\n\n /**\n * Adding user to the credentials map. Those user credentials can be a human's credentials\n * as [username:password] or agent container credentials as [containerID:containerID].\n */\n public void addUser(String username, String password) {\n userCredentials.put(username, password);\n }\n\n public void removeUser(String username) {\n userCredentials.remove(username);\n }\n}\n\nopaca-platform/src/main/java/de/gtarc/opaca/platform/auth/JwtUtil.java\n@Service\npublic class JwtUtil {\n \n @Autowired\n private PlatformConfig config;\n\n @Autowired\n private TokenUserDetailsService tokenUserDetailsService;\n\n public String generateTokenForUser(String username, String password) {\n UserDetails userDetails = tokenUserDetailsService.loadUserByUsername(username);\n if (userDetails.getPassword().equals(password)) {\n return createToken(username, Duration.ofHours(1));\n } else {\n throw new BadCredentialsException(\"Wrong password\");\n }\n }\n\n public String generateTokenForAgentContainer(String containerId) {\n // TODO expiration date of 10 hours does not work for agent containers, should be able to run for weeks\n return createToken(containerId, Duration.ofHours(10));\n }\n\n private String createToken(String username, Duration duration) {\n return Jwts.builder().setSubject(username)\n .setIssuedAt(new Date(System.currentTimeMillis()))\n .setExpiration(new Date(System.currentTimeMillis() + duration.toMillis()))\n .signWith(SignatureAlgorithm.HS256, config.secret).compact();\n }\n\n public boolean validateToken(String token, UserDetails userDetails) {\n return (getUsernameFromToken(token).equals(userDetails.getUsername()) &&\n getExpirationDateFromToken(token).after(new Date()));\n }\n\n public String getUsernameFromToken(String token) {\n return Jwts.parser().setSigningKey(config.secret).parseClaimsJws(token).getBody().getSubject();\n }\n\n private Date getExpirationDateFromToken(String token) {\n return Jwts.parser().setSigningKey(config.secret).parseClaimsJws(token).getBody().getExpiration();\n }\n\n}\n\nopaca-platform/src/main/java/de/gtarc/opaca/platform/containerclient/DockerClient.java\n@Log\npublic class DockerClient implements ContainerClient {\n\n private PlatformConfig config;\n\n /** Client for accessing (remote) Docker runtime */\n private com.github.dockerjava.api.DockerClient dockerClient;\n\n /** additional Docker-specific information on agent containers */\n private Map dockerContainers;\n\n /** Available Docker Auth */\n private Map auth;\n\n /** Set of already used ports on target Docker host */\n private Set usedPorts;\n\n @Data\n @AllArgsConstructor\n public static class DockerContainerInfo {\n String containerId;\n AgentContainer.Connectivity connectivity;\n }\n\n @Override\n public void initialize(PlatformConfig config, SessionData sessionData) {\n this.config = config;\n\n DockerClientConfig dockerConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()\n .withDockerHost(getDockerHost())\n .build();\n\n DockerHttpClient dockerHttpClient = new ApacheDockerHttpClient.Builder()\n .dockerHost(dockerConfig.getDockerHost())\n .sslConfig(dockerConfig.getSSLConfig())\n .maxConnections(100)\n .connectionTimeout(Duration.ofSeconds(30))\n .responseTimeout(Duration.ofSeconds(45))\n .build();\n\n this.auth = loadDockerAuth();\n this.dockerClient = DockerClientImpl.getInstance(dockerConfig, dockerHttpClient);\n this.dockerContainers = sessionData.dockerContainers;\n this.usedPorts = sessionData.usedPorts;\n }\n\n @Override\n public void testConnectivity() {\n this.dockerClient.listContainersCmd().exec();\n }\n\n @Override\n public AgentContainer.Connectivity startContainer(String containerId, String token, PostAgentContainer container) throws IOException, NoSuchElementException {\n var image = container.getImage();\n var imageName = image.getImageName();\n var extraPorts = image.getExtraPorts();\n\n try {\n if (! isImagePresent(imageName)) {\n pullDockerImage(imageName);\n }\n\n // port mappings for API- and Extra-Ports\n var newPorts = new HashSet();\n Map portMap = Stream.concat(Stream.of(image.getApiPort()), extraPorts.keySet().stream())\n .collect(Collectors.toMap(p -> p, p -> reserveNextFreePort(p, newPorts)));\n // translate to Docker PortBindings (incl. ExposedPort descriptions)\n List portBindings = portMap.entrySet().stream()\n .map(e -> PortBinding.parse(e.getValue() + \":\" + e.getKey() + \"/\" + getProtocol(e.getKey(), image)))\n .collect(Collectors.toList());\n\n log.info(\"Creating Container...\");\n CreateContainerResponse res = dockerClient.createContainerCmd(imageName)\n .withEnv(buildEnv(containerId, token, image.getParameters(), container.getArguments()))\n .withHostConfig(HostConfig.newHostConfig().withPortBindings(portBindings))\n .withExposedPorts(portBindings.stream().map(PortBinding::getExposedPort).collect(Collectors.toList()))\n .exec();\n\n log.info(String.format(\"Result: %s\", res));\n\n log.info(\"Starting Container...\");\n dockerClient.startContainerCmd(res.getId()).exec();\n\n var connectivity = new AgentContainer.Connectivity(\n getContainerBaseUrl(),\n portMap.get(image.getApiPort()),\n extraPorts.keySet().stream().collect(Collectors.toMap(portMap::get, extraPorts::get))\n );\n dockerContainers.put(containerId, new DockerContainerInfo(res.getId(), connectivity));\n usedPorts.addAll(newPorts);\n\n return connectivity;\n\n } catch (NotFoundException e) {\n // might theoretically happen if image is deleted between pull and run...\n log.warning(\"Image not found: \" + imageName);\n throw new NoSuchElementException(\"Image not found: \" + imageName);\n } catch (DockerException e) {\n throw new IOException(\"Failed to start Docker container.\", e);\n }\n }\n\n private String[] buildEnv(String containerId, String token, List parameters, Map arguments) {\n return config.buildContainerEnv(containerId, token, parameters, arguments).entrySet().stream()\n .map(e -> String.format(\"%s=%s\", e.getKey(), e.getValue()))\n .toArray(String[]::new);\n }\n\n @Override\n public void stopContainer(String containerId) throws IOException {\n try {\n var containerInfo = dockerContainers.remove(containerId);\n usedPorts.remove(containerInfo.connectivity.getApiPortMapping());\n usedPorts.removeAll(containerInfo.connectivity.getExtraPortMappings().keySet());\n dockerClient.stopContainerCmd(containerInfo.containerId).exec();\n } catch (NotModifiedException e) {\n var msg = \"Could not stop Container \" + containerId + \"; already stopped?\";\n log.warning(msg);\n throw new NoSuchElementException(msg);\n }\n // TODO possibly that the container refuses being stopped? call \"kill\" instead? how to test this?\n }\n\n @Override\n public String getUrl(String containerId) {\n var conn = dockerContainers.get(containerId).connectivity;\n return conn.getPublicUrl() + \":\" + conn.getApiPortMapping();\n }\n\n private String getProtocol(int port, AgentContainerImage image) {\n if (image.getExtraPorts().containsKey(port)) {\n String protocol = image.getExtraPorts().get(port).getProtocol();\n return \"udp\".equalsIgnoreCase(protocol) ? \"udp\" : \"tcp\";\n } else {\n return \"tcp\";\n }\n }\n\n private String getLocalDockerHost() {\n // Just differentiates between Windows and others for now\n return SystemUtils.IS_OS_WINDOWS\n ? \"npipe:////./pipe/docker_engine\"\n : \"unix:///var/run/docker.sock\";\n }\n\n private String getDockerHost() {\n return Strings.isNullOrEmpty(config.remoteDockerHost)\n ? getLocalDockerHost()\n : String.format(\"tcp://%s:%s\", config.remoteDockerHost, config.remoteDockerPort);\n }\n\n private String getContainerBaseUrl() {\n return Strings.isNullOrEmpty(config.remoteDockerHost)\n ? config.getOwnBaseUrl().replaceAll(\":\\\\d+$\", \"\")\n : String.format(\"http://%s\", config.remoteDockerHost);\n }\n\n /**\n * Try to pull the Docker image from registry where it can be found (according to image name).\n * Raise NoSuchElementException if image can not be pulled for whatever reason.\n */\n private void pullDockerImage(String imageName) {\n log.info(\"Pulling Image...\" + imageName);\n try {\n var registry = imageName.split(\"/\")[0];\n dockerClient.pullImageCmd(imageName)\n .withAuthConfig(this.auth.get(registry))\n .exec(new PullImageResultCallback())\n .awaitCompletion();\n } catch (InterruptedException e) {\n log.warning(e.getMessage());\n } catch (InternalServerErrorException e) {\n log.severe(\"Pull Image failed: \" + e.getMessage());\n throw new NoSuchElementException(\"Failed to Pull image: \" + e.getMessage());\n }\n }\n\n /**\n * Starting from the given preferred port, get and reserve the next free port.\n */\n private int reserveNextFreePort(int port, Set newPorts) {\n while (!isPortAvailable(port, newPorts)) ++port;\n newPorts.add(port);\n return port;\n }\n\n private boolean isPortAvailable(int port, Set newPorts) {\n if (usedPorts.contains(port) || newPorts.contains(port)) return false;\n try (var s1 = new ServerSocket(port); var s2 = new DatagramSocket(port)) {\n return true;\n } catch (IOException e) {\n return false;\n }\n }\n\n private boolean isImagePresent(String imageName) {\n try {\n this.dockerClient.inspectImageCmd(imageName).exec();\n return true;\n } catch (NotFoundException e) {\n return false;\n }\n }\n \n private Map loadDockerAuth() {\n return config.loadDockerAuth().stream().collect(Collectors.toMap(\n PlatformConfig.ImageRegistryAuth::getRegistry,\n x -> new AuthConfig()\n .withRegistryAddress(x.getRegistry())\n .withUsername(x.getLogin())\n .withPassword(x.getLogin())));\n }\n}\n\nopaca-model/src/main/java/de/gtarc/opaca/util/ApiProxy.java\npublic class ApiProxy implements RuntimePlatformApi, AgentContainerApi {\n\n public final String baseUrl;\n private final RestHelper client;\n\n public ApiProxy(String baseUrl) {\n this(baseUrl, null);\n }\n\n public ApiProxy(String baseUrl, String token) {\n this.baseUrl = baseUrl;\n this.client = new RestHelper(baseUrl, token);\n }\n\n // INFO ROUTES\n\n @Override\n public RuntimePlatform getPlatformInfo() throws IOException {\n return client.get(\"/info\", RuntimePlatform.class);\n }\n\n @SuppressWarnings({\"unchecked\"})\n @Override\n public List getHistory() throws IOException {\n return client.get(\"/history\", List.class);\n }\n\n @Override\n public AgentContainer getContainerInfo() throws IOException {\n return client.get(\"/info\", AgentContainer.class);\n }\n\n // AUTHENTICATION\n\n @Override\n public String login(Login loginParams) throws IOException {\n // token should be raw string\n return client.readStream(client.request(\"POST\", \"/login\", loginParams));\n }\n\n // AGENT ROUTES\n\n @SuppressWarnings({\"unchecked\"})\n @Override\n public List getAgents() throws IOException {\n return client.get(\"/agents\", List.class);\n }\n\n @Override\n public AgentDescription getAgent(String agentId) throws IOException {\n var path = String.format(\"/agents/%s\", agentId);\n return client.get(path, AgentDescription.class);\n }\n\n @Override\n public void send(String agentId, Message message, String containerId, boolean forward) throws IOException {\n var path = String.format(\"/send/%s?%s\", agentId, buildQuery(containerId, forward, null));\n client.post(path, message, null);\n }\n\n @Override\n public void broadcast(String channel, Message message, String containerId, boolean forward) throws IOException {\n var path = String.format(\"/broadcast/%s?%s\", channel, buildQuery(containerId, forward, null));\n client.post(path, message, null);\n }\n\n @Override\n public JsonNode invoke(String action, Map parameters, int timeout, String containerId, boolean forward) throws IOException {\n var path = String.format(\"/invoke/%s?%s\", action, buildQuery(containerId, forward, timeout));\n return client.post(path, parameters, JsonNode.class);\n }\n\n @Override\n public JsonNode invoke(String action, Map parameters, String agentId, int timeout, String containerId, boolean forward) throws IOException {\n var path = String.format(\"/invoke/%s/%s?%s\", action, agentId, buildQuery(containerId, forward, timeout));\n return client.post(path, parameters, JsonNode.class);\n }\n\n @Override\n public ResponseEntity getStream(String stream, String containerId, boolean forward) throws IOException {\n var path = String.format(\"/stream/%s?%s\", stream, buildQuery(containerId, forward, null));\n return client.getStream(path);\n }\n\n @Override\n public ResponseEntity getStream(String stream, String agentId, String containerId, boolean forward) throws IOException {\n var path = String.format(\"/stream/%s/%s?%s\", stream, agentId, buildQuery(containerId, forward, null));\n return client.getStream(path);\n }\n\n // CONTAINER ROUTES\n\n @Override\n public String addContainer(PostAgentContainer container) throws IOException {\n return client.post(\"/containers\", container, String.class);\n }\n\n @SuppressWarnings({\"unchecked\"})\n @Override\n public List getContainers() throws IOException {\n return client.get(\"/containers\", List.class);\n }\n\n @Override\n public AgentContainer getContainer(String containerId) throws IOException {\n var path = String.format(\"/containers/%s\", containerId);\n return client.get(path, AgentContainer.class);\n }\n\n @Override\n public boolean removeContainer(String containerId) throws IOException {\n var path = String.format(\"/containers/%s\", containerId);\n return client.delete(path, null, Boolean.class);\n }\n\n // CONNECTING ROUTES\n\n @Override\n public boolean connectPlatform(LoginConnection loginConnection) throws IOException {\n return client.post(\"/connections\", loginConnection, Boolean.class);\n }\n\n @SuppressWarnings({\"unchecked\"})\n @Override\n public List getConnections() throws IOException {\n return client.get(\"/connections\", List.class);\n }\n\n @Override\n public boolean disconnectPlatform(String url) throws IOException {\n return client.delete(\"/connections\", url, Boolean.class);\n }\n\n @Override\n public boolean notifyUpdateContainer(String containerId) throws IOException {\n return client.post(\"/containers/notify\", containerId, Boolean.class);\n }\n\n @Override\n public boolean notifyUpdatePlatform(String platformUrl) throws IOException {\n return client.post(\"/connections/notify\", platformUrl, Boolean.class);\n }\n\n /**\n * Helper method for building Query string (without initial ?); will be more useful when there are more.\n */\n private String buildQuery(String containerId, Boolean forward, Integer timeout) {\n Map params = new HashMap<>(); // Map.of does not work with nullable values\n params.put(\"containerId\", containerId);\n params.put(\"forward\", forward);\n params.put(\"timeout\", timeout);\n return buildQuery(params);\n }\n\n private String buildQuery(Map params) {\n StringBuilder builder = new StringBuilder();\n for (Map.Entry entry : params.entrySet()) {\n if (entry.getValue() != null) {\n builder.append(String.format(\"&%s=%s\", entry.getKey(), entry.getValue()));\n }\n }\n return builder.toString().replaceFirst(\"&\", \"\");\n }\n\n}", "answers": ["public class PlatformImpl implements RuntimePlatformApi {"], "length": 2241, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "e4722efa-5bd7-49ce-bac6-41c7de88d16c", "reasoning": "The file PlatformImpl.java starts with package and imports, then a comment, followed by the @Log and @Component annotations. The next logical line is the class declaration that uses these annotations. In this project, PlatformImpl provides the concrete implementation of the API interfaces RuntimePlatformApi and AgentContainerApi, so the class should be declared as public and implement those interfaces.", "reasoning_model_answer": "public class PlatformImpl implements RuntimePlatformApi, AgentContainerApi {", "assistant_with_reasoning": "\nThe file PlatformImpl.java starts with package and imports, then a comment, followed by the @Log and @Component annotations. The next logical line is the class declaration that uses these annotations. In this project, PlatformImpl provides the concrete implementation of the API interfaces RuntimePlatformApi and AgentContainerApi, so the class should be declared as public and implement those interfaces.\n\npublic class PlatformImpl implements RuntimePlatformApi, AgentContainerApi {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.585, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25915, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public class PlatformImpl implements RuntimePlatformApi, AgentContainerApi {", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\nimport javax.sound.sampled.AudioFormat;\r\nimport javax.sound.sampled.AudioInputStream;\r\nimport dev.mccue.jlayer.decoder.Bitstream;\r\nimport dev.mccue.jlayer.decoder.BitstreamException;\r\nimport dev.mccue.jlayer.decoder.Decoder;\r\nimport dev.mccue.jlayer.decoder.DecoderException;\r\nimport dev.mccue.jlayer.decoder.Equalizer;\r\nimport dev.mccue.jlayer.decoder.Header;\r\nimport dev.mccue.jlayer.decoder.Obuffer;\r\nimport dev.mccue.mp3spi.PropertiesContainer;\r\nimport dev.mccue.mp3spi.mpeg.sampled.file.IcyListener;\r\nimport dev.mccue.mp3spi.mpeg.sampled.file.tag.TagParseEvent;\r\nimport dev.mccue.mp3spi.mpeg.sampled.file.tag.TagParseListener;\r\nimport dev.mccue.tritonus.share.TDebug;\r\nimport dev.mccue.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream;\r", "context": "mp3spi/src/main/java/dev/mccue/mp3spi/mpeg/sampled/convert/DecodedMpegAudioInputStream.java\n/*\r\n * DecodedMpegAudioInputStream.\r\n * \r\n * JavaZOOM : mp3spi@javazoom.net \r\n * \t\t\t\thttp://www.javazoom.net\r\n *\r\n *-----------------------------------------------------------------------------\r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU Library General Public License as published\r\n * by the Free Software Foundation; either version 2 of the License, or\r\n * (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Library General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Library General Public\r\n * License along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r\n *------------------------------------------------------------------------\r\n */\r\n\r\npackage dev.mccue.mp3spi.mpeg.sampled.convert;\r\n\r\n\r\n\r\n\r\n/**\r\n * Main decoder.\r\n */\r\n@SuppressWarnings(\"unchecked\")\r\npublic class DecodedMpegAudioInputStream extends TAsynchronousFilteredAudioInputStream implements PropertiesContainer, TagParseListener\r\n{\r\n\tprivate InputStream m_encodedStream;\r\n\tprivate Bitstream m_bitstream;\r\n\tprivate Decoder m_decoder;\r\n\tprivate Equalizer m_equalizer;\r\n\tprivate float[] m_equalizer_values;\r\n\tprivate Header m_header;\r\n\tprivate DMAISObuffer m_oBuffer;\r\n\r\n\t// Bytes info.\r\n\tprivate long byteslength = -1;\r\n\tprivate long currentByte = 0;\t\r\n\t// Frame info.\r\n\tprivate int frameslength = -1;\r\n\tprivate long currentFrame = 0;\r\n\tprivate int currentFramesize = 0;\r\n\tprivate int currentBitrate = -1;\r\n\t// Time info.\r\n\tprivate long currentMicrosecond = 0;\r\n\t// Shoutcast stream info\r\n\tprivate IcyListener shoutlst = null;\r\n\t\r\n\r\n\tprivate HashMap properties = null;\r\n\r\n\tpublic DecodedMpegAudioInputStream(AudioFormat outputFormat, AudioInputStream inputStream)\r\n\t{\r\n\t\tsuper(outputFormat, -1);\r\n\t\tif (TDebug.TraceAudioConverter) \r\n\t\t{\r\n\t\t\tTDebug.out(\">DecodedMpegAudioInputStream(AudioFormat outputFormat, AudioInputStream inputStream)\");\r\n\t\t}\r\n\t\ttry\r\n\t\t{\r\n\t\t\t// Try to find out inputstream length to allow skip.\r\n\t\t\tbyteslength = inputStream.available();\r\n\t\t}\r\n\t\tcatch (IOException e)\r\n\t\t{\r\n\t\t\tTDebug.out(\"DecodedMpegAudioInputStream : Cannot run inputStream.available() : \"+e.getMessage());\r\n\t\t\tbyteslength = -1;\r\n\t\t}\t\t\r\n\t\tm_encodedStream = inputStream;\t\t\r\n\t\tshoutlst = IcyListener.getInstance();\r\n\t\tshoutlst.reset();\r\n\t\tm_bitstream = new Bitstream(inputStream);\r\n\t\tm_decoder = new Decoder(null);\r\n\njlayer-decoder/src/main/java/dev/mccue/jlayer/decoder/Decoder.java\npublic class Decoder implements DecoderErrors\r\n{\r\n\tstatic private final Params DEFAULT_PARAMS = new Params();\r\n\t\r\n\t/**\r\n\t * The Bistream from which the MPEG audio frames are read.\r\n\t */\r\n\t//private Bitstream\t\t\t\tstream;\r\n\t\r\n\t/**\r\n\t * The Obuffer instance that will receive the decoded\r\n\t * PCM samples.\r\n\t */\r\n\tprivate Obuffer output;\r\n\t\t\r\n\t/**\r\n\t * Synthesis filter for the left channel.\r\n\t */\r\n\tprivate SynthesisFilter filter1;\r\n\t\r\n\t/**\r\n\t * Sythesis filter for the right channel.\r\n\t */\r\n\tprivate SynthesisFilter filter2;\r\n\t\t\t\r\n\t/**\r\n\t * The decoder used to decode layer III frames.\r\n\t */\r\n\tprivate LayerIIIDecoder l3decoder;\r\n\tprivate LayerIIDecoder l2decoder;\r\n\tprivate LayerIDecoder l1decoder;\r\n\t\r\n\tprivate int\t\t\t\t\t\toutputFrequency;\r\n\tprivate int\t\t\t\t\t\toutputChannels;\r\n\t\r\n\tprivate Equalizer equalizer = new Equalizer();\r\n\t\r\n\tprivate Params\t\t\t\t\tparams;\r\n\t\r\n\tprivate boolean\t\t\t\t\tinitialized;\r\n\t\t\r\n\t\r\n\t/**\r\n\t * Creates a new Decoder instance with default \r\n\t * parameters.\r\n\t */\r\n\t\r\n\tpublic Decoder()\r\n\t{\r\n\t\tthis(null);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a new Decoder instance with default \r\n\t * parameters.\r\n\t * \r\n\t * @param params0\tThe Params instance that describes\r\n\t *\t\t\t\t\tthe customizable aspects of the decoder. \r\n\t */\r\n\tpublic Decoder(Params params0)\r\n\t{\r\n\t\tif (params0==null)\r\n\t\t\tparams0 = DEFAULT_PARAMS;\r\n\t\r\n\t\tparams = params0;\r\n\t\t\r\n\t\tEqualizer eq = params.getInitialEqualizerSettings();\r\n\t\tif (eq!=null)\r\n\t\t{\r\n\t\t\tequalizer.setFrom(eq);\r\n\t\t}\r\n\t}\r\n\t\r\n\tstatic public Params getDefaultParams()\r\n\t{\r\n\t\treturn (Params)DEFAULT_PARAMS.clone();\r\n\t}\r\n\t\r\n\tpublic void setEqualizer(Equalizer eq)\r\n\t{\r\n\t\tif (eq==null)\r\n\t\t\teq = Equalizer.PASS_THRU_EQ;\r\n\t\t\r\n\t\tequalizer.setFrom(eq);\r\n\t\t\r\n\t\tfloat[] factors = equalizer.getBandFactors();\r\n\r\n\t\tif (filter1!=null)\r\n\t\t\tfilter1.setEQ(factors);\r\n\t\t\r\n\t\tif (filter2!=null)\r\n\t\t\tfilter2.setEQ(factors);\t\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Decodes one frame from an MPEG audio bitstream.\r\n\t * \r\n\t * @param header\t\tThe header describing the frame to decode.\r\n\t * @param stream\t\tThe bistream that provides the bits for te body of the frame.\r\n\t * \r\n\t * @return A SampleBuffer containing the decoded samples.\r\n\t */\r\n\tpublic Obuffer decodeFrame(Header header, Bitstream stream)\r\n\t\tthrows DecoderException\r\n\t{\r\n\t\tif (!initialized)\r\n\t\t{\r\n\t\t\tinitialize(header);\r\n\t\t}\r\n\t\t\r\n\t\tint layer = header.layer();\r\n\t\t\r\n\t\toutput.clear_buffer();\r\n\t\t\r\n\t\tFrameDecoder decoder = retrieveDecoder(header, stream, layer);\r\n\t\t\r\n\t\tdecoder.decodeFrame();\r\n\t\t\t\t\r\n\t\toutput.write_buffer(1);\r\n\t\t\r\n\t\treturn output;\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Changes the output buffer. This will take effect the next time\r\n\t * decodeFrame() is called. \r\n\t */\r\n\tpublic void setOutputBuffer(Obuffer out)\r\n\t{\r\n\t\toutput = out;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retrieves the sample frequency of the PCM samples output\r\n\t * by this decoder. This typically corresponds to the sample\r\n\t * rate encoded in the MPEG audio stream.\r\n\t * \r\n\t * @return the sample rate (in Hz) of the samples written to the\r\n\t *\t\toutput buffer when decoding. \r\n\t */\r\n\tpublic int getOutputFrequency()\r\n\t{\r\n\t\treturn outputFrequency;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retrieves the number of channels of PCM samples output by\r\n\t * this decoder. This usually corresponds to the number of\r\n\t * channels in the MPEG audio stream, although it may differ.\r\n\t * \r\n\t * @return The number of output channels in the decoded samples: 1 \r\n\t *\t\tfor mono, or 2 for stereo.\r\n\t *\t\t\r\n\t */\r\n\tpublic int getOutputChannels()\r\n\t{\r\n\t\treturn outputChannels;\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retrieves the maximum number of samples that will be written to\r\n\t * the output buffer when one frame is decoded. This can be used to\r\n\t * help calculate the size of other buffers whose size is based upon \r\n\t * the number of samples written to the output buffer. NB: this is\r\n\t * an upper bound and fewer samples may actually be written, depending\r\n\t * upon the sample rate and number of channels.\r\n\t * \r\n\t * @return The maximum number of samples that are written to the \r\n\t *\t\toutput buffer when decoding a single frame of MPEG audio.\r\n\t */\r\n\tpublic int getOutputBlockSize()\r\n\t{\r\n\t\treturn Obuffer.OBUFFERSIZE;\r\n\t}\r\n\t\r\n\t\r\n\tprotected DecoderException newDecoderException(int errorcode)\r\n\t{\r\n\t\treturn new DecoderException(errorcode, null);\r\n\t}\r\n\t\r\n\tprotected DecoderException newDecoderException(int errorcode, Throwable throwable)\r\n\t{\r\n\t\treturn new DecoderException(errorcode, throwable);\r\n\t}\r\n\t\r\n\tprotected FrameDecoder retrieveDecoder(Header header, Bitstream stream, int layer)\r\n\t\tthrows DecoderException\r\n\t{\r\n\t\tFrameDecoder decoder = null;\r\n\t\t\r\n\t\t// REVIEW: allow channel output selection type\r\n\t\t// (LEFT, RIGHT, BOTH, DOWNMIX)\r\n\t\tswitch (layer)\r\n\t\t{\r\n\t\tcase 3:\r\n\t\t\tif (l3decoder==null)\r\n\t\t\t{\r\n\t\t\t\tl3decoder = new LayerIIIDecoder(stream,\r\n\t\t\t\t\theader, filter1, filter2, \r\n\t\t\t\t\toutput, OutputChannels.BOTH_CHANNELS);\r\n\t\t\t}\t\t\t\t\t\t\r\n\t\t\t\r\n\t\t\tdecoder = l3decoder;\r\n\t\t\tbreak;\r\n\t\tcase 2:\r\n\t\t\tif (l2decoder==null)\r\n\t\t\t{\r\n\t\t\t\tl2decoder = new LayerIIDecoder();\r\n\t\t\t\tl2decoder.create(stream, \r\n\t\t\t\t\theader, filter1, filter2, \r\n\t\t\t\t\toutput, OutputChannels.BOTH_CHANNELS);\r\n\t\t\t}\r\n\t\t\tdecoder = l2decoder;\r\n\t\t\tbreak;\r\n\t\tcase 1:\r\n\t\t\tif (l1decoder==null)\r\n\t\t\t{\r\n\t\t\t\tl1decoder = new LayerIDecoder();\r\n\t\t\t\tl1decoder.create(stream, \r\n\t\t\t\t\theader, filter1, filter2, \r\n\t\t\t\t\toutput, OutputChannels.BOTH_CHANNELS);\r\n\t\t\t}\r\n\t\t\tdecoder = l1decoder;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\t\t\t\t\r\n\t\tif (decoder==null)\r\n\t\t{\r\n\t\t\tthrow newDecoderException(UNSUPPORTED_LAYER, null);\r\n\t\t}\r\n\t\t\r\n\t\treturn decoder;\r\n\t}\r\n\t\r\n\tprivate void initialize(Header header)\r\n\t\tthrows DecoderException\r\n\t{\r\n\t\t\r\n\t\t// REVIEW: allow customizable scale factor\r\n\t\tfloat scalefactor = 32700.0f;\r\n\t\t\r\n\t\tint mode = header.mode();\r\n\t\tint layer = header.layer();\r\n\t\tint channels = mode==Header.SINGLE_CHANNEL ? 1 : 2;\r\n\r\n\t\t\t\t\t\r\n\t\t// set up output buffer if not set up by client.\r\n\t\tif (output==null)\r\n\t\t\toutput = new SampleBuffer(header.frequency(), channels);\r\n\t\t\r\n\t\tfloat[] factors = equalizer.getBandFactors();\r\n\t\tfilter1 = new SynthesisFilter(0, scalefactor, factors);\r\n \t\t\r\n\t\t// REVIEW: allow mono output for stereo\r\n\t\tif (channels==2) \r\n\t\t\tfilter2 = new SynthesisFilter(1, scalefactor, factors);\r\n\r\n\t\toutputChannels = channels;\r\n\t\toutputFrequency = header.frequency();\r\n\t\t\r\n\t\tinitialized = true;\r\n\t}\r\n\t\r\n\t/**\r\n\t * The Params class presents the customizable\r\n\t * aspects of the decoder. \r\n\t *

\r\n\t * Instances of this class are not thread safe. \r\n\t */\r\n\tpublic static class Params implements Cloneable\r\n\t{\r\n\t\tprivate OutputChannels outputChannels = OutputChannels.BOTH;\r\n\t\t\r\n\t\tprivate Equalizer\t\tequalizer = new Equalizer();\r\n\t\t\r\n\t\tpublic Params()\r\n\t\t{\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tpublic Object clone()\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\treturn super.clone();\r\n\t\t\t}\r\n\t\t\tcatch (CloneNotSupportedException ex)\r\n\t\t\t{\t\t\t\t\r\n\t\t\t\tthrow new InternalError(this+\": \"+ex);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\t\t\r\n\t\tpublic void setOutputChannels(OutputChannels out)\r\n\t\t{\r\n\t\t\tif (out==null)\r\n\t\t\t\tthrow new NullPointerException(\"out\");\r\n\t\t\t\r\n\t\t\toutputChannels = out;\r\n\t\t}\r\n\t\t\r\n\t\tpublic OutputChannels getOutputChannels()\r\n\t\t{\r\n\t\t\treturn outputChannels;\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Retrieves the equalizer settings that the decoder's equalizer\r\n\t\t * will be initialized from.\r\n\t\t *

\r\n\t\t * The Equalizer instance returned \r\n\t\t * cannot be changed in real time to affect the \r\n\t\t * decoder output as it is used only to initialize the decoders\r\n\t\t * EQ settings. To affect the decoder's output in realtime,\r\n\t\t * use the Equalizer returned from the getEqualizer() method on\r\n\t\t * the decoder. \r\n\t\t * \r\n\t\t * @return\tThe Equalizer used to initialize the\r\n\t\t *\t\t\tEQ settings of the decoder. \r\n\t\t */\r\n\t\tpublic Equalizer getInitialEqualizerSettings()\r\n\t\t{\r\n\t\t\treturn equalizer;\t\r\n\t\t}\r\n\t\t\t\t\r\n\t};\r\n}\r\n\njlayer-decoder/src/main/java/dev/mccue/jlayer/decoder/DecoderException.java\npublic class DecoderException extends JavaLayerException\r\n\timplements DecoderErrors\r\n{\t\r\n\tprivate int\t\terrorcode = UNKNOWN_ERROR;\r\n\t\r\n\tpublic DecoderException(String msg, Throwable t)\r\n\t{\r\n\t\tsuper(msg, t);\t\r\n\t}\r\n\t\r\n\tpublic DecoderException(int errorcode, Throwable t)\r\n\t{\r\n\t\tthis(getErrorString(errorcode), t);\r\n\t\tthis.errorcode = errorcode;\r\n\t}\r\n\t\r\n\tpublic int getErrorCode()\r\n\t{\r\n\t\treturn errorcode;\t\r\n\t}\r\n\t\r\n\t\r\n\tstatic public String getErrorString(int errorcode)\r\n\t{\r\n\t\t// REVIEW: use resource file to map error codes\r\n\t\t// to locale-sensitive strings. \r\n\t\t\r\n\t\treturn \"Decoder errorcode \"+Integer.toHexString(errorcode);\r\n\t}\r\n\t\r\n\t\r\n}\r\n\nmp3spi/src/main/java/dev/mccue/mp3spi/mpeg/sampled/file/tag/TagParseListener.java\npublic interface TagParseListener extends EventListener {\n\t/** Called when a tag is found (parsed from the stream,\n\t received via UDP, etc.)\n\t */\n\tpublic void tagParsed(TagParseEvent tpe);\n}\n\nmp3spi/src/main/java/dev/mccue/mp3spi/PropertiesContainer.java\npublic interface PropertiesContainer\r\n{\r\n\tpublic Map properties();\r\n}\r\n\njlayer-decoder/src/main/java/dev/mccue/jlayer/decoder/BitstreamException.java\npublic class BitstreamException extends JavaLayerException\r\n\timplements BitstreamErrors\r\n{\t\r\n\tprivate int errorcode = UNKNOWN_ERROR;\r\n\t\r\n\tpublic BitstreamException(String msg, Throwable t)\r\n\t{\r\n\t\tsuper(msg, t);\t\r\n\t}\r\n\t\r\n\tpublic BitstreamException(int errorcode, Throwable t)\r\n\t{\r\n\t\tthis(getErrorString(errorcode), t);\r\n\t\tthis.errorcode = errorcode;\r\n\t}\r\n\t\r\n\tpublic int getErrorCode()\r\n\t{\r\n\t\treturn errorcode;\t\r\n\t}\r\n\t\r\n\t\r\n\tstatic public String getErrorString(int errorcode)\r\n\t{\r\n\t\t// REVIEW: use resource bundle to map error codes\r\n\t\t// to locale-sensitive strings.\r\n\t\t\r\n\t\treturn \"Bitstream errorcode \"+Integer.toHexString(errorcode);\r\n\t}\r\n\t\r\n\t\r\n}\r\n\ntritonus-share/src/main/java/dev/mccue/tritonus/share/TDebug.java\npublic class TDebug\r\n{\r\n\tpublic static boolean\t\tSHOW_ACCESS_CONTROL_EXCEPTIONS = false;\r\n\tprivate static final String\tPROPERTY_PREFIX = \"tritonus.\";\r\n\t// The stream we output to\r\n\tpublic static PrintStream\tm_printStream = System.out;\r\n\r\n\tprivate static String indent=\"\";\r\n\r\n\t// meta-general\r\n\tpublic static boolean\tTraceAllExceptions = getBooleanProperty(\"TraceAllExceptions\");\r\n\tpublic static boolean\tTraceAllWarnings = getBooleanProperty(\"TraceAllWarnings\");\r\n\r\n\t// general\r\n\tpublic static boolean\tTraceInit = getBooleanProperty(\"TraceInit\");\r\n\tpublic static boolean\tTraceCircularBuffer = getBooleanProperty(\"TraceCircularBuffer\");\r\n\tpublic static boolean\tTraceService = getBooleanProperty(\"TraceService\");\r\n\r\n\t// sampled common implementation\r\n\tpublic static boolean\tTraceAudioSystem = getBooleanProperty(\"TraceAudioSystem\");\r\n\tpublic static boolean\tTraceAudioConfig = getBooleanProperty(\"TraceAudioConfig\");\r\n\tpublic static boolean\tTraceAudioInputStream = getBooleanProperty(\"TraceAudioInputStream\");\r\n\tpublic static boolean\tTraceMixerProvider = getBooleanProperty(\"TraceMixerProvider\");\r\n\tpublic static boolean\tTraceControl = getBooleanProperty(\"TraceControl\");\r\n\tpublic static boolean\tTraceLine = getBooleanProperty(\"TraceLine\");\r\n\tpublic static boolean\tTraceDataLine = getBooleanProperty(\"TraceDataLine\");\r\n\tpublic static boolean\tTraceMixer = getBooleanProperty(\"TraceMixer\");\r\n\tpublic static boolean\tTraceSourceDataLine = getBooleanProperty(\"TraceSourceDataLine\");\r\n\tpublic static boolean\tTraceTargetDataLine = getBooleanProperty(\"TraceTargetDataLine\");\r\n\tpublic static boolean\tTraceClip = getBooleanProperty(\"TraceClip\");\r\n\tpublic static boolean\tTraceAudioFileReader = getBooleanProperty(\"TraceAudioFileReader\");\r\n\tpublic static boolean\tTraceAudioFileWriter = getBooleanProperty(\"TraceAudioFileWriter\");\r\n\tpublic static boolean\tTraceAudioConverter = getBooleanProperty(\"TraceAudioConverter\");\r\n\tpublic static boolean\tTraceAudioOutputStream = getBooleanProperty(\"TraceAudioOutputStream\");\r\n\r\n\t// sampled specific implementation\r\n\tpublic static boolean\tTraceEsdNative = getBooleanProperty(\"TraceEsdNative\");\r\n\tpublic static boolean\tTraceEsdStreamNative = getBooleanProperty(\"TraceEsdStreamNative\");\r\n\tpublic static boolean\tTraceEsdRecordingStreamNative = getBooleanProperty(\"TraceEsdRecordingStreamNative\");\r\n\tpublic static boolean\tTraceAlsaNative = getBooleanProperty(\"TraceAlsaNative\");\r\n\tpublic static boolean\tTraceAlsaMixerNative = getBooleanProperty(\"TraceAlsaMixerNative\");\r\n\tpublic static boolean\tTraceAlsaPcmNative = getBooleanProperty(\"TraceAlsaPcmNative\");\r\n\tpublic static boolean\tTraceMixingAudioInputStream = getBooleanProperty(\"TraceMixingAudioInputStream\");\r\n\tpublic static boolean\tTraceOggNative = getBooleanProperty(\"TraceOggNative\");\r\n\tpublic static boolean\tTraceVorbisNative = getBooleanProperty(\"TraceVorbisNative\");\r\n\r\n\t// midi common implementation\r\n\tpublic static boolean\tTraceMidiSystem = getBooleanProperty(\"TraceMidiSystem\");\r\n\tpublic static boolean\tTraceMidiConfig = getBooleanProperty(\"TraceMidiConfig\");\r\n\tpublic static boolean\tTraceMidiDeviceProvider = getBooleanProperty(\"TraceMidiDeviceProvider\");\r\n\tpublic static boolean\tTraceSequencer = getBooleanProperty(\"TraceSequencer\");\r\n\tpublic static boolean\tTraceSynthesizer = getBooleanProperty(\"TraceSynthesizer\");\r\n\tpublic static boolean\tTraceMidiDevice = getBooleanProperty(\"TraceMidiDevice\");\r\n\r\n\t// midi specific implementation\r\n\tpublic static boolean\tTraceAlsaSeq = getBooleanProperty(\"TraceAlsaSeq\");\r\n\tpublic static boolean\tTraceAlsaSeqDetails = getBooleanProperty(\"TraceAlsaSeqDetails\");\r\n\tpublic static boolean\tTraceAlsaSeqNative = getBooleanProperty(\"TraceAlsaSeqNative\");\r\n\tpublic static boolean\tTracePortScan = getBooleanProperty(\"TracePortScan\");\r\n\tpublic static boolean\tTraceAlsaMidiIn = getBooleanProperty(\"TraceAlsaMidiIn\");\r\n\tpublic static boolean\tTraceAlsaMidiOut = getBooleanProperty(\"TraceAlsaMidiOut\");\r\n\tpublic static boolean\tTraceAlsaMidiChannel = getBooleanProperty(\"TraceAlsaMidiChannel\");\r\n\r\n\tpublic static boolean\tTraceFluidNative = getBooleanProperty(\"TraceFluidNative\");\r\n\r\n\t// misc\r\n\tpublic static boolean\tTraceAlsaCtlNative = getBooleanProperty(\"TraceAlsaCtlNative\");\r\n\tpublic static boolean\tTraceCdda = getBooleanProperty(\"TraceCdda\");\r\n\tpublic static boolean\tTraceCddaNative = getBooleanProperty(\"TraceCddaNative\");\r\n\r\n\r\n\r\n\t// make this method configurable to write to file, write to stderr,...\r\n\tpublic static void out(String strMessage)\r\n\t{\r\n\t\tif (strMessage.length()>0 && strMessage.charAt(0)=='<') {\r\n\t\t\tif (indent.length()>2) {\t\r\n\t\t\t\tindent=indent.substring(2);\r\n\t\t\t} else {\r\n\t\t\t\tindent=\"\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tString newMsg=null;\r\n\t\tif (indent!=\"\" && strMessage.indexOf(\"\\n\")>=0) {\r\n\t\t\tnewMsg=\"\";\r\n\t\t\tStringTokenizer tokenizer=new StringTokenizer(strMessage, \"\\n\");\r\n\t\t\twhile (tokenizer.hasMoreTokens()) {\r\n\t\t\t\tnewMsg+=indent+tokenizer.nextToken()+\"\\n\";\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tnewMsg=indent+strMessage;\r\n\t\t}\r\n\t\tm_printStream.println(newMsg);\r\n\t\tif (strMessage.length()>0 && strMessage.charAt(0)=='>') {\r\n\t\t\t\tindent+=\" \";\r\n\t\t} \r\n\t}\r\n\r\n\r\n\r\n\tpublic static void out(Throwable throwable)\r\n\t{\r\n\t\tthrowable.printStackTrace(m_printStream);\r\n\t}\r\n\r\n\r\n\r\n\tpublic static void assertion(boolean bAssertion)\r\n\t{\r\n\t\tif (!bAssertion)\r\n\t\t{\r\n\t\t\tthrow new AssertException();\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tpublic static class AssertException\r\n\textends RuntimeException\r\n\t{\r\n\t\tprivate static final long serialVersionUID = 1;\r\n\r\n\t\tpublic AssertException()\r\n\t\t{\r\n\t\t}\r\n\r\n\r\n\r\n\t\tpublic AssertException(String sMessage)\r\n\t\t{\r\n\t\t\tsuper(sMessage);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tprivate static boolean getBooleanProperty(String strName)\r\n\t{\r\n\t\tString\tstrPropertyName = PROPERTY_PREFIX + strName;\r\n\t\tString\tstrValue = \"false\";\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstrValue = System.getProperty(strPropertyName, \"false\");\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tif (SHOW_ACCESS_CONTROL_EXCEPTIONS)\r\n\t\t\t{\r\n\t\t\t\tout(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\t// TDebug.out(\"property: \" + strPropertyName + \"=\" + strValue);\r\n\t\tboolean\tbValue = strValue.toLowerCase().equals(\"true\");\r\n\t\t// TDebug.out(\"bValue: \" + bValue);\r\n\t\treturn bValue;\r\n\t}\r\n}\r\n\njlayer-decoder/src/main/java/dev/mccue/jlayer/decoder/Equalizer.java\npublic final class Equalizer\r\n{\t\t\r\n\t/**\r\n\t * Equalizer setting to denote that a given band will not be\r\n\t * present in the output signal.\r\n\t */\r\n\tstatic public final float BAND_NOT_PRESENT = Float.NEGATIVE_INFINITY;\r\n\t\t\r\n\tstatic public final Equalizer\tPASS_THRU_EQ = new Equalizer();\r\n\t\r\n\tprivate static final int BANDS = 32;\r\n\t\r\n\tprivate final float[]\tsettings = new float[BANDS];\r\n\t\r\n\t/**\r\n\t * Creates a new Equalizer instance. \r\n\t */\r\n\tpublic Equalizer()\r\n\t{\t\t\r\n\t}\r\n\t\r\n//\tprivate Equalizer(float b1, float b2, float b3, float b4, float b5,\r\n//\t\t\t\t\t float b6, float b7, float b8, float b9, float b10, float b11,\r\n//\t\t\t\t\t float b12, float b13, float b14, float b15, float b16,\r\n//\t\t\t\t\t float b17, float b18, float b19, float b20);\r\n\r\n\tpublic Equalizer(float[] settings)\r\n\t{\r\n\t\tsetFrom(settings);\r\n\t}\r\n\t\r\n\tpublic Equalizer(EQFunction eq)\r\n\t{\r\n\t\tsetFrom(eq);\r\n\t}\r\n\t\r\n\tpublic void setFrom(float[] eq)\r\n\t{\r\n\t\treset();\r\n\t\tint max = (eq.length > BANDS) ? BANDS : eq.length;\r\n\t\t\r\n\t\tfor (int i=0; i=0) && (band=0) && (band 1.0f)\r\n\t\t\treturn 1.0f;\r\n\t\tif (eq < -1.0f)\r\n\t\t\treturn -1.0f;\r\n\t\t\r\n\t\treturn eq;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retrieves an array of floats whose values represent a\r\n\t * scaling factor that can be applied to linear samples\r\n\t * in each band to provide the equalization represented by\r\n\t * this instance. \r\n\t * \r\n\t * @return\tan array of factors that can be applied to the\r\n\t *\t\t\tsubbands.\r\n\t */\r\n\tfloat[] getBandFactors()\r\n\t{\r\n\t\tfloat[] factors = new float[BANDS];\r\n\t\tfor (int i=0, maxCount=BANDS; i\nThe constructor has just created the Decoder instance. The next logical step is to initialise the Equalizer that will be used for audio processing. The class has a field `private Equalizer m_equalizer;` which is still null, so the next line should instantiate it.\n\nm_equalizer = new Equalizer();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.722, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 23113, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "m_equalizer = new Equalizer();", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import cloud.commandframework.context.CommandContext;\nimport cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;\nimport java.awt.Graphics2D;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Stream;\nimport net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;\nimport net.pl3x.map.core.command.CommandHandler;\nimport net.pl3x.map.core.command.Pl3xMapCommand;\nimport net.pl3x.map.core.command.Sender;\nimport net.pl3x.map.core.command.argument.RendererArgument;\nimport net.pl3x.map.core.command.argument.WorldArgument;\nimport net.pl3x.map.core.command.argument.ZoomArgument;\nimport net.pl3x.map.core.configuration.Config;\nimport net.pl3x.map.core.configuration.Lang;\nimport net.pl3x.map.core.image.io.IO;\nimport net.pl3x.map.core.markers.Point;\nimport net.pl3x.map.core.renderer.Renderer;\nimport net.pl3x.map.core.world.World;\nimport org.jetbrains.annotations.NotNull;\nimport static net.pl3x.map.core.world.World.PNG_MATCHER;", "context": "core/src/main/java/net/pl3x/map/core/command/commands/StitchCommand.java\n/*\n * MIT License\n *\n * Copyright (c) 2020-2023 William Blake Galbreath\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage net.pl3x.map.core.command.commands;\n\n\npublic class StitchCommand extends Pl3xMapCommand {\n public StitchCommand(@NotNull CommandHandler handler) {\n super(handler);\n }\n\n @Override\n public void register() {\n getHandler().registerSubcommand(builder -> builder.literal(\"stitch\")\n .argument(WorldArgument.of(\"world\"), description(Lang.COMMAND_ARGUMENT_REQUIRED_WORLD_DESCRIPTION))\n .argument(RendererArgument.of(\"renderer\"), description(Lang.COMMAND_ARGUMENT_REQUIRED_RENDERER_DESCRIPTION))\n .argument(ZoomArgument.optional(\"zoom\"), description(Lang.COMMAND_ARGUMENT_OPTIONAL_ZOOM_DESCRIPTION))\n .meta(MinecraftExtrasMetaKeys.DESCRIPTION, Lang.parse(Lang.COMMAND_STITCH_DESCRIPTION))\n .permission(\"pl3xmap.command.stitch\")\n .handler(this::execute));\n }\n\n private void execute(@NotNull CommandContext<@NotNull Sender> context) {\n CompletableFuture.runAsync(() -> executeAsync(context));\n }\n\n\ncore/src/main/java/net/pl3x/map/core/command/argument/RendererArgument.java\n@SuppressWarnings(\"unused\")\npublic class RendererArgument extends CommandArgument<@NotNull C, Renderer.@NotNull Builder> {\n protected RendererArgument(boolean required, @NotNull String name, @NotNull String defaultValue, @NotNull BiFunction<@NotNull CommandContext<@NotNull C>, @NotNull String, @NotNull List<@NotNull String>> suggestionsProvider, @NotNull ArgumentDescription defaultDescription) {\n super(required, name, new RendererParser<>(), defaultValue, Renderer.Builder.class, suggestionsProvider, defaultDescription);\n }\n\n /**\n * Create a new {@link RendererArgument} builder.\n *\n * @param name argument name\n * @return new renderer argument builder\n */\n public static CommandArgument.@NotNull Builder<@NotNull C, Renderer.@NotNull Builder> builder(@NotNull String name) {\n return new RendererArgument.Builder<>(name);\n }\n\n /**\n * Create a required {@link RendererArgument}.\n *\n * @param name argument name\n * @return constructed renderer argument\n */\n public static @NotNull CommandArgument<@NotNull C, Renderer.@NotNull Builder> of(@NotNull String name) {\n return RendererArgument.<@NotNull C>builder(name).asRequired().build();\n }\n\n /**\n * Create an optional {@link RendererArgument}.\n *

\n * All arguments prior to any other required argument must also be required.\n *\n * @param name argument name\n * @return constructed renderer argument\n */\n public static @NotNull CommandArgument<@NotNull C, Renderer.@NotNull Builder> optional(@NotNull String name) {\n return RendererArgument.<@NotNull C>builder(name).asOptional().build();\n }\n\n /**\n * Create an optional {@link RendererArgument} with a default value.\n *

\n * All arguments prior to any other required argument must also be required.\n *\n * @param name argument name\n * @param defaultValue default value that will be used if none was supplied\n * @return constructed renderer argument\n */\n public static @NotNull CommandArgument<@NotNull C, Renderer.@NotNull Builder> optional(@NotNull String name, @NotNull String defaultValue) {\n return RendererArgument.<@NotNull C>builder(name).asOptionalWithDefault(defaultValue).build();\n }\n\n /**\n * Mutable builder for {@link RendererArgument} instances.\n *\n * @param command sender type\n */\n public static class Builder extends CommandArgument.Builder<@NotNull C, Renderer.@NotNull Builder> {\n private Builder(@NotNull String name) {\n super(Renderer.Builder.class, name);\n }\n\n @Override\n public @NotNull CommandArgument<@NotNull C, Renderer.@NotNull Builder> build() {\n return new RendererArgument<>(isRequired(), getName(), getDefaultValue(), getSuggestionsProvider(), getDefaultDescription());\n }\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/image/io/IO.java\npublic abstract class IO {\n private static final Registry<@NotNull Type> TYPES = new Registry<>();\n\n public static void register() {\n IO.register(\"bmp\", new Bmp());\n IO.register(\"gif\", new Gif());\n IO.register(\"jpg\", new Jpg());\n IO.register(\"jpeg\", get(\"jpg\"));\n IO.register(\"png\", new Png());\n }\n\n public static void register(@NotNull String name, @NotNull Type type) {\n if (TYPES.has(name)) {\n throw new IllegalStateException(String.format(\"IO type %s already registered\", name));\n }\n TYPES.register(name, type);\n }\n\n public static void unregister() {\n TYPES.unregister();\n }\n\n public static void unregister(@NotNull String name) {\n TYPES.unregister(name);\n }\n\n public static @NotNull Type get(@NotNull String format) {\n Type type = TYPES.get(format.toLowerCase(Locale.ROOT));\n if (type == null) {\n throw new IllegalStateException(\"Unknown or unsupported image format\");\n }\n return type;\n }\n\n public abstract static class Type extends Keyed {\n public Type(@NotNull String key) {\n super(key);\n }\n\n public @NotNull BufferedImage createBuffer() {\n return new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);\n }\n\n public int color(int argb) {\n return argb;\n }\n\n public @Nullable BufferedImage read(@NotNull Path path) {\n BufferedImage buffer = null;\n ImageReader reader = null;\n try (ImageInputStream in = ImageIO.createImageInputStream(Files.newInputStream(path))) {\n reader = ImageIO.getImageReadersBySuffix(getKey()).next();\n reader.setInput(in, false, true);\n buffer = reader.read(0);\n in.flush();\n } catch (IOException e) {\n Logger.warn(\"Could not read tile image: \" + path);\n e.printStackTrace();\n } finally {\n if (reader != null) {\n reader.dispose();\n }\n }\n return buffer;\n }\n\n public void write(@NotNull Path path, @NotNull BufferedImage buffer) {\n Path tmp = FileUtil.tmp(path);\n ImageWriter writer = null;\n try (ImageOutputStream out = ImageIO.createImageOutputStream(tmp.toFile())) {\n writer = ImageIO.getImageWritersBySuffix(getKey()).next();\n ImageWriteParam param = writer.getDefaultWriteParam();\n if (param.canWriteCompressed()) {\n param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n if (param.getCompressionType() == null) {\n param.setCompressionType(param.getCompressionTypes()[0]);\n }\n param.setCompressionQuality((float) Config.WEB_TILE_QUALITY);\n }\n writer.setOutput(out);\n writer.write(null, new IIOImage(buffer, null, null), param);\n out.flush();\n } catch (IOException e) {\n Logger.warn(\"Could not write tile image: \" + tmp);\n e.printStackTrace();\n } finally {\n if (writer != null) {\n writer.dispose();\n }\n }\n try {\n FileUtil.atomicMove(tmp, path);\n } catch (IOException e) {\n Logger.warn(\"Could not write tile image: \" + path);\n e.printStackTrace();\n }\n }\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/world/World.java\npublic abstract class World extends Keyed {\n public static final PathMatcher JSON_MATCHER = FileSystems.getDefault().getPathMatcher(\"glob:**/*.json\");\n public static final PathMatcher MCA_MATCHER = FileSystems.getDefault().getPathMatcher(\"glob:**/r.*.*.mca\");\n public static final PathMatcher PNG_MATCHER = FileSystems.getDefault().getPathMatcher(\"glob:**/*_*.png\");\n\n private final Path customMarkersDirectory;\n private final Path markersDirectory;\n private final Path regionDirectory;\n private final Path tilesDirectory;\n private final WorldConfig worldConfig;\n\n private final long seed;\n private final Point spawn;\n private final Type type;\n\n private final BiomeManager biomeManager;\n private final BiomeRegistry biomeRegistry;\n private final Registry<@NotNull Layer> layerRegistry;\n\n private final LoadingCache<@NotNull Long, @NotNull Region> regionCache;\n private final RegionModifiedState regionModifiedState;\n //private final RegionFileWatcher regionFileWatcher;\n private final UpdateMarkerData markerTask;\n private final Map<@NotNull String, Renderer.@NotNull Builder> renderers = new LinkedHashMap<>();\n\n public World(@NotNull String name, long seed, @NotNull Point spawn, @NotNull Type type, @NotNull Path regionDirectory) {\n super(name);\n\n this.seed = seed;\n this.spawn = spawn;\n this.type = type;\n\n String safeNameForDirectories = name.replace(\":\", \"-\");\n\n this.regionDirectory = regionDirectory;\n this.tilesDirectory = FileUtil.getTilesDir().resolve(safeNameForDirectories);\n this.customMarkersDirectory = Pl3xMap.api().getMainDir().resolve(\"markers\").resolve(safeNameForDirectories);\n this.markersDirectory = getTilesDirectory().resolve(\"markers\");\n\n FileUtil.createDirs(this.regionDirectory);\n FileUtil.createDirs(this.tilesDirectory);\n FileUtil.createDirs(this.customMarkersDirectory);\n FileUtil.createDirs(this.markersDirectory);\n\n this.worldConfig = new WorldConfig(this);\n\n this.biomeManager = new BiomeManager(hashSeed(getSeed()));\n this.biomeRegistry = new BiomeRegistry();\n this.layerRegistry = new Registry<>();\n\n this.regionCache = Caffeine.newBuilder()\n .expireAfterWrite(1, TimeUnit.MINUTES)\n .maximumSize(100)\n .build(this::loadRegion);\n\n this.regionModifiedState = new RegionModifiedState(this);\n //this.regionFileWatcher = new RegionFileWatcher(this);\n this.markerTask = new UpdateMarkerData(this);\n }\n\n protected void init() {\n if (!isEnabled()) {\n return;\n }\n\n getBiomeRegistry().init(this);\n\n //this.regionFileWatcher.start();\n\n getConfig().RENDER_RENDERERS.forEach((id, icon) -> {\n Renderer.Builder renderer = Pl3xMap.api().getRendererRegistry().get(id);\n if (renderer == null) {\n return;\n }\n Path path = FileUtil.getWebDir().resolve(\"images/icon/\" + icon + \".png\");\n try {\n IconImage image = new IconImage(icon, ImageIO.read(path.toFile()), \"png\");\n Pl3xMap.api().getIconRegistry().register(image);\n } catch (IOException e) {\n Logger.severe(\"Cannot load world renderer icon \" + path, e);\n }\n this.renderers.put(renderer.getKey(), renderer);\n });\n\n if (WorldBorderLayerConfig.ENABLED) {\n Logger.debug(\"Registering world border layer\");\n getLayerRegistry().register(WorldBorderLayer.KEY, new WorldBorderLayer(this));\n }\n\n if (SpawnLayerConfig.ENABLED) {\n Logger.debug(\"Registering spawn layer\");\n getLayerRegistry().register(SpawnLayer.KEY, new SpawnLayer(this));\n }\n\n if (PlayersLayerConfig.ENABLED) {\n Logger.debug(\"Registering player tracker layer\");\n getLayerRegistry().register(PlayersLayer.KEY, new PlayersLayer(this));\n }\n\n Logger.debug(\"Checking all region files\");\n Pl3xMap.api().getRegionProcessor().addRegions(this, listRegions(false));\n\n Logger.debug(\"Starting marker task\");\n Pl3xMap.api().getScheduler().addTask(1, true, this.markerTask);\n\n // load up custom markers\n Logger.debug(\"Loading custom markers for \" + getName());\n for (Path file : getCustomMarkerFiles()) {\n CustomLayer.load(this, file);\n }\n }\n\n public void cleanup() {\n this.regionCache.invalidateAll();\n getRegionModifiedState().save();\n }\n\n public @NotNull Path getCustomMarkersDirectory() {\n return this.customMarkersDirectory;\n }\n\n public @NotNull Path getMarkersDirectory() {\n return this.markersDirectory;\n }\n\n public @NotNull Path getRegionDirectory() {\n return this.regionDirectory;\n }\n\n public @NotNull Path getTilesDirectory() {\n return this.tilesDirectory;\n }\n\n public @NotNull WorldConfig getConfig() {\n return this.worldConfig;\n }\n\n public @NotNull RegionModifiedState getRegionModifiedState() {\n return this.regionModifiedState;\n }\n\n //public @NotNull RegionFileWatcher getRegionFileWatcher() {\n // return this.regionFileWatcher;\n //}\n\n public @NotNull UpdateMarkerData getMarkerTask() {\n return this.markerTask;\n }\n\n public @NotNull Map<@NotNull String, Renderer.@NotNull Builder> getRenderers() {\n return Collections.unmodifiableMap(this.renderers);\n }\n\n /**\n * Get whether this world is enabled.\n *\n * @return true if enabled\n */\n public boolean isEnabled() {\n return getConfig().ENABLED;\n }\n\n public @NotNull String getName() {\n return getKey();\n }\n\n public long getSeed() {\n return this.seed;\n }\n\n public @NotNull Point getSpawn() {\n return this.spawn;\n }\n\n public int getSkylight() {\n return getConfig().RENDER_SKYLIGHT;\n }\n\n /**\n * Get the world's type.\n *\n * @return world type\n */\n public @NotNull Type getType() {\n return this.type;\n }\n\n public @NotNull BiomeManager getBiomeManager() {\n return this.biomeManager;\n }\n\n public @NotNull BiomeRegistry getBiomeRegistry() {\n return this.biomeRegistry;\n }\n\n public @NotNull Registry getLayerRegistry() {\n return this.layerRegistry;\n }\n\n public abstract @NotNull T getLevel();\n\n public abstract long hashSeed(long seed);\n\n public abstract boolean hasCeiling();\n\n public abstract int getMinBuildHeight();\n\n public abstract int getMaxBuildHeight();\n\n public abstract int getLogicalHeight();\n\n public abstract double getBorderMinX();\n\n public abstract double getBorderMinZ();\n\n public abstract double getBorderMaxX();\n\n public abstract double getBorderMaxZ();\n\n public abstract @NotNull Collection<@NotNull Player> getPlayers();\n\n public boolean visibleBlock(int blockX, int blockZ) {\n for (Area area : getConfig().VISIBLE_AREAS) {\n if (area.containsBlock(blockX, blockZ)) {\n return true;\n }\n }\n return getConfig().VISIBLE_AREAS.isEmpty();\n }\n\n public boolean visibleChunk(int chunkX, int chunkZ) {\n for (Area area : getConfig().VISIBLE_AREAS) {\n if (area.containsChunk(chunkX, chunkZ)) {\n return true;\n }\n }\n return getConfig().VISIBLE_AREAS.isEmpty();\n }\n\n public boolean visibleRegion(int regionX, int regionZ) {\n for (Area area : getConfig().VISIBLE_AREAS) {\n if (area.containsRegion(regionX, regionZ)) {\n return true;\n }\n }\n return getConfig().VISIBLE_AREAS.isEmpty();\n }\n\n public @NotNull Chunk getChunk(@Nullable Region region, int chunkX, int chunkZ) {\n return getRegion(region, chunkX >> 5, chunkZ >> 5).getChunk(chunkX, chunkZ);\n }\n\n public @NotNull Region getRegion(@Nullable Region region, int regionX, int regionZ) {\n if (region != null && region.getX() == regionX && region.getZ() == regionZ) {\n return region;\n }\n return getRegion(Mathf.asLong(regionX, regionZ));\n }\n\n private @NotNull Region getRegion(long pos) {\n return this.regionCache.get(pos);\n }\n\n public void unloadRegion(int regionX, int regionZ) {\n unloadRegion(Mathf.asLong(regionX, regionZ));\n }\n\n private void unloadRegion(long pos) {\n this.regionCache.invalidate(pos);\n }\n\n public @NotNull Collection<@NotNull Path> getRegionFiles() {\n if (!Files.exists(getRegionDirectory())) {\n return Collections.emptySet();\n }\n try (Stream stream = Files.list(getRegionDirectory())) {\n return stream.filter(MCA_MATCHER::matches).toList();\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to list region files in directory '\" + getRegionDirectory().toAbsolutePath() + \"'\", e);\n }\n }\n\n public @NotNull Collection<@NotNull Path> getCustomMarkerFiles() {\n if (!Files.exists(getCustomMarkersDirectory())) {\n return Collections.emptySet();\n }\n try (Stream stream = Files.list(getCustomMarkersDirectory())) {\n return stream.filter(JSON_MATCHER::matches).toList();\n } catch (IOException e) {\n throw new RuntimeException(\"Failed to list custom marker files in directory '\" + getCustomMarkersDirectory().toAbsolutePath() + \"'\", e);\n }\n }\n\n public @NotNull Collection<@NotNull Point> listRegions(boolean ignoreTimestamp) {\n return FileUtil.regionPathsToPoints(this, getRegionFiles(), ignoreTimestamp);\n }\n\n private @NotNull Region loadRegion(long pos) {\n int x = Mathf.longToX(pos);\n int z = Mathf.longToZ(pos);\n return new Region(this, x, z, getMCAFile(x, z));\n }\n\n private @NotNull Path getMCAFile(int regionX, int regionZ) {\n return getRegionDirectory().resolve(\"r.\" + regionX + \".\" + regionZ + \".mca\");\n }\n\n @Override\n public boolean equals(@Nullable Object o) {\n if (this == o) {\n return true;\n }\n if (o == null) {\n return false;\n }\n if (this.getClass() != o.getClass()) {\n return false;\n }\n World other = (World) o;\n return getLevel() == other.getLevel();\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getName());\n }\n\n @Override\n public abstract @NotNull String toString();\n\n /**\n * Represents a world's type.\n */\n public enum Type {\n OVERWORLD,\n NETHER,\n THE_END,\n CUSTOM;\n\n private final String name;\n\n Type() {\n this.name = name().toLowerCase(Locale.ROOT);\n }\n\n /**\n * Get the world type from a server level.\n *\n * @param dimension dimension name\n * @return world type\n */\n public static @NotNull Type get(@NotNull String dimension) {\n return switch (dimension) {\n case \"minecraft:overworld\" -> OVERWORLD;\n case \"minecraft:the_nether\" -> NETHER;\n case \"minecraft:the_end\" -> THE_END;\n default -> CUSTOM;\n };\n }\n\n @Override\n public @NotNull String toString() {\n return this.name;\n }\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/command/argument/ZoomArgument.java\npublic class ZoomArgument extends CommandArgument<@NotNull C, @NotNull Integer> {\n protected ZoomArgument(boolean required, @NotNull String name, @NotNull String defaultValue, @NotNull BiFunction<@NotNull CommandContext<@NotNull C>, @NotNull String, @NotNull List<@NotNull String>> suggestionsProvider, @NotNull ArgumentDescription defaultDescription) {\n super(required, name, new ZoomParser<>(), defaultValue, Integer.class, suggestionsProvider, defaultDescription);\n }\n\n /**\n * Create a new {@link ZoomArgument} builder.\n *\n * @param name argument name\n * @return new player argument builder\n */\n public static CommandArgument.@NotNull Builder<@NotNull C, @NotNull Integer> newBuilder(@NotNull String name) {\n return new Builder<>(name);\n }\n\n /**\n * Create a required {@link ZoomArgument}.\n *\n * @param name argument name\n * @return constructed player argument\n */\n public static @NotNull CommandArgument<@NotNull C, @NotNull Integer> of(@NotNull String name) {\n return ZoomArgument.<@NotNull C>newBuilder(name).asRequired().build();\n }\n\n /**\n * Create an optional {@link ZoomArgument}.\n *

\n * All arguments prior to any other required argument must also be required.\n *\n * @param name argument name\n * @return constructed player argument\n */\n public static @NotNull CommandArgument<@NotNull C, @NotNull Integer> optional(@NotNull String name) {\n return ZoomArgument.<@NotNull C>newBuilder(name).asOptional().build();\n }\n\n /**\n * Create an optional {@link ZoomArgument} with a default value.\n *

\n * All arguments prior to any other required argument must also be required.\n *\n * @param name argument name\n * @param defaultValue default value that will be used if none was supplied\n * @return constructed player argument\n */\n public static @NotNull CommandArgument<@NotNull C, @NotNull Integer> optional(@NotNull String name, @NotNull String defaultValue) {\n return ZoomArgument.<@NotNull C>newBuilder(name).asOptionalWithDefault(defaultValue).build();\n }\n\n /**\n * Mutable builder for {@link ZoomArgument} instances.\n *\n * @param command sender type\n */\n public static class Builder extends CommandArgument.Builder<@NotNull C, @NotNull Integer> {\n private Builder(@NotNull String name) {\n super(Integer.class, name);\n }\n\n @Override\n public @NotNull CommandArgument<@NotNull C, @NotNull Integer> build() {\n return new ZoomArgument<>(isRequired(), getName(), getDefaultValue(), getSuggestionsProvider(), getDefaultDescription());\n }\n }\n}", "answers": [" private void executeAsync(@NotNull CommandContext<@NotNull Sender> context) {"], "length": 2138, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "0e903f89-c1fd-482f-a2d9-45cf7b4ab7ae", "reasoning": "The StitchCommand class defines a register method and an execute method that delegates to an asynchronous method executeAsync. The imports at the end of the file set up needed classes, and the next logical line is the declaration of the private executeAsync method that will contain the command's logic.", "reasoning_model_answer": "private void executeAsync(@NotNull CommandContext<@NotNull Sender> context) {", "assistant_with_reasoning": "\nThe StitchCommand class defines a register method and an execute method that delegates to an asynchronous method executeAsync. The imports at the end of the file set up needed classes, and the next logical line is the declaration of the private executeAsync method that will contain the command's logic.\n\nprivate void executeAsync(@NotNull CommandContext<@NotNull Sender> context) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.999, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 3, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 24470, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private void executeAsync(@NotNull CommandContext<@NotNull Sender> context) {", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.ObjectStreamException;\nimport java.io.Serializable;\nimport java.util.function.Function;\nimport edu.uky.cs.nil.sabre.Exceptions;\nimport edu.uky.cs.nil.sabre.Fluent;\nimport edu.uky.cs.nil.sabre.Number;\nimport edu.uky.cs.nil.sabre.Settings;\nimport edu.uky.cs.nil.sabre.State;\nimport edu.uky.cs.nil.sabre.Utilities;\nimport edu.uky.cs.nil.sabre.io.DefaultParser;\nimport edu.uky.cs.nil.sabre.util.Unique;", "context": "src/edu/uky/cs/nil/sabre/logic/Arithmetic.java\npackage edu.uky.cs.nil.sabre.logic;\n\n\n\n/**\n * An arithmetic expression is a {@link Numeric numeric expression} whose value\n * if the results of applying {@link Operator an arithmetic operation} to two\n * numeric values.\n * \n * @author Stephen G. Ware\n */\npublic class Arithmetic implements Numeric {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/**\n\t * An arithmetic operator is a singleton object that specifies how to\n\t * combine two numeric input values into a numeric output value.\n\t * \n\t * @author Stephen G. Ware\n\t */\n\tpublic static abstract class Operator implements Comparable, Serializable, Unique {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = Arithmetic.serialVersionUID;\n\t\t\n\t\tprivate Operator() {}\n\t\t\n\t\t@Override\n\t\tpublic int compareTo(Operator other) {\n\t\t\treturn hashCode() - other.hashCode();\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the result of applying this operator to two input values.\n\t\t * If both values are numbers, this method calls {@link\n\t\t * #calculate(Number, Number)}, otherwise this method returns {@link\n\t\t * Unknown unknown}.\n\t\t * \n\t\t * @param left the value on the left of the arithmetic operator\n\t\t * @param right the value on the right of the arithmetic operator\n\t\t * @return the result of applying the arithmetic operation to the\n\t\t * values\n\t\t */\n\t\tpublic Value calculate(Value left, Value right) {\n\t\t\tif(left instanceof Number && right instanceof Number)\n\t\t\t\treturn calculate((Number) left, (Number) right);\n\t\t\telse\n\t\t\t\treturn Unknown.UNKNOWN;\n\t\t}\n\t\t\n\t\t/**\n\t\t * This method is called from {@link #calculate(Value, Value)} when\n\t\t * both values are {@link Number numbers} and returns the result of\n\t\t * applying this operator to two numbers.\n\t\t * \n\t\t * @param left the number on the left of the arithmetic operator\n\t\t * @param right the number on the right of the arithmetic operator\n\t\t * @return the result of applying the arithmetic operation to the\n\t\t * numbers\n\t\t */\n\t\tprotected abstract Number calculate(Number left, Number right);\n\t\t\n\t\t/**\n\t\t * If an {@link Arithmetic arithmetic expression} using this operator\n\t\t * and the given left and right values can be simplified (for example,\n\t\t * if the left and right values are both {@link Value values}), this\n\t\t * method returns the simplified expression. Otherwise, this method\n\t\t * returns null.\n\t\t * \n\t\t * @param left the {@link Arithmetic#left left side} of an \n\t\t * arithmetic expression using this operator\n\t\t * @param right the {@link Arithmetic#right right side} of an\n\t\t * arithmetic expression using this operator\n\t\t * @return a simplified logical expression or null if the expression\n\t\t * cannot be simplified\n\t\t */\n\t\tpublic Expression simplify(Expression left, Expression right) {\n\t\t\tif(left instanceof Value && right instanceof Value)\n\t\t\t\treturn calculate((Value) left, (Value) right);\n\t\t\telse\n\t\t\t\treturn null;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Isolates a query {@link Fluent fluent} on the left side of a {@link\n\t\t * Comparison comparison} which has an arithmetic expression using this\n\t\t * operator {@link Comparison#left on its left}.\n\t\t * \n\t\t * @param query the fluent that should be isolated\n\t\t * @param left the {@link Arithmetic#left left side of the arithmetic\n\t\t * expression} which appears on the left side of the comparison\n\t\t * @param right the {@link Arithmetic#right right side of the\n\t\t * arithmetic expression} which appear on the left side of the\n\t\t * comparison\n\t\t * @param inequality the {@link Comparison.Operator comparison\n\t\t * operator} used in the {@link Comparison comparison}\n\t\t * @param rhs the {@link Comparison#right right side of the comparison}\n\t\t * @return a comparison with the flight as its left side\n\t\t */\n\t\tprotected Expression isolate(Fluent query, Expression left, Expression right, Comparison.Operator inequality, Expression rhs) {\n\t\t\tthrow Exceptions.cannotIsolate(query, new Comparison(inequality, new Arithmetic(this, left, right), rhs));\n\t\t}\n\t}\n\t\n\t/**\n\t * An {@link Operator arithmetic operator} for adding the left and right\n\t * sides of an {@link Arithmetic arithmetic expression}.\n\t */\n\tpublic static final Operator ADD = new Operator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn DefaultParser.ADDITION_KEYWORD;\n\t\t}\n\n\t\t/**\n\t\t * Adds two numbers.\n\t\t * \n\t\t * @param left the number on the left\n\t\t * @param right the number on the right\n\t\t * @return the result of adding the numbers\n\t\t */\n\t\t@Override\n\t\tprotected Number calculate(Number left, Number right) {\n\t\t\treturn left.add(right);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expression simplify(Expression left, Expression right) {\n\t\t\tif(left.equals(Number.ZERO))\n\t\t\t\treturn right;\n\t\t\telse if(right.equals(Number.ZERO))\n\t\t\t\treturn left;\n\t\t\telse\n\t\t\t\treturn super.simplify(left, right);\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected Expression isolate(Fluent query, Expression left, Expression right, Comparison.Operator inequality, Expression rhs) {\n\t\t\tif(left.occurs(query))\n\t\t\t\treturn new Comparison(inequality, left, new Arithmetic(SUBTRACT, rhs, right)).isolate(query);\n\t\t\telse if(right.occurs(query))\n\t\t\t\treturn new Comparison(inequality, new Arithmetic(this, right, left), rhs).isolate(query);\n\t\t\telse\n\t\t\t\treturn super.isolate(query, left, right, inequality, rhs);\n\t\t}\n\t\t\n\t\tprivate Object readResolve() throws ObjectStreamException {\n\t\t\treturn ADD;\n\t\t}\n\t};\n\t\n\t/**\n\t * An {@link Operator arithmetic operator} for subtracting the right side\n\t * of an {@link Arithmetic arithmetic expression} from the left.\n\t */\n\tpublic static final Operator SUBTRACT = new Operator() {\n\t\t\n\t\t/** Serial version ID */\n\t\tprivate static final long serialVersionUID = 1;\n\t\t\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn 1;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\nsrc/edu/uky/cs/nil/sabre/State.java\n@FunctionalInterface\npublic interface State {\n\n\t/**\n\t * Returns the value assigned to a fluent in the current state.\n\t * \n\t * @param fluent the fluent\n\t * @return the value\n\t */\n\tpublic Value getValue(Fluent fluent);\n}\n\nsrc/edu/uky/cs/nil/sabre/Number.java\npublic class Number implements Numeric, Value {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/** A mapping of Java doubles to their unique corresponding number objects */\n\tprivate static final HashMap numbers = new HashMap<>();\n\t\n\t/**\n\t * Converts a {@link java.lang.Number Java Number} to a {@link\n\t * Value value}, interning it to ensure that there is only ever one number\n\t * object with this value. If this method is called multiple times with the\n\t * same input value, it will return the same number object every time.\n\t * \n\t * @param value the value of the number\n\t * @return the number object\n\t */\n\tpublic static final Number get(java.lang.Number value) {\n\t\tvalue = Double.valueOf(value.doubleValue());\n\t\tif(value.equals(Double.NaN) || value.equals(-0.0))\n\t\t\tthrow Exceptions.notANumber(value);\n\t\tNumber number = numbers.get(value);\n\t\tif(number == null)\n\t\t\tnumber = new Number((Double) value);\n\t\treturn number;\n\t}\n\t\n\t/** A constant representing zero */\n\tpublic static final Number ZERO = get(0);\n\t\n\t/** A constant representing one */\n\tpublic static final Number ONE = get(1);\n\t\n\t/** A constant representing positive infinity */\n\tpublic static final Number POSITIVE_INFINITY = get(Double.POSITIVE_INFINITY);\n\t\n\t/** A constant representing negative infinity */\n\tpublic static final Number NEGATIVE_INFINITY = get(Double.NEGATIVE_INFINITY);\n\t\n\t/**\n\t * Returns the larger of two numbers.\n\t * \n\t * @param n1 the first number\n\t * @param n2 the second number\n\t * @return n2 if it is larger, n1 otherwise\n\t */\n\tpublic static final Number max(Number n1, Number n2) {\n\t\tif(n2.isGreaterThan(n1))\n\t\t\treturn n2;\n\t\telse\n\t\t\treturn n1;\n\t}\n\t\n\t/**\n\t * Returns the smaller of two numbers.\n\t * \n\t * @param n1 the first number\n\t * @param n2 the second number\n\t * @return n2 if it is smaller, n1 otherwise\n\t */\n\tpublic static final Number min(Number n1, Number n2) {\n\t\tif(n2.isLessThan(n1))\n\t\t\treturn n2;\n\t\telse\n\t\t\treturn n1;\n\t}\n\t\n\t/** The value of this number as a Java {@code double} */\n\tpublic final java.lang.Double value;\n\t\n\t/**\n\t * Constructs a new number.\n\t * \n\t * @param value the value\n\t */\n\tprivate Number(java.lang.Double value) {\n\t\tthis.value = value;\n\t\tnumbers.put(value, this);\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn value.hashCode();\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn Utilities.DEFAULT_PRINTER.toString(this);\n\t}\n\t\n\t@Override\n\tpublic int compareTo(Logical other) {\n\t\tif(other.equals(False.FALSE) || other.equals(True.TRUE) || other.equals(Unknown.UNKNOWN))\n\t\t\treturn 1;\n\t\telse if(other instanceof Number)\n\t\t\treturn Double.compare(value, ((Number) other).value);\n\t\telse\n\t\t\treturn -1;\n\t}\n\t\n\t@Override\n\tpublic boolean isGround() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic Number apply(Function function) {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Number simplify() {\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic Number evaluate(State state) {\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Number prepend(Parameter character) {\n\t\treturn this;\n\t}\n\t\n\t/**\n\t * Tests whether this number is larger than a given second number.\n\t * \n\t * @param other the second number\n\t * @return true if this number is larger than the second, false otherwise\n\t */\n\tpublic boolean isGreaterThan(Number other) {\n\t\treturn compareTo(other) > 0;\n\t}\n\n\t/**\n\t * Tests whether this number is larger than or the same as a given second\n\t * number.\n\t * \n\t * @param other the second number\n\t * @return true if this number is larger than or the same as the second,\n\t * false otherwise\n\t */\n\tpublic boolean isGreaterThanOrEqualTo(Number other) {\n\t\treturn isGreaterThan(other) || equals(other);\n\t}\n\n\t/**\n\t * Tests whether this number is smaller than a given second number.\n\t * \n\t * @param other the second number\n\t * @return true if this number is smaller than the second, false otherwise\n\t */\n\tpublic boolean isLessThan(Number other) {\n\t\treturn compareTo(other) < 0;\n\t}\n\n\t/**\n\t * Tests whether this number is smaller than or the same as a given second\n\t * number.\n\t * \n\t * @param other the second number\n\t * @return true if this number is smaller than or the same as the second,\n\t * false otherwise\n\t */\n\tpublic boolean isLessThanOrEqualTo(Number other) {\n\t\treturn isLessThan(other) || equals(other);\n\t}\n\n\t/**\n\t * Returns a new number which is the sum of this number and the given\n\t * second number.\n\t * \n\t * @param number the second number\n\t * @return the sum of the two numbers\n\t */\n\tpublic Number add(Number number) {\n\t\tif(this.equals(POSITIVE_INFINITY) || number.equals(POSITIVE_INFINITY))\n\t\t\treturn POSITIVE_INFINITY;\n\t\telse\n\t\t\treturn get(value.doubleValue() + number.value.doubleValue());\n\t}\n\n\t/**\n\t * Returns a new number which is the difference of this number and the\n\t * given second number.\n\t * \n\t * @param number the second number\n\t * @return the difference of the two numbers\n\t */\n\tpublic Number subtract(Number number) {\n\t\tif(this.equals(POSITIVE_INFINITY) || number.equals(NEGATIVE_INFINITY))\n\t\t\treturn POSITIVE_INFINITY;\n\t\telse if(number.equals(POSITIVE_INFINITY))\n\t\t\treturn NEGATIVE_INFINITY;\n\t\telse\n\t\t\treturn get(value.doubleValue() - number.value.doubleValue());\n\t}\n\n\t/**\n\t * Returns a new number which is the product of this number and the given\n\t * second number.\n\t * \n\t * @param number the second number\n\t * @return the product of the two numbers\n\t */\n\tpublic Number multiply(Number number) {\n\t\tif(this.equals(ZERO) || number.equals(ZERO))\n\t\t\treturn ZERO;\n\t\telse\n\t\t\treturn get(value.doubleValue() * number.value.doubleValue());\n\t}\n\n\t/**\n\t * Returns a new number which is the quotient of this number and the given\n\t * second number.\n\t * \n\t * @param number the second number\n\t * @return the quotient of the two numbers\n\t */\n\tpublic Number divide(Number number) {\n\t\tif(number.equals(ZERO))\n\t\t\tthrow Exceptions.divideByZero(this);\n\t\telse if(this.equals(ZERO) || number.equals(POSITIVE_INFINITY) || number.equals(NEGATIVE_INFINITY))\n\t\t\treturn ZERO;\n\t\telse\n\t\t\treturn get(value.doubleValue() / number.value.doubleValue());\n\t}\n\t\n\t/**\n\t * Ensures there is at most one object for each unique value.\n\t * \n\t * @return the same object used for all numbers of this value\n\t * @throws ObjectStreamException if deserialization failed\n\t */\n\tprivate Object readResolve() throws ObjectStreamException {\n\t\treturn get(value);\n\t}\n}\n\nsrc/edu/uky/cs/nil/sabre/util/Unique.java\npublic interface Unique {\n\n\t@Override\n\tpublic int hashCode();\n}\n\nsrc/edu/uky/cs/nil/sabre/Settings.java\npublic class Settings {\n\n\t/** The full name of this software library */\n\tpublic static final String TITLE = \"The Sabre Narrative Planner\";\n\t\n\t/** The list of primary authors */\n\tpublic static final String AUTHORS = \"Stephen G. Ware\";\n\t\n\t/** The major version number comes before the decimal points */\n\tpublic static final int MAJOR_VERSION_NUMBER = 0;\n\t\n\t/** The minor version number comes after the decimal point */\n\tpublic static final int MINOR_VERSION_NUMBER = 7;\n\t\n\t/** The full version number (major + minor) as a string */\n\tpublic static final String VERSION_STRING = MAJOR_VERSION_NUMBER + \".\" + MINOR_VERSION_NUMBER;\n\t\n\t/**\n\t * A long encoding the version number which can be used as a serial version UID\n\t */\n\tpublic static final long VERSION_UID = java.nio.ByteBuffer.allocate(8).putInt(MAJOR_VERSION_NUMBER).putInt(MINOR_VERSION_NUMBER).getLong(0);\n\t\n\t/** A header including title, authors, and version number */\n\tpublic static final String CREDITS = TITLE + \" v\" + VERSION_STRING + \" by \" + AUTHORS;\n\t\n\t/** The name of the Boolean type which is pre-defined in all problems */\n\tpublic static final String BOOLEAN_TYPE_NAME = \"boolean\";\n\t\n\t/** The ID number and index of the Boolean type */\n\tpublic static final int BOOLEAN_TYPE_ID = 0;\n\t\n\t/** The comment associated with the Boolean type by default */\n\tpublic static final String BOOLEAN_TYPE_COMMENT = \"\";\n\t\n\t/** The name of the number type which is pre-defined in all problems */\n\tpublic static final String NUMBER_TYPE_NAME = \"number\";\n\t\n\t/** The ID number and index of the number type */\n\tpublic static final int NUMBER_TYPE_ID = 1;\n\t\n\t/** The comment associated with the number type by default */\n\tpublic static final String NUMBER_TYPE_COMMENT = \"\";\n\t\n\t/**\n\t * The name of the entity type which is the parent type of all other types\n\t * and is pre-defined in all problems\n\t */\n\tpublic static final String ENTITY_TYPE_NAME = \"entity\";\n\t\n\t/** The ID number and index of the entity type */\n\tpublic static final int ENTITY_TYPE_ID = 2;\n\t\n\t/** The comment associated with the entity type by default */\n\tpublic static final String ENTITY_TYPE_COMMENT = \"\";\n\t\n\t/**\n\t * The name of the character type which represents beings with beliefs and\n\t * intentions and is pre-defined in all problems\n\t */\n\tpublic static final String CHARACTER_TYPE_NAME = \"character\";\n\t\n\t/** The ID number and index of the character type */\n\tpublic static final int CHARACTER_TYPE_ID = 3;\n\t\n\t/** The comment associated with the character type by default */\n\tpublic static final String CHARACTER_TYPE_COMMENT = \"\";\n\t\n\t/** The comment associated with a newly defined type by default */\n\tpublic static final String DEFAULT_TYPE_COMMENT = \"\";\n\t\n\t/** The comment associated with a newly defined entity by default */\n\tpublic static final String DEFAULT_ENTITY_COMMENT = \"\";\t\n\t\n\t/** The comment associated with a newly defined problem by default */\n\tpublic static final String DEFAULT_PROBLEM_COMMENT = \"\";\n}", "answers": ["\t\t\treturn DefaultParser.SUBTRACTION_KEYWORD;"], "length": 2188, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "e711e73c-f092-4080-9258-d468daeacb28", "reasoning": "The code is defining the SUBTRACT operator, mirroring the ADD operator defined earlier. In ADD, the toString method returns DefaultParser.ADDITION_KEYWORD. Therefore, SUBTRACT's toString should return the corresponding subtraction keyword constant. The next line after the method signature is the return statement with DefaultParser.SUBTRACTION_KEYWORD.", "reasoning_model_answer": "return DefaultParser.SUBTRACTION_KEYWORD;", "assistant_with_reasoning": "\nThe code is defining the SUBTRACT operator, mirroring the ADD operator defined earlier. In ADD, the toString method returns DefaultParser.ADDITION_KEYWORD. Therefore, SUBTRACT's toString should return the corresponding subtraction keyword constant. The next line after the method signature is the return statement with DefaultParser.SUBTRACTION_KEYWORD.\n\nreturn DefaultParser.SUBTRACTION_KEYWORD;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.446, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16066, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return DefaultParser.SUBTRACTION_KEYWORD;", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.IOException;\nimport net.minecraft.network.Packet;\nimport net.minecraft.network.PacketBuffer;\nimport net.minecraft.network.play.INetHandlerPlayClient;\nimport net.minecraft.util.BlockPos;", "context": "src/minecraft/net/minecraft/network/play/server/S25PacketBlockBreakAnim.java\npackage net.minecraft.network.play.server;\n\n\npublic class S25PacketBlockBreakAnim implements Packet {\n private int breakerId;\n private BlockPos position;\n private int progress;\n\n public S25PacketBlockBreakAnim() {\n }\n\n public S25PacketBlockBreakAnim(int breakerId, BlockPos pos, int progress) {\n this.breakerId = breakerId;\n this.position = pos;\n this.progress = progress;\n }\n\n @Override\n public void readPacketData(PacketBuffer buf) throws IOException {\n this.breakerId = buf.readVarIntFromBuffer();\n this.position = buf.readBlockPos();\n this.progress = buf.readUnsignedByte();\n }\n\n @Override\n public void writePacketData(PacketBuffer buf) throws IOException {\n buf.writeVarIntToBuffer(this.breakerId);\n\nsrc/minecraft/net/minecraft/util/BlockPos.java\npublic class BlockPos extends Vec3i {\n public static final BlockPos ORIGIN = new BlockPos(0, 0, 0);\n private static final int NUM_X_BITS = 1 + MathHelper.calculateLogBaseTwo(MathHelper.roundUpToPowerOfTwo(30000000));\n private static final int NUM_Z_BITS = NUM_X_BITS;\n private static final int NUM_Y_BITS = 64 - NUM_X_BITS - NUM_Z_BITS;\n private static final int Y_SHIFT = 0 + NUM_Z_BITS;\n private static final int X_SHIFT = Y_SHIFT + NUM_Y_BITS;\n private static final long X_MASK = (1L << NUM_X_BITS) - 1L;\n private static final long Y_MASK = (1L << NUM_Y_BITS) - 1L;\n private static final long Z_MASK = (1L << NUM_Z_BITS) - 1L;\n\n public BlockPos(int x, int y, int z) {\n super(x, y, z);\n }\n\n public BlockPos(double x, double y, double z) {\n super(x, y, z);\n }\n\n public BlockPos(Entity source) {\n this(source.posX, source.posY, source.posZ);\n }\n\n public BlockPos(Vec3 source) {\n this(source.xCoord, source.yCoord, source.zCoord);\n }\n\n public BlockPos(Vec3i source) {\n this(source.getX(), source.getY(), source.getZ());\n }\n\n public boolean equalsBlockPos(BlockPos blockPos) {\n return this.getX() == blockPos.getX() && this.getY() == blockPos.getY() && this.getZ() == blockPos.getZ();\n }\n\n public boolean equalsBlockPosXZ(BlockPos blockPos) {\n return this.getX() == blockPos.getX() && this.getZ() == blockPos.getZ();\n }\n\n public BlockPos add(double x, double y, double z) {\n return x == 0.0 && y == 0.0 && z == 0.0 ? this : new BlockPos((double)this.getX() + x, (double)this.getY() + y, (double)this.getZ() + z);\n }\n\n public BlockPos add(int x, int y, int z) {\n return x == 0 && y == 0 && z == 0 ? this : new BlockPos(this.getX() + x, this.getY() + y, this.getZ() + z);\n }\n\n public BlockPos add(Vec3i vec) {\n return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0\n ? this\n : new BlockPos(this.getX() + vec.getX(), this.getY() + vec.getY(), this.getZ() + vec.getZ());\n }\n\n public BlockPos subtract(Vec3i vec) {\n return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0\n ? this\n : new BlockPos(this.getX() - vec.getX(), this.getY() - vec.getY(), this.getZ() - vec.getZ());\n }\n\n public BlockPos up() {\n return this.up(1);\n }\n\n public BlockPos up(int n) {\n return this.offset(EnumFacing.UP, n);\n }\n\n public BlockPos down() {\n return this.down(1);\n }\n\n public BlockPos down(int n) {\n return this.offset(EnumFacing.DOWN, n);\n }\n\n public BlockPos north() {\n return this.north(1);\n }\n\n public BlockPos north(int n) {\n return this.offset(EnumFacing.NORTH, n);\n }\n\n public BlockPos south() {\n return this.south(1);\n }\n\n public BlockPos south(int n) {\n return this.offset(EnumFacing.SOUTH, n);\n }\n\n public BlockPos west() {\n return this.west(1);\n }\n\n public BlockPos west(int n) {\n return this.offset(EnumFacing.WEST, n);\n }\n\n public BlockPos east() {\n return this.east(1);\n }\n\n public BlockPos east(int n) {\n return this.offset(EnumFacing.EAST, n);\n }\n\n public BlockPos offset(EnumFacing facing) {\n return this.offset(facing, 1);\n }\n\n public BlockPos offset(EnumFacing facing, int n) {\n return n == 0\n ? this\n : new BlockPos(this.getX() + facing.getFrontOffsetX() * n, this.getY() + facing.getFrontOffsetY() * n, this.getZ() + facing.getFrontOffsetZ() * n);\n }\n\n public BlockPos crossProduct(Vec3i vec) {\n return new BlockPos(\n this.getY() * vec.getZ() - this.getZ() * vec.getY(),\n this.getZ() * vec.getX() - this.getX() * vec.getZ(),\n this.getX() * vec.getY() - this.getY() * vec.getX()\n );\n }\n\n public long toLong() {\n return ((long)this.getX() & X_MASK) << X_SHIFT | ((long)this.getY() & Y_MASK) << Y_SHIFT | ((long)this.getZ() & Z_MASK) << 0;\n }\n\n public static BlockPos fromLong(long serialized) {\n int i = (int)(serialized << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS);\n int j = (int)(serialized << 64 - Y_SHIFT - NUM_Y_BITS >> 64 - NUM_Y_BITS);\n int k = (int)(serialized << 64 - NUM_Z_BITS >> 64 - NUM_Z_BITS);\n return new BlockPos(i, j, k);\n }\n\n public static Iterable getAllInBox(BlockPos from, BlockPos to) {\n final BlockPos blockpos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ()));\n final BlockPos blockpos1 = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ()));\n return new Iterable() {\n @Override\n public Iterator iterator() {\n return new AbstractIterator() {\n private BlockPos lastReturned = null;\n\n protected BlockPos computeNext() {\n if (this.lastReturned == null) {\n this.lastReturned = blockpos;\n return this.lastReturned;\n } else if (this.lastReturned.equals(blockpos1)) {\n return this.endOfData();\n } else {\n int i = this.lastReturned.getX();\n int j = this.lastReturned.getY();\n int k = this.lastReturned.getZ();\n if (i < blockpos1.getX()) {\n ++i;\n } else if (j < blockpos1.getY()) {\n i = blockpos.getX();\n ++j;\n } else if (k < blockpos1.getZ()) {\n i = blockpos.getX();\n j = blockpos.getY();\n ++k;\n }\n\n this.lastReturned = new BlockPos(i, j, k);\n return this.lastReturned;\n }\n }\n };\n }\n };\n }\n\n public static Iterable getAllInBoxMutable(BlockPos from, BlockPos to) {\n final BlockPos blockpos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ()));\n final BlockPos blockpos1 = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ()));\n return new Iterable() {\n @Override\n public Iterator iterator() {\n return new AbstractIterator() {\n private BlockPos.MutableBlockPos theBlockPos = null;\n\n protected BlockPos.MutableBlockPos computeNext() {\n if (this.theBlockPos == null) {\n this.theBlockPos = new BlockPos.MutableBlockPos(blockpos.getX(), blockpos.getY(), blockpos.getZ());\n return this.theBlockPos;\n } else if (this.theBlockPos.equals(blockpos1)) {\n return this.endOfData();\n } else {\n int i = this.theBlockPos.getX();\n int j = this.theBlockPos.getY();\n int k = this.theBlockPos.getZ();\n if (i < blockpos1.getX()) {\n ++i;\n } else if (j < blockpos1.getY()) {\n i = blockpos.getX();\n ++j;\n } else if (k < blockpos1.getZ()) {\n i = blockpos.getX();\n j = blockpos.getY();\n ++k;\n }\n\n this.theBlockPos.x = i;\n this.theBlockPos.y = j;\n this.theBlockPos.z = k;\n return this.theBlockPos;\n }\n }\n };\n }\n };\n }\n\n public static final class MutableBlockPos extends BlockPos {\n private int x;\n private int y;\n private int z;\n\n public MutableBlockPos() {\n this(0, 0, 0);\n }\n\n public MutableBlockPos(int x_, int y_, int z_) {\n super(0, 0, 0);\n this.x = x_;\n this.y = y_;\n this.z = z_;\n }\n\n @Override\n public int getX() {\n return this.x;\n }\n\n @Override\n public int getY() {\n return this.y;\n }\n\n @Override\n public int getZ() {\n return this.z;\n }\n\n public BlockPos.MutableBlockPos func_181079_c(int p_181079_1_, int p_181079_2_, int p_181079_3_) {\n this.x = p_181079_1_;\n this.y = p_181079_2_;\n this.z = p_181079_3_;\n return this;\n }\n }\n}\n\nsrc/minecraft/net/minecraft/network/PacketBuffer.java\npublic class PacketBuffer extends ByteBuf {\n private final ByteBuf buf;\n\n public PacketBuffer(ByteBuf wrapped) {\n this.buf = wrapped;\n }\n\n public static int getVarIntSize(int input) {\n for(int i = 1; i < 5; ++i) {\n if ((input & -1 << i * 7) == 0) {\n return i;\n }\n }\n\n return 5;\n }\n\n public void writeByteArray(byte[] array) {\n this.writeVarIntToBuffer(array.length);\n this.writeBytes(array);\n }\n\n public byte[] readByteArray() {\n byte[] abyte = new byte[this.readVarIntFromBuffer()];\n this.readBytes(abyte);\n return abyte;\n }\n\n public BlockPos readBlockPos() {\n return BlockPos.fromLong(this.readLong());\n }\n\n public void writeBlockPos(BlockPos pos) {\n this.writeLong(pos.toLong());\n }\n\n public IChatComponent readChatComponent() throws IOException {\n return IChatComponent.Serializer.jsonToComponent(this.readStringFromBuffer(32767));\n }\n\n public void writeChatComponent(IChatComponent component) throws IOException {\n this.writeString(IChatComponent.Serializer.componentToJson(component));\n }\n\n public > T readEnumValue(Class enumClass) {\n return enumClass.getEnumConstants()[this.readVarIntFromBuffer()];\n }\n\n public void writeEnumValue(Enum value) {\n this.writeVarIntToBuffer(value.ordinal());\n }\n\n public int readVarIntFromBuffer() {\n int i = 0;\n int j = 0;\n\n byte b0;\n do {\n b0 = this.readByte();\n i |= (b0 & 127) << j++ * 7;\n if (j > 5) {\n throw new RuntimeException(\"VarInt too big\");\n }\n } while((b0 & 128) == 128);\n\n return i;\n }\n\n public long readVarLong() {\n long i = 0L;\n int j = 0;\n\n byte b0;\n do {\n b0 = this.readByte();\n i |= (long)(b0 & 127) << j++ * 7;\n if (j > 10) {\n throw new RuntimeException(\"VarLong too big\");\n }\n } while((b0 & 128) == 128);\n\n return i;\n }\n\n public void writeUuid(UUID uuid) {\n this.writeLong(uuid.getMostSignificantBits());\n this.writeLong(uuid.getLeastSignificantBits());\n }\n\n public UUID readUuid() {\n return new UUID(this.readLong(), this.readLong());\n }\n\n public void writeVarIntToBuffer(int input) {\n while((input & -128) != 0) {\n this.writeByte(input & 127 | 128);\n input >>>= 7;\n }\n\n this.writeByte(input);\n }\n\n public void writeVarLong(long value) {\n while((value & -128L) != 0L) {\n this.writeByte((int)(value & 127L) | 128);\n value >>>= 7;\n }\n\n this.writeByte((int)value);\n }\n\n public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) {\n if (nbt == null) {\n this.writeByte(0);\n } else {\n try {\n CompressedStreamTools.write(nbt, new ByteBufOutputStream(this));\n } catch (IOException var3) {\n throw new EncoderException(var3);\n }\n }\n }\n\n public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException {\n int i = this.readerIndex();\n byte b0 = this.readByte();\n if (b0 == 0) {\n return null;\n } else {\n this.readerIndex(i);\n return CompressedStreamTools.read(new ByteBufInputStream(this), new NBTSizeTracker(2097152L));\n }\n }\n\n public void writeItemStackToBuffer(ItemStack stack) {\n if (stack == null) {\n this.writeShort(-1);\n } else {\n this.writeShort(Item.getIdFromItem(stack.getItem()));\n this.writeByte(stack.stackSize);\n this.writeShort(stack.getMetadata());\n NBTTagCompound nbttagcompound = null;\n if (stack.getItem().isDamageable() || stack.getItem().getShareTag()) {\n nbttagcompound = stack.getTagCompound();\n }\n\n this.writeNBTTagCompoundToBuffer(nbttagcompound);\n }\n }\n\n public ItemStack readItemStackFromBuffer() throws IOException {\n ItemStack itemstack = null;\n int i = this.readShort();\n if (i >= 0) {\n int j = this.readByte();\n int k = this.readShort();\n itemstack = new ItemStack(Item.getItemById(i), j, k);\n itemstack.setTagCompound(this.readNBTTagCompoundFromBuffer());\n }\n\n return itemstack;\n }\n\n public String readStringFromBuffer(int maxLength) {\n int i = this.readVarIntFromBuffer();\n if (i > maxLength * 4) {\n throw new DecoderException(\"The received encoded string buffer length is longer than maximum allowed (\" + i + \" > \" + maxLength * 4 + \")\");\n } else if (i < 0) {\n throw new DecoderException(\"The received encoded string buffer length is less than zero! Weird string!\");\n } else {\n String s = new String(this.readBytes(i).array(), Charsets.UTF_8);\n if (s.length() > maxLength) {\n throw new DecoderException(\"The received string length is longer than maximum allowed (\" + i + \" > \" + maxLength + \")\");\n } else {\n return s;\n }\n }\n }\n\n public PacketBuffer writeString(String string) {\n byte[] abyte = string.getBytes(Charsets.UTF_8);\n if (abyte.length > 32767) {\n throw new EncoderException(\"String too big (was \" + string.length() + \" bytes encoded, max \" + 32767 + \")\");\n } else {\n this.writeVarIntToBuffer(abyte.length);\n this.writeBytes(abyte);\n return this;\n }\n }\n\n @Override\n public int capacity() {\n return this.buf.capacity();\n }\n\n @Override\n public ByteBuf capacity(int p_capacity_1_) {\n return this.buf.capacity(p_capacity_1_);\n }\n\n @Override\n public int maxCapacity() {\n return this.buf.maxCapacity();\n }\n\n @Override\n public ByteBufAllocator alloc() {\n return this.buf.alloc();\n }\n\n @Override\n public ByteOrder order() {\n return this.buf.order();\n }\n\n @Override\n public ByteBuf order(ByteOrder p_order_1_) {\n return this.buf.order(p_order_1_);\n }\n\n @Override\n public ByteBuf unwrap() {\n return this.buf.unwrap();\n }\n\n @Override\n public boolean isDirect() {\n return this.buf.isDirect();\n }\n\n @Override\n public int readerIndex() {\n return this.buf.readerIndex();\n }\n\n @Override\n public ByteBuf readerIndex(int p_readerIndex_1_) {\n return this.buf.readerIndex(p_readerIndex_1_);\n }\n\n @Override\n public int writerIndex() {\n return this.buf.writerIndex();\n }\n\n @Override\n public ByteBuf writerIndex(int p_writerIndex_1_) {\n return this.buf.writerIndex(p_writerIndex_1_);\n }\n\n @Override\n public ByteBuf setIndex(int p_setIndex_1_, int p_setIndex_2_) {\n return this.buf.setIndex(p_setIndex_1_, p_setIndex_2_);\n }\n\n @Override\n public int readableBytes() {\n return this.buf.readableBytes();\n }\n\n @Override\n public int writableBytes() {\n return this.buf.writableBytes();\n }\n\n @Override\n public int maxWritableBytes() {\n return this.buf.maxWritableBytes();\n }\n\n @Override\n public boolean isReadable() {\n return this.buf.isReadable();\n }\n\n @Override\n public boolean isReadable(int p_isReadable_1_) {\n return this.buf.isReadable(p_isReadable_1_);\n }\n\n @Override\n public boolean isWritable() {\n return this.buf.isWritable();\n }\n\n @Override\n public boolean isWritable(int p_isWritable_1_) {\n return this.buf.isWritable(p_isWritable_1_);\n }\n\n @Override\n public ByteBuf clear() {\n return this.buf.clear();\n }\n\n @Override\n public ByteBuf markReaderIndex() {\n return this.buf.markReaderIndex();\n }\n\n @Override\n public ByteBuf resetReaderIndex() {\n return this.buf.resetReaderIndex();\n }\n\n @Override\n public ByteBuf markWriterIndex() {\n return this.buf.markWriterIndex();\n }\n\n @Override\n public ByteBuf resetWriterIndex() {\n return this.buf.resetWriterIndex();\n }\n\n @Override\n public ByteBuf discardReadBytes() {\n return this.buf.discardReadBytes();\n }\n\n @Override\n public ByteBuf discardSomeReadBytes() {\n return this.buf.discardSomeReadBytes();\n }\n\n @Override\n public ByteBuf ensureWritable(int p_ensureWritable_1_) {\n return this.buf.ensureWritable(p_ensureWritable_1_);\n }\n\n @Override\n public int ensureWritable(int p_ensureWritable_1_, boolean p_ensureWritable_2_) {\n return this.buf.ensureWritable(p_ensureWritable_1_, p_ensureWritable_2_);\n }\n\n @Override\n public boolean getBoolean(int p_getBoolean_1_) {\n return this.buf.getBoolean(p_getBoolean_1_);\n }\n\n @Override\n public byte getByte(int p_getByte_1_) {\n return this.buf.getByte(p_getByte_1_);\n }\n\n @Override\n public short getUnsignedByte(int p_getUnsignedByte_1_) {\n return this.buf.getUnsignedByte(p_getUnsignedByte_1_);\n }\n\n @Override\n public short getShort(int p_getShort_1_) {\n return this.buf.getShort(p_getShort_1_);\n }\n\n @Override\n public int getUnsignedShort(int p_getUnsignedShort_1_) {\n return this.buf.getUnsignedShort(p_getUnsignedShort_1_);\n }\n\n @Override\n public int getMedium(int p_getMedium_1_) {\n return this.buf.getMedium(p_getMedium_1_);\n }\n\n @Override\n public int getUnsignedMedium(int p_getUnsignedMedium_1_) {\n return this.buf.getUnsignedMedium(p_getUnsignedMedium_1_);\n }\n\n @Override\n public int getInt(int p_getInt_1_) {\n return this.buf.getInt(p_getInt_1_);\n }\n\n @Override\n public long getUnsignedInt(int p_getUnsignedInt_1_) {\n return this.buf.getUnsignedInt(p_getUnsignedInt_1_);\n }\n\n @Override\n public long getLong(int p_getLong_1_) {\n return this.buf.getLong(p_getLong_1_);\n }\n\n @Override\n public char getChar(int p_getChar_1_) {\n return this.buf.getChar(p_getChar_1_);\n }\n\n @Override\n public float getFloat(int p_getFloat_1_) {\n return this.buf.getFloat(p_getFloat_1_);\n }\n\n @Override\n public double getDouble(int p_getDouble_1_) {\n return this.buf.getDouble(p_getDouble_1_);\n }\n\n @Override\n public ByteBuf getBytes(int p_getBytes_1_, ByteBuf p_getBytes_2_) {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_);\n }\n\n @Override\n public ByteBuf getBytes(int p_getBytes_1_, ByteBuf p_getBytes_2_, int p_getBytes_3_) {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_, p_getBytes_3_);\n }\n\n @Override\n public ByteBuf getBytes(int p_getBytes_1_, ByteBuf p_getBytes_2_, int p_getBytes_3_, int p_getBytes_4_) {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_, p_getBytes_3_, p_getBytes_4_);\n }\n\n @Override\n public ByteBuf getBytes(int p_getBytes_1_, byte[] p_getBytes_2_) {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_);\n }\n\n @Override\n public ByteBuf getBytes(int p_getBytes_1_, byte[] p_getBytes_2_, int p_getBytes_3_, int p_getBytes_4_) {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_, p_getBytes_3_, p_getBytes_4_);\n }\n\n @Override\n public ByteBuf getBytes(int p_getBytes_1_, ByteBuffer p_getBytes_2_) {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_);\n }\n\n @Override\n public ByteBuf getBytes(int p_getBytes_1_, OutputStream p_getBytes_2_, int p_getBytes_3_) throws IOException {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_, p_getBytes_3_);\n }\n\n @Override\n public int getBytes(int p_getBytes_1_, GatheringByteChannel p_getBytes_2_, int p_getBytes_3_) throws IOException {\n return this.buf.getBytes(p_getBytes_1_, p_getBytes_2_, p_getBytes_3_);\n }\n\n @Override\n public ByteBuf setBoolean(int p_setBoolean_1_, boolean p_setBoolean_2_) {\n return this.buf.setBoolean(p_setBoolean_1_, p_setBoolean_2_);\n }\n\n @Override\n public ByteBuf setByte(int p_setByte_1_, int p_setByte_2_) {\n return this.buf.setByte(p_setByte_1_, p_setByte_2_);\n }\n\n @Override\n public ByteBuf setShort(int p_setShort_1_, int p_setShort_2_) {\n return this.buf.setShort(p_setShort_1_, p_setShort_2_);\n }\n\n @Override\n public ByteBuf setMedium(int p_setMedium_1_, int p_setMedium_2_) {\n return this.buf.setMedium(p_setMedium_1_, p_setMedium_2_);\n }\n\n @Override\n public ByteBuf setInt(int p_setInt_1_, int p_setInt_2_) {\n return this.buf.setInt(p_setInt_1_, p_setInt_2_);\n }\n\n @Override\n public ByteBuf setLong(int p_setLong_1_, long p_setLong_2_) {\n return this.buf.setLong(p_setLong_1_, p_setLong_2_);\n }\n\n @Override\n public ByteBuf setChar(int p_setChar_1_, int p_setChar_2_) {\n return this.buf.setChar(p_setChar_1_, p_setChar_2_);\n }\n\n @Override\n public ByteBuf setFloat(int p_setFloat_1_, float p_setFloat_2_) {\n return this.buf.setFloat(p_setFloat_1_, p_setFloat_2_);\n }\n\n @Override\n public ByteBuf setDouble(int p_setDouble_1_, double p_setDouble_2_) {\n return this.buf.setDouble(p_setDouble_1_, p_setDouble_2_);\n }\n\n @Override\n public ByteBuf setBytes(int p_setBytes_1_, ByteBuf p_setBytes_2_) {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_);\n }\n\n @Override\n public ByteBuf setBytes(int p_setBytes_1_, ByteBuf p_setBytes_2_, int p_setBytes_3_) {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_, p_setBytes_3_);\n }\n\n @Override\n public ByteBuf setBytes(int p_setBytes_1_, ByteBuf p_setBytes_2_, int p_setBytes_3_, int p_setBytes_4_) {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_, p_setBytes_3_, p_setBytes_4_);\n }\n\n @Override\n public ByteBuf setBytes(int p_setBytes_1_, byte[] p_setBytes_2_) {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_);\n }\n\n @Override\n public ByteBuf setBytes(int p_setBytes_1_, byte[] p_setBytes_2_, int p_setBytes_3_, int p_setBytes_4_) {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_, p_setBytes_3_, p_setBytes_4_);\n }\n\n @Override\n public ByteBuf setBytes(int p_setBytes_1_, ByteBuffer p_setBytes_2_) {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_);\n }\n\n @Override\n public int setBytes(int p_setBytes_1_, InputStream p_setBytes_2_, int p_setBytes_3_) throws IOException {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_, p_setBytes_3_);\n }\n\n @Override\n public int setBytes(int p_setBytes_1_, ScatteringByteChannel p_setBytes_2_, int p_setBytes_3_) throws IOException {\n return this.buf.setBytes(p_setBytes_1_, p_setBytes_2_, p_setBytes_3_);\n }\n\n @Override\n public ByteBuf setZero(int p_setZero_1_, int p_setZero_2_) {\n return this.buf.setZero(p_setZero_1_, p_setZero_2_);\n }\n\n @Override\n public boolean readBoolean() {\n return this.buf.readBoolean();\n }\n\n @Override\n public byte readByte() {\n return this.buf.readByte();\n }\n\n @Override\n public short readUnsignedByte() {\n return this.buf.readUnsignedByte();\n }\n\n @Override\n public short readShort() {\n return this.buf.readShort();\n }\n\n @Override\n public int readUnsignedShort() {\n return this.buf.readUnsignedShort();\n }\n\n @Override\n public int readMedium() {\n return this.buf.readMedium();\n }\n\n @Override\n public int readUnsignedMedium() {\n return this.buf.readUnsignedMedium();\n }\n\n @Override\n public int readInt() {\n return this.buf.readInt();\n }\n\n @Override\n public long readUnsignedInt() {\n return this.buf.readUnsignedInt();\n }\n\n @Override\n public long readLong() {\n return this.buf.readLong();\n }\n\n @Override\n public char readChar() {\n return this.buf.readChar();\n }\n\n @Override\n public float readFloat() {\n return this.buf.readFloat();\n }\n\n @Override\n public double readDouble() {\n return this.buf.readDouble();\n }\n\n @Override\n public ByteBuf readBytes(int p_readBytes_1_) {\n return this.buf.readBytes(p_readBytes_1_);\n }\n\n @Override\n public ByteBuf readSlice(int p_readSlice_1_) {\n return this.buf.readSlice(p_readSlice_1_);\n }\n\n @Override\n public ByteBuf readBytes(ByteBuf p_readBytes_1_) {\n return this.buf.readBytes(p_readBytes_1_);\n }\n\n @Override\n public ByteBuf readBytes(ByteBuf p_readBytes_1_, int p_readBytes_2_) {\n return this.buf.readBytes(p_readBytes_1_, p_readBytes_2_);\n }\n\n @Override\n public ByteBuf readBytes(ByteBuf p_readBytes_1_, int p_readBytes_2_, int p_readBytes_3_) {\n return this.buf.readBytes(p_readBytes_1_, p_readBytes_2_, p_readBytes_3_);\n }\n\n @Override\n public ByteBuf readBytes(byte[] p_readBytes_1_) {\n return this.buf.readBytes(p_readBytes_1_);\n }\n\n @Override\n public ByteBuf readBytes(byte[] p_readBytes_1_, int p_readBytes_2_, int p_readBytes_3_) {\n return this.buf.readBytes(p_readBytes_1_, p_readBytes_2_, p_readBytes_3_);\n }\n\n @Override\n public ByteBuf readBytes(ByteBuffer p_readBytes_1_) {\n return this.buf.readBytes(p_readBytes_1_);\n }\n\n @Override\n public ByteBuf readBytes(OutputStream p_readBytes_1_, int p_readBytes_2_) throws IOException {\n return this.buf.readBytes(p_readBytes_1_, p_readBytes_2_);\n }\n\n @Override\n public int readBytes(GatheringByteChannel p_readBytes_1_, int p_readBytes_2_) throws IOException {\n return this.buf.readBytes(p_readBytes_1_, p_readBytes_2_);\n }\n\n @Override\n public ByteBuf skipBytes(int p_skipBytes_1_) {\n return this.buf.skipBytes(p_skipBytes_1_);\n }\n\n @Override\n public ByteBuf writeBoolean(boolean p_writeBoolean_1_) {\n return this.buf.writeBoolean(p_writeBoolean_1_);\n }\n\n @Override\n public ByteBuf writeByte(int p_writeByte_1_) {\n return this.buf.writeByte(p_writeByte_1_);\n }\n\n @Override\n public ByteBuf writeShort(int p_writeShort_1_) {\n return this.buf.writeShort(p_writeShort_1_);\n }\n\n @Override\n public ByteBuf writeMedium(int p_writeMedium_1_) {\n return this.buf.writeMedium(p_writeMedium_1_);\n }\n\n @Override\n public ByteBuf writeInt(int p_writeInt_1_) {\n return this.buf.writeInt(p_writeInt_1_);\n }\n\n @Override\n public ByteBuf writeLong(long p_writeLong_1_) {\n return this.buf.writeLong(p_writeLong_1_);\n }\n\n @Override\n public ByteBuf writeChar(int p_writeChar_1_) {\n return this.buf.writeChar(p_writeChar_1_);\n }\n\n @Override\n public ByteBuf writeFloat(float p_writeFloat_1_) {\n return this.buf.writeFloat(p_writeFloat_1_);\n }\n\n @Override\n public ByteBuf writeDouble(double p_writeDouble_1_) {\n return this.buf.writeDouble(p_writeDouble_1_);\n }\n\n @Override\n public ByteBuf writeBytes(ByteBuf p_writeBytes_1_) {\n return this.buf.writeBytes(p_writeBytes_1_);\n }\n\n @Override\n public ByteBuf writeBytes(ByteBuf p_writeBytes_1_, int p_writeBytes_2_) {\n return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_);\n }\n\n @Override\n public ByteBuf writeBytes(ByteBuf p_writeBytes_1_, int p_writeBytes_2_, int p_writeBytes_3_) {\n return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_, p_writeBytes_3_);\n }\n\n @Override\n public ByteBuf writeBytes(byte[] p_writeBytes_1_) {\n return this.buf.writeBytes(p_writeBytes_1_);\n }\n\n @Override\n public ByteBuf writeBytes(byte[] p_writeBytes_1_, int p_writeBytes_2_, int p_writeBytes_3_) {\n return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_, p_writeBytes_3_);\n }\n\n @Override\n public ByteBuf writeBytes(ByteBuffer p_writeBytes_1_) {\n return this.buf.writeBytes(p_writeBytes_1_);\n }\n\n @Override\n public int writeBytes(InputStream p_writeBytes_1_, int p_writeBytes_2_) throws IOException {\n return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_);\n }\n\n @Override\n public int writeBytes(ScatteringByteChannel p_writeBytes_1_, int p_writeBytes_2_) throws IOException {\n return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_);\n }\n\n @Override\n public ByteBuf writeZero(int p_writeZero_1_) {\n return this.buf.writeZero(p_writeZero_1_);\n }\n\n @Override\n public int indexOf(int p_indexOf_1_, int p_indexOf_2_, byte p_indexOf_3_) {\n return this.buf.indexOf(p_indexOf_1_, p_indexOf_2_, p_indexOf_3_);\n }\n\n @Override\n public int bytesBefore(byte p_bytesBefore_1_) {\n return this.buf.bytesBefore(p_bytesBefore_1_);\n }\n\n @Override\n public int bytesBefore(int p_bytesBefore_1_, byte p_bytesBefore_2_) {\n return this.buf.bytesBefore(p_bytesBefore_1_, p_bytesBefore_2_);\n }\n\n @Override\n public int bytesBefore(int p_bytesBefore_1_, int p_bytesBefore_2_, byte p_bytesBefore_3_) {\n return this.buf.bytesBefore(p_bytesBefore_1_, p_bytesBefore_2_, p_bytesBefore_3_);\n }\n\n @Override\n public int forEachByte(ByteBufProcessor p_forEachByte_1_) {\n return this.buf.forEachByte(p_forEachByte_1_);\n }\n\n @Override\n public int forEachByte(int p_forEachByte_1_, int p_forEachByte_2_, ByteBufProcessor p_forEachByte_3_) {\n return this.buf.forEachByte(p_forEachByte_1_, p_forEachByte_2_, p_forEachByte_3_);\n }\n\n @Override\n public int forEachByteDesc(ByteBufProcessor p_forEachByteDesc_1_) {\n return this.buf.forEachByteDesc(p_forEachByteDesc_1_);\n }\n\n @Override\n public int forEachByteDesc(int p_forEachByteDesc_1_, int p_forEachByteDesc_2_, ByteBufProcessor p_forEachByteDesc_3_) {\n return this.buf.forEachByteDesc(p_forEachByteDesc_1_, p_forEachByteDesc_2_, p_forEachByteDesc_3_);\n }\n\n @Override\n public ByteBuf copy() {\n return this.buf.copy();\n }\n\n @Override\n public ByteBuf copy(int p_copy_1_, int p_copy_2_) {\n return this.buf.copy(p_copy_1_, p_copy_2_);\n }\n\n @Override\n public ByteBuf slice() {\n return this.buf.slice();\n }\n\n @Override\n public ByteBuf slice(int p_slice_1_, int p_slice_2_) {\n return this.buf.slice(p_slice_1_, p_slice_2_);\n }\n\n @Override\n public ByteBuf duplicate() {\n return this.buf.duplicate();\n }\n\n @Override\n public int nioBufferCount() {\n return this.buf.nioBufferCount();\n }\n\n @Override\n public ByteBuffer nioBuffer() {\n return this.buf.nioBuffer();\n }\n\n @Override\n public ByteBuffer nioBuffer(int p_nioBuffer_1_, int p_nioBuffer_2_) {\n return this.buf.nioBuffer(p_nioBuffer_1_, p_nioBuffer_2_);\n }\n\n @Override\n public ByteBuffer internalNioBuffer(int p_internalNioBuffer_1_, int p_internalNioBuffer_2_) {\n return this.buf.internalNioBuffer(p_internalNioBuffer_1_, p_internalNioBuffer_2_);\n }\n\n @Override\n public ByteBuffer[] nioBuffers() {\n return this.buf.nioBuffers();\n }\n\n @Override\n public ByteBuffer[] nioBuffers(int p_nioBuffers_1_, int p_nioBuffers_2_) {\n return this.buf.nioBuffers(p_nioBuffers_1_, p_nioBuffers_2_);\n }\n\n @Override\n public boolean hasArray() {\n return this.buf.hasArray();\n }\n\n @Override\n public byte[] array() {\n return this.buf.array();\n }\n\n @Override\n public int arrayOffset() {\n return this.buf.arrayOffset();\n }\n\n @Override\n public boolean hasMemoryAddress() {\n return this.buf.hasMemoryAddress();\n }\n\n @Override\n public long memoryAddress() {\n return this.buf.memoryAddress();\n }\n\n @Override\n public String toString(Charset p_toString_1_) {\n return this.buf.toString(p_toString_1_);\n }\n\n @Override\n public String toString(int p_toString_1_, int p_toString_2_, Charset p_toString_3_) {\n return this.buf.toString(p_toString_1_, p_toString_2_, p_toString_3_);\n }\n\n @Override\n public int hashCode() {\n return this.buf.hashCode();\n }\n\n @Override\n public boolean equals(Object p_equals_1_) {\n return this.buf.equals(p_equals_1_);\n }\n\n @Override\n public int compareTo(ByteBuf p_compareTo_1_) {\n return this.buf.compareTo(p_compareTo_1_);\n }\n\n @Override\n public String toString() {\n return this.buf.toString();\n }\n\n @Override\n public ByteBuf retain(int p_retain_1_) {\n return this.buf.retain(p_retain_1_);\n }\n\n @Override\n public ByteBuf retain() {\n return this.buf.retain();\n }\n\n @Override\n public int refCnt() {\n return this.buf.refCnt();\n }\n\n @Override\n public boolean release() {\n return this.buf.release();\n }\n\n @Override\n public boolean release(int p_release_1_) {\n return this.buf.release(p_release_1_);\n }\n}", "answers": [" buf.writeBlockPos(this.position);"], "length": 3039, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "24f5139d-864c-45fc-945d-04d55cbbe60d", "reasoning": "In the writePacketData method, the packet fields must be written in the same order they are read. The read method reads breakerId, then position, then progress. After writing the breakerId with writeVarIntToBuffer, the next field to write is the BlockPos, using the PacketBuffer method writeBlockPos. Therefore the next line is buf.writeBlockPos(this.position);", "reasoning_model_answer": "buf.writeBlockPos(this.position);", "assistant_with_reasoning": "\nIn the writePacketData method, the packet fields must be written in the same order they are read. The read method reads breakerId, then position, then progress. After writing the breakerId with writeVarIntToBuffer, the next field to write is the BlockPos, using the PacketBuffer method writeBlockPos. Therefore the next line is buf.writeBlockPos(this.position);\n\nbuf.writeBlockPos(this.position);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.023, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33961, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "buf.writeBlockPos(this.position);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.IOException;\nimport org.eclipse.jgit.errors.IncorrectObjectTypeException;\nimport org.eclipse.jgit.errors.MissingObjectException;\nimport org.eclipse.jgit.lib.AnyObjectId;\nimport org.eclipse.jgit.lib.Constants;", "context": "org.eclipse.jgit/src/org/eclipse/jgit/revwalk/RevTree.java\n/*\n * Copyright (C) 2009, Google Inc.\n * Copyright (C) 2008, Marek Zawirski \n * Copyright (C) 2008, Shawn O. Pearce and others\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Distribution License v. 1.0 which is available at\n * https://www.eclipse.org/org/documents/edl-v10.php.\n *\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\npackage org.eclipse.jgit.revwalk;\n\n\n\n/**\n * A reference to a tree of subtrees/files.\n */\npublic class RevTree extends RevObject {\n\t/**\n\t * Create a new tree reference.\n\t *\n\t * @param id\n\t * object name for the tree.\n\t */\n\tprotected RevTree(AnyObjectId id) {\n\t\tsuper(id);\n\t}\n\n\t@Override\n\norg.eclipse.jgit/src/org/eclipse/jgit/lib/AnyObjectId.java\npublic abstract class AnyObjectId implements Comparable {\n\n\t/**\n\t * Compare two object identifier byte sequences for equality.\n\t *\n\t * @param firstObjectId\n\t * the first identifier to compare. Must not be null.\n\t * @param secondObjectId\n\t * the second identifier to compare. Must not be null.\n\t * @return true if the two identifiers are the same.\n\t * @deprecated use {@link #isEqual(AnyObjectId, AnyObjectId)} instead\n\t */\n\t@Deprecated\n\t@SuppressWarnings(\"AmbiguousMethodReference\")\n\tpublic static boolean equals(final AnyObjectId firstObjectId,\n\t\t\tfinal AnyObjectId secondObjectId) {\n\t\treturn isEqual(firstObjectId, secondObjectId);\n\t}\n\n\t/**\n\t * Compare two object identifier byte sequences for equality.\n\t *\n\t * @param firstObjectId\n\t * the first identifier to compare. Must not be null.\n\t * @param secondObjectId\n\t * the second identifier to compare. Must not be null.\n\t * @return true if the two identifiers are the same.\n\t * @since 5.4\n\t */\n\tpublic static boolean isEqual(final AnyObjectId firstObjectId,\n\t\t\tfinal AnyObjectId secondObjectId) {\n\t\tif (References.isSameObject(firstObjectId, secondObjectId)) {\n\t\t\treturn true;\n\t\t}\n\t\t// We test word 3 first since the git file-based ODB\n\t\t// uses the first byte of w1, and we use w2 as the\n\t\t// hash code, one of those probably came up with these\n\t\t// two instances which we are comparing for equality.\n\t\t// Therefore the first two words are very likely to be\n\t\t// identical. We want to break away from collisions as\n\t\t// quickly as possible.\n\t\treturn firstObjectId.w3 == secondObjectId.w3\n\t\t\t\t&& firstObjectId.w4 == secondObjectId.w4\n\t\t\t\t&& firstObjectId.w5 == secondObjectId.w5\n\t\t\t\t&& firstObjectId.w1 == secondObjectId.w1\n\t\t\t\t&& firstObjectId.w2 == secondObjectId.w2;\n\t}\n\n\tint w1;\n\n\tint w2;\n\n\tint w3;\n\n\tint w4;\n\n\tint w5;\n\n\t/**\n\t * Get the first 8 bits of the ObjectId.\n\t *\n\t * This is a faster version of {@code getByte(0)}.\n\t *\n\t * @return a discriminator usable for a fan-out style map. Returned values\n\t * are unsigned and thus are in the range [0,255] rather than the\n\t * signed byte range of [-128, 127].\n\t */\n\tpublic final int getFirstByte() {\n\t\treturn w1 >>> 24;\n\t}\n\n\t/**\n\t * Get any byte from the ObjectId.\n\t *\n\t * Callers hard-coding {@code getByte(0)} should instead use the much faster\n\t * special case variant {@link #getFirstByte()}.\n\t *\n\t * @param index\n\t * index of the byte to obtain from the raw form of the ObjectId.\n\t * Must be in range [0,\n\t * {@link org.eclipse.jgit.lib.Constants#OBJECT_ID_LENGTH}).\n\t * @return the value of the requested byte at {@code index}. Returned values\n\t * are unsigned and thus are in the range [0,255] rather than the\n\t * signed byte range of [-128, 127].\n\t * @throws java.lang.ArrayIndexOutOfBoundsException\n\t * {@code index} is less than 0, equal to\n\t * {@link org.eclipse.jgit.lib.Constants#OBJECT_ID_LENGTH}, or\n\t * greater than\n\t * {@link org.eclipse.jgit.lib.Constants#OBJECT_ID_LENGTH}.\n\t */\n\tpublic final int getByte(int index) {\n\t\tint w;\n\t\tswitch (index >> 2) {\n\t\tcase 0:\n\t\t\tw = w1;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tw = w2;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tw = w3;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tw = w4;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tw = w5;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new ArrayIndexOutOfBoundsException(index);\n\t\t}\n\n\t\treturn (w >>> (8 * (3 - (index & 3)))) & 0xff;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *

\n\t * Compare this ObjectId to another and obtain a sort ordering.\n\t */\n\t@Override\n\tpublic final int compareTo(AnyObjectId other) {\n\t\tif (this == other)\n\t\t\treturn 0;\n\n\t\tint cmp;\n\n\t\tcmp = NB.compareUInt32(w1, other.w1);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w2, other.w2);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w3, other.w3);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w4, other.w4);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\treturn NB.compareUInt32(w5, other.w5);\n\t}\n\n\t/**\n\t * Compare this ObjectId to a network-byte-order ObjectId.\n\t *\n\t * @param bs\n\t * array containing the other ObjectId in network byte order.\n\t * @param p\n\t * position within {@code bs} to start the compare at. At least\n\t * 20 bytes, starting at this position are required.\n\t * @return a negative integer, zero, or a positive integer as this object is\n\t * less than, equal to, or greater than the specified object.\n\t */\n\tpublic final int compareTo(byte[] bs, int p) {\n\t\tint cmp;\n\n\t\tcmp = NB.compareUInt32(w1, NB.decodeInt32(bs, p));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w2, NB.decodeInt32(bs, p + 4));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w3, NB.decodeInt32(bs, p + 8));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w4, NB.decodeInt32(bs, p + 12));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\treturn NB.compareUInt32(w5, NB.decodeInt32(bs, p + 16));\n\t}\n\n\t/**\n\t * Compare this ObjectId to a network-byte-order ObjectId.\n\t *\n\t * @param bs\n\t * array containing the other ObjectId in network byte order.\n\t * @param p\n\t * position within {@code bs} to start the compare at. At least 5\n\t * integers, starting at this position are required.\n\t * @return a negative integer, zero, or a positive integer as this object is\n\t * less than, equal to, or greater than the specified object.\n\t */\n\tpublic final int compareTo(int[] bs, int p) {\n\t\tint cmp;\n\n\t\tcmp = NB.compareUInt32(w1, bs[p]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w2, bs[p + 1]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w3, bs[p + 2]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w4, bs[p + 3]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\treturn NB.compareUInt32(w5, bs[p + 4]);\n\t}\n\n\t/**\n\t * Tests if this ObjectId starts with the given abbreviation.\n\t *\n\t * @param abbr\n\t * the abbreviation.\n\t * @return true if this ObjectId begins with the abbreviation; else false.\n\t */\n\tpublic boolean startsWith(AbbreviatedObjectId abbr) {\n\t\treturn abbr.prefixCompare(this) == 0;\n\t}\n\n\t@Override\n\tpublic final int hashCode() {\n\t\treturn w2;\n\t}\n\n\t/**\n\t * Determine if this ObjectId has exactly the same value as another.\n\t *\n\t * @param other\n\t * the other id to compare to. May be null.\n\t * @return true only if both ObjectIds have identical bits.\n\t */\n\t@SuppressWarnings({ \"NonOverridingEquals\", \"AmbiguousMethodReference\" })\n\tpublic final boolean equals(AnyObjectId other) {\n\t\treturn other != null ? isEqual(this, other) : false;\n\t}\n\n\t@Override\n\tpublic final boolean equals(Object o) {\n\t\tif (o instanceof AnyObjectId) {\n\t\t\treturn equals((AnyObjectId) o);\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in raw binary.\n\t *\n\t * @param w\n\t * the buffer to copy to. Must be in big endian order.\n\t */\n\tpublic void copyRawTo(ByteBuffer w) {\n\t\tw.putInt(w1);\n\t\tw.putInt(w2);\n\t\tw.putInt(w3);\n\t\tw.putInt(w4);\n\t\tw.putInt(w5);\n\t}\n\n\t/**\n\t * Copy this ObjectId to a byte array.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t * @param o\n\t * the offset within b to write at.\n\t */\n\tpublic void copyRawTo(byte[] b, int o) {\n\t\tNB.encodeInt32(b, o, w1);\n\t\tNB.encodeInt32(b, o + 4, w2);\n\t\tNB.encodeInt32(b, o + 8, w3);\n\t\tNB.encodeInt32(b, o + 12, w4);\n\t\tNB.encodeInt32(b, o + 16, w5);\n\t}\n\n\t/**\n\t * Copy this ObjectId to an int array.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t * @param o\n\t * the offset within b to write at.\n\t */\n\tpublic void copyRawTo(int[] b, int o) {\n\t\tb[o] = w1;\n\t\tb[o + 1] = w2;\n\t\tb[o + 2] = w3;\n\t\tb[o + 3] = w4;\n\t\tb[o + 4] = w5;\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in raw binary.\n\t *\n\t * @param w\n\t * the stream to write to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyRawTo(OutputStream w) throws IOException {\n\t\twriteRawInt(w, w1);\n\t\twriteRawInt(w, w2);\n\t\twriteRawInt(w, w3);\n\t\twriteRawInt(w, w4);\n\t\twriteRawInt(w, w5);\n\t}\n\n\tprivate static void writeRawInt(OutputStream w, int v)\n\t\t\tthrows IOException {\n\t\tw.write(v >>> 24);\n\t\tw.write(v >>> 16);\n\t\tw.write(v >>> 8);\n\t\tw.write(v);\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in hex format.\n\t *\n\t * @param w\n\t * the stream to copy to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyTo(OutputStream w) throws IOException {\n\t\tw.write(toHexByteArray());\n\t}\n\n\t/**\n\t * Copy this ObjectId to a byte array in hex format.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t * @param o\n\t * the offset within b to write at.\n\t */\n\tpublic void copyTo(byte[] b, int o) {\n\t\tformatHexByte(b, o + 0, w1);\n\t\tformatHexByte(b, o + 8, w2);\n\t\tformatHexByte(b, o + 16, w3);\n\t\tformatHexByte(b, o + 24, w4);\n\t\tformatHexByte(b, o + 32, w5);\n\t}\n\n\t/**\n\t * Copy this ObjectId to a ByteBuffer in hex format.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t */\n\tpublic void copyTo(ByteBuffer b) {\n\t\tb.put(toHexByteArray());\n\t}\n\n\tprivate byte[] toHexByteArray() {\n\t\tfinal byte[] dst = new byte[Constants.OBJECT_ID_STRING_LENGTH];\n\t\tformatHexByte(dst, 0, w1);\n\t\tformatHexByte(dst, 8, w2);\n\t\tformatHexByte(dst, 16, w3);\n\t\tformatHexByte(dst, 24, w4);\n\t\tformatHexByte(dst, 32, w5);\n\t\treturn dst;\n\t}\n\n\tprivate static final byte[] hexbyte = { '0', '1', '2', '3', '4', '5', '6',\n\t\t\t'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n\n\tprivate static void formatHexByte(byte[] dst, int p, int w) {\n\t\tint o = p + 7;\n\t\twhile (o >= p && w != 0) {\n\t\t\tdst[o--] = hexbyte[w & 0xf];\n\t\t\tw >>>= 4;\n\t\t}\n\t\twhile (o >= p)\n\t\t\tdst[o--] = '0';\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in hex format.\n\t *\n\t * @param w\n\t * the stream to copy to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyTo(Writer w) throws IOException {\n\t\tw.write(toHexCharArray());\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in hex format.\n\t *\n\t * @param tmp\n\t * temporary char array to buffer construct into before writing.\n\t * Must be at least large enough to hold 2 digits for each byte\n\t * of object id (40 characters or larger).\n\t * @param w\n\t * the stream to copy to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyTo(char[] tmp, Writer w) throws IOException {\n\t\ttoHexCharArray(tmp);\n\t\tw.write(tmp, 0, Constants.OBJECT_ID_STRING_LENGTH);\n\t}\n\n\t/**\n\t * Copy this ObjectId to a StringBuilder in hex format.\n\t *\n\t * @param tmp\n\t * temporary char array to buffer construct into before writing.\n\t * Must be at least large enough to hold 2 digits for each byte\n\t * of object id (40 characters or larger).\n\t * @param w\n\t * the string to append onto.\n\t */\n\tpublic void copyTo(char[] tmp, StringBuilder w) {\n\t\ttoHexCharArray(tmp);\n\t\tw.append(tmp, 0, Constants.OBJECT_ID_STRING_LENGTH);\n\t}\n\n\tprivate char[] toHexCharArray() {\n\t\tfinal char[] dst = new char[Constants.OBJECT_ID_STRING_LENGTH];\n\t\ttoHexCharArray(dst);\n\t\treturn dst;\n\t}\n\n\tprivate void toHexCharArray(char[] dst) {\n\t\tformatHexChar(dst, 0, w1);\n\t\tformatHexChar(dst, 8, w2);\n\t\tformatHexChar(dst, 16, w3);\n\t\tformatHexChar(dst, 24, w4);\n\t\tformatHexChar(dst, 32, w5);\n\t}\n\n\tprivate static final char[] hexchar = { '0', '1', '2', '3', '4', '5', '6',\n\t\t\t'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n\n\tstatic void formatHexChar(char[] dst, int p, int w) {\n\t\tint o = p + 7;\n\t\twhile (o >= p && w != 0) {\n\t\t\tdst[o--] = hexchar[w & 0xf];\n\t\t\tw >>>= 4;\n\t\t}\n\t\twhile (o >= p)\n\t\t\tdst[o--] = '0';\n\t}\n\n\t@SuppressWarnings(\"nls\")\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AnyObjectId[\" + name() + \"]\";\n\t}\n\n\t/**\n\t *

name.

\n\t *\n\t * @return string form of the SHA-1, in lower case hexadecimal.\n\t */\n\tpublic final String name() {\n\t\treturn new String(toHexCharArray());\n\t}\n\n\t/**\n\t * Get string form of the SHA-1, in lower case hexadecimal.\n\t *\n\t * @return string form of the SHA-1, in lower case hexadecimal.\n\t */\n\tpublic final String getName() {\n\t\treturn name();\n\t}\n\n\t/**\n\t * Return an abbreviation (prefix) of this object SHA-1.\n\t *

\n\t * This implementation does not guarantee uniqueness. Callers should instead\n\t * use\n\t * {@link org.eclipse.jgit.lib.ObjectReader#abbreviate(AnyObjectId, int)} to\n\t * obtain a unique abbreviation within the scope of a particular object\n\t * database.\n\t *\n\t * @param len\n\t * length of the abbreviated string.\n\t * @return SHA-1 abbreviation.\n\t */\n\tpublic AbbreviatedObjectId abbreviate(int len) {\n\t\tfinal int a = AbbreviatedObjectId.mask(len, 1, w1);\n\t\tfinal int b = AbbreviatedObjectId.mask(len, 2, w2);\n\t\tfinal int c = AbbreviatedObjectId.mask(len, 3, w3);\n\t\tfinal int d = AbbreviatedObjectId.mask(len, 4, w4);\n\t\tfinal int e = AbbreviatedObjectId.mask(len, 5, w5);\n\t\treturn new AbbreviatedObjectId(len, a, b, c, d, e);\n\t}\n\n\t/**\n\t * Obtain an immutable copy of this current object name value.\n\t *

\n\t * Only returns this if this instance is an unsubclassed\n\t * instance of {@link org.eclipse.jgit.lib.ObjectId}; otherwise a new\n\t * instance is returned holding the same value.\n\t *

\n\t * This method is useful to shed any additional memory that may be tied to\n\t * the subclass, yet retain the unique identity of the object id for future\n\t * lookups within maps and repositories.\n\t *\n\t * @return an immutable copy, using the smallest memory footprint possible.\n\t */\n\tpublic final ObjectId copy() {\n\t\tif (getClass() == ObjectId.class)\n\t\t\treturn (ObjectId) this;\n\t\treturn new ObjectId(this);\n\t}\n\n\t/**\n\t * Obtain an immutable copy of this current object name value.\n\t *

\n\t * See {@link #copy()} if this is a possibly subclassed (but\n\t * immutable) identity and the application needs a lightweight identity\n\t * only reference.\n\t *\n\t * @return an immutable copy. May be this if this is already\n\t * an immutable instance.\n\t */\n\tpublic abstract ObjectId toObjectId();\n}", "answers": ["\tpublic final int getType() {"], "length": 2172, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "61974541-98b8-4aab-9e1e-351646b5b1c2", "reasoning": "In RevTree.java, after the constructor the class overrides the abstract getType() method from RevObject. The snippet ends with an @Override annotation, so the next line should be the method signature for getType(), which is 'public int getType() {'. This matches the JGit source where RevTree returns Constants.OBJ_TREE.", "reasoning_model_answer": "public int getType() {", "assistant_with_reasoning": "\nIn RevTree.java, after the constructor the class overrides the abstract getType() method from RevObject. The snippet ends with an @Override annotation, so the next line should be the method signature for getType(), which is 'public int getType() {'. This matches the JGit source where RevTree returns Constants.OBJ_TREE.\n\npublic int getType() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.647, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 15107, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public int getType() {", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "import cn.hutool.captcha.generator.RandomGenerator;\nimport cn.hutool.core.io.IoUtil;\nimport cn.hutool.core.util.RandomUtil;\nimport com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;\nimport com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport com.xht.cloud.framework.core.api.response.PageResponse;\nimport com.xht.cloud.framework.core.constant.CommonConstants;\nimport com.xht.cloud.framework.core.support.StringUtils;\nimport com.xht.cloud.framework.exception.Assert;\nimport com.xht.cloud.framework.exception.business.UserNameNotFountException;\nimport com.xht.cloud.framework.mybatis.core.DataScopeFieldBuilder;\nimport com.xht.cloud.framework.mybatis.core.enums.DataScopeTypeEnums;\nimport com.xht.cloud.framework.mybatis.handler.DataScopeFactory;\nimport com.xht.cloud.framework.mybatis.tool.PageTool;\nimport com.xht.cloud.framework.redis.key.RedisKeyTool;\nimport com.xht.cloud.framework.redis.service.RedisService;\nimport com.xht.cloud.framework.security.constant.UserTypeEnums;\nimport com.xht.cloud.framework.security.support.SecurityContextUtil;\nimport com.xht.cloud.system.enums.MenuTypeEnums;\nimport com.xht.cloud.system.manager.MinioManager;\nimport com.xht.cloud.system.module.dept.controller.response.SysDeptResponse;\nimport com.xht.cloud.system.module.dept.convert.SysDeptConvert;\nimport com.xht.cloud.system.module.dept.dao.dataobject.SysDeptDO;\nimport com.xht.cloud.system.module.dept.dao.mapper.SysDeptMapper;\nimport com.xht.cloud.system.module.permissions.dao.dataobject.SysMenuDO;\nimport com.xht.cloud.system.module.permissions.dao.dataobject.SysRoleDO;\nimport com.xht.cloud.system.module.permissions.dao.mapper.SysMenuMapper;\nimport com.xht.cloud.system.module.permissions.dao.mapper.SysRoleMapper;\nimport com.xht.cloud.system.module.user.controller.request.SysUserBaseAddUpdate;\nimport com.xht.cloud.system.module.user.controller.request.SysUserProfileRequest;\nimport com.xht.cloud.system.module.user.controller.request.SysUserQueryRequest;\nimport com.xht.cloud.system.module.user.controller.request.UpdatePassWordRequest;\nimport com.xht.cloud.system.module.user.controller.response.SysUserProfileResponse;\nimport com.xht.cloud.system.module.user.controller.response.SysUserResponse;\nimport com.xht.cloud.system.module.user.controller.response.SysUserVo;\nimport com.xht.cloud.system.module.user.convert.SysUserConvert;\nimport com.xht.cloud.system.module.user.convert.SysUserProfileConvert;\nimport com.xht.cloud.system.module.user.dao.dataobject.SysUserDO;\nimport com.xht.cloud.system.module.user.dao.dataobject.SysUserProfileDO;\nimport com.xht.cloud.system.module.user.dao.mapper.SysUserMapper;\nimport com.xht.cloud.system.module.user.dao.mapper.SysUserProfileMapper;\nimport com.xht.cloud.system.module.user.dao.wrapper.SysUserWrapper;\nimport com.xht.cloud.system.module.user.service.ISysUserService;\nimport lombok.RequiredArgsConstructor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.jetbrains.annotations.NotNull;\nimport org.springframework.security.crypto.password.PasswordEncoder;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\nimport org.springframework.util.CollectionUtils;\nimport java.io.InputStream;\nimport java.time.LocalDateTime;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\nimport java.util.stream.Collectors;", "context": "xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/service/impl/SysUserServiceImpl.java\npackage com.xht.cloud.system.module.user.service.impl;\n\n\n\n/**\n * 描述 :用户\n *\n * @author : xht\n **/\n@Slf4j\n@Service\n@RequiredArgsConstructor\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/dept/dao/dataobject/SysDeptDO.java\n@Data\n@TableName(value = \"sys_dept\")\npublic class SysDeptDO extends BaseDO {\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n private String id;\n\n /**\n * 父id\n */\n @TableField(value = \"parent_id\")\n private String parentId;\n\n /**\n * 指定主管ID(用户id)\n */\n @TableField(value = \"director_id\")\n private String directorId;\n\n /**\n * 部门名称\n */\n @TableField(value = \"dept_name\")\n private String deptName;\n\n /**\n * 部门编码\n */\n @TableField(value = \"dept_code\")\n private String deptCode;\n\n /**\n * 部门分类(0-境内 1境外)\n */\n @TableField(value = \"dept_type\")\n private String deptType;\n\n /**\n * 部门负责人\n */\n @TableField(value = \"dept_leader\")\n private String deptLeader;\n\n /**\n * 联系电话\n */\n @TableField(value = \"dept_tel\")\n private String deptTel;\n\n /**\n * 排序\n */\n @TableField(value = \"dept_sort\")\n private Integer deptSort;\n\n /**\n * 部门状态(0停用1正常)\n */\n @TableField(value = \"dept_status\")\n private String deptStatus;\n\n /**\n * 部门描述\n */\n @TableField(value = \"description\")\n private String description;\n\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/dao/mapper/SysUserProfileMapper.java\n@Mapper\npublic interface SysUserProfileMapper extends BaseMapperX {\n\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/controller/response/SysUserVo.java\n@Data\npublic class SysUserVo {\n\n private SysUserResponse sysUser;\n\n private SysUserProfileResponse profile;\n\n /**\n * 角色编码\n */\n private Set roleCode;\n\n /**\n * 数据权限 {@link com.xht.cloud.framework.mybatis.core.enums.DeptUserDataScopeEnum}\n */\n private Integer dataScope;\n\n /**\n * 菜单权限或者其他权限\n */\n private Set authorities;\n\n /**\n * 部门信息\n */\n private SysDeptResponse dept;\n}\n\nxht-cloud-framework/xht-cloud-spring-boot-start-redis/src/main/java/com/xht/cloud/framework/redis/key/RedisKeyTool.java\npublic final class RedisKeyTool {\n\n private static final String DEFAULT_CONJUNCTION = \":\";\n\n /**\n * 生成key\n */\n public static String createName(String... key) {\n return ArrayUtil.join(key, DEFAULT_CONJUNCTION);\n }\n\n /**\n * 格式化 Key\n *\n * @param args 格式化的参数\n * @return Key\n */\n public static String createNameTemplate(@NonNull final String keyTemplate, @NonNull Object... args) {\n return StrFormatter.format(keyTemplate, args);\n }\n\n /**\n * 生成key\n */\n public static RedisKeyBO createKey(String... key) {\n return new RedisKeyBO(createName(key));\n }\n\n /**\n * 生成key\n */\n public static RedisKeyBO createKeyTemplate(@NonNull final String keyTemplate, @NonNull Object... args) {\n return new RedisKeyBO(createNameTemplate(keyTemplate, args));\n }\n\n}\n\nxht-cloud-framework/xht-cloud-framework-exception/src/main/java/com/xht/cloud/framework/exception/Assert.java\npublic abstract class Assert {\n\n /**\n * 字符串为空抛出异常\n *\n * @param str 字符串\n */\n public static void hasText(String str) {\n hasText(str, \"[Assertion failed] Must not empty\");\n }\n\n /**\n * 字符串为空抛出异常\n *\n * @param str 字符串\n * @param errorCode 异常状态码\n */\n public static void hasText(String str, IErrorStatusCode errorCode) {\n if (!StringUtils.hasText(str)) {\n fail(errorCode);\n }\n }\n\n /**\n * 字符串为空抛出异常\n *\n * @param str 字符串\n * @param errMessage 异常描述\n */\n public static void hasText(String str, String errMessage) {\n if (!StringUtils.hasText(str)) {\n fail(errMessage);\n }\n }\n\n /**\n * 对象不为空抛出异常\n *\n * @param object 对象\n * @param errorCode 异常状态码\n */\n public static void notNull(Object object, IErrorStatusCode errorCode) {\n if (Objects.isNull(object)) {\n fail(errorCode);\n }\n }\n\n /**\n * 对象不为空抛出异常\n *\n * @param object 对象\n * @param errMessage 异常描述\n */\n public static void notNull(Object object, String errMessage) {\n if (Objects.isNull(object)) {\n fail(errMessage);\n }\n }\n\n /**\n * 对象不为空抛出异常\n *\n * @param object 对象\n */\n public static void notNull(Object object) {\n notNull(object, \"[Assertion failed] Must not null\");\n }\n\n\n /**\n * 集合为空排除异常\n *\n * @param collection 集合\n * @param errorCode 异常状态码\n */\n public static void notEmpty(Collection collection, IErrorStatusCode errorCode) {\n if (Objects.isNull(collection) || collection.isEmpty()) {\n fail(errorCode);\n }\n }\n\n /**\n * 集合为空排除异常\n *\n * @param collection 集合\n * @param errMessage 异常信息\n */\n public static void notEmpty(Collection collection, String errMessage) {\n if (Objects.isNull(collection) || collection.isEmpty()) {\n fail(errMessage);\n }\n }\n\n /**\n * 集合为空排除异常\n *\n * @param collection 集合\n */\n public static void notEmpty(Collection collection) {\n notEmpty(collection, \"[Assertion failed] Collection must not be empty: it must contain at least 1 element\");\n }\n\n /**\n * map集合为空排除异常\n *\n * @param map map集合\n * @param errorCode 异常状态码\n */\n public static void notEmpty(Map map, IErrorStatusCode errorCode) {\n if (Objects.isNull(map) || map.isEmpty()) {\n fail(errorCode);\n }\n }\n\n /**\n * map集合为空排除异常\n *\n * @param map map集合\n * @param errMessage 异常信息\n */\n public static void notEmpty(Map map, String errMessage) {\n if (Objects.isNull(map) || map.isEmpty()) {\n fail(errMessage);\n }\n }\n\n /**\n * map集合为空排除异常\n *\n * @param map map集合\n */\n public static void notEmpty(Map map) {\n notEmpty(map, \"[Assertion failed] Map must not be empty: it must contain at least one entry\");\n }\n\n /**\n * 直接抛出异常\n *\n * @param s 异常描述信息\n */\n public static void fail(String s) {\n throw ExceptionFactory.bizException(s);\n }\n\n /**\n * 直接抛出异常\n *\n * @param errorStatusCode 异常状态码\n */\n public static void fail(IErrorStatusCode errorStatusCode) {\n throw ExceptionFactory.bizException(errorStatusCode);\n }\n\n\n /**\n * 断言是否为假,如果为 true 抛出{@link BizException}\n *\n * @param flag 布尔值\n * @param message 错误信息\n */\n public static void isFalse(boolean flag, String message) {\n isFalse(flag, () -> ExceptionFactory.bizException(message));\n }\n\n\n /**\n * 断言是否为假,如果为 {@code true} 抛出指定类型异常
\n * 并使用指定的函数获取错误信息返回\n *

\n     *  Assert.isFalse(i > 0, ()->{\n     *      // to query relation message\n     *      return new IllegalArgumentException(\"relation message to return\");\n     *  });\n     * 
\n *\n * @param 异常类型\n * @param expression 布尔值\n * @param errorSupplier 指定断言不通过时抛出的异常\n * @throws X if expression is {@code false}\n */\n public static void isFalse(boolean expression, Supplier errorSupplier) throws X {\n if (expression) {\n throw errorSupplier.get();\n }\n }\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/dao/wrapper/SysUserWrapper.java\npublic final class SysUserWrapper implements EntityWrapper {\n\n /**\n * 私有化构造器\n */\n private SysUserWrapper() {\n }\n\n /**\n * 获取实例\n */\n public static SysUserWrapper getInstance() {\n return Instance.INSTANCE.getInstance();\n }\n\n /**\n * 实例处理化\n */\n private enum Instance {\n\n INSTANCE;\n\n private final SysUserWrapper wrapper;\n\n Instance() {\n wrapper = new SysUserWrapper();\n }\n\n public SysUserWrapper getInstance() {\n return wrapper;\n }\n }\n\n /**\n * 获取 {@link LambdaQueryWrapper}\n *\n * @param entity 实体类\n * @return {@link LambdaQueryWrapper}\n */\n @Override\n public LambdaQueryWrapper lambdaQuery(SysUserDO entity) {\n if (Objects.isNull(entity)) {\n return lambdaQuery();\n }\n LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();\n return wrapper\n .eq(StringUtils.hasText(entity.getId()), SysUserDO::getId, entity.getId())\n .like(StringUtils.hasText(entity.getNickName()), SysUserDO::getNickName, entity.getNickName())\n .like(StringUtils.hasText(entity.getUserName()), SysUserDO::getUserName, entity.getUserName())\n .eq(StringUtils.hasText(entity.getPassWord()), SysUserDO::getPassWord, entity.getPassWord())\n .eq(StringUtils.hasText(entity.getPassWordSalt()), SysUserDO::getPassWordSalt, entity.getPassWordSalt())\n .eq(StringUtils.hasText(entity.getPassWordOld()), SysUserDO::getPassWordOld, entity.getPassWordOld())\n .eq(StringUtils.hasText(entity.getPassWordSaltOld()), SysUserDO::getPassWordSaltOld, entity.getPassWordSaltOld())\n .eq(StringUtils.hasText(entity.getDeptId()), SysUserDO::getDeptId, entity.getDeptId())\n .eq(StringUtils.hasText(entity.getUserAvatar()), SysUserDO::getUserAvatar, entity.getUserAvatar())\n .eq(StringUtils.hasText(entity.getUserType()), SysUserDO::getUserType, entity.getUserType())\n .eq(StringUtils.hasText(entity.getQqOpenid()), SysUserDO::getQqOpenid, entity.getQqOpenid())\n .eq(StringUtils.hasText(entity.getWxOpenid()), SysUserDO::getWxOpenid, entity.getWxOpenid())\n .eq(StringUtils.hasText(entity.getWxUnionid()), SysUserDO::getWxUnionid, entity.getWxUnionid())\n .eq(StringUtils.hasText(entity.getIsLock()), SysUserDO::getIsLock, entity.getIsLock())\n .eq(StringUtils.hasText(entity.getIsActive()), SysUserDO::getIsActive, entity.getIsActive())\n .eq(StringUtils.hasText(entity.getIsAdmin()), SysUserDO::getIsAdmin, entity.getIsAdmin())\n .eq(!ObjectUtils.isEmpty(entity.getRegisteredTime()), SysUserDO::getRegisteredTime, entity.getRegisteredTime())\n .eq(!ObjectUtils.isEmpty(entity.getLastLoginTime()), SysUserDO::getLastLoginTime, entity.getLastLoginTime())\n ;\n }\n\n /**\n * 获取 {@link LambdaUpdateWrapper}\n *\n * @param entity 实体类\n * @return {@link LambdaUpdateWrapper}\n */\n @Override\n public LambdaUpdateWrapper lambdaUpdate(SysUserDO entity) {\n if (Objects.isNull(entity)) {\n return lambdaUpdate();\n }\n LambdaUpdateWrapper wrapper = new LambdaUpdateWrapper<>();\n return wrapper\n .set(SysUserDO::getNickName, entity.getNickName())\n .set(SysUserDO::getUserName, entity.getUserName())\n .set(SysUserDO::getPassWord, entity.getPassWord())\n .set(SysUserDO::getPassWordSalt, entity.getPassWordSalt())\n .set(SysUserDO::getPassWordOld, entity.getPassWordOld())\n .set(SysUserDO::getPassWordSaltOld, entity.getPassWordSaltOld())\n .set(SysUserDO::getDeptId, entity.getDeptId())\n .set(SysUserDO::getUserAvatar, entity.getUserAvatar())\n .set(SysUserDO::getUserType, entity.getUserType())\n .set(SysUserDO::getQqOpenid, entity.getQqOpenid())\n .set(SysUserDO::getWxOpenid, entity.getWxOpenid())\n .set(SysUserDO::getWxUnionid, entity.getWxUnionid())\n .set(SysUserDO::getIsLock, entity.getIsLock())\n .set(SysUserDO::getIsActive, entity.getIsActive())\n .set(SysUserDO::getIsAdmin, entity.getIsAdmin())\n .set(SysUserDO::getRegisteredTime, entity.getRegisteredTime())\n .set(SysUserDO::getLastLoginTime, entity.getLastLoginTime())\n ;\n }\n\n\n}\n\nxht-cloud-framework/xht-cloud-spring-boot-start-security/src/main/java/com/xht/cloud/framework/security/support/SecurityContextUtil.java\npublic final class SecurityContextUtil {\n\n\n /**\n * 获取Authentication\n */\n public static Optional getAuthentication() {\n return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());\n }\n\n /**\n * 判断用户是否登录\n * @return true 登录 false未登录\n */\n public static boolean isLogin() {\n Authentication authentication = getAuthentication().orElse(null);\n return Objects.nonNull(authentication) && authentication.isAuthenticated();\n }\n\n\n /**\n * 获取当前的登录账号\n *\n * @return 当前登录账号\n */\n public static String getUserName() {\n Authentication authentication = getAuthentication().orElse(null);\n if (Objects.nonNull(authentication)) {\n return authentication.getName();\n }\n return SecurityConstant.UNKNOWN_USER_NAME;\n }\n\n /**\n * 获取用户\n */\n public static Optional getUser() {\n if (isLogin()) {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n Object principal = authentication.getPrincipal();\n if (principal instanceof CustomUserDetails customUserDetails) {\n return Optional.of(customUserDetails);\n }\n return Optional.empty();\n }\n return Optional.empty();\n }\n\n /**\n * 检测当前token是否是客户端认证\n * @return true 客户端认证\n */\n public static boolean isClientCredentials() {\n Authentication authentication = getAuthentication().orElse(null);\n if (Objects.isNull(authentication)) {\n return false;\n }\n return authentication.getPrincipal() instanceof OAuth2IntrospectionAuthenticatedPrincipal;\n }\n\n\n /**\n * @return 获取当前用户的数据权限\n */\n public static Integer getDataScope() {\n CustomUserDetails user = getUser().orElseThrow(() -> new RuntimeException(\"暂无权限查看,请联系管理员重新分配部门级数据权限!\"));\n return user.getDataScope();\n }\n\n /**\n * 判断当前登录用户是不是管理员\n *\n * @return {@link Boolean} true 是 false不是\n */\n public static boolean isAdmin() {\n CustomUserDetails user = getUser().orElse(null);\n if (Objects.isNull(user)) {\n return Boolean.FALSE;\n }\n AdminProperties adminProperties = SpringUtil.getBean(AdminProperties.class);\n String include = adminProperties.getInclude();\n List includes = adminProperties.getIncludes();\n Set roleCode = adminProperties.getRoleCode();\n String usernameLogin = user.getUsername();\n List roleCodeLogin = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();\n return Objects.equals(include, usernameLogin) || CollectionUtils.contains(includes.iterator(), usernameLogin) || CollectionUtils.containsAny(roleCode, roleCodeLogin);\n }\n\n /**\n * 判断当前用户是不是管理员\n *\n * @return {@link Boolean} true 是 false不是\n */\n public static Optional isAdmin(String userName) {\n AdminProperties adminProperties = SpringUtil.getBean(AdminProperties.class);\n String include = adminProperties.getInclude();\n List includes = adminProperties.getIncludes();\n return Objects.equals(include, userName) || CollectionUtils.contains(includes.listIterator(), userName) ? Optional.of(true) : Optional.empty();\n }\n\n /**\n * 判断角色用户是不是管理员\n *\n * @return {@link Boolean} true 是 false不是\n */\n public static Optional isAdminRole(String roleCode) {\n AdminProperties adminProperties = SpringUtil.getBean(AdminProperties.class);\n Set includes = adminProperties.getRoleCode();\n return CollectionUtils.contains(includes.iterator(), roleCode) ? Optional.of(true) : Optional.empty();\n }\n\n /**\n * 判断角色用户是不是管理员\n *\n * @return {@link Boolean} true 是 false不是\n */\n public static Optional isAdminRole(List roleCode) {\n AdminProperties adminProperties = SpringUtil.getBean(AdminProperties.class);\n Set includes = adminProperties.getRoleCode();\n return CollectionUtils.containsAny(includes, roleCode) ? Optional.of(true) : Optional.empty();\n }\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/dao/dataobject/SysUserProfileDO.java\n@Data\n@TableName(value = \"sys_user_profile\")\npublic class SysUserProfileDO extends BaseDO {\n\n /**\n * ID\n */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n private String id;\n\n /**\n * 用户ID\n */\n @TableField(value = \"user_id\")\n private String userId;\n\n /**\n * 真实姓名\n */\n @TableField(value = \"real_name\")\n private String realName;\n\n /**\n * 性别,0:未知,1:男,2:女\n */\n @TableField(value = \"gender\")\n private String gender;\n\n /**\n * 身份证号码\n */\n @TableField(value = \"id_card_number\")\n private String idCardNumber;\n\n /**\n * 手机号码\n */\n @TableField(value = \"phone_number\")\n private String phoneNumber;\n\n /**\n * 邮箱\n */\n @TableField(value = \"email\")\n private String email;\n\n /**\n * 生日\n */\n @TableField(value = \"birthday\")\n private LocalDateTime birthday;\n\n /**\n * 地址\n */\n @TableField(value = \"address\")\n private String address;\n\n /**\n * 详细地址\n */\n @TableField(value = \"address_detailed\")\n private String addressDetailed;\n\n /**\n * 个人描述\n */\n @TableField(value = \"description\")\n private String description;\n\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/dao/dataobject/SysUserDO.java\n@Data\n@TableName(value = \"sys_user\")\npublic class SysUserDO extends BaseDO {\n\n /**\n * 用户ID\n */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n private String id;\n\n /**\n * 用户名(昵称)\n */\n @TableField(value = \"nick_name\")\n private String nickName;\n\n /**\n * 用户名(账号)\n */\n @TableField(value = \"user_name\")\n private String userName;\n\n /**\n * 密码\n */\n @TableField(value = \"pass_word\")\n private String passWord;\n\n /**\n * 密码盐值\n */\n @TableField(value = \"pass_word_salt\")\n private String passWordSalt;\n\n /**\n * 旧密码\n */\n @TableField(value = \"pass_word_old\")\n private String passWordOld;\n\n /**\n * 旧密码盐值\n */\n @TableField(value = \"pass_word_salt_old\")\n private String passWordSaltOld;\n\n /**\n * 部门id\n */\n @TableField(value = \"dept_id\")\n private String deptId;\n\n /**\n * 头像地址\n */\n @TableField(value = \"user_avatar\")\n private String userAvatar;\n\n /**\n * 账号类型,0 系统管理员 1 用户 2 商家\n */\n @TableField(value = \"user_type\")\n private String userType;\n\n /**\n * QQ互联openid\n */\n @TableField(value = \"qq_openid\")\n private String qqOpenid;\n\n /**\n * 微信openid\n */\n @TableField(value = \"wx_openid\")\n private String wxOpenid;\n\n /**\n * 微信unionid\n */\n @TableField(value = \"wx_unionid\")\n private String wxUnionid;\n\n /**\n * 是否锁定 0-锁定 1-正常\n */\n @TableField(value = \"is_lock\")\n private String isLock;\n\n /**\n * 是否激活,0-未激活,1-激活\n */\n @TableField(value = \"is_active\")\n private String isActive;\n\n /**\n * 是否超级管理员,0-不是,1-是\n */\n @TableField(value = \"is_admin\")\n private String isAdmin;\n\n /**\n * 注册时间\n */\n @TableField(value = \"registered_time\")\n private LocalDateTime registeredTime;\n\n /**\n * 最后一次登录时间\n */\n @TableField(value = \"last_login_time\")\n private LocalDateTime lastLoginTime;\n\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/convert/SysUserProfileConvert.java\n@Mapper(componentModel = \"spring\")\npublic interface SysUserProfileConvert {\n\n /**\n * {@link SysUserProfileRequest} to {@link SysUserProfileDO}\n */\n @Named(value = \"addRequestToDo\")\n SysUserProfileDO toDO(SysUserProfileRequest request);\n\n /**\n * {@link SysUserProfileDO} to {@link SysUserProfileResponse}\n */\n @Named(value = \"DoToResponse\")\n SysUserProfileResponse toResponse(SysUserProfileDO testDO);\n\n\n /**\n * list转换 {@link SysUserProfileDO} to {@link SysUserProfileResponse}\n */\n @Named(value = \"DoToResponseCollection\")\n @IterableMapping(qualifiedByName = \"DoToResponse\")\n List toResponse(List testDO);\n\n /**\n * 分页转换 {@link SysUserProfileDO} to {@link SysUserProfileResponse}\n */\n default PageResponse toPageResponse(IPage iPage) {\n if (Objects.nonNull(iPage)) {\n PageResponse pageResponse = PageTool.cloneEmpty(iPage);\n pageResponse.setList(toResponse(iPage.getRecords()));\n return pageResponse;\n }\n return PageTool.empty();\n }\n\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/service/ISysUserService.java\npublic interface ISysUserService {\n\n /**\n * 创建\n *\n * @param request {@link SysUserBaseAddUpdate}\n * @return {@link String} 主键\n */\n String create(SysUserBaseAddUpdate request);\n\n /**\n * 根据id修改\n *\n * @param request {@link SysUserBaseAddUpdate}\n */\n String update(SysUserBaseAddUpdate request);\n\n /**\n * 删除\n *\n * @param ids {@link List} id集合\n */\n void remove(List ids);\n\n /**\n * 根据id查询详细\n *\n * @param id {@link String} 数据库主键\n * @return {@link SysUserResponse}\n */\n SysUserVo findById(String id);\n\n /**\n * 分页查询\n *\n * @param queryRequest {@link SysUserQueryRequest}\n * @return {@link PageResponse} 分页详情\n */\n PageResponse findPage(SysUserQueryRequest queryRequest);\n\n /**\n * 根据userName查询详细\n *\n * @param userName {@link String} 用户名称\n * @return {@link SysUserVo}\n */\n SysUserVo findByUserName(String userName);\n\n /**\n * 校验账号是否存在\n *\n * @param userName 用户名称\n * @return {@link Boolean}\n */\n boolean validationUserName(String userName);\n\n /**\n * 修改登录用户信息\n *\n * @param userName 账号\n * @param request 请求信息\n */\n void updateUserProfile(String userName, SysUserProfileRequest request);\n\n /**\n * 修改当前登录用户密码\n *\n * @param userName 账号\n * @param request 请求信息\n */\n void updateUserPassword(String userName, UpdatePassWordRequest request);\n\n /**\n * 重置账号密码\n *\n * @param userId 用户id\n */\n String resetUserPassword(String userId);\n\n /**\n * 修改当前登录用户头像\n *\n * @param userName 账号\n * @param inputStream 头像io流\n * @return 头像地址\n */\n String updateUserAvatar(String userName, InputStream inputStream);\n\n}\n\nxht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/user/convert/SysUserConvert.java\n@Mapper(componentModel = \"spring\")\npublic interface SysUserConvert {\n\n /**\n * {@link SysUserAddRequest} to {@link SysUserDO}\n */\n @Named(value = \"requestToDo\")\n SysUserDO toDO(SysUserAddRequest addRequest);\n\n /**\n * {@link SysUserUpdateRequest} to {@link SysUserDO}\n */\n @Named(value = \"updateRequestToDo\")\n SysUserDO toDO(SysUserUpdateRequest updateRequest);\n\n /**\n * {@link SysUserQueryRequest} to {@link SysUserDO}\n */\n @Named(value = \"queryRequestToDo\")\n SysUserDO toDO(SysUserQueryRequest queryRequest);\n\n /**\n * {@link SysUserDO} to {@link SysUserResponse}\n */\n @Named(value = \"DoToResponse\")\n SysUserResponse toResponse(SysUserDO testDO);\n\n\n /**\n * list转换 {@link SysUserDO} to {@link SysUserResponse}\n */\n @Named(value = \"DoToResponseCollection\")\n @IterableMapping(qualifiedByName = \"DoToResponse\")\n List toResponse(List testDO);\n\n /**\n * 分页转换 {@link SysUserDO} to {@link SysUserResponse}\n */\n default PageResponse toPageResponse(IPage iPage) {\n if (Objects.nonNull(iPage)) {\n PageResponse pageResponse = PageTool.cloneEmpty(iPage);\n pageResponse.setList(toResponse(iPage.getRecords()));\n return pageResponse;\n }\n return PageTool.empty();\n }\n\n default UserResponseDTO toDTO(SysUserVo sysUserVo) {\n if (Objects.isNull(sysUserVo)) {\n return null;\n }\n SysUserResponse sysUser = sysUserVo.getSysUser();\n UserResponseDTO responseDTO = new UserResponseDTO();\n responseDTO.setId(sysUser.getId());\n responseDTO.setNickName(sysUser.getNickName());\n responseDTO.setUserName(sysUser.getUserName());\n responseDTO.setPassWord(sysUser.getPassWord());\n responseDTO.setPassWordSalt(sysUser.getPassWordSalt());\n responseDTO.setUserType(sysUser.getUserType());\n responseDTO.setQqOpenid(sysUser.getQqOpenid());\n responseDTO.setWxOpenid(sysUser.getWxOpenid());\n responseDTO.setWxUnionid(sysUser.getWxOpenid());\n responseDTO.setIsActive(sysUser.getIsActive());\n responseDTO.setIsAdmin(sysUser.getIsAdmin());\n responseDTO.setRegisteredTime(sysUser.getRegisteredTime());\n responseDTO.setLastLoginTime(sysUser.getLastLoginTime());\n responseDTO.setRoleCode(sysUserVo.getRoleCode());\n responseDTO.setDataScope(sysUserVo.getDataScope());\n responseDTO.setDeptId(sysUser.getDeptId());\n return responseDTO;\n }\n}", "answers": ["public class SysUserServiceImpl implements ISysUserService {"], "length": 2176, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "4c67b7dd-3e0f-417c-9e6d-6efc8c1515ed", "reasoning": "The file shows package, comment, and class-level annotations (@Slf4j, @Service, @RequiredArgsConstructor). After the import statements, the next logical line is the class declaration that implements the service interface. In this project, service implementations are declared as 'public class implements ISysUserService {'. Therefore the next line should be the class declaration.", "reasoning_model_answer": "public class SysUserServiceImpl implements ISysUserService {", "assistant_with_reasoning": "\nThe file shows package, comment, and class-level annotations (@Slf4j, @Service, @RequiredArgsConstructor). After the import statements, the next logical line is the class declaration that implements the service interface. In this project, service implementations are declared as 'public class implements ISysUserService {'. Therefore the next line should be the class declaration.\n\npublic class SysUserServiceImpl implements ISysUserService {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.073, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 29681, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public class SysUserServiceImpl implements ISysUserService {", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "import com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\nimport com.siam.package_common.constant.Quantity;\nimport com.siam.package_common.entity.BasicResult;\nimport com.siam.package_common.exception.StoneCustomerException;\nimport com.siam.package_weixin_pay.entity.TransfersDto;\nimport com.siam.package_common.util.Base64Utils;\nimport com.siam.package_common.util.CommonUtils;\nimport com.siam.package_common.util.GenerateNo;\nimport com.siam.system.modular.package_goods.service.SettingService;\nimport com.siam.system.modular.package_order.controller.member.WxPayService;\nimport com.siam.system.modular.package_goods.entity.Setting;\nimport com.siam.system.modular.package_user.auth.cache.MemberSessionManager;\nimport com.siam.system.modular.package_user.entity.Member;\nimport com.siam.system.modular.package_user.entity.MemberBillingRecord;\nimport com.siam.system.modular.package_user.entity.MemberTradeRecord;\nimport com.siam.system.modular.package_user.entity.MemberWithdrawRecord;\nimport com.siam.system.modular.package_user.mapper.MemberWithdrawRecordMapper;\nimport com.siam.system.modular.package_user.model.example.MemberWithdrawRecordExample;\nimport com.siam.system.modular.package_user.model.param.MemberWithdrawRecordParam;\nimport com.siam.system.modular.package_user.service.*;\nimport com.siam.system.util.TokenUtil;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport java.math.BigDecimal;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;", "context": "siam-system/system-provider/src/main/java/com/siam/system/modular/package_user/service_impl/MemberWithdrawRecordServiceImpl.java\npackage com.siam.system.modular.package_user.service_impl;\n\n\n\n@Slf4j\n@Service\npublic class MemberWithdrawRecordServiceImpl extends ServiceImpl implements MemberWithdrawRecordService {\n\n @Autowired\n private MemberWithdrawRecordMapper memberWithdrawRecordMapper;\n\n// @Autowired\n// private SettingService settingService;\n\n @Autowired\n private MemberService memberService;\n\n @Autowired\n private MemberTradeRecordService memberTradeRecordService;\n\n @Autowired\n private SettingService settingService;\n\n @Autowired\n private WxPayService wxPayService;\n\n @Autowired\n private MemberBillingRecordService memberBillingRecordService;\n\n @Autowired\n private MemberSessionManager memberSessionManager;\n\n// @Autowired\n// private SettingService settingService;\n\n @Override\n public int countByExample(MemberWithdrawRecordExample example) {\n return memberWithdrawRecordMapper.countByExample(example);\n }\n\n @Override\n public void deleteByPrimaryKey(Integer id) {\n memberWithdrawRecordMapper.deleteByPrimaryKey(id);\n }\n\n @Override\n public void insert(MemberWithdrawRecordParam param) {\n //TODO-这里如果真实姓名未初始化时,还会输入一个真实姓名\n Member loginMember = memberSessionManager.getSession(TokenUtil.getToken());\n Member dbMember = memberService.selectByPrimaryKey(loginMember.getId());\n\n if(StringUtils.isBlank(dbMember.getRealName())){\n throw new StoneCustomerException(\"您的真实姓名还未填写\");\n }\n\n //判断密码是否匹配\n String paymentPassword = Base64Utils.decode(param.getPaymentPassword());\n paymentPassword = CommonUtils.genMd5Password(paymentPassword, dbMember.getPaymentPasswordSalt());\n if(!paymentPassword.equals(dbMember.getPaymentPassword())){\n throw new StoneCustomerException(500, \"支付密码输入错误,请重新输入\");\n }\n\n if(param.getWithdrawAmount().compareTo(BigDecimal.ZERO) <= 0){\n throw new StoneCustomerException(\"提现金额必须大于0\");\n }\n\n Setting setting = settingService.selectCurrent();\n if(dbMember.getInviteRewardAmount().compareTo(setting.getMemberWithdrawMeetAmount()) < 0){\n throw new StoneCustomerException(\"奖励金累计到(≥)\" + setting.getMemberWithdrawMeetAmount() + \"元才可以提现\");\n }\n\n //自动计算平台手续费\n BigDecimal memberWithdrawFee = setting.getMemberWithdrawFee().divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);\n BigDecimal platformFee = param.getWithdrawAmount().multiply(memberWithdrawFee).setScale(2, BigDecimal.ROUND_HALF_UP);\n BigDecimal totalAmount = param.getWithdrawAmount().add(platformFee).setScale(2, BigDecimal.ROUND_HALF_UP);\n\n BigDecimal actualAmount = param.getWithdrawAmount();\n if(totalAmount.compareTo(dbMember.getInviteRewardAmount()) > 0){\n actualAmount = param.getWithdrawAmount().subtract(platformFee).setScale(2, BigDecimal.ROUND_HALF_UP);\n totalAmount = param.getWithdrawAmount();\n }\n\n log.debug(\"\\n\\nmemberWithdrawFee = \" + memberWithdrawFee);\n log.debug(\"\\n\\nmemberWithdrawRecord.getWithdrawAmount() = \" + param.getWithdrawAmount());\n log.debug(\"\\n\\nplatformFee = \" + platformFee);\n log.debug(\"\\n\\nactualAmount = \" + actualAmount);\n log.debug(\"\\n\\ntotalAmount = \" + totalAmount);\n //判断余额是否充足\n if(totalAmount.compareTo(dbMember.getInviteRewardAmount()) > 0){\n throw new StoneCustomerException(\"奖励金不足,请重新填写提现金额\");\n }\n\n // 获取订单编号\n int i = 0;\n String orderNo = GenerateNo.getOrderNo();\n while (true){\n if(i == 99){\n throw new StoneCustomerException(\"无法生成订单编号\");\n }\n log.debug(\"\\n获取订单编号...\");\n MemberWithdrawRecordExample memberWithdrawRecordExample = new MemberWithdrawRecordExample();\n memberWithdrawRecordExample.createCriteria().andOrderNoEqualTo(orderNo);\n int result = this.countByExample(memberWithdrawRecordExample);\n if(result > 0){\n orderNo = GenerateNo.getOrderNo();\n }else{\n break;\n }\n i++;\n }\n\n param.setMemberId(loginMember.getId());\n param.setOrderNo(orderNo);\n param.setCoinType(Quantity.INT_1);\n param.setPlatformFee(platformFee);\n param.setActualAmount(actualAmount);\n param.setCreateTime(new Date());\n param.setUpdateTime(new Date());\n this.save(param);\n\n //减少用户的邀请新用户注册奖励金额\n BigDecimal updateWithdrawableBalance = dbMember.getInviteRewardAmount().subtract(totalAmount).setScale(2, BigDecimal.ROUND_HALF_UP);\n\n Member updateMember = new Member();\n updateMember.setId(dbMember.getId());\n updateMember.setInviteRewardAmount(updateWithdrawableBalance);\n updateMember.setTotalWithdrawInviteRewardAmount(dbMember.getTotalWithdrawInviteRewardAmount().add(totalAmount));\n updateMember.setUpdateTime(new Date());\n memberService.updateByPrimaryKeySelective(updateMember);\n dbMember = memberService.selectByPrimaryKey(loginMember.getId());\n\n //TODO-增加用户账单记录\n MemberBillingRecord memberBillingRecord = new MemberBillingRecord();\n memberBillingRecord.setMemberId(dbMember.getId());\n memberBillingRecord.setType(MemberBillingRecord.TYPE_INVITE_REWARD_AMOUNT_WITHDRAW);\n memberBillingRecord.setOperateType(MemberBillingRecord.OPERATE_TYPE_SUB);\n memberBillingRecord.setCoinType(MemberBillingRecord.COIN_TYPE_INVITE_REWARD_AMOUNT);\n memberBillingRecord.setNumber(actualAmount);\n memberBillingRecord.setServiceFee(platformFee);\n /*memberBillingRecord.setServiceFee(memberWithdrawRecord.getPlatformFee());*/\n memberBillingRecord.setMessage(\"用户提现 -- 订单号\" + param.getOrderNo());\n memberBillingRecord.setCreateTime(new Date());\n memberBillingRecordService.insertSelective(memberBillingRecord);\n }\n\n @Override\n public MemberWithdrawRecord selectByPrimaryKey(Integer id) {\n return memberWithdrawRecordMapper.selectByPrimaryKey(id);\n }\n\n @Override\n public void updateByPrimaryKeySelective(MemberWithdrawRecord memberWithdrawRecord) {\n memberWithdrawRecordMapper.updateByPrimaryKeySelective(memberWithdrawRecord);\n }\n\n @Override\n public Page getListByPage(MemberWithdrawRecordParam param) {\n //获取当前登录用户绑定的门店编号\n Member loginMember = memberSessionManager.getSession(TokenUtil.getToken());\n param.setMemberId(loginMember.getId());\n Page> page = memberWithdrawRecordMapper.getListByPage(new Page(param.getPageNo(), param.getPageSize()), param);\n return page;\n }\n\n @Override\n public Page getListByPageJoinMember(MemberWithdrawRecordParam param) {\n Page> page = memberWithdrawRecordMapper.getListByPageJoinMember(new Page(param.getPageNo(), param.getPageSize()), param);\n return page;\n }\n\n @Override\n public Map statisticalAmount(MemberWithdrawRecordParam param) {\n BigDecimal withdrawalSuccessfulAmount = memberWithdrawRecordMapper.statisticalAmountByWithdrawalSuccessful(param);\n\n Map map = new HashMap<>();\n map.put(\"withdrawalSuccessfulAmount\", withdrawalSuccessfulAmount);\n return map;\n }\n\n @Override\n public void autoPayment() {\n //查询所有符合条件的用户提现记录,进行自动打款\n Setting setting = settingService.selectCurrent();\n List memberWithdrawRecordList = memberWithdrawRecordMapper.selectByNeedAutoPayment(setting.getMemberWithdrawAuditThreshold());\n memberWithdrawRecordList.forEach(memberWithdrawRecord -> {\n Member dbMember = memberService.selectByPrimaryKey(memberWithdrawRecord.getMemberId());\n\n //企业付款到零钱\n String orderNo = memberWithdrawRecord.getOrderNo();\n TransfersDto transfersDto = new TransfersDto();\n transfersDto.setOpenid(dbMember.getOpenId());\n transfersDto.setAmount(memberWithdrawRecord.getWithdrawAmount().doubleValue());\n transfersDto.setRe_user_name(dbMember.getRealName());\n transfersDto.setPartner_trade_no(orderNo);\n transfersDto.setDesc(\"暹罗外卖-用户提现到账\");\n boolean isPaySuccess = wxPayService.payToBalance(transfersDto);\n if(!isPaySuccess){\n throw new StoneCustomerException(\"打款失败,请联系管理员\");\n }\n\n //修改用户申请信息\n MemberWithdrawRecord updateMemberWithdrawRecord = new MemberWithdrawRecord();\n updateMemberWithdrawRecord.setId(memberWithdrawRecord.getId());\n updateMemberWithdrawRecord.setAuditStatus(Quantity.INT_2);\n updateMemberWithdrawRecord.setAuditTime(new Date());\n updateMemberWithdrawRecord.setUpdateTime(new Date());\n this.updateByPrimaryKeySelective(updateMemberWithdrawRecord);\n\n //添加用户交易记录\n MemberTradeRecord insertMemberTradeRecord = new MemberTradeRecord();\n insertMemberTradeRecord.setMemberId(dbMember.getId());\n insertMemberTradeRecord.setOutTradeNo(orderNo);\n insertMemberTradeRecord.setType(Quantity.INT_4);\n insertMemberTradeRecord.setPaymentMode(Quantity.INT_1);\n insertMemberTradeRecord.setAmount(memberWithdrawRecord.getWithdrawAmount());\n insertMemberTradeRecord.setStatus(Quantity.INT_2);\n insertMemberTradeRecord.setCreateTime(new Date());\n insertMemberTradeRecord.setUpdateTime(new Date());\n memberTradeRecordService.insertSelective(insertMemberTradeRecord);\n });\n }\n\n @Override\n public void auditApplyWithdraw(MemberWithdrawRecordParam param) {\n BasicResult basicResult = new BasicResult();\n\n if(param.getStatus() == Quantity.INT_2 && StringUtils.isBlank(param.getOpinion())){\n throw new StoneCustomerException(\"审核不通过时,审核意见不能为空\");\n }\n\n MemberWithdrawRecord dbMemberWithdrawRecord = this.selectByPrimaryKey(param.getId());\n if(dbMemberWithdrawRecord.getAuditStatus() != Quantity.INT_1){\n throw new StoneCustomerException(\"该提现记录的审核状态错误\");\n }\n\n Member dbMember = memberService.selectByPrimaryKey(dbMemberWithdrawRecord.getMemberId());\n\n //TODO-进行提现操作\n if(param.getStatus() == Quantity.INT_1){\n //企业付款到零钱\n String orderNo = dbMemberWithdrawRecord.getOrderNo();\n\nsiam-common/src/main/java/com/siam/package_common/util/GenerateNo.java\npublic class GenerateNo {\n\n //商品编号\n private static String productNo;\n\n //订单编号\n private static String orderNo;\n\n private static final String format= \"yyyyMMddHHmmss\";\n\n private static final String chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" ;\n\n private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);\n\n /**\n * 商品编号\n *\n * @return\n */\n public static String getProductNo(){\n productNo = simpleDateFormat.format(new Date());\n productNo = \"P\"+productNo+(int)((Math.random()*9+1)*1000)+getUpperLetter();\n return productNo;\n }\n\n /**\n * 订单编号 18位全数字\n *\n * @return\n */\n public static String getOrderNo(){\n //orderNo = simpleDateFormat.format(new Date());\n //orderNo = \"D\"+orderNo+(int)((Math.random()*9+1)*1000)+getUpperLetter();\n orderNo = \"\" + (int)((Math.random()*9+1)*1000000000);\n orderNo = orderNo+(int)((Math.random()*9+1)*10000000);\n return orderNo;\n }\n\n\n /**\n * 获取随机大写字母\n *\n * @return\n */\n private static char getUpperLetter() {\n return (chars.charAt((int) (Math.random() * 26)));\n }\n\n /**\n * 32位uuid\n *\n * @return\n */\n public static String getUUID(){\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n /**\n * 16位uuid\n *\n * @return\n */\n public static String getOrderIdByUUId() {\n int machineId = 1;//最大支持1-9个集群机器部署\n int hashCodeV = UUID.randomUUID().toString().hashCode();\n if(hashCodeV < 0) {//有可能是负数\n hashCodeV = - hashCodeV;\n }\n // 0 代表前面补充0\n // 4 代表长度为4\n // d 代表参数为正数型\n return machineId + String.format(\"%017d\", hashCodeV);\n }\n\n public static void main(String[] args) {\n String no = GenerateNo.getOrderNo();\n System.out.println(no + \" \" + no.length());\n System.out.println(GenerateNo.getOrderIdByUUId() + \" \" + GenerateNo.getOrderIdByUUId().length());\n }\n}\n\nsiam-system/system-api/src/main/java/com/siam/system/modular/package_user/entity/MemberTradeRecord.java\n@Data\n@TableName(\"tb_member_trade_record\")\n@ApiModel(value = \"用户交易表\")\npublic class MemberTradeRecord {\n\n Date startTime;\n Date endTime;\n\n @ApiModelProperty(notes = \"主键id\")\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n @ApiModelProperty(notes = \"商家账号id\")\n private Integer merchantId;\n\n @ApiModelProperty(notes = \"用户id\")\n private Integer memberId;\n\n @ApiModelProperty(notes = \"交易单号(支付平台的订单号)\")\n private String tradeNo;\n\n @ApiModelProperty(notes = \"商户单号(网站平台的订单号)\")\n private String outTradeNo;\n\n @ApiModelProperty(notes = \"交易类型 1=用户订单付款 2=用户会员充值 3=用户自取订单改为配送 4=商家余额提现\")\n private Integer type;\n\n @ApiModelProperty(notes = \"支付方式 1=微信 2=支付宝 3=平台余额 4=网银 5=银行转账\")\n private Integer paymentMode;\n\n @ApiModelProperty(notes = \"金额\")\n private BigDecimal amount;\n\n @ApiModelProperty(notes = \"交易状态 1=待支付 2=支付成功 3=支付失败 3=交易超时自动关闭\")\n private Integer status;\n\n @ApiModelProperty(notes = \"创建时间\")\n private Date createTime;\n\n @ApiModelProperty(notes = \"修改时间\")\n private Date updateTime;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Integer getMemberId() {\n return memberId;\n }\n\n public void setMemberId(Integer memberId) {\n this.memberId = memberId;\n }\n\n public Integer getMerchantId() {\n return merchantId;\n }\n\n public void setMerchantId(Integer merchantId) {\n this.merchantId = merchantId;\n }\n\n public String getOutTradeNo() {\n return outTradeNo;\n }\n\n public void setOutTradeNo(String outTradeNo) {\n this.outTradeNo = outTradeNo == null ? null : outTradeNo.trim();\n }\n\n public String getTradeNo() {\n return tradeNo;\n }\n\n public void setTradeNo(String tradeNo) {\n this.tradeNo = tradeNo == null ? null : tradeNo.trim();\n }\n\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public Integer getPaymentMode() {\n return paymentMode;\n }\n\n public void setPaymentMode(Integer paymentMode) {\n this.paymentMode = paymentMode;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n}\n\nsiam-common/src/main/java/com/siam/package_common/constant/Quantity.java\npublic class Quantity {\n\n public static final byte BYTE_0 = (byte) 0;\n public static final byte BYTE_1 = (byte) 1;\n public static final byte BYTE_2 = (byte) 2;\n public static final byte BYTE_3 = (byte) 3;\n\n public static final int INT_MINUS_1 = -1;\n public static final int INT_MINUS_60 = -60;\n\n public static final int INT_0 = 0;\n public static final int INT_1 = 1;\n public static final int INT_2 = 2;\n public static final int INT_3 = 3;\n public static final int INT_4 = 4;\n public static final int INT_5 = 5;\n public static final int INT_6 = 6;\n public static final int INT_7 = 7;\n public static final int INT_8 = 8;\n public static final int INT_9 = 9;\n public static final int INT_10 = 10;\n public static final int INT_11 = 11;\n public static final int INT_12 = 12;\n public static final int INT_13 = 13;\n public static final int INT_14 = 14;\n public static final int INT_15 = 15;\n public static final int INT_16 = 16;\n public static final int INT_17 = 17;\n public static final int INT_18 = 18;\n public static final int INT_19 = 19;\n\n public static final long LONG_0 = 0;\n public static final long LONG_1 = 1;\n public static final long LONG_2 = 2;\n public static final long LONG_3 = 3;\n public static final long LONG_4 = 4;\n\n}\n\nsiam-common/src/main/java/com/siam/package_common/util/Base64Utils.java\npublic class Base64Utils {\n\n // code characters for values 0..63\n private static char[] alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\".toCharArray();\n\n // lookup table for converting base64 characters to value in range 0..63\n private static byte[] codes = new byte[256];\n\n static {\n for (int i = 0; i < 256; i++) {\n codes[i] = -1;\n // LoggerUtil.debug(i + \"&\" + codes[i] + \" \");\n }\n for (int i = 'A'; i <= 'Z'; i++) {\n codes[i] = (byte) (i - 'A');\n // LoggerUtil.debug(i + \"&\" + codes[i] + \" \");\n }\n\n for (int i = 'a'; i <= 'z'; i++) {\n codes[i] = (byte) (26 + i - 'a');\n // LoggerUtil.debug(i + \"&\" + codes[i] + \" \");\n }\n for (int i = '0'; i <= '9'; i++) {\n codes[i] = (byte) (52 + i - '0');\n // LoggerUtil.debug(i + \"&\" + codes[i] + \" \");\n }\n codes['+'] = 62;\n codes['/'] = 63;\n }\n\n /**\n * 编码字符串\n *\n * @param data 源字符串\n * @return String\n */\n public static String encode(String data) {\n return new String(encode(data.getBytes()));\n }\n\n /**\n * 解码字符串\n *\n * @param data 源字符串\n * @return String\n */\n public static String decode(String data) {\n return new String(decode(data.toCharArray()));\n }\n\n /**\n * 编码byte[]\n *\n * @param data 源\n * @return char[]\n */\n public static char[] encode(byte[] data) {\n char[] out = new char[((data.length + 2) / 3) * 4];\n for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {\n boolean quad = false;\n boolean trip = false;\n\n int val = (0xFF & (int) data[i]);\n val <<= 8;\n if ((i + 1) < data.length) {\n val |= (0xFF & (int) data[i + 1]);\n trip = true;\n }\n val <<= 8;\n if ((i + 2) < data.length) {\n val |= (0xFF & (int) data[i + 2]);\n quad = true;\n }\n out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];\n val >>= 6;\n out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];\n val >>= 6;\n out[index + 1] = alphabet[val & 0x3F];\n val >>= 6;\n out[index + 0] = alphabet[val & 0x3F];\n }\n return out;\n }\n\n /**\n * 解码\n *\n * @param data 编码后的字符数组\n * @return byte[]\n */\n public static byte[] decode(char[] data) {\n\n int tempLen = data.length;\n for (int ix = 0; ix < data.length; ix++) {\n if ((data[ix] > 255) || codes[data[ix]] < 0) {\n --tempLen; // ignore non-valid chars and padding\n }\n }\n // calculate required length:\n // -- 3 bytes for every 4 valid base64 chars\n // -- plus 2 bytes if there are 3 extra base64 chars,\n // or plus 1 byte if there are 2 extra.\n\n int len = (tempLen / 4) * 3;\n if ((tempLen % 4) == 3) {\n len += 2;\n }\n if ((tempLen % 4) == 2) {\n len += 1;\n\n }\n byte[] out = new byte[len];\n\n int shift = 0; // # of excess bits stored in accum\n int accum = 0; // excess bits\n int index = 0;\n\n // we now go through the entire array (NOT using the 'tempLen' value)\n for (int ix = 0; ix < data.length; ix++) {\n int value = (data[ix] > 255) ? -1 : codes[data[ix]];\n\n if (value >= 0) { // skip over non-code\n accum <<= 6; // bits shift up by 6 each time thru\n shift += 6; // loop, with new bits being put in\n accum |= value; // at the bottom.\n if (shift >= 8) { // whenever there are 8 or more shifted in,\n shift -= 8; // write them out (from the top, leaving any\n out[index++] = // excess at the bottom for next iteration.\n (byte) ((accum >> shift) & 0xff);\n }\n }\n }\n\n // if there is STILL something wrong we just have to throw up now!\n if (index != out.length) {\n throw new Error(\"Miscalculated data length (wrote \" + index\n + \" instead of \" + out.length + \")\");\n }\n\n return out;\n }\n\n /**\n * 编码文件\n *\n * @param file 源文件\n * @return\n * @throws IOException\n */\n public static void encode(File file) throws IOException {\n if (!file.exists()) {\n System.exit(0);\n }\n\n else {\n byte[] decoded = readBytes(file);\n char[] encoded = encode(decoded);\n writeChars(file, encoded);\n }\n file = null;\n }\n\n /**\n * 解码文件。\n *\n * @param file 源文件\n * @return\n * @throws IOException\n */\n public static void decode(File file) throws IOException {\n if (!file.exists()) {\n System.exit(0);\n } else {\n char[] encoded = readChars(file);\n byte[] decoded = decode(encoded);\n writeBytes(file, decoded);\n }\n file = null;\n }\n\n /**\n * 将文件转化为字节数据\n *\n * @param file\n * @return byte[]\n * @throws IOException\n **/\n private static byte[] readBytes(File file) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n byte[] b = null;\n InputStream fis = null;\n InputStream is = null;\n try {\n fis = new FileInputStream(file);\n is = new BufferedInputStream(fis);\n int count = 0;\n byte[] buf = new byte[16384];\n while ((count = is.read(buf)) != -1) {\n if (count > 0) {\n baos.write(buf, 0, count);\n }\n }\n b = baos.toByteArray();\n\n } finally {\n try {\n if (fis != null)\n fis.close();\n if (is != null)\n is.close();\n if (baos != null)\n baos.close();\n } catch (Exception e) {\n System.out.println(e);\n }\n }\n\n return b;\n }\n\n /**\n * 将文件转化为字符数据\n *\n * @param file\n * @return char[]\n * @throws IOException\n **/\n private static char[] readChars(File file) throws IOException {\n CharArrayWriter caw = new CharArrayWriter();\n Reader fr = null;\n Reader in = null;\n try {\n fr = new FileReader(file);\n in = new BufferedReader(fr);\n int count = 0;\n char[] buf = new char[16384];\n while ((count = in.read(buf)) != -1) {\n if (count > 0) {\n caw.write(buf, 0, count);\n }\n }\n\n } finally {\n try {\n if (caw != null)\n caw.close();\n if (in != null)\n in.close();\n if (fr != null)\n fr.close();\n } catch (Exception e) {\n System.out.println(e);\n }\n }\n return caw.toCharArray();\n }\n\n /**\n * 将字节数据写入文件\n *\n * @param file\n * @param data\n * @return\n * @throws IOException\n **/\n private static void writeBytes(File file, byte[] data) throws IOException {\n OutputStream fos = null;\n OutputStream os = null;\n try {\n fos = new FileOutputStream(file);\n os = new BufferedOutputStream(fos);\n os.write(data);\n\n } finally {\n try {\n if (os != null)\n os.close();\n if (fos != null)\n fos.close();\n } catch (Exception e) {\n System.out.println(e);\n }\n }\n }\n\n /**\n * 将字符数据写入文件\n *\n * @param file\n * @param data\n * @return\n * @throws IOException\n **/\n private static void writeChars(File file, char[] data) throws IOException {\n Writer fos = null;\n Writer os = null;\n try {\n fos = new FileWriter(file);\n os = new BufferedWriter(fos);\n os.write(data);\n\n } finally {\n try {\n if (os != null)\n os.close();\n if (fos != null)\n fos.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n}", "answers": [" TransfersDto transfersDto = new TransfersDto();"], "length": 2341, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "fb54ea0e-172a-48ec-be3c-9f2471b69dff", "reasoning": "We are inside the auditApplyWithdraw method. After retrieving the order number, the code needs to prepare a payment request similar to the autoPayment method. The first step is to instantiate a TransfersDto object to hold the payment details. Therefore the next line should create this object.", "reasoning_model_answer": "TransfersDto transfersDto = new TransfersDto();", "assistant_with_reasoning": "\nWe are inside the auditApplyWithdraw method. After retrieving the order number, the code needs to prepare a payment request similar to the autoPayment method. The first step is to instantiate a TransfersDto object to hold the payment details. Therefore the next line should create this object.\n\nTransfersDto transfersDto = new TransfersDto();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.352, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 27431, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "TransfersDto transfersDto = new TransfersDto();", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.sql.rowset.serial.SerialException;\nimport javax.swing.text.html.HTML;\nimport com.alibaba.fastjson.JSON;\nimport com.alibaba.fastjson.JSONObject;\nimport com.nhXJH.common.exception.ServiceException;\nimport com.nhXJH.common.utils.StringUtils;\nimport com.nhXJH.enums.DelEnums;\nimport com.nhXJH.enums.PurchaseNodeStatusEnums;\nimport com.nhXJH.enums.StatusEnums;\nimport com.nhXJH.web.domain.BasePurchaseRequisition;\nimport com.nhXJH.web.domain.BasePurchaseRequisitionSub;\nimport com.nhXJH.web.domain.PurchaseRequisition;\nimport com.nhXJH.web.domain.param.PurchaseParam;\nimport com.nhXJH.web.domain.param.TempParam;\nimport com.nhXJH.web.domain.vo.BasePurchaseRequisitionVO;\nimport com.nhXJH.web.domain.vo.MyMatterVO;\nimport com.nhXJH.web.service.IBasePurchaseRequisitionService;\nimport io.swagger.annotations.Api;\nimport io.swagger.annotations.ApiOperation;\nimport org.apache.ibatis.annotations.Param;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.*;\nimport com.nhXJH.common.annotation.Log;\nimport com.nhXJH.common.core.controller.BaseController;\nimport com.nhXJH.common.core.domain.AjaxResult;\nimport com.nhXJH.common.enums.BusinessType;\nimport com.nhXJH.common.utils.poi.ExcelUtil;\nimport com.nhXJH.common.core.page.TableDataInfo;", "context": "nhXJH-admin/src/main/java/com/nhXJH/web/controller/appllication/BasePurchaseRequisitionController.java\npackage com.nhXJH.web.controller.appllication;\n\n\n\n/**\n * 采购申请信息Controller\n * \n * @author xjh\n * @date 2022-02-28\n */\n@RestController\n@RequestMapping(\"/userApplication/purchase\")\n@Api(tags = {\"采购申请信息\"})\npublic class BasePurchaseRequisitionController extends BaseController {\n @Autowired\n private IBasePurchaseRequisitionService basePurchaseRequisitionService;\n\n /**\n * 查询采购申请信息列表\n */\n @PreAuthorize(\"@ss.hasAnyRoles('libraryAdmin,admin')\") //@PreAuthorize(\"@ss.hasPermi('userApplication:purchase:list')\")\n @GetMapping(\"/list\")\n @ApiOperation(value =\"查询采购申请信息列表\",notes = \"查询采购申请信息列表\")\n public TableDataInfo list(BasePurchaseRequisition basePurchaseRequisition) {\n startPage();\n List list = basePurchaseRequisitionService.selectBasePurchaseRequisitionList(basePurchaseRequisition);\n basePurchaseRequisitionService.updateTimeout(list);\n return getDataTable(list);\n }\n\n\n /**\n * 查询采购申请信息列表\n */\n @PreAuthorize(\"@ss.hasAnyRoles('libraryAdmin,admin')\") //@PreAuthorize(\"@ss.hasPermi('userApplication:purchase:list')\")\n @GetMapping(\"/mine\")\n @ApiOperation(value =\"查询采购申请信息列表\",notes = \"查询采购申请信息列表\")\n public TableDataInfo mine(BasePurchaseRequisition purchaseRequisition) {\n purchaseRequisition.setCreatePersonal(getUserId());\n List list = basePurchaseRequisitionService.getMyMatter(purchaseRequisition);\n int count = StringUtils.isNull(list)?0:list.size();\n startPage();\n list = basePurchaseRequisitionService.getMyMatter(purchaseRequisition);\n TableDataInfo info = getDataTable(list);\n info.setTotal(count);\n return info;\n }\n /**\n * 查询采购申请信息列表\n */\n @PreAuthorize(\"@ss.hasAnyRoles('libraryAdmin,admin')\") //@PreAuthorize(\"@ss.hasPermi('userApplication:purchase:list')\")\n @GetMapping(\"/vo\")\n @ApiOperation(value =\"查询采购申请信息列表\",notes = \"查询采购申请信息列表\")\n public TableDataInfo vo(BasePurchaseRequisition basePurchaseRequisition) {\n startPage();\n basePurchaseRequisition.setCreatePersonal(getUserId());\n List list = basePurchaseRequisitionService.selectBasePurchaseRequisitionVOList(basePurchaseRequisition);\n Integer total = null==list?0:list.size();\n TableDataInfo info = getDataTable(list);\n info.setTotal(total);\n return info;\n }\n\n /**\n * 查询采购申请信息列表\n */\n @PreAuthorize(\"@ss.hasAnyRoles('libraryAdmin,admin')\") //@PreAuthorize(\"@ss.hasPermi('userApplication:purchase:list')\")\n @GetMapping(\"/approved/list\")\n @ApiOperation(value =\"查询采购申请信息列表\",notes = \"查询采购申请信息列表\")\n public TableDataInfo approved(BasePurchaseRequisition basePurchaseRequisition) {\n startPage();\n basePurchaseRequisition.setCreatePersonal(getUserId());\n List list = basePurchaseRequisitionService.selectApproved(basePurchaseRequisition);\n return getDataTable(list);\n }\n\n /**\n * 导出采购申请信息列表\n */\n @PreAuthorize(\"@ss.hasAnyRoles('libraryAdmin,admin')\") //@PreAuthorize(\"@ss.hasPermi('userApplication:purchase:export')\")\n @Log(title = \"采购申请信息\", businessType = BusinessType.EXPORT)\n @PostMapping(\"/export\")\n @ApiOperation(value =\"导出采购申请信息列表\",notes = \"导出采购申请信息列表\")\n public void export(HttpServletResponse response, BasePurchaseRequisition basePurchaseRequisition) {\n List list = basePurchaseRequisitionService.selectBasePurchaseRequisitionList(basePurchaseRequisition);\n\nnhXJH-admin/src/main/java/com/nhXJH/web/domain/param/PurchaseParam.java\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PurchaseParam {\n @ApiModelProperty(\"申请\")\n private BasePurchaseRequisition purchase;\n @ApiModelProperty(\"申请子项\")\n private BasePurchaseRequisitionSub[] subPurchase;\n private String submitType;\n\n public List getSubPurchase(){\n if (null == subPurchase){\n return new ArrayList<>();\n }\n List arr = new ArrayList<>();\n for (int i=0;i rows;\n\n /** 消息状态码 */\n private int code;\n\n /** 消息内容 */\n private String msg;\n\n /**\n * 表格数据对象\n */\n public TableDataInfo() {\n }\n\n /**\n * 分页\n * \n * @param list 列表数据\n * @param total 总记录数\n */\n public TableDataInfo(List list, int total) {\n this.rows = list;\n this.total = total;\n }\n\n public int getTotal() {\n return total;\n }\n\n public void setTotal(int total) {\n this.total = total;\n }\n\n public List getRows() {\n return rows;\n }\n\n public void setRows(List rows) {\n this.rows = rows;\n }\n\n public int getCode() {\n return code;\n }\n\n public void setCode(int code) {\n this.code = code;\n }\n\n public String getMsg() {\n return msg;\n }\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n}\n\nnhXJH-common/src/main/java/com/nhXJH/common/core/controller/BaseController.java\npublic class BaseController {\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @InitBinder\n public void initBinder(WebDataBinder binder) {\n // Date 类型转换\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {\n @Override\n public void setAsText(String text) {\n setValue(DateUtils.parseDate(text));\n }\n });\n }\n\n /**\n * 设置请求分页数据\n */\n protected void startPage() {\n PageUtils.startPage();\n }\n\n /**\n * 设置请求排序数据\n */\n protected void startOrderBy() {\n PageDomain pageDomain = TableSupport.buildPageRequest();\n if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {\n String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());\n PageHelper.orderBy(orderBy);\n }\n }\n\n /**\n * 响应请求分页数据\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n protected TableDataInfo getDataTable(List list) {\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(HttpStatus.SUCCESS);\n rspData.setMsg(\"查询成功\");\n rspData.setRows(list);\n rspData.setTotal((int) new PageInfo(list).getTotal());\n return rspData;\n }\n\n /**\n * 返回成功\n */\n public AjaxResult success() {\n return AjaxResult.success();\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error() {\n return AjaxResult.error();\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(String message) {\n return AjaxResult.success(message);\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error(String message) {\n return AjaxResult.error(message);\n }\n\n /**\n * 响应返回结果\n * \n * @param rows 影响行数\n * @return 操作结果\n */\n protected AjaxResult toAjax(int rows) {\n return rows > 0 ? AjaxResult.success() : AjaxResult.error();\n }\n\n /**\n * 响应返回结果\n * \n * @param result 结果\n * @return 操作结果\n */\n protected AjaxResult toAjax(boolean result) {\n return result ? success() : error();\n }\n\n /**\n * 页面跳转\n */\n public String redirect(String url) {\n return StringUtils.format(\"redirect:{}\", url);\n }\n\n /**\n * 获取用户缓存信息\n */\n public LoginUser getLoginUser() {\n return SecurityUtils.getLoginUser();\n }\n\n /**\n * 获取登录用户id\n */\n public Long getUserId() {\n return getLoginUser().getUserId();\n }\n\n /**\n * 获取登录部门id\n */\n public Long getDeptId() {\n return getLoginUser().getDeptId();\n }\n\n /**\n * 获取登录用户名\n */\n public String getUsername() {\n return getLoginUser().getUsername();\n }\n}\n\nnhXJH-admin/src/main/java/com/nhXJH/web/domain/param/TempParam.java\n@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class TempParam {\n String data;\n String arr;\n}\n\nnhXJH-admin/src/main/java/com/nhXJH/web/domain/BasePurchaseRequisition.java\n@TableName(\"base_purchase_requisition\")\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BasePurchaseRequisition extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 记录id */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n @ApiModelProperty(\"id\")\n private Long id;\n\n /** 记录id */\n @ApiModelProperty(\"上一版本即修改前的id\")\n private Long agoId;\n\n /** 采购申请标题文字 */\n @Excel(name = \"采购申请标题文字\")\n @ApiModelProperty(\"采购申请标题文字\")\n private String title;\n\n /** 采购申请人id */\n @ApiModelProperty(\"采购申请标题文字\")\n private Long approvePersonal;\n\n /** 采购申请部门 */\n @Excel(name = \"采购申请部门\")\n @ApiModelProperty(\"采购申请部门\")\n private Long approveDept;\n\n /** 采购开始时间 */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @Excel(name = \"采购开始时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(\"采购开始时间\")\n private Date startTime;\n\n /** 采购结束时间 */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @Excel(name = \"采购结束时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(\"采购结束时间\")\n private Date endTime;\n\n /** 有效期至某年某月某日某时某分某秒结束 */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @Excel(name = \"有效期至某年某月某日某时某分某秒结束\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(\"有效期至某年某月某日某时某分某秒结束\")\n private Date termValidity;\n\n /** 采购流程模板id */\n @ApiModelProperty(\"有效期至某年某月某日某时某分某秒结束\")\n private Long purchaseTemplate;\n\n /** 采购链状态,默认零(申请发起),处理中(一),处理完成(2),被取消(-1) */\n @Excel(name = \"采购链状态,默认零\", readConverterExp = \"申=请发起\")\n @ApiModelProperty(\"采购链状态,默认零\")\n private String purchaseStatus;\n\n /** 采购说明 */\n @Excel(name = \"采购说明\")\n @ApiModelProperty(\"采购说明\")\n private String mark;\n\n// /** 是否被删除 */\n// @ApiModelProperty(\"采购说明\")\n// private String isDel;\n\n /** 记录状态(默认1表示已存在,被删除0) */\n @Excel(name = \"记录状态\", readConverterExp = \"默=认1表示已存在,被删除0\")\n @ApiModelProperty(\"记录状态\")\n private String status;\n\n// /** 创建人ID */\n// @Excel(name = \"创建人ID\")\n// @ApiModelProperty(\"创建人ID\")\n// private Long createPersonal;\n//\n// /** 更新人id */\n// @Excel(name = \"更新人id\")\n// @ApiModelProperty(\"更新人id\")\n// private Long updatePersonal;\n\n\n\n}\n\nnhXJH-admin/src/main/java/com/nhXJH/web/domain/vo/MyMatterVO.java\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MyMatterVO {\n /** 记录ID */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n @ApiModelProperty(\"id\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Long id;\n\n /** 当前处理批次ID */\n @Excel(name = \"当前处理批次ID\")\n @ApiModelProperty(\"当前处理批次ID\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Long groupId;\n\n /** 处理类型,1表示采购申请,2表示图书销毁,3表示图书封存,4表示图书公开申请,等其他类型其他表示 */\n @Excel(name = \"处理类型\",readConverterExp = \"1=采购申请,2=图书销毁,3=图书封存,4=图书公开申请,5=其他类型\")\n @ApiModelProperty(\"处理类型,1表示采购申请,2表示图书销毁,3表示图书封存,4表示图书公开申请,等其他类型其他表示\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private String queueType;\n\n /** 待处理人ID */\n @Excel(name = \"待处理人ID\")\n @ApiModelProperty(\"待处理人ID\")\n private Long handelPersonal;\n\n /** 当前处理结点id */\n @Excel(name = \"当前处理结点\")\n @ApiModelProperty(\"当前处理结点\")\n private Long handelNode;\n\n /** 待处理审批申请ID */\n @Excel(name = \"待处理审批申请ID\")\n @ApiModelProperty(\"待处理审批申请ID\")\n private Long purchaseId;\n\n /** 是否已读,默认未读0,已读使用1表示 */\n @Excel(name = \"是否已读\",readConverterExp = \"0=未读,1=已读\")\n @ApiModelProperty(\"是否已读,默认未读0,已读使用1表示\")\n private String hasRead;\n\n /** 处理结果,未处理0表示,已处理1表示 */\n @Excel(name = \"处理结果\",readConverterExp = \"0=未处理,1=已处理\")\n @ApiModelProperty(\"处理结果,未处理0表示,已处理1表示\")\n private String result;\n\n /** 采购申请标题文字 */\n @Excel(name = \"采购申请标题文字\")\n @ApiModelProperty(\"采购申请标题文字\")\n private String title;\n}\n\nnhXJH-common/src/main/java/com/nhXJH/common/utils/StringUtils.java\npublic class StringUtils extends org.apache.commons.lang3.StringUtils {\n /** 空字符串 */\n private static final String NULLSTR = \"\";\n\n /** 下划线 */\n private static final char SEPARATOR = '_';\n\n /**\n * 获取参数不为空值\n * \n * @param value defaultValue 要判断的value\n * @return value 返回值\n */\n public static T nvl(T value, T defaultValue) {\n return value != null ? value : defaultValue;\n }\n\n /**\n * * 判断一个Collection是否为空, 包含List,Set,Queue\n * \n * @param coll 要判断的Collection\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Collection coll) {\n return isNull(coll) || coll.isEmpty();\n }\n\n /**\n * * 判断一个Collection是否非空,包含List,Set,Queue\n * \n * @param coll 要判断的Collection\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Collection coll) {\n return !isEmpty(coll);\n }\n\n /**\n * * 判断一个对象数组是否为空\n * \n * @param objects 要判断的对象数组\n ** @return true:为空 false:非空\n */\n public static boolean isEmpty(Object[] objects) {\n return isNull(objects) || (objects.length == 0);\n }\n\n /**\n * * 判断一个对象数组是否非空\n * \n * @param objects 要判断的对象数组\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Object[] objects) {\n return !isEmpty(objects);\n }\n\n /**\n * * 判断一个Map是否为空\n * \n * @param map 要判断的Map\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Map map) {\n return isNull(map) || map.isEmpty();\n }\n\n /**\n * * 判断一个Map是否为空\n * \n * @param map 要判断的Map\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Map map) {\n return !isEmpty(map);\n }\n\n /**\n * * 判断一个字符串是否为空串\n * \n * @param str String\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(String str) {\n return isNull(str) || NULLSTR.equals(str.trim());\n }\n\n /**\n * * 判断一个字符串是否为非空串\n * \n * @param str String\n * @return true:非空串 false:空串\n */\n public static boolean isNotEmpty(String str) {\n return !isEmpty(str);\n }\n\n /**\n * * 判断一个对象是否为空\n * \n * @param object Object\n * @return true:为空 false:非空\n */\n public static boolean isNull(Object object) {\n return object == null;\n }\n\n /**\n * * 判断一个对象是否非空\n * \n * @param object Object\n * @return true:非空 false:空\n */\n public static boolean isNotNull(Object object) {\n return !isNull(object);\n }\n\n /**\n * * 判断一个对象是否是数组类型(Java基本型别的数组)\n * \n * @param object 对象\n * @return true:是数组 false:不是数组\n */\n public static boolean isArray(Object object) {\n return isNotNull(object) && object.getClass().isArray();\n }\n\n /**\n * 去空格\n */\n public static String trim(String str) {\n return (str == null ? \"\" : str.trim());\n }\n\n /**\n * 截取字符串\n * \n * @param str 字符串\n * @param start 开始\n * @return 结果\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return NULLSTR;\n }\n\n if (start < 0) {\n start = str.length() + start;\n }\n\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return NULLSTR;\n }\n\n return str.substring(start);\n }\n\n /**\n * 截取字符串\n * \n * @param str 字符串\n * @param start 开始\n * @param end 结束\n * @return 结果\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return NULLSTR;\n }\n\n if (end < 0) {\n end = str.length() + end;\n }\n if (start < 0) {\n start = str.length() + start;\n }\n\n if (end > str.length()) {\n end = str.length();\n }\n\n if (start > end) {\n return NULLSTR;\n }\n\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n\n return str.substring(start, end);\n }\n\n /**\n * 格式化文本, {} 表示占位符
\n * 此方法只是简单将占位符 {} 按照顺序替换为参数
\n * 如果想输出 {} 使用 \\\\转义 { 即可,如果想输出 {} 之前的 \\ 使用双转义符 \\\\\\\\ 即可
\n * 例:
\n * 通常使用:format(\"this is {} for {}\", \"a\", \"b\") -> this is a for b
\n * 转义{}: format(\"this is \\\\{} for {}\", \"a\", \"b\") -> this is \\{} for a
\n * 转义\\: format(\"this is \\\\\\\\{} for {}\", \"a\", \"b\") -> this is \\a for b
\n * \n * @param template 文本模板,被替换的部分用 {} 表示\n * @param params 参数值\n * @return 格式化后的文本\n */\n public static String format(String template, Object... params) {\n if (isEmpty(params) || isEmpty(template)) {\n return template;\n }\n return StrFormatter.format(template, params);\n }\n\n /**\n * 是否为http(s)://开头\n * \n * @param link 链接\n * @return 结果\n */\n public static boolean ishttp(String link) {\n return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);\n }\n\n /**\n * 字符串转set\n * \n * @param str 字符串\n * @param sep 分隔符\n * @return set集合\n */\n public static final Set str2Set(String str, String sep) {\n return new HashSet(str2List(str, sep, true, false));\n }\n\n /**\n * 字符串转list\n * \n * @param str 字符串\n * @param sep 分隔符\n * @param filterBlank 过滤纯空白\n * @param trim 去掉首尾空白\n * @return list集合\n */\n public static final List str2List(String str, String sep, boolean filterBlank, boolean trim) {\n List list = new ArrayList();\n if (StringUtils.isEmpty(str)) {\n return list;\n }\n\n // 过滤空白字符串\n if (filterBlank && StringUtils.isBlank(str)) {\n return list;\n }\n String[] split = str.split(sep);\n for (String string : split) {\n if (filterBlank && StringUtils.isBlank(string)) {\n continue;\n }\n if (trim) {\n string = string.trim();\n }\n list.add(string);\n }\n\n return list;\n }\n\n /**\n * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写\n *\n * @param cs 指定字符串\n * @param searchCharSequences 需要检查的字符串数组\n * @return 是否包含任意一个字符串\n */\n public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {\n if (isEmpty(cs) || isEmpty(searchCharSequences)) {\n return false;\n }\n for (CharSequence testStr : searchCharSequences) {\n if (containsIgnoreCase(cs, testStr)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 驼峰转下划线命名\n */\n public static String toUnderScoreCase(String str) {\n if (str == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n // 前置字符是否大写\n boolean preCharIsUpperCase = true;\n // 当前字符是否大写\n boolean curreCharIsUpperCase = true;\n // 下一字符是否大写\n boolean nexteCharIsUpperCase = true;\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (i > 0) {\n preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));\n }\n else {\n preCharIsUpperCase = false;\n }\n\n curreCharIsUpperCase = Character.isUpperCase(c);\n\n if (i < (str.length() - 1)) {\n nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));\n }\n\n if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {\n sb.append(SEPARATOR);\n }\n else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {\n sb.append(SEPARATOR);\n }\n sb.append(Character.toLowerCase(c));\n }\n\n return sb.toString();\n }\n\n /**\n * 是否包含字符串\n * \n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs) {\n if (str != null && strs != null) {\n for (String s : strs) {\n if (str.equalsIgnoreCase(trim(s))) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld\n * \n * @param name 转换前的下划线大写方式命名的字符串\n * @return 转换后的驼峰式命名的字符串\n */\n public static String convertToCamelCase(String name) {\n StringBuilder result = new StringBuilder();\n // 快速检查\n if (name == null || name.isEmpty()) {\n // 没必要转换\n return \"\";\n }\n else if (!name.contains(\"_\")) {\n // 不含下划线,仅将首字母大写\n return name.substring(0, 1).toUpperCase() + name.substring(1);\n }\n // 用下划线将原始字符串分割\n String[] camels = name.split(\"_\");\n for (String camel : camels) {\n // 跳过原始字符串中开头、结尾的下换线或双重下划线\n if (camel.isEmpty()) {\n continue;\n }\n // 首字母大写\n result.append(camel.substring(0, 1).toUpperCase());\n result.append(camel.substring(1).toLowerCase());\n }\n return result.toString();\n }\n\n /**\n * 驼峰式命名法 例如:user_name->userName\n */\n public static String toCamelCase(String s) {\n if (s == null) {\n return null;\n }\n s = s.toLowerCase();\n StringBuilder sb = new StringBuilder(s.length());\n boolean upperCase = false;\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n\n if (c == SEPARATOR) {\n upperCase = true;\n }\n else if (upperCase) {\n sb.append(Character.toUpperCase(c));\n upperCase = false;\n }\n else {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n /**\n * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串\n * \n * @param str 指定字符串\n * @param strs 需要检查的字符串数组\n * @return 是否匹配\n */\n public static boolean matches(String str, List strs) {\n if (isEmpty(str) || isEmpty(strs)) {\n return false;\n }\n for (String pattern : strs) {\n if (isMatch(pattern, str)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断url是否与规则配置: \n * ? 表示单个字符; \n * * 表示一层路径内的任意字符串,不可跨层级; \n * ** 表示任意层路径;\n * \n * @param pattern 匹配规则\n * @param url 需要匹配的url\n * @return\n */\n public static boolean isMatch(String pattern, String url) {\n AntPathMatcher matcher = new AntPathMatcher();\n return matcher.match(pattern, url);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T cast(Object obj) {\n return (T) obj;\n }\n\n /**\n * 过滤特殊字符\n * */\n public static String stringFilter(String str){\n String regEx=\"[\\\\u00A0\\\\s\\\"`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]\";\n Pattern p = Pattern.compile(regEx);\n Matcher m = p.matcher(str);\n return m.replaceAll(\"\").trim();\n }\n /**\n * 是否包含特殊字符特殊字符\n * */\n public static boolean hasSpecialChar(String str){\n String regEx=\"[\\\\u00A0\\\\s\\\"`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]\";\n Pattern p = Pattern.compile(regEx);\n Matcher m = p.matcher(str);\n return m.find();\n }\n\n public static String replaceBlank(String str) {\n String dest = \"\";\n if (str!=null) {\n Pattern p = Pattern.compile(\"\\\\s{2,}|\\t|\\r|\\n\");\n Matcher m = p.matcher(str);\n dest = m.replaceAll(\"\");\n }\n return dest;\n }\n}", "answers": [" ExcelUtil util = new ExcelUtil(BasePurchaseRequisition.class);"], "length": 2407, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "986344c5-004a-4350-8aff-ea6c4dd45b70", "reasoning": "The export method has just retrieved the list of BasePurchaseRequisition objects. The next logical step is to create an ExcelUtil instance for this entity type to export the data to the HttpServletResponse. The project imports ExcelUtil, so the next line should instantiate it with the BasePurchaseRequisition class.", "reasoning_model_answer": "ExcelUtil util = new ExcelUtil(BasePurchaseRequisition.class);", "assistant_with_reasoning": "\nThe export method has just retrieved the list of BasePurchaseRequisition objects. The next logical step is to create an ExcelUtil instance for this entity type to export the data to the HttpServletResponse. The project imports ExcelUtil, so the next line should instantiate it with the BasePurchaseRequisition class.\n\nExcelUtil util = new ExcelUtil(BasePurchaseRequisition.class);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.169, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 26613, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "ExcelUtil util = new ExcelUtil(BasePurchaseRequisition.class);", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.List;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport com.ruoyi.common.utils.text.Convert;\nimport com.ruoyi.project.tool.gen.domain.GenTableColumn;\nimport com.ruoyi.project.tool.gen.mapper.GenTableColumnMapper;", "context": "src/main/java/com/ruoyi/project/tool/gen/service/GenTableColumnServiceImpl.java\npackage com.ruoyi.project.tool.gen.service;\n\n\n/**\n * 业务字段 服务层实现\n * \n * @author ruoyi\n */\n@Service\npublic class GenTableColumnServiceImpl implements IGenTableColumnService \n{\n\t@Autowired\n\tprivate GenTableColumnMapper genTableColumnMapper;\n\n\t/**\n * 查询业务字段列表\n * \n * @param genTableColumn 业务字段信息\n * @return 业务字段集合\n */\n\t@Override\n\tpublic List selectGenTableColumnListByTableId(GenTableColumn genTableColumn)\n\t{\n\nsrc/main/java/com/ruoyi/project/tool/gen/domain/GenTableColumn.java\npublic class GenTableColumn extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 编号 */\n private Long columnId;\n\n /** 归属表编号 */\n private Long tableId;\n\n /** 列名称 */\n private String columnName;\n\n /** 列描述 */\n private String columnComment;\n\n /** 列类型 */\n private String columnType;\n\n /** JAVA类型 */\n private String javaType;\n\n /** JAVA字段名 */\n @NotBlank(message = \"Java属性不能为空\")\n private String javaField;\n\n /** 是否主键(1是) */\n private String isPk;\n\n /** 是否自增(1是) */\n private String isIncrement;\n\n /** 是否必填(1是) */\n private String isRequired;\n\n /** 是否为插入字段(1是) */\n private String isInsert;\n\n /** 是否编辑字段(1是) */\n private String isEdit;\n\n /** 是否列表字段(1是) */\n private String isList;\n\n /** 是否查询字段(1是) */\n private String isQuery;\n\n /** 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围) */\n private String queryType;\n\n /** 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、upload上传控件、summernote富文本控件) */\n private String htmlType;\n\n /** 字典类型 */\n private String dictType;\n\n /** 排序 */\n private Integer sort;\n\n public void setColumnId(Long columnId)\n {\n this.columnId = columnId;\n }\n\n public Long getColumnId()\n {\n return columnId;\n }\n\n public void setTableId(Long tableId)\n {\n this.tableId = tableId;\n }\n\n public Long getTableId()\n {\n return tableId;\n }\n\n public void setColumnName(String columnName)\n {\n this.columnName = columnName;\n }\n\n public String getColumnName()\n {\n return columnName;\n }\n\n public void setColumnComment(String columnComment)\n {\n this.columnComment = columnComment;\n }\n\n public String getColumnComment()\n {\n return columnComment;\n }\n\n public void setColumnType(String columnType)\n {\n this.columnType = columnType;\n }\n\n public String getColumnType()\n {\n return columnType;\n }\n\n public void setJavaType(String javaType)\n {\n this.javaType = javaType;\n }\n\n public String getJavaType()\n {\n return javaType;\n }\n\n public void setJavaField(String javaField)\n {\n this.javaField = javaField;\n }\n\n public String getJavaField()\n {\n return javaField;\n }\n\n public String getCapJavaField()\n {\n return StringUtils.capitalize(javaField);\n }\n\n public void setIsPk(String isPk)\n {\n this.isPk = isPk;\n }\n\n public String getIsPk()\n {\n return isPk;\n }\n\n public boolean isPk()\n {\n return isPk(this.isPk);\n }\n\n public boolean isPk(String isPk)\n {\n return isPk != null && StringUtils.equals(\"1\", isPk);\n }\n\n public String getIsIncrement()\n {\n return isIncrement;\n }\n\n public void setIsIncrement(String isIncrement)\n {\n this.isIncrement = isIncrement;\n }\n\n public boolean isIncrement()\n {\n return isIncrement(this.isIncrement);\n }\n\n public boolean isIncrement(String isIncrement)\n {\n return isIncrement != null && StringUtils.equals(\"1\", isIncrement);\n }\n\n public void setIsRequired(String isRequired)\n {\n this.isRequired = isRequired;\n }\n\n public String getIsRequired()\n {\n return isRequired;\n }\n\n public boolean isRequired()\n {\n return isRequired(this.isRequired);\n }\n\n public boolean isRequired(String isRequired)\n {\n return isRequired != null && StringUtils.equals(\"1\", isRequired);\n }\n\n public void setIsInsert(String isInsert)\n {\n this.isInsert = isInsert;\n }\n\n public String getIsInsert()\n {\n return isInsert;\n }\n\n public boolean isInsert()\n {\n return isInsert(this.isInsert);\n }\n\n public boolean isInsert(String isInsert)\n {\n return isInsert != null && StringUtils.equals(\"1\", isInsert);\n }\n\n public void setIsEdit(String isEdit)\n {\n this.isEdit = isEdit;\n }\n\n public String getIsEdit()\n {\n return isEdit;\n }\n\n public boolean isEdit()\n {\n return isInsert(this.isEdit);\n }\n\n public boolean isEdit(String isEdit)\n {\n return isEdit != null && StringUtils.equals(\"1\", isEdit);\n }\n\n public void setIsList(String isList)\n {\n this.isList = isList;\n }\n\n public String getIsList()\n {\n return isList;\n }\n\n public boolean isList()\n {\n return isList(this.isList);\n }\n\n public boolean isList(String isList)\n {\n return isList != null && StringUtils.equals(\"1\", isList);\n }\n\n public void setIsQuery(String isQuery)\n {\n this.isQuery = isQuery;\n }\n\n public String getIsQuery()\n {\n return isQuery;\n }\n\n public boolean isQuery()\n {\n return isQuery(this.isQuery);\n }\n\n public boolean isQuery(String isQuery)\n {\n return isQuery != null && StringUtils.equals(\"1\", isQuery);\n }\n\n public void setQueryType(String queryType)\n {\n this.queryType = queryType;\n }\n\n public String getQueryType()\n {\n return queryType;\n }\n\n public String getHtmlType()\n {\n return htmlType;\n }\n\n public void setHtmlType(String htmlType)\n {\n this.htmlType = htmlType;\n }\n\n public void setDictType(String dictType)\n {\n this.dictType = dictType;\n }\n\n public String getDictType()\n {\n return dictType;\n }\n\n public void setSort(Integer sort)\n {\n this.sort = sort;\n }\n\n public Integer getSort()\n {\n return sort;\n }\n\n public boolean isSuperColumn()\n {\n return isSuperColumn(this.javaField);\n }\n\n public static boolean isSuperColumn(String javaField)\n {\n return StringUtils.equalsAnyIgnoreCase(javaField,\n // BaseEntity\n \"createBy\", \"createTime\", \"updateBy\", \"updateTime\", \"remark\",\n // TreeEntity\n \"parentName\", \"parentId\", \"orderNum\", \"ancestors\");\n }\n\n public boolean isUsableColumn()\n {\n return isUsableColumn(javaField);\n }\n\n public static boolean isUsableColumn(String javaField)\n {\n // isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单\n return StringUtils.equalsAnyIgnoreCase(javaField, \"parentId\", \"orderNum\", \"remark\");\n }\n\n public String readConverterExp()\n {\n String remarks = StringUtils.substringBetween(this.columnComment, \"(\", \")\");\n StringBuffer sb = new StringBuffer();\n if (StringUtils.isNotEmpty(remarks))\n {\n for (String value : remarks.split(\" \"))\n {\n if (StringUtils.isNotEmpty(value))\n {\n Object startStr = value.subSequence(0, 1);\n String endStr = value.substring(1);\n sb.append(\"\").append(startStr).append(\"=\").append(endStr).append(\",\");\n }\n }\n return sb.deleteCharAt(sb.length() - 1).toString();\n }\n else\n {\n return this.columnComment;\n }\n }\n}\n\nsrc/main/java/com/ruoyi/common/utils/text/Convert.java\npublic class Convert\n{\n /**\n * 转换为字符串
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static String toStr(Object value, String defaultValue)\n {\n if (null == value)\n {\n return defaultValue;\n }\n if (value instanceof String)\n {\n return (String) value;\n }\n return value.toString();\n }\n\n /**\n * 转换为字符串
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static String toStr(Object value)\n {\n return toStr(value, null);\n }\n\n /**\n * 转换为字符
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Character toChar(Object value, Character defaultValue)\n {\n if (null == value)\n {\n return defaultValue;\n }\n if (value instanceof Character)\n {\n return (Character) value;\n }\n\n final String valueStr = toStr(value, null);\n return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);\n }\n\n /**\n * 转换为字符
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Character toChar(Object value)\n {\n return toChar(value, null);\n }\n\n /**\n * 转换为byte
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Byte toByte(Object value, Byte defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Byte)\n {\n return (Byte) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).byteValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Byte.parseByte(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为byte
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Byte toByte(Object value)\n {\n return toByte(value, null);\n }\n\n /**\n * 转换为Short
\n * 如果给定的值为null,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Short toShort(Object value, Short defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Short)\n {\n return (Short) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).shortValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Short.parseShort(valueStr.trim());\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Short
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Short toShort(Object value)\n {\n return toShort(value, null);\n }\n\n /**\n * 转换为Number
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Number toNumber(Object value, Number defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Number)\n {\n return (Number) value;\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return NumberFormat.getInstance().parse(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Number
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Number toNumber(Object value)\n {\n return toNumber(value, null);\n }\n\n /**\n * 转换为int
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Integer toInt(Object value, Integer defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Integer)\n {\n return (Integer) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).intValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Integer.parseInt(valueStr.trim());\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为int
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Integer toInt(Object value)\n {\n return toInt(value, null);\n }\n\n /**\n * 转换为Integer数组
\n * \n * @param str 被转换的值\n * @return 结果\n */\n public static Integer[] toIntArray(String str)\n {\n return toIntArray(\",\", str);\n }\n\n /**\n * 转换为Long数组
\n * \n * @param str 被转换的值\n * @return 结果\n */\n public static Long[] toLongArray(String str)\n {\n return toLongArray(\",\", str);\n }\n\n /**\n * 转换为Integer数组
\n * \n * @param split 分隔符\n * @param split 被转换的值\n * @return 结果\n */\n public static Integer[] toIntArray(String split, String str)\n {\n if (StringUtils.isEmpty(str))\n {\n return new Integer[] {};\n }\n String[] arr = str.split(split);\n final Integer[] ints = new Integer[arr.length];\n for (int i = 0; i < arr.length; i++)\n {\n final Integer v = toInt(arr[i], 0);\n ints[i] = v;\n }\n return ints;\n }\n\n /**\n * 转换为Long数组
\n * \n * @param split 分隔符\n * @param str 被转换的值\n * @return 结果\n */\n public static Long[] toLongArray(String split, String str)\n {\n if (StringUtils.isEmpty(str))\n {\n return new Long[] {};\n }\n String[] arr = str.split(split);\n final Long[] longs = new Long[arr.length];\n for (int i = 0; i < arr.length; i++)\n {\n final Long v = toLong(arr[i], null);\n longs[i] = v;\n }\n return longs;\n }\n\n /**\n * 转换为String数组
\n * \n * @param str 被转换的值\n * @return 结果\n */\n public static String[] toStrArray(String str)\n {\n return toStrArray(\",\", str);\n }\n\n /**\n * 转换为String数组
\n * \n * @param split 分隔符\n * @param split 被转换的值\n * @return 结果\n */\n public static String[] toStrArray(String split, String str)\n {\n return str.split(split);\n }\n\n /**\n * 转换为long
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Long toLong(Object value, Long defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Long)\n {\n return (Long) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).longValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n // 支持科学计数法\n return new BigDecimal(valueStr.trim()).longValue();\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为long
\n * 如果给定的值为null,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Long toLong(Object value)\n {\n return toLong(value, null);\n }\n\n /**\n * 转换为double
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Double toDouble(Object value, Double defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Double)\n {\n return (Double) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).doubleValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n // 支持科学计数法\n return new BigDecimal(valueStr.trim()).doubleValue();\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为double
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Double toDouble(Object value)\n {\n return toDouble(value, null);\n }\n\n /**\n * 转换为Float
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Float toFloat(Object value, Float defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Float)\n {\n return (Float) value;\n }\n if (value instanceof Number)\n {\n return ((Number) value).floatValue();\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Float.parseFloat(valueStr.trim());\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Float
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Float toFloat(Object value)\n {\n return toFloat(value, null);\n }\n\n /**\n * 转换为boolean
\n * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static Boolean toBool(Object value, Boolean defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof Boolean)\n {\n return (Boolean) value;\n }\n String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n valueStr = valueStr.trim().toLowerCase();\n switch (valueStr)\n {\n case \"true\":\n return true;\n case \"false\":\n return false;\n case \"yes\":\n return true;\n case \"ok\":\n return true;\n case \"no\":\n return false;\n case \"1\":\n return true;\n case \"0\":\n return false;\n default:\n return defaultValue;\n }\n }\n\n /**\n * 转换为boolean
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static Boolean toBool(Object value)\n {\n return toBool(value, null);\n }\n\n /**\n * 转换为Enum对象
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * \n * @param clazz Enum的Class\n * @param value 值\n * @param defaultValue 默认值\n * @return Enum\n */\n public static > E toEnum(Class clazz, Object value, E defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (clazz.isAssignableFrom(value.getClass()))\n {\n @SuppressWarnings(\"unchecked\")\n E myE = (E) value;\n return myE;\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return Enum.valueOf(clazz, valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为Enum对象
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * \n * @param clazz Enum的Class\n * @param value 值\n * @return Enum\n */\n public static > E toEnum(Class clazz, Object value)\n {\n return toEnum(clazz, value, null);\n }\n\n /**\n * 转换为BigInteger
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static BigInteger toBigInteger(Object value, BigInteger defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof BigInteger)\n {\n return (BigInteger) value;\n }\n if (value instanceof Long)\n {\n return BigInteger.valueOf((Long) value);\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return new BigInteger(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为BigInteger
\n * 如果给定的值为空,或者转换失败,返回默认值null
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static BigInteger toBigInteger(Object value)\n {\n return toBigInteger(value, null);\n }\n\n /**\n * 转换为BigDecimal
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @param defaultValue 转换错误时的默认值\n * @return 结果\n */\n public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue)\n {\n if (value == null)\n {\n return defaultValue;\n }\n if (value instanceof BigDecimal)\n {\n return (BigDecimal) value;\n }\n if (value instanceof Long)\n {\n return new BigDecimal((Long) value);\n }\n if (value instanceof Double)\n {\n return new BigDecimal((Double) value);\n }\n if (value instanceof Integer)\n {\n return new BigDecimal((Integer) value);\n }\n final String valueStr = toStr(value, null);\n if (StringUtils.isEmpty(valueStr))\n {\n return defaultValue;\n }\n try\n {\n return new BigDecimal(valueStr);\n }\n catch (Exception e)\n {\n return defaultValue;\n }\n }\n\n /**\n * 转换为BigDecimal
\n * 如果给定的值为空,或者转换失败,返回默认值
\n * 转换失败不会报错\n * \n * @param value 被转换的值\n * @return 结果\n */\n public static BigDecimal toBigDecimal(Object value)\n {\n return toBigDecimal(value, null);\n }\n\n /**\n * 将对象转为字符串
\n * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法\n * \n * @param obj 对象\n * @return 字符串\n */\n public static String utf8Str(Object obj)\n {\n return str(obj, CharsetKit.CHARSET_UTF_8);\n }\n\n /**\n * 将对象转为字符串
\n * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法\n * \n * @param obj 对象\n * @param charsetName 字符集\n * @return 字符串\n */\n public static String str(Object obj, String charsetName)\n {\n return str(obj, Charset.forName(charsetName));\n }\n\n /**\n * 将对象转为字符串
\n * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法\n * \n * @param obj 对象\n * @param charset 字符集\n * @return 字符串\n */\n public static String str(Object obj, Charset charset)\n {\n if (null == obj)\n {\n return null;\n }\n\n if (obj instanceof String)\n {\n return (String) obj;\n }\n else if (obj instanceof byte[])\n {\n return str((byte[]) obj, charset);\n }\n else if (obj instanceof Byte[])\n {\n byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj);\n return str(bytes, charset);\n }\n else if (obj instanceof ByteBuffer)\n {\n return str((ByteBuffer) obj, charset);\n }\n return obj.toString();\n }\n\n /**\n * 将byte数组转为字符串\n * \n * @param bytes byte数组\n * @param charset 字符集\n * @return 字符串\n */\n public static String str(byte[] bytes, String charset)\n {\n return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));\n }\n\n /**\n * 解码字节码\n * \n * @param data 字符串\n * @param charset 字符集,如果此字段为空,则解码的结果取决于平台\n * @return 解码后的字符串\n */\n public static String str(byte[] data, Charset charset)\n {\n if (data == null)\n {\n return null;\n }\n\n if (null == charset)\n {\n return new String(data);\n }\n return new String(data, charset);\n }\n\n /**\n * 将编码的byteBuffer数据转换为字符串\n * \n * @param data 数据\n * @param charset 字符集,如果为空使用当前系统字符集\n * @return 字符串\n */\n public static String str(ByteBuffer data, String charset)\n {\n if (data == null)\n {\n return null;\n }\n\n return str(data, Charset.forName(charset));\n }\n\n /**\n * 将编码的byteBuffer数据转换为字符串\n * \n * @param data 数据\n * @param charset 字符集,如果为空使用当前系统字符集\n * @return 字符串\n */\n public static String str(ByteBuffer data, Charset charset)\n {\n if (null == charset)\n {\n charset = Charset.defaultCharset();\n }\n return charset.decode(data).toString();\n }\n\n // ----------------------------------------------------------------------- 全角半角转换\n /**\n * 半角转全角\n * \n * @param input String.\n * @return 全角字符串.\n */\n public static String toSBC(String input)\n {\n return toSBC(input, null);\n }\n\n /**\n * 半角转全角\n * \n * @param input String\n * @param notConvertSet 不替换的字符集合\n * @return 全角字符串.\n */\n public static String toSBC(String input, Set notConvertSet)\n {\n char c[] = input.toCharArray();\n for (int i = 0; i < c.length; i++)\n {\n if (null != notConvertSet && notConvertSet.contains(c[i]))\n {\n // 跳过不替换的字符\n continue;\n }\n\n if (c[i] == ' ')\n {\n c[i] = '\\u3000';\n }\n else if (c[i] < '\\177')\n {\n c[i] = (char) (c[i] + 65248);\n\n }\n }\n return new String(c);\n }\n\n /**\n * 全角转半角\n * \n * @param input String.\n * @return 半角字符串\n */\n public static String toDBC(String input)\n {\n return toDBC(input, null);\n }\n\n /**\n * 替换全角为半角\n * \n * @param text 文本\n * @param notConvertSet 不替换的字符集合\n * @return 替换后的字符\n */\n public static String toDBC(String text, Set notConvertSet)\n {\n char c[] = text.toCharArray();\n for (int i = 0; i < c.length; i++)\n {\n if (null != notConvertSet && notConvertSet.contains(c[i]))\n {\n // 跳过不替换的字符\n continue;\n }\n\n if (c[i] == '\\u3000')\n {\n c[i] = ' ';\n }\n else if (c[i] > '\\uFF00' && c[i] < '\\uFF5F')\n {\n c[i] = (char) (c[i] - 65248);\n }\n }\n String returnString = new String(c);\n\n return returnString;\n }\n\n /**\n * 数字金额大写转换 先写个完整的然后将如零拾替换成零\n * \n * @param n 数字\n * @return 中文大写数字\n */\n public static String digitUppercase(double n)\n {\n String[] fraction = { \"角\", \"分\" };\n String[] digit = { \"零\", \"壹\", \"贰\", \"叁\", \"肆\", \"伍\", \"陆\", \"柒\", \"捌\", \"玖\" };\n String[][] unit = { { \"元\", \"万\", \"亿\" }, { \"\", \"拾\", \"佰\", \"仟\" } };\n\n String head = n < 0 ? \"负\" : \"\";\n n = Math.abs(n);\n\n String s = \"\";\n for (int i = 0; i < fraction.length; i++)\n {\n s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll(\"(零.)+\", \"\");\n }\n if (s.length() < 1)\n {\n s = \"整\";\n }\n int integerPart = (int) Math.floor(n);\n\n for (int i = 0; i < unit[0].length && integerPart > 0; i++)\n {\n String p = \"\";\n for (int j = 0; j < unit[1].length && n > 0; j++)\n {\n p = digit[integerPart % 10] + unit[1][j] + p;\n integerPart = integerPart / 10;\n }\n s = p.replaceAll(\"(零.)*零$\", \"\").replaceAll(\"^$\", \"零\") + unit[0][i] + s;\n }\n return head + s.replaceAll(\"(零.)*零元\", \"元\").replaceFirst(\"(零.)+\", \"\").replaceAll(\"(零.)+\", \"零\").replaceAll(\"^整$\", \"零元整\");\n }\n}", "answers": ["\t return genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn);"], "length": 2986, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "8983cb5c-1f6d-4f16-81e4-883973618819", "reasoning": "The method selectGenTableColumnListByTableId should retrieve a list of GenTableColumn objects based on the provided genTableColumn (which contains the tableId). The service has an autowired GenTableColumnMapper, which likely provides a method with the same name to query the database. Therefore, the next line should return the result of calling that mapper method with the given parameter.", "reasoning_model_answer": "return genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn);", "assistant_with_reasoning": "\nThe method selectGenTableColumnListByTableId should retrieve a list of GenTableColumn objects based on the provided genTableColumn (which contains the tableId). The service has an autowired GenTableColumnMapper, which likely provides a method with the same name to query the database. Therefore, the next line should return the result of calling that mapper method with the given parameter.\n\nreturn genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.3, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 30309, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn);", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import nl.rrd.senseeact.client.exception.HttpFieldError;\nimport nl.rrd.senseeact.client.model.RegexUserAccess;\nimport nl.rrd.senseeact.client.model.RegexUserAccessTable;\nimport nl.rrd.senseeact.client.model.Role;\nimport nl.rrd.senseeact.dao.Database;\nimport nl.rrd.senseeact.dao.DatabaseCriteria;\nimport nl.rrd.senseeact.dao.DatabaseSort;\nimport nl.rrd.senseeact.service.ProtocolVersion;\nimport nl.rrd.senseeact.service.exception.BadRequestException;\nimport nl.rrd.senseeact.service.exception.ForbiddenException;\nimport nl.rrd.senseeact.service.exception.HttpException;\nimport nl.rrd.senseeact.service.model.User;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.regex.Pattern;", "context": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/controller/project/RegexUserAccessController.java\npackage nl.rrd.senseeact.service.controller.project;\n\n\n\npublic class RegexUserAccessController {\n\tprivate static final Object LOCK = new Object();\n\n\tprivate RegexUserAccessTable table;\n\n\tpublic RegexUserAccessController(RegexUserAccessTable table) {\n\nSenSeeActServiceLib/src/main/java/nl/rrd/senseeact/service/exception/HttpException.java\npublic abstract class HttpException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate HttpError error;\n\n\t/**\n\t * Constructs a new HTTP exception with default error code 0.\n\t * \n\t * @param message the error message\n\t */\n\tpublic HttpException(String message) {\n\t\tsuper(message);\n\t\terror = new HttpError(null, message);\n\t}\n\t\n\t/**\n\t * Constructs a new HTTP exception.\n\t * \n\t * @param code the error code (default null)\n\t * @param message the error message\n\t */\n\tpublic HttpException(String code, String message) {\n\t\tsuper(message);\n\t\terror = new HttpError(code, message);\n\t}\n\t\n\t/**\n\t * Constructs a new HTTP exception with the specified error.\n\t * \n\t * @param error the error\n\t */\n\tpublic HttpException(HttpError error) {\n\t\tsuper(error.getMessage());\n\t\tthis.error = error;\n\t}\n\n\t/**\n\t * Returns the error details.\n\t * \n\t * @return the error details\n\t */\n\tpublic HttpError getError() {\n\t\treturn error;\n\t}\n\t\n\t/**\n\t * Returns the HTTP exception for the specified HTTP status code.\n\t * Unsupported status codes will be mapped to an {@link\n\t * InternalServerErrorException InternalServerErrorException}.\n\t * \n\t * @param statusCode the HTTP status code\n\t * @param error the error details\n\t * @return the HTTP exception\n\t */\n\tpublic static HttpException forStatus(int statusCode, HttpError error) {\n\t\tswitch (statusCode) {\n\t\tcase 400:\n\t\t\treturn new BadRequestException(error);\n\t\tcase 401:\n\t\t\treturn new UnauthorizedException(error);\n\t\tcase 403:\n\t\t\treturn new ForbiddenException(error);\n\t\tcase 404:\n\t\t\treturn new NotFoundException(error);\n\t\tcase 501:\n\t\t\treturn new NotImplementedException(error);\n\t\tdefault:\n\t\t\treturn new InternalServerErrorException(error);\n\t\t}\n\t}\n}\n\nSenSeeActServiceLib/src/main/java/nl/rrd/senseeact/service/exception/BadRequestException.java\n@ResponseStatus(value=HttpStatus.BAD_REQUEST)\npublic class BadRequestException extends HttpException {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic BadRequestException() {\n\t\tsuper(\"Bad Request\");\n\t}\n\n\tpublic BadRequestException(String message) {\n\t\tsuper(message);\n\t}\n\t\n\tpublic BadRequestException(String code, String message) {\n\t\tsuper(code, message);\n\t}\n\t\n\tpublic BadRequestException(HttpError error) {\n\t\tsuper(error);\n\t}\n\t\n\tpublic BadRequestException appendInvalidInput(BadRequestException other) {\n\t\tList errors = new ArrayList<>();\n\t\tfor (HttpFieldError error : getError().getFieldErrors()) {\n\t\t\terrors.add(error);\n\t\t}\n\t\tfor (HttpFieldError error : other.getError().getFieldErrors()) {\n\t\t\terrors.add(error);\n\t\t}\n\t\treturn withInvalidInput(errors);\n\t}\n\t\n\tpublic BadRequestException appendInvalidInput(\n\t\t\tHttpFieldError... fieldErrors) {\n\t\treturn appendInvalidInput(Arrays.asList(fieldErrors));\n\t}\n\t\n\tpublic BadRequestException appendInvalidInput(\n\t\t\tList fieldErrors) {\n\t\tList newErrors = new ArrayList<>();\n\t\tfor (HttpFieldError error : getError().getFieldErrors()) {\n\t\t\tnewErrors.add(error);\n\t\t}\n\t\tfor (HttpFieldError error : fieldErrors) {\n\t\t\tnewErrors.add(error);\n\t\t}\n\t\treturn withInvalidInput(newErrors);\n\t}\n\t\n\tpublic static BadRequestException withInvalidInput(\n\t\t\tHttpFieldError... fieldErrors) {\n\t\treturn withInvalidInput(Arrays.asList(fieldErrors));\n\t}\n\n\tpublic static BadRequestException withInvalidInput(\n\t\t\tList fieldErrors) {\n\t\tStringBuffer errorMsg = new StringBuffer();\n\t\tString newline = System.getProperty(\"line.separator\");\n\t\tfor (HttpFieldError fieldError : fieldErrors) {\n\t\t\tif (errorMsg.length() > 0)\n\t\t\t\terrorMsg.append(newline);\n\t\t\terrorMsg.append(fieldError.getMessage());\n\t\t}\n\t\tHttpError error = new HttpError(ErrorCode.INVALID_INPUT,\n\t\t\t\terrorMsg.toString());\n\t\tfor (HttpFieldError fieldError : fieldErrors) {\n\t\t\terror.addFieldError(fieldError);\n\t\t}\n\t\treturn new BadRequestException(error);\n\t}\n}\n\nDataAccessObjects/src/main/java/nl/rrd/senseeact/dao/DatabaseSort.java\n@JsonIgnoreProperties(ignoreUnknown=true)\npublic class DatabaseSort {\n\tprivate String column = null;\n\tprivate boolean ascending = true;\n\n\t/**\n\t * This default constructor is used for JSON serialization.\n\t */\n\tpublic DatabaseSort() {\n\t}\n\t\n\t/**\n\t * Constructs a new instance. Note that string comparisons are sensitive to\n\t * case and diacritics. This is normal in MongoDB and SQLite, but different\n\t * than the default in MySQL.\n\t * \n\t * @param column the column name\n\t * @param ascending true if the column should be sorted in ascending order,\n\t * false if it should be sorted in descending order\n\t */\n\tpublic DatabaseSort(String column, boolean ascending) {\n\t\tthis.column = column;\n\t\tthis.ascending = ascending;\n\t}\n\t\n\t/**\n\t * Returns the column name.\n\t * \n\t * @return the column name\n\t */\n\tpublic String getColumn() {\n\t\treturn column;\n\t}\n\t\n\t/**\n\t * Sets the column name.\n\t * \n\t * @param column the colum name\n\t */\n\tpublic void setColumn(String column) {\n\t\tthis.column = column;\n\t}\n\n\t/**\n\t * Returns whether the column should be sorted in ascending order.\n\t * \n\t * @return true if the column should be sorted in ascending order, false if\n\t * it should be sorted in descending order\n\t */\n\tpublic boolean isAscending() {\n\t\treturn ascending;\n\t}\n\n\t/**\n\t * Sets whether the column should be sorted in ascending order.\n\t * \n\t * @param ascending true if the column should be sorted in ascending order,\n\t * false if it should be sorted in descending order\n\t */\n\tpublic void setAscending(boolean ascending) {\n\t\tthis.ascending = ascending;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn column + \" \" + (ascending ? \"ASC\" : \"DESC\");\n\t}\n\t\n\tpublic static DatabaseSort[] reverse(DatabaseSort[] sort) {\n\t\tDatabaseSort[] result = new DatabaseSort[sort.length];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tDatabaseSort orig = sort[i];\n\t\t\tresult[i] = new DatabaseSort(orig.column, !orig.ascending);\n\t\t}\n\t\treturn result;\n\t}\n}\n\nSenSeeActClient/src/main/java/nl/rrd/senseeact/client/exception/HttpFieldError.java\npublic class HttpFieldError extends JsonObject {\n\tprivate String field = null;\n\tprivate String message = null;\n\n\t/**\n\t * Constructs a new empty field error.\n\t */\n\tpublic HttpFieldError() {\n\t}\n\t\n\t/**\n\t * Constructs a new HTTP field error without an error code and message.\n\t * \n\t * @param field the field name\n\t */\n\tpublic HttpFieldError(String field) {\n\t\tthis.field = field;\n\t}\n\n\t/**\n\t * Constructs a new HTTP field error without an error code.\n\t * \n\t * @param field the field name\n\t * @param message the error message (can be an empty string or null)\n\t */\n\tpublic HttpFieldError(String field, String message) {\n\t\tthis.field = field;\n\t\tthis.message = message;\n\t}\n\n\t/**\n\t * Returns the field name.\n\t * \n\t * @return the field name\n\t */\n\tpublic String getField() {\n\t\treturn field;\n\t}\n\n\t/**\n\t * Sets the field name.\n\t * \n\t * @param field the field name\n\t */\n\tpublic void setField(String field) {\n\t\tthis.field = field;\n\t}\n\n\t/**\n\t * Returns the error message.\n\t * \n\t * @return the error message (can be an empty string or null)\n\t */\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n\n\t/**\n\t * Sets the error message.\n\t * \n\t * @param message the error message (can be an empty string or null)\n\t */\n\tpublic void setMessage(String message) {\n\t\tthis.message = message;\n\t}\n}\n\nSenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/RegexUserAccessTable.java\npublic class RegexUserAccessTable extends DatabaseTableDef {\n\tprivate static final int VERSION = 0;\n\n\tpublic RegexUserAccessTable(String name) {\n\t\tsuper(name, RegexUserAccess.class, VERSION, false);\n\t}\n\n\t@Override\n\tpublic int upgradeTable(int version, Database db, String physTable)\n\t\t\tthrows DatabaseException {\n\t\treturn 0;\n\t}\n}\n\nDataAccessObjects/src/main/java/nl/rrd/senseeact/dao/DatabaseCriteria.java\npublic abstract class DatabaseCriteria {\n\t\n\t/**\n\t * Formats the specified value for logging. Depending on the argument type\n\t * it returns:\n\t * \n\t *

    \n\t *
  • null: null
  • \n\t *
  • number: value.toString()
  • \n\t *
  • string: JSON string
  • \n\t *

\n\t * \n\t * @param value the value (number, string or null)\n\t * @return the formatted value\n\t */\n\tprotected String formatValue(Object value) {\n\t\tif (value == null)\n\t\t\treturn \"null\";\n\t\tif (value instanceof Number)\n\t\t\treturn value.toString();\n\t\tString result = value.toString();\n\t\tObjectMapper mapper = new ObjectMapper();\n\t\ttry {\n\t\t\treturn mapper.writeValueAsString(result);\n\t\t} catch (JsonProcessingException ex) {\n\t\t\tthrow new RuntimeException(\"Can't convert string to JSON: \" +\n\t\t\t\t\tex.getMessage(), ex);\n\t\t}\n\t}\n\n\tpublic abstract boolean containsColumn(String column);\n\t\n\t@Override\n\tpublic abstract int hashCode();\n\t\n\t@Override\n\tpublic abstract boolean equals(Object obj);\n\t\n\t@Override\n\tpublic abstract String toString();\n\t\n\tpublic static class Equal extends DatabaseCriteria {\n\t\tprivate String column;\n\t\tprivate Object value;\n\t\t\n\t\t/**\n\t\t * Note that string comparisons are sensitive to case and diacritics.\n\t\t * This is normal in MongoDB and SQLite, but different than the default\n\t\t * in MySQL.\n\t\t * \n\t\t * @param column the column name\n\t\t * @param value the value\n\t\t */\n\t\tpublic Equal(String column, String value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic Equal(String column, Number value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\n\t\tpublic String getColumn() {\n\t\t\treturn column;\n\t\t}\n\t\t\n\t\tpublic Object getValue() {\n\t\t\treturn value;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\treturn column.equals(this.column);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = column.hashCode();\n\t\t\tObject normVal = PrimitiveValueComparison.normalizeValue(value);\n\t\t\tresult = 31 * result + (normVal != null ? normVal.hashCode() : 0);\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tEqual other = (Equal)obj;\n\t\t\tif (!column.equals(other.column))\n\t\t\t\treturn false;\n\t\t\tif (!PrimitiveValueComparison.isEqual(value, other.value))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn column + \" = \" + formatValue(value);\n\t\t}\n\t}\n\t\n\tpublic static class NotEqual extends DatabaseCriteria {\n\t\tprivate String column;\n\t\tprivate Object value;\n\n\t\t/**\n\t\t * Note that string comparisons are sensitive to case and diacritics.\n\t\t * This is normal in MongoDB and SQLite, but different than the default\n\t\t * in MySQL.\n\t\t * \n\t\t * @param column the column name\n\t\t * @param value the value\n\t\t */\n\t\tpublic NotEqual(String column, String value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic NotEqual(String column, Number value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\n\t\tpublic String getColumn() {\n\t\t\treturn column;\n\t\t}\n\t\t\n\t\tpublic Object getValue() {\n\t\t\treturn value;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\treturn column.equals(this.column);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = column.hashCode();\n\t\t\tObject normVal = PrimitiveValueComparison.normalizeValue(value);\n\t\t\tresult = 31 * result + (normVal != null ? normVal.hashCode() : 0);\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tNotEqual other = (NotEqual)obj;\n\t\t\tif (!column.equals(other.column))\n\t\t\t\treturn false;\n\t\t\tif (!PrimitiveValueComparison.isEqual(value, other.value))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn column + \" != \" + formatValue(value);\n\t\t}\n\t}\n\t\n\tpublic static class LessThan extends DatabaseCriteria {\n\t\tprivate String column;\n\t\tprivate Object value;\n\n\t\t/**\n\t\t * Note that string comparisons are sensitive to case and diacritics.\n\t\t * This is normal in MongoDB and SQLite, but different than the default\n\t\t * in MySQL.\n\t\t * \n\t\t * @param column the column name\n\t\t * @param value the value\n\t\t */\n\t\tpublic LessThan(String column, String value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic LessThan(String column, Number value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic String getColumn() {\n\t\t\treturn column;\n\t\t}\n\t\t\n\t\tpublic Object getValue() {\n\t\t\treturn value;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\treturn column.equals(this.column);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = column.hashCode();\n\t\t\tObject normVal = PrimitiveValueComparison.normalizeValue(value);\n\t\t\tresult = 31 * result + (normVal != null ? normVal.hashCode() : 0);\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tLessThan other = (LessThan)obj;\n\t\t\tif (!column.equals(other.column))\n\t\t\t\treturn false;\n\t\t\tif (!PrimitiveValueComparison.isEqual(value, other.value))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn column + \" < \" + formatValue(value);\n\t\t}\n\t}\n\t\n\tpublic static class GreaterThan extends DatabaseCriteria {\n\t\tprivate String column;\n\t\tprivate Object value;\n\n\t\t/**\n\t\t * Note that string comparisons are sensitive to case and diacritics.\n\t\t * This is normal in MongoDB and SQLite, but different than the default\n\t\t * in MySQL.\n\t\t * \n\t\t * @param column the column name\n\t\t * @param value the value\n\t\t */\n\t\tpublic GreaterThan(String column, String value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic GreaterThan(String column, Number value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic String getColumn() {\n\t\t\treturn column;\n\t\t}\n\t\t\n\t\tpublic Object getValue() {\n\t\t\treturn value;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\treturn column.equals(this.column);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = column.hashCode();\n\t\t\tObject normVal = PrimitiveValueComparison.normalizeValue(value);\n\t\t\tresult = 31 * result + (normVal != null ? normVal.hashCode() : 0);\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tGreaterThan other = (GreaterThan)obj;\n\t\t\tif (!column.equals(other.column))\n\t\t\t\treturn false;\n\t\t\tif (!PrimitiveValueComparison.isEqual(value, other.value))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn column + \" > \" + formatValue(value);\n\t\t}\n\t}\n\t\n\tpublic static class LessEqual extends DatabaseCriteria {\n\t\tprivate String column;\n\t\tprivate Object value;\n\n\t\t/**\n\t\t * Note that string comparisons are sensitive to case and diacritics.\n\t\t * This is normal in MongoDB and SQLite, but different than the default\n\t\t * in MySQL.\n\t\t * \n\t\t * @param column the column name\n\t\t * @param value the value\n\t\t */\n\t\tpublic LessEqual(String column, String value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic LessEqual(String column, Number value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic String getColumn() {\n\t\t\treturn column;\n\t\t}\n\t\t\n\t\tpublic Object getValue() {\n\t\t\treturn value;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\treturn column.equals(this.column);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = column.hashCode();\n\t\t\tObject normVal = PrimitiveValueComparison.normalizeValue(value);\n\t\t\tresult = 31 * result + (normVal != null ? normVal.hashCode() : 0);\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tLessEqual other = (LessEqual)obj;\n\t\t\tif (!column.equals(other.column))\n\t\t\t\treturn false;\n\t\t\tif (!PrimitiveValueComparison.isEqual(value, other.value))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn column + \" <= \" + formatValue(value);\n\t\t}\n\t}\n\t\n\tpublic static class GreaterEqual extends DatabaseCriteria {\n\t\tprivate String column;\n\t\tprivate Object value;\n\n\t\t/**\n\t\t * Note that string comparisons are sensitive to case and diacritics.\n\t\t * This is normal in MongoDB and SQLite, but different than the default\n\t\t * in MySQL.\n\t\t * \n\t\t * @param column the column name\n\t\t * @param value the value\n\t\t */\n\t\tpublic GreaterEqual(String column, String value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic GreaterEqual(String column, Number value) {\n\t\t\tthis.column = column;\n\t\t\tthis.value = value;\n\t\t}\n\t\t\n\t\tpublic String getColumn() {\n\t\t\treturn column;\n\t\t}\n\t\t\n\t\tpublic Object getValue() {\n\t\t\treturn value;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\treturn column.equals(this.column);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = column.hashCode();\n\t\t\tObject normVal = PrimitiveValueComparison.normalizeValue(value);\n\t\t\tresult = 31 * result + (normVal != null ? normVal.hashCode() : 0);\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tGreaterEqual other = (GreaterEqual)obj;\n\t\t\tif (!column.equals(other.column))\n\t\t\t\treturn false;\n\t\t\tif (!PrimitiveValueComparison.isEqual(value, other.value))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn column + \" >= \" + formatValue(value);\n\t\t}\n\t}\n\t\n\tpublic static class And extends DatabaseCriteria {\n\t\tprivate DatabaseCriteria[] operands;\n\t\t\n\t\tpublic And(DatabaseCriteria... operands) {\n\t\t\tthis.operands = operands;\n\t\t}\n\t\t\n\t\tpublic DatabaseCriteria[] getOperands() {\n\t\t\treturn operands;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\tfor (DatabaseCriteria operand : operands) {\n\t\t\t\tif (operand.containsColumn(column))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = 0;\n\t\t\tfor (DatabaseCriteria operand : operands) {\n\t\t\t\tresult += operand.hashCode();\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tAnd other = (And)obj;\n\t\t\tSet thisOps = new HashSet<>(\n\t\t\t\t\tArrays.asList(operands));\n\t\t\tSet otherOps = new HashSet<>(\n\t\t\t\t\tArrays.asList(other.operands));\n\t\t\tif (!thisOps.equals(otherOps))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tif (operands.length == 0)\n\t\t\t\treturn \"\";\n\t\t\tif (operands.length == 1)\n\t\t\t\treturn operands[0].toString();\n\t\t\tStringBuilder result = new StringBuilder(\n\t\t\t\t\t\"(\" + operands[0].toString() + \")\");\n\t\t\tfor (int i = 1; i < operands.length; i++) {\n\t\t\t\tresult.append(\" AND (\" + operands[i] + \")\");\n\t\t\t}\n\t\t\treturn result.toString();\n\t\t}\n\t}\n\t\n\tpublic static class Or extends DatabaseCriteria {\n\t\tprivate DatabaseCriteria[] operands;\n\t\t\n\t\tpublic Or(DatabaseCriteria... operands) {\n\t\t\tthis.operands = operands;\n\t\t}\n\t\t\n\t\tpublic DatabaseCriteria[] getOperands() {\n\t\t\treturn operands;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsColumn(String column) {\n\t\t\tfor (DatabaseCriteria operand : operands) {\n\t\t\t\tif (operand.containsColumn(column))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint result = 0;\n\t\t\tfor (DatabaseCriteria operand : operands) {\n\t\t\t\tresult += operand.hashCode();\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj)\n\t\t\t\treturn true;\n\t\t\tif (obj == null)\n\t\t\t\treturn false;\n\t\t\tif (getClass() != obj.getClass())\n\t\t\t\treturn false;\n\t\t\tOr other = (Or)obj;\n\t\t\tSet thisOps = new HashSet(\n\t\t\t\t\tArrays.asList(operands));\n\t\t\tSet otherOps = new HashSet(\n\t\t\t\t\tArrays.asList(other.operands));\n\t\t\tif (!thisOps.equals(otherOps))\n\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tif (operands.length == 0)\n\t\t\t\treturn \"\";\n\t\t\tif (operands.length == 1)\n\t\t\t\treturn operands[0].toString();\n\t\t\tStringBuilder result = new StringBuilder(\n\t\t\t\t\t\"(\" + operands[0].toString() + \")\");\n\t\t\tfor (int i = 1; i < operands.length; i++) {\n\t\t\t\tresult.append(\" OR (\" + operands[i] + \")\");\n\t\t\t}\n\t\t\treturn result.toString();\n\t\t}\n\t}\n}", "answers": ["\t\tthis.table = table;"], "length": 2552, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "483c8864-4fcf-4361-b523-73096e28a8e8", "reasoning": "The constructor of RegexUserAccessController receives a RegexUserAccessTable argument. The next logical step is to store this argument in the instance field 'table' so the controller can use it later. Therefore the next line should assign the parameter to the field.", "reasoning_model_answer": "this.table = table;", "assistant_with_reasoning": "\nThe constructor of RegexUserAccessController receives a RegexUserAccessTable argument. The next logical step is to store this argument in the instance field 'table' so the controller can use it later. Therefore the next line should assign the parameter to the field.\n\nthis.table = table;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.373, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21594, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "this.table = table;", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.beans.PropertyEditorSupport;\nimport java.util.Date;\nimport java.util.List;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.web.bind.WebDataBinder;\nimport org.springframework.web.bind.annotation.InitBinder;\nimport com.github.pagehelper.PageHelper;\nimport com.github.pagehelper.PageInfo;\nimport com.ruoyi.common.utils.DateUtils;\nimport com.ruoyi.common.utils.PageUtils;\nimport com.ruoyi.common.utils.StringUtils;\nimport com.ruoyi.common.utils.security.ShiroUtils;\nimport com.ruoyi.common.utils.sql.SqlUtil;\nimport com.ruoyi.framework.web.domain.AjaxResult;\nimport com.ruoyi.framework.web.domain.AjaxResult.Type;\nimport com.ruoyi.framework.web.page.PageDomain;\nimport com.ruoyi.framework.web.page.TableDataInfo;\nimport com.ruoyi.framework.web.page.TableSupport;\nimport com.ruoyi.project.system.user.domain.User;", "context": "src/main/java/com/ruoyi/framework/web/controller/BaseController.java\npackage com.ruoyi.framework.web.controller;\n\n\n/**\n * web层通用数据处理\n * \n * @author ruoyi\n */\npublic class BaseController\n{\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n \n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @InitBinder\n public void initBinder(WebDataBinder binder)\n {\n // Date 类型转换\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport()\n {\n @Override\n public void setAsText(String text)\n {\n setValue(DateUtils.parseDate(text));\n }\n });\n }\n\n /**\n * 设置请求分页数据\n */\n protected void startPage()\n {\n PageUtils.startPage();\n }\n\n /**\n * 设置请求排序数据\n */\n protected void startOrderBy()\n {\n PageDomain pageDomain = TableSupport.buildPageRequest();\n if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))\n {\n String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());\n PageHelper.orderBy(orderBy);\n }\n }\n\n /**\n * 响应请求分页数据\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n protected TableDataInfo getDataTable(List list)\n {\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(0);\n rspData.setRows(list);\n rspData.setTotal(new PageInfo(list).getTotal());\n return rspData;\n }\n\n /**\n * 响应返回结果\n * \n * @param rows 影响行数\n * @return 操作结果\n */\n protected AjaxResult toAjax(int rows)\n {\n return rows > 0 ? success() : error();\n }\n\n /**\n * 响应返回结果\n * \n * @param result 结果\n * @return 操作结果\n */\n protected AjaxResult toAjax(boolean result)\n {\n return result ? success() : error();\n }\n\n /**\n * 返回成功\n */\n public AjaxResult success()\n {\n return AjaxResult.success();\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error()\n {\n return AjaxResult.error();\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(String message)\n {\n return AjaxResult.success(message);\n }\n\n /**\n * 返回成功数据\n */\n public static AjaxResult success(Object data)\n {\n return AjaxResult.success(\"操作成功\", data);\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error(String message)\n {\n return AjaxResult.error(message);\n }\n\n /**\n * 返回错误码消息\n */\n public AjaxResult error(Type type, String message)\n {\n return new AjaxResult(type, message);\n }\n\n /**\n * 页面跳转\n */\n public String redirect(String url)\n {\n return StringUtils.format(\"redirect:{}\", url);\n }\n\n /**\n * 获取用户缓存信息\n */\n public User getSysUser()\n {\n return ShiroUtils.getSysUser();\n }\n\n /**\n * 设置用户缓存信息\n */\n public void setSysUser(User user)\n {\n ShiroUtils.setSysUser(user);\n }\n\n /**\n * 获取登录用户id\n */\n\nsrc/main/java/com/ruoyi/common/utils/PageUtils.java\npublic class PageUtils extends PageHelper\n{\n /**\n * 设置请求分页数据\n */\n public static void startPage()\n {\n PageDomain pageDomain = TableSupport.buildPageRequest();\n Integer pageNum = pageDomain.getPageNum();\n Integer pageSize = pageDomain.getPageSize();\n if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))\n {\n String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());\n Boolean reasonable = pageDomain.getReasonable();\n PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);\n }\n }\n}\n\nsrc/main/java/com/ruoyi/framework/web/page/TableSupport.java\npublic class TableSupport\n{\n /**\n * 当前记录起始索引\n */\n public static final String PAGE_NUM = \"pageNum\";\n\n /**\n * 每页显示记录数\n */\n public static final String PAGE_SIZE = \"pageSize\";\n\n /**\n * 排序列\n */\n public static final String ORDER_BY_COLUMN = \"orderByColumn\";\n\n /**\n * 排序的方向 \"desc\" 或者 \"asc\".\n */\n public static final String IS_ASC = \"isAsc\";\n\n /**\n * 分页参数合理化\n */\n public static final String REASONABLE = \"reasonable\";\n\n /**\n * 封装分页对象\n */\n public static PageDomain getPageDomain()\n {\n PageDomain pageDomain = new PageDomain();\n pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));\n pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));\n pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));\n pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));\n pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));\n return pageDomain;\n }\n\n public static PageDomain buildPageRequest()\n {\n return getPageDomain();\n }\n}\n\nsrc/main/java/com/ruoyi/framework/web/domain/AjaxResult.java\npublic enum Type\n{\n /** 成功 */\n SUCCESS(0),\n /** 警告 */\n WARN(301),\n /** 错误 */\n ERROR(500);\n private final int value;\n\n Type(int value)\n {\n this.value = value;\n }\n\n public int value()\n {\n return this.value;\n }\n}\n\nsrc/main/java/com/ruoyi/framework/web/page/PageDomain.java\npublic class PageDomain\n{\n /** 当前记录起始索引 */\n private Integer pageNum;\n\n /** 每页显示记录数 */\n private Integer pageSize;\n\n /** 排序列 */\n private String orderByColumn;\n\n /** 排序的方向desc或者asc */\n private String isAsc = \"asc\";\n\n /** 分页参数合理化 */\n private Boolean reasonable = true;\n\n public String getOrderBy()\n {\n if (StringUtils.isEmpty(orderByColumn))\n {\n return \"\";\n }\n return StringUtils.toUnderScoreCase(orderByColumn) + \" \" + isAsc;\n }\n\n public Integer getPageNum()\n {\n return pageNum;\n }\n\n public void setPageNum(Integer pageNum)\n {\n this.pageNum = pageNum;\n }\n\n public Integer getPageSize()\n {\n return pageSize;\n }\n\n public void setPageSize(Integer pageSize)\n {\n this.pageSize = pageSize;\n }\n\n public String getOrderByColumn()\n {\n return orderByColumn;\n }\n\n public void setOrderByColumn(String orderByColumn)\n {\n this.orderByColumn = orderByColumn;\n }\n\n public String getIsAsc()\n {\n return isAsc;\n }\n\n public void setIsAsc(String isAsc)\n {\n this.isAsc = isAsc;\n }\n\n public Boolean getReasonable()\n {\n if (StringUtils.isNull(reasonable))\n {\n return Boolean.TRUE;\n }\n return reasonable;\n }\n\n public void setReasonable(Boolean reasonable)\n {\n this.reasonable = reasonable;\n }\n}\n\nsrc/main/java/com/ruoyi/common/utils/DateUtils.java\npublic class DateUtils extends org.apache.commons.lang3.time.DateUtils\n{\n public static String YYYY = \"yyyy\";\n\n public static String YYYY_MM = \"yyyy-MM\";\n\n public static String YYYY_MM_DD = \"yyyy-MM-dd\";\n\n public static String YYYYMMDDHHMMSS = \"yyyyMMddHHmmss\";\n\n public static String YYYY_MM_DD_HH_MM_SS = \"yyyy-MM-dd HH:mm:ss\";\n\n private static String[] parsePatterns = {\n \"yyyy-MM-dd\", \"yyyy-MM-dd HH:mm:ss\", \"yyyy-MM-dd HH:mm\", \"yyyy-MM\", \n \"yyyy/MM/dd\", \"yyyy/MM/dd HH:mm:ss\", \"yyyy/MM/dd HH:mm\", \"yyyy/MM\",\n \"yyyy.MM.dd\", \"yyyy.MM.dd HH:mm:ss\", \"yyyy.MM.dd HH:mm\", \"yyyy.MM\"};\n\n /**\n * 获取当前Date型日期\n * \n * @return Date() 当前日期\n */\n public static Date getNowDate()\n {\n return new Date();\n }\n\n /**\n * 获取当前日期, 默认格式为yyyy-MM-dd\n * \n * @return String\n */\n public static String getDate()\n {\n return dateTimeNow(YYYY_MM_DD);\n }\n\n public static final String getTime()\n {\n return dateTimeNow(YYYY_MM_DD_HH_MM_SS);\n }\n\n public static final String dateTimeNow()\n {\n return dateTimeNow(YYYYMMDDHHMMSS);\n }\n\n public static final String dateTimeNow(final String format)\n {\n return parseDateToStr(format, new Date());\n }\n\n public static final String dateTime(final Date date)\n {\n return parseDateToStr(YYYY_MM_DD, date);\n }\n\n public static final String parseDateToStr(final String format, final Date date)\n {\n return new SimpleDateFormat(format).format(date);\n }\n\n public static final Date dateTime(final String format, final String ts)\n {\n try\n {\n return new SimpleDateFormat(format).parse(ts);\n }\n catch (ParseException e)\n {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 日期路径 即年/月/日 如2018/08/08\n */\n public static final String datePath()\n {\n Date now = new Date();\n return DateFormatUtils.format(now, \"yyyy/MM/dd\");\n }\n\n /**\n * 日期路径 即年/月/日 如20180808\n */\n public static final String dateTime()\n {\n Date now = new Date();\n return DateFormatUtils.format(now, \"yyyyMMdd\");\n }\n\n /**\n * 日期型字符串转化为日期 格式\n */\n public static Date parseDate(Object str)\n {\n if (str == null)\n {\n return null;\n }\n try\n {\n return parseDate(str.toString(), parsePatterns);\n }\n catch (ParseException e)\n {\n return null;\n }\n }\n\n /**\n * 获取服务器启动时间\n */\n public static Date getServerStartDate()\n {\n long time = ManagementFactory.getRuntimeMXBean().getStartTime();\n return new Date(time);\n }\n\n /**\n * 计算相差天数\n */\n public static int differentDaysByMillisecond(Date date1, Date date2)\n {\n return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));\n }\n\n /**\n * 计算两个时间差\n */\n public static String getDatePoor(Date endDate, Date nowDate)\n {\n long nd = 1000 * 24 * 60 * 60;\n long nh = 1000 * 60 * 60;\n long nm = 1000 * 60;\n // long ns = 1000;\n // 获得两个时间的毫秒时间差异\n long diff = endDate.getTime() - nowDate.getTime();\n // 计算差多少天\n long day = diff / nd;\n // 计算差多少小时\n long hour = diff % nd / nh;\n // 计算差多少分钟\n long min = diff % nd % nh / nm;\n // 计算差多少秒//输出结果\n // long sec = diff % nd % nh % nm / ns;\n return day + \"天\" + hour + \"小时\" + min + \"分钟\";\n }\n\n /**\n * 增加 LocalDateTime ==> Date\n */\n public static Date toDate(LocalDateTime temporalAccessor)\n {\n ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());\n return Date.from(zdt.toInstant());\n }\n\n /**\n * 增加 LocalDate ==> Date\n */\n public static Date toDate(LocalDate temporalAccessor)\n {\n LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));\n ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());\n return Date.from(zdt.toInstant());\n }\n}\n\nsrc/main/java/com/ruoyi/project/system/user/domain/User.java\npublic class User extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, prompt = \"用户编号\")\n private Long userId;\n\n /** 部门ID */\n @Excel(name = \"部门编号\", type = Type.IMPORT)\n private Long deptId;\n\n /** 部门父ID */\n private Long parentId;\n\n /** 角色ID */\n private Long roleId;\n\n /** 登录名称 */\n @Excel(name = \"登录名称\")\n private String loginName;\n\n /** 用户名称 */\n @Excel(name = \"用户名称\")\n private String userName;\n\n /** 用户类型 */\n private String userType;\n\n /** 用户邮箱 */\n @Excel(name = \"用户邮箱\")\n private String email;\n\n /** 手机号码 */\n @Excel(name = \"手机号码\")\n private String phonenumber;\n\n /** 用户性别 */\n @Excel(name = \"用户性别\", readConverterExp = \"0=男,1=女,2=未知\")\n private String sex;\n\n /** 用户头像 */\n private String avatar;\n\n /** 密码 */\n private String password;\n\n /** 盐加密 */\n private String salt;\n\n /** 帐号状态(0正常 1停用) */\n @Excel(name = \"帐号状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 最后登录IP */\n @Excel(name = \"最后登录IP\", type = Type.EXPORT)\n private String loginIp;\n\n /** 最后登录时间 */\n @Excel(name = \"最后登录时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\", type = Type.EXPORT)\n private Date loginDate;\n\n /** 密码最后更新时间 */\n private Date pwdUpdateDate;\n\n /** 部门对象 */\n @Excels({\n @Excel(name = \"部门名称\", targetAttr = \"deptName\", type = Type.EXPORT),\n @Excel(name = \"部门负责人\", targetAttr = \"leader\", type = Type.EXPORT)\n })\n private Dept dept;\n\n private List roles;\n\n /** 角色组 */\n private Long[] roleIds;\n\n /** 岗位组 */\n private Long[] postIds;\n\n public User()\n {\n\n }\n\n public User(Long userId)\n {\n this.userId = userId;\n }\n\n public Long getUserId()\n {\n return userId;\n }\n\n public void setUserId(Long userId)\n {\n this.userId = userId;\n }\n\n public boolean isAdmin()\n {\n return isAdmin(this.userId);\n }\n\n public static boolean isAdmin(Long userId)\n {\n return userId != null && 1L == userId;\n }\n\n public Long getDeptId()\n {\n return deptId;\n }\n\n public void setDeptId(Long deptId)\n {\n this.deptId = deptId;\n }\n\n public Long getParentId()\n {\n return parentId;\n }\n\n public void setParentId(Long parentId)\n {\n this.parentId = parentId;\n }\n\n public Long getRoleId()\n {\n return roleId;\n }\n\n public void setRoleId(Long roleId)\n {\n this.roleId = roleId;\n }\n\n @Xss(message = \"登录账号不能包含脚本字符\")\n @NotBlank(message = \"登录账号不能为空\")\n @Size(min = 0, max = 30, message = \"登录账号长度不能超过30个字符\")\n public String getLoginName()\n {\n return loginName;\n }\n\n public void setLoginName(String loginName)\n {\n this.loginName = loginName;\n }\n\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @Size(min = 0, max = 30, message = \"用户昵称长度不能超过30个字符\")\n public String getUserName()\n {\n return userName;\n }\n\n public void setUserName(String userName)\n {\n this.userName = userName;\n }\n\n public String getUserType()\n {\n return userType;\n }\n\n public void setUserType(String userType)\n {\n this.userType = userType;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail()\n {\n return email;\n }\n\n public void setEmail(String email)\n {\n this.email = email;\n }\n\n @Size(min = 0, max = 11, message = \"手机号码长度不能超过11个字符\")\n public String getPhonenumber()\n {\n return phonenumber;\n }\n\n public void setPhonenumber(String phonenumber)\n {\n this.phonenumber = phonenumber;\n }\n\n public String getSex()\n {\n return sex;\n }\n\n public void setSex(String sex)\n {\n this.sex = sex;\n }\n\n public String getAvatar()\n {\n return avatar;\n }\n\n public void setAvatar(String avatar)\n {\n this.avatar = avatar;\n }\n\n @JsonIgnore\n public String getPassword()\n {\n return password;\n }\n\n public void setPassword(String password)\n {\n this.password = password;\n }\n\n public String getSalt()\n {\n return salt;\n }\n\n public void setSalt(String salt)\n {\n this.salt = salt;\n }\n\n /**\n * 生成随机盐\n */\n public void randomSalt()\n {\n // 一个Byte占两个字节,此处生成的3字节,字符串长度为6\n SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();\n String hex = secureRandom.nextBytes(3).toHex();\n setSalt(hex);\n }\n\n public String getStatus()\n {\n return status;\n }\n\n public void setStatus(String status)\n {\n this.status = status;\n }\n\n public String getDelFlag()\n {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag)\n {\n this.delFlag = delFlag;\n }\n\n public String getLoginIp()\n {\n return loginIp;\n }\n\n public void setLoginIp(String loginIp)\n {\n this.loginIp = loginIp;\n }\n\n public Date getLoginDate()\n {\n return loginDate;\n }\n\n public void setLoginDate(Date loginDate)\n {\n this.loginDate = loginDate;\n }\n\n public Date getPwdUpdateDate()\n {\n return pwdUpdateDate;\n }\n\n public void setPwdUpdateDate(Date pwdUpdateDate)\n {\n this.pwdUpdateDate = pwdUpdateDate;\n }\n\n public Dept getDept()\n {\n if (dept == null)\n {\n dept = new Dept();\n }\n return dept;\n }\n\n public void setDept(Dept dept)\n {\n this.dept = dept;\n }\n\n public List getRoles()\n {\n return roles;\n }\n\n public void setRoles(List roles)\n {\n this.roles = roles;\n }\n\n public Long[] getRoleIds()\n {\n return roleIds;\n }\n\n public void setRoleIds(Long[] roleIds)\n {\n this.roleIds = roleIds;\n }\n\n public Long[] getPostIds()\n {\n return postIds;\n }\n\n public void setPostIds(Long[] postIds)\n {\n this.postIds = postIds;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"userId\", getUserId())\n .append(\"deptId\", getDeptId())\n .append(\"loginName\", getLoginName())\n .append(\"userName\", getUserName())\n .append(\"userType\", getUserType())\n .append(\"email\", getEmail())\n .append(\"phonenumber\", getPhonenumber())\n .append(\"sex\", getSex())\n .append(\"avatar\", getAvatar())\n .append(\"password\", getPassword())\n .append(\"salt\", getSalt())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"loginIp\", getLoginIp())\n .append(\"loginDate\", getLoginDate())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .append(\"dept\", getDept())\n .append(\"roles\", getRoles())\n .toString();\n }\n}\n\nsrc/main/java/com/ruoyi/framework/web/domain/AjaxResult.java\npublic class AjaxResult extends HashMap\n{\n private static final long serialVersionUID = 1L;\n\n /** 状态码 */\n public static final String CODE_TAG = \"code\";\n\n /** 返回内容 */\n public static final String MSG_TAG = \"msg\";\n\n /** 数据对象 */\n public static final String DATA_TAG = \"data\";\n\n /**\n * 状态类型\n */\n public enum Type\n {\n /** 成功 */\n SUCCESS(0),\n /** 警告 */\n WARN(301),\n /** 错误 */\n ERROR(500);\n private final int value;\n\n Type(int value)\n {\n this.value = value;\n }\n\n public int value()\n {\n return this.value;\n }\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。\n */\n public AjaxResult()\n {\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n *\n * @param type 状态类型\n * @param msg 返回内容\n */\n public AjaxResult(Type type, String msg)\n {\n super.put(CODE_TAG, type.value);\n super.put(MSG_TAG, msg);\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n *\n * @param type 状态类型\n * @param msg 返回内容\n * @param data 数据对象\n */\n public AjaxResult(Type type, String msg, Object data)\n {\n super.put(CODE_TAG, type.value);\n super.put(MSG_TAG, msg);\n if (StringUtils.isNotNull(data))\n {\n super.put(DATA_TAG, data);\n }\n }\n\n /**\n * 方便链式调用\n *\n * @param key 键\n * @param value 值\n * @return 数据对象\n */\n @Override\n public AjaxResult put(String key, Object value)\n {\n super.put(key, value);\n return this;\n }\n\n /**\n * 返回成功消息\n *\n * @return 成功消息\n */\n public static AjaxResult success()\n {\n return AjaxResult.success(\"操作成功\");\n }\n\n /**\n * 返回成功数据\n *\n * @return 成功消息\n */\n public static AjaxResult success(Object data)\n {\n return AjaxResult.success(\"操作成功\", data);\n }\n\n /**\n * 返回成功消息\n *\n * @param msg 返回内容\n * @return 成功消息\n */\n public static AjaxResult success(String msg)\n {\n return AjaxResult.success(msg, null);\n }\n\n /**\n * 返回成功消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 成功消息\n */\n public static AjaxResult success(String msg, Object data)\n {\n return new AjaxResult(Type.SUCCESS, msg, data);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static AjaxResult warn(String msg)\n {\n return AjaxResult.warn(msg, null);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static AjaxResult warn(String msg, Object data)\n {\n return new AjaxResult(Type.WARN, msg, data);\n }\n\n /**\n * 返回错误消息\n *\n * @return\n */\n public static AjaxResult error()\n {\n return AjaxResult.error(\"操作失败\");\n }\n\n /**\n * 返回错误消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static AjaxResult error(String msg)\n {\n return AjaxResult.error(msg, null);\n }\n\n /**\n * 返回错误消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static AjaxResult error(String msg, Object data)\n {\n return new AjaxResult(Type.ERROR, msg, data);\n }\n}", "answers": [" public Long getUserId()"], "length": 2224, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "6a6f8a16-0753-4223-9664-fcf71a37fc25", "reasoning": "The BaseController class ends with a comment \"获取登录用户id\" (Get logged-in user ID). In the original ruoyi framework, the next code defines a method to return the current user's ID. The first line of that method is the signature `public Long getUserId()`. Therefore the next line of code after the comment is the method signature.", "reasoning_model_answer": "public Long getUserId()", "assistant_with_reasoning": "\nThe BaseController class ends with a comment \"获取登录用户id\" (Get logged-in user ID). In the original ruoyi framework, the next code defines a method to return the current user's ID. The first line of that method is the signature `public Long getUserId()`. Therefore the next line of code after the comment is the method signature.\n\npublic Long getUserId()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.884, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22562, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public Long getUserId()", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import android.content.ActivityNotFoundException;\nimport android.content.Intent;\nimport android.content.pm.ActivityInfo;\nimport android.net.Uri;\nimport android.view.View;\nimport com.buaa.food.R;\nimport com.buaa.food.aop.SingleClick;\nimport com.buaa.food.app.TitleBarFragment;\nimport com.buaa.food.ui.activity.AboutActivity;\nimport com.buaa.food.ui.activity.BrowserActivity;\nimport com.buaa.food.ui.activity.DialogActivity;\nimport com.buaa.food.ui.activity.GuideActivity;\nimport com.buaa.food.ui.activity.HomeActivity;\nimport com.buaa.food.ui.activity.ImagePreviewActivity;\nimport com.buaa.food.ui.activity.ImageSelectActivity;\nimport com.buaa.food.ui.activity.LoginActivity;\nimport com.buaa.food.ui.activity.PasswordForgetActivity;\nimport com.buaa.food.ui.activity.PasswordResetActivity;\nimport com.buaa.food.ui.activity.PersonalDataActivity;\nimport com.buaa.food.ui.activity.PhoneResetActivity;\nimport com.buaa.food.ui.activity.RegisterActivity;\nimport com.buaa.food.ui.activity.SettingActivity;\nimport com.buaa.food.ui.activity.StatusActivity;\nimport com.buaa.food.ui.activity.VideoPlayActivity;\nimport com.buaa.food.ui.activity.VideoSelectActivity;\nimport com.buaa.food.ui.dialog.InputDialog;\nimport com.buaa.food.ui.dialog.MessageDialog;\nimport com.tencent.bugly.crashreport.CrashReport;\nimport java.util.ArrayList;\nimport java.util.List;", "context": "app/src/main/java/com/buaa/food/ui/fragment/MineFragment.java\npackage com.buaa.food.ui.fragment;\n\n\n\n\n\npublic final class MineFragment extends TitleBarFragment {\n\n public static MineFragment newInstance() {\n return new MineFragment();\n }\n\n @Override\n protected int getLayoutId() {\n return R.layout.mine_fragment;\n }\n\n @Override\n protected void initView() {\n setOnClickListener(R.id.btn_mine_dialog, R.id.btn_mine_hint, R.id.btn_mine_login, R.id.btn_mine_register, R.id.btn_mine_forget,\n R.id.btn_mine_reset, R.id.btn_mine_change, R.id.btn_mine_personal, R.id.btn_mine_setting, R.id.btn_mine_about,\n R.id.btn_mine_guide, R.id.btn_mine_browser, R.id.btn_mine_image_select, R.id.btn_mine_image_preview,\n R.id.btn_mine_video_select, R.id.btn_mine_video_play, R.id.btn_mine_crash, R.id.btn_mine_pay);\n }\n\n @Override\n protected void initData() {\n\n }\n\n @SingleClick\n @Override\n public void onClick(View view) {\n int viewId = view.getId();\n if (viewId == R.id.btn_mine_dialog) {\n\n startActivity(DialogActivity.class);\n\n } else if (viewId == R.id.btn_mine_hint) {\n\n startActivity(StatusActivity.class);\n\n } else if (viewId == R.id.btn_mine_login) {\n\n startActivity(LoginActivity.class);\n\n } else if (viewId == R.id.btn_mine_register) {\n\n startActivity(RegisterActivity.class);\n\n } else if (viewId == R.id.btn_mine_forget) {\n\n startActivity(PasswordForgetActivity.class);\n\n } else if (viewId == R.id.btn_mine_reset) {\n\n startActivity(PasswordResetActivity.class);\n\n } else if (viewId == R.id.btn_mine_change) {\n\n\napp/src/main/java/com/buaa/food/ui/dialog/InputDialog.java\npublic final class InputDialog {\n\n public static final class Builder\n extends CommonDialog.Builder\n implements BaseDialog.OnShowListener,\n TextView.OnEditorActionListener {\n\n @Nullable\n private OnListener mListener;\n private final RegexEditText mInputView;\n\n public Builder(Context context) {\n super(context);\n setCustomView(R.layout.input_dialog);\n\n mInputView = findViewById(R.id.tv_input_message);\n mInputView.setOnEditorActionListener(this);\n\n addOnShowListener(this);\n }\n\n public Builder setHint(@StringRes int id) {\n return setHint(getString(id));\n }\n public Builder setHint(CharSequence text) {\n mInputView.setHint(text);\n return this;\n }\n\n public Builder setContent(@StringRes int id) {\n return setContent(getString(id));\n }\n public Builder setContent(CharSequence text) {\n mInputView.setText(text);\n Editable editable = mInputView.getText();\n if (editable == null) {\n return this;\n }\n int index = editable.length();\n if (index <= 0) {\n return this;\n }\n mInputView.requestFocus();\n mInputView.setSelection(index);\n return this;\n }\n\n public Builder setInputRegex(String regex) {\n mInputView.setInputRegex(regex);\n return this;\n }\n\n public Builder setListener(OnListener listener) {\n mListener = listener;\n return this;\n }\n\n /**\n * {@link BaseDialog.OnShowListener}\n */\n @Override\n public void onShow(BaseDialog dialog) {\n postDelayed(() -> showKeyboard(mInputView), 500);\n }\n\n @SingleClick\n @Override\n public void onClick(View view) {\n int viewId = view.getId();\n if (viewId == R.id.tv_ui_confirm) {\n autoDismiss();\n if (mListener == null) {\n return;\n }\n Editable editable = mInputView.getText();\n mListener.onConfirm(getDialog(), editable != null ? editable.toString() : \"\");\n } else if (viewId == R.id.tv_ui_cancel) {\n autoDismiss();\n if (mListener == null) {\n return;\n }\n mListener.onCancel(getDialog());\n }\n }\n\n /**\n * {@link TextView.OnEditorActionListener}\n */\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n // 模拟点击确认按钮\n onClick(findViewById(R.id.tv_ui_confirm));\n return true;\n }\n return false;\n }\n }\n\n public interface OnListener {\n\n /**\n * 点击确定时回调\n */\n void onConfirm(BaseDialog dialog, String content);\n\n /**\n * 点击取消时回调\n */\n default void onCancel(BaseDialog dialog) {}\n }\n}\n\napp/src/main/java/com/buaa/food/ui/activity/BrowserActivity.java\npublic final class BrowserActivity extends AppActivity\n implements StatusAction, OnRefreshListener {\n\n private static final String INTENT_KEY_IN_URL = \"url\";\n\n @CheckNet\n @Log\n public static void start(Context context, String url) {\n if (TextUtils.isEmpty(url)) {\n return;\n }\n Intent intent = new Intent(context, BrowserActivity.class);\n intent.putExtra(INTENT_KEY_IN_URL, url);\n if (!(context instanceof Activity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n context.startActivity(intent);\n }\n\n private StatusLayout mStatusLayout;\n private ProgressBar mProgressBar;\n private SmartRefreshLayout mRefreshLayout;\n private BrowserView mBrowserView;\n\n @Override\n protected int getLayoutId() {\n return R.layout.browser_activity;\n }\n\n @Override\n protected void initView() {\n mStatusLayout = findViewById(R.id.hl_browser_hint);\n mProgressBar = findViewById(R.id.pb_browser_progress);\n mRefreshLayout = findViewById(R.id.sl_browser_refresh);\n mBrowserView = findViewById(R.id.wv_browser_view);\n\n // 设置 WebView 生命管控\n mBrowserView.setLifecycleOwner(this);\n // 设置网页刷新监听\n mRefreshLayout.setOnRefreshListener(this);\n }\n\n @Override\n protected void initData() {\n showLoading();\n\n mBrowserView.setBrowserViewClient(new AppBrowserViewClient());\n mBrowserView.setBrowserChromeClient(new AppBrowserChromeClient(mBrowserView));\n mBrowserView.loadUrl(getString(INTENT_KEY_IN_URL));\n }\n\n @Override\n public StatusLayout getStatusLayout() {\n return mStatusLayout;\n }\n\n @Override\n public void onLeftClick(View view) {\n finish();\n }\n\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n if (keyCode == KeyEvent.KEYCODE_BACK && mBrowserView.canGoBack()) {\n // 后退网页并且拦截该事件\n mBrowserView.goBack();\n return true;\n }\n return super.onKeyDown(keyCode, event);\n }\n\n /**\n * 重新加载当前页\n */\n @CheckNet\n private void reload() {\n mBrowserView.reload();\n }\n\n /**\n * {@link OnRefreshListener}\n */\n\n @Override\n public void onRefresh(@NonNull RefreshLayout refreshLayout) {\n reload();\n }\n\n private class AppBrowserViewClient extends BrowserView.BrowserViewClient {\n\n /**\n * 网页加载错误时回调,这个方法会在 onPageFinished 之前调用\n */\n @Override\n public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {\n // 这里为什么要用延迟呢?因为加载出错之后会先调用 onReceivedError 再调用 onPageFinished\n post(() -> showError(listener -> reload()));\n }\n\n /**\n * 开始加载网页\n */\n @Override\n public void onPageStarted(WebView view, String url, Bitmap favicon) {\n mProgressBar.setVisibility(View.VISIBLE);\n }\n\n /**\n * 完成加载网页\n */\n @Override\n public void onPageFinished(WebView view, String url) {\n mProgressBar.setVisibility(View.GONE);\n mRefreshLayout.finishRefresh();\n showComplete();\n }\n }\n\n private class AppBrowserChromeClient extends BrowserView.BrowserChromeClient {\n\n private AppBrowserChromeClient(BrowserView view) {\n super(view);\n }\n\n /**\n * 收到网页标题\n */\n @Override\n public void onReceivedTitle(WebView view, String title) {\n if (title == null) {\n return;\n }\n setTitle(title);\n }\n\n @Override\n public void onReceivedIcon(WebView view, Bitmap icon) {\n if (icon == null) {\n return;\n }\n setRightIcon(new BitmapDrawable(getResources(), icon));\n }\n\n /**\n * 收到加载进度变化\n */\n @Override\n public void onProgressChanged(WebView view, int newProgress) {\n mProgressBar.setProgress(newProgress);\n }\n }\n}\n\napp/src/main/java/com/buaa/food/ui/dialog/MessageDialog.java\npublic final class MessageDialog {\n\n public static final class Builder\n extends CommonDialog.Builder {\n\n @Nullable\n private OnListener mListener;\n\n private final TextView mMessageView;\n\n public Builder(Context context) {\n super(context);\n setCustomView(R.layout.message_dialog);\n mMessageView = findViewById(R.id.tv_message_message);\n }\n\n public Builder setMessage(@StringRes int id) {\n return setMessage(getString(id));\n }\n public Builder setMessage(CharSequence text) {\n mMessageView.setText(text);\n return this;\n }\n\n public Builder setListener(OnListener listener) {\n mListener = listener;\n return this;\n }\n\n @Override\n public BaseDialog create() {\n // 如果内容为空就抛出异常\n if (\"\".equals(mMessageView.getText().toString())) {\n throw new IllegalArgumentException(\"Dialog message not null\");\n }\n return super.create();\n }\n\n @SingleClick\n @Override\n public void onClick(View view) {\n int viewId = view.getId();\n if (viewId == R.id.tv_ui_confirm) {\n autoDismiss();\n if (mListener == null) {\n return;\n }\n mListener.onConfirm(getDialog());\n } else if (viewId == R.id.tv_ui_cancel) {\n autoDismiss();\n if (mListener == null) {\n return;\n }\n mListener.onCancel(getDialog());\n }\n }\n }\n\n public interface OnListener {\n\n /**\n * 点击确定时回调\n */\n void onConfirm(BaseDialog dialog);\n\n /**\n * 点击取消时回调\n */\n default void onCancel(BaseDialog dialog) {}\n }\n}\n\napp/src/main/java/com/buaa/food/app/TitleBarFragment.java\npublic abstract class TitleBarFragment extends AppFragment\n implements TitleBarAction {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 */\n private ImmersionBar mImmersionBar;\n\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n // 设置标题栏点击监听\n if (getTitleBar() != null) {\n getTitleBar().setOnTitleBarListener(this);\n }\n\n if (isStatusBarEnabled()) {\n // 初始化沉浸式状态栏\n getStatusBarConfig().init();\n\n if (getTitleBar() != null) {\n // 设置标题栏沉浸\n ImmersionBar.setTitleBar(this, getTitleBar());\n }\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n if (isStatusBarEnabled()) {\n // 重新初始化状态栏\n getStatusBarConfig().init();\n }\n }\n\n /**\n * 是否在 Fragment 使用沉浸式\n */\n public boolean isStatusBarEnabled() {\n return false;\n }\n\n /**\n * 获取状态栏沉浸的配置对象\n */\n @NonNull\n protected ImmersionBar getStatusBarConfig() {\n if (mImmersionBar == null) {\n mImmersionBar = createStatusBarConfig();\n }\n return mImmersionBar;\n }\n\n /**\n * 初始化沉浸式\n */\n @NonNull\n protected ImmersionBar createStatusBarConfig() {\n return ImmersionBar.with(this)\n // 默认状态栏字体颜色为黑色\n .statusBarDarkFont(isStatusBarDarkFont())\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white)\n // 状态栏字体和导航栏内容自动变色,必须指定状态栏颜色和导航栏颜色才可以自动变色\n .autoDarkModeEnable(true, 0.2f);\n }\n\n /**\n * 获取状态栏字体颜色\n */\n protected boolean isStatusBarDarkFont() {\n // 返回真表示黑色字体\n return getAttachActivity().isStatusBarDarkFont();\n }\n\n @Override\n @Nullable\n public TitleBar getTitleBar() {\n if (mTitleBar == null || !isLoading()) {\n mTitleBar = obtainTitleBar((ViewGroup) getView());\n }\n return mTitleBar;\n }\n}\n\napp/src/main/java/com/buaa/food/ui/activity/VideoPlayActivity.java\npublic class VideoPlayActivity extends AppActivity\n implements PlayerView.OnPlayListener {\n\n public static final String INTENT_KEY_PARAMETERS = \"parameters\";\n\n private PlayerView mPlayerView;\n private VideoPlayActivity.Builder mBuilder;\n\n @Override\n protected int getLayoutId() {\n return R.layout.video_play_activity;\n }\n\n @Override\n protected void initView() {\n mPlayerView = findViewById(R.id.pv_video_play_view);\n mPlayerView.setLifecycleOwner(this);\n mPlayerView.setOnPlayListener(this);\n }\n\n @Override\n protected void initData() {\n mBuilder = getParcelable(INTENT_KEY_PARAMETERS);\n if (mBuilder == null) {\n throw new IllegalArgumentException(\"are you ok?\");\n }\n\n mPlayerView.setVideoTitle(mBuilder.getVideoTitle());\n mPlayerView.setVideoSource(mBuilder.getVideoSource());\n mPlayerView.setGestureEnabled(mBuilder.isGestureEnabled());\n\n if (mBuilder.isAutoPlay()) {\n mPlayerView.start();\n }\n }\n\n /**\n * {@link PlayerView.OnPlayListener}\n */\n @Override\n public void onClickBack(PlayerView view) {\n onBackPressed();\n }\n\n @Override\n public void onPlayStart(PlayerView view) {\n int progress = mBuilder.getPlayProgress();\n if (progress > 0) {\n mPlayerView.setProgress(progress);\n }\n }\n\n @Override\n public void onPlayProgress(PlayerView view) {\n // 记录播放进度\n mBuilder.setPlayProgress(view.getProgress());\n }\n\n @Override\n public void onPlayEnd(PlayerView view) {\n if (mBuilder.isLoopPlay()) {\n mPlayerView.setProgress(0);\n mPlayerView.start();\n return;\n }\n\n if (mBuilder.isAutoOver()) {\n finish();\n }\n }\n\n @NonNull\n @Override\n protected ImmersionBar createStatusBarConfig() {\n return super.createStatusBarConfig()\n // 隐藏状态栏和导航栏\n .hideBar(BarHide.FLAG_HIDE_BAR);\n }\n\n @Override\n protected void onSaveInstanceState(@NonNull Bundle outState) {\n super.onSaveInstanceState(outState);\n // 保存播放进度\n outState.putParcelable(INTENT_KEY_PARAMETERS, mBuilder);\n }\n\n @Override\n protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n // 读取播放进度\n mBuilder = savedInstanceState.getParcelable(INTENT_KEY_PARAMETERS);\n }\n\n /** 竖屏播放 */\n public static final class Portrait extends VideoPlayActivity {}\n\n /** 横屏播放 */\n public static final class Landscape extends VideoPlayActivity {}\n\n /**\n * 播放参数构建\n */\n public static final class Builder implements Parcelable {\n\n /** 视频源 */\n private String videoSource;\n /** 视频标题 */\n private String videoTitle;\n\n /** 播放进度 */\n private int playProgress;\n /** 手势开关 */\n private boolean gestureEnabled = true;\n /** 循环播放 */\n private boolean loopPlay = false;\n /** 自动播放 */\n private boolean autoPlay = true;\n /** 播放完关闭 */\n private boolean autoOver = true;\n\n /** 播放方向 */\n private int activityOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;\n\n public Builder() {}\n\n protected Builder(Parcel in) {\n videoSource = in.readString();\n videoTitle = in.readString();\n activityOrientation = in.readInt();\n\n playProgress = in.readInt();\n gestureEnabled = in.readByte() != 0;\n loopPlay = in.readByte() != 0;\n autoPlay = in.readByte() != 0;\n autoOver = in.readByte() != 0;\n }\n\n public Builder setVideoSource(File file) {\n videoSource = file.getPath();\n if (videoTitle == null) {\n videoTitle = file.getName();\n }\n return this;\n }\n\n public Builder setVideoSource(String url) {\n videoSource = url;\n return this;\n }\n\n private String getVideoSource() {\n return videoSource;\n }\n\n public Builder setVideoTitle(String title) {\n videoTitle = title;\n return this;\n }\n\n private String getVideoTitle() {\n return videoTitle;\n }\n\n public Builder setPlayProgress(int progress) {\n playProgress = progress;\n return this;\n }\n\n private int getPlayProgress() {\n return playProgress;\n }\n\n public Builder setGestureEnabled(boolean enabled) {\n gestureEnabled = enabled;\n return this;\n }\n\n private boolean isGestureEnabled() {\n return gestureEnabled;\n }\n\n public Builder setLoopPlay(boolean enabled) {\n loopPlay = enabled;\n return this;\n }\n\n private boolean isLoopPlay() {\n return loopPlay;\n }\n\n public Builder setAutoPlay(boolean enabled) {\n autoPlay = enabled;\n return this;\n }\n\n public boolean isAutoPlay() {\n return autoPlay;\n }\n\n public Builder setAutoOver(boolean enabled) {\n autoOver = enabled;\n return this;\n }\n\n private boolean isAutoOver() {\n return autoOver;\n }\n\n public Builder setActivityOrientation(int orientation) {\n activityOrientation = orientation;\n return this;\n }\n\n public void start(Context context) {\n Intent intent = new Intent();\n switch (activityOrientation) {\n case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:\n intent.setClass(context, VideoPlayActivity.Landscape.class);\n break;\n case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:\n intent.setClass(context, VideoPlayActivity.Portrait.class);\n break;\n default:\n intent.setClass(context, VideoPlayActivity.class);\n break;\n }\n\n intent.putExtra(INTENT_KEY_PARAMETERS, this);\n if (!(context instanceof Activity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n context.startActivity(intent);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(videoSource);\n dest.writeString(videoTitle);\n dest.writeInt(activityOrientation);\n dest.writeInt(playProgress);\n dest.writeByte(gestureEnabled ? (byte) 1 : (byte) 0);\n dest.writeByte(loopPlay ? (byte) 1 : (byte) 0);\n dest.writeByte(autoPlay ? (byte) 1 : (byte) 0);\n dest.writeByte(autoOver ? (byte) 1 : (byte) 0);\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n @Override\n public Builder createFromParcel(Parcel source) {\n return new Builder(source);\n }\n\n @Override\n public Builder[] newArray(int size) {\n return new Builder[size];\n }\n };\n }\n}\n\napp/src/main/java/com/buaa/food/ui/activity/LoginActivity.java\npublic final class LoginActivity extends AppActivity\n implements UmengLogin.OnLoginListener,\n KeyboardWatcher.SoftKeyboardStateListener,\n TextView.OnEditorActionListener {\n\n private static final String INTENT_KEY_IN_PHONE = \"phone\";\n private static final String INTENT_KEY_IN_PASSWORD = \"password\";\n // private SharedPreferences preferences;\n\n @Log\n public static void start(Context context, String phone, String password) {\n Intent intent = new Intent(context, LoginActivity.class);\n intent.putExtra(INTENT_KEY_IN_PHONE, phone);\n intent.putExtra(INTENT_KEY_IN_PASSWORD, password);\n if (!(context instanceof Activity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n System.out.println(\"Start Login !!!!\");\n context.startActivity(intent);\n }\n\n private ImageView mLogoView;\n\n private ViewGroup mBodyLayout;\n private EditText mPhoneView;\n private EditText mPasswordView;\n\n private View mForgetView;\n private SubmitButton mCommitView;\n\n private View mOtherView;\n private View mQQView;\n private View mWeChatView;\n private DataBaseHelper dataBaseHelper;\n\n /** logo 缩放比例 */\n private final float mLogoScale = 0.8f;\n /** 动画时间 */\n private final int mAnimTime = 300;\n\n @Override\n protected int getLayoutId() {\n return R.layout.login_activity;\n }\n\n @Override\n protected void initView() {\n mLogoView = findViewById(R.id.iv_login_logo);\n mBodyLayout = findViewById(R.id.ll_login_body);\n mPhoneView = findViewById(R.id.et_login_phone);\n mPasswordView = findViewById(R.id.et_login_password);\n mForgetView = findViewById(R.id.tv_login_forget);\n mCommitView = findViewById(R.id.btn_login_commit);\n mOtherView = findViewById(R.id.ll_login_other);\n mQQView = findViewById(R.id.iv_login_qq);\n mWeChatView = findViewById(R.id.iv_login_wechat);\n dataBaseHelper = new DataBaseHelper(this);\n System.out.println(\"Enter Login InitView!!!!\");\n\n setOnClickListener(mForgetView, mCommitView, mQQView, mWeChatView);\n\n mPasswordView.setOnEditorActionListener(this);\n\n InputTextManager.with(this)\n .addView(mPhoneView)\n .addView(mPasswordView)\n .setMain(mCommitView)\n .build();\n }\n\n @Override\n protected void initData() {\n System.out.println(\"Start Login InitData!!!!\");\n postDelayed(() -> {\n KeyboardWatcher.with(LoginActivity.this)\n .setListener(LoginActivity.this);\n }, 500);\n\n // 判断用户当前有没有安装 QQ\n if (!UmengClient.isAppInstalled(this, Platform.QQ)) {\n mQQView.setVisibility(View.GONE);\n }\n\n // 判断用户当前有没有安装微信\n if (!UmengClient.isAppInstalled(this, Platform.WECHAT)) {\n mWeChatView.setVisibility(View.GONE);\n }\n\n // 如果这两个都没有安装就隐藏提示\n if (mQQView.getVisibility() == View.GONE && mWeChatView.getVisibility() == View.GONE) {\n mOtherView.setVisibility(View.GONE);\n }\n\n // 自动填充手机号和密码\n mPhoneView.setText(getString(INTENT_KEY_IN_PHONE));\n mPasswordView.setText(getString(INTENT_KEY_IN_PASSWORD));\n }\n\n @Override\n public void onRightClick(View view) {\n System.out.println(\"Start Login OnRightClick!!!!\");\n // 跳转到注册界面\n RegisterActivity.start(this, mPhoneView.getText().toString(),\n mPasswordView.getText().toString(), (phone, password) -> {\n // 如果已经注册成功,就执行登录操作\n mPhoneView.setText(phone);\n mPasswordView.setText(password);\n mPasswordView.requestFocus();\n mPasswordView.setSelection(mPasswordView.getText().length());\n onClick(mCommitView);\n });\n }\n\n @SingleClick \n @Override\n public void onClick(View view) {\n System.out.println(\"Start Login OnClick!!!!\");\n if (view == mForgetView) {\n startActivity(PasswordForgetActivity.class);\n return;\n }\n\n if (view == mCommitView) {\n String phone = mPhoneView.getText().toString();\n String password = mPasswordView.getText().toString();\n\n hideKeyboard(getCurrentFocus()); // 隐藏软键盘\n\n if (phone.length() != 11) {\n mPhoneView.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.shake_anim));\n mCommitView.showError(3000);\n toast(R.string.common_phone_input_error);\n return;\n }\n\n if (dataBaseHelper.checkPhone(phone)) {\n if (dataBaseHelper.checkPhonePassword(phone, password)) {\n Toast.makeText(LoginActivity.this, \"Login Successfully\", Toast.LENGTH_SHORT).show();\n UserAuth.setLocalUserPhone(phone);\n mCommitView.showSucceed();\n HomeActivity.start(getContext(), MineFragment.class);\n } else {\n Toast.makeText(LoginActivity.this, \"Login Failed\", Toast.LENGTH_SHORT).show();\n mCommitView.showError(3000);\n }\n } else {\n Toast.makeText(LoginActivity.this, \"No User Found\", Toast.LENGTH_SHORT).show();\n mCommitView.showError(3000);\n }\n }\n\n if (view == mQQView || view == mWeChatView) {\n toast(\"记得改好第三方 AppID 和 Secret,否则会调不起来哦\");\n Platform platform;\n if (view == mQQView) {\n platform = Platform.QQ;\n } else if (view == mWeChatView) {\n platform = Platform.WECHAT;\n toast(\"也别忘了改微信 \" + WXEntryActivity.class.getSimpleName() + \" 类所在的包名哦\");\n } else {\n throw new IllegalStateException(\"are you ok?\");\n }\n UmengClient.login(this, platform, this);\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n // 友盟回调\n UmengClient.onActivityResult(this, requestCode, resultCode, data);\n }\n\n /**\n * {@link UmengLogin.OnLoginListener}\n */\n\n /**\n * 授权成功的回调\n *\n * @param platform 平台名称\n * @param data 用户资料返回\n */\n @Override\n public void onSucceed(Platform platform, UmengLogin.LoginData data) {\n if (isFinishing() || isDestroyed()) {\n // Glide:You cannot start a load for a destroyed activity\n return;\n }\n\n // 判断第三方登录的平台\n switch (platform) {\n case QQ:\n break;\n case WECHAT:\n break;\n default:\n break;\n }\n\n GlideApp.with(this)\n .load(data.getAvatar())\n .circleCrop()\n .into(mLogoView);\n\n toast(\"昵称:\" + data.getName() + \"\\n\" +\n \"性别:\" + data.getSex() + \"\\n\" +\n \"id:\" + data.getId() + \"\\n\" +\n \"token:\" + data.getToken());\n }\n\n /**\n * 授权失败的回调\n *\n * @param platform 平台名称\n * @param t 错误原因\n */\n @Override\n public void onError(Platform platform, Throwable t) {\n toast(\"第三方登录出错:\" + t.getMessage());\n }\n\n /**\n * {@link KeyboardWatcher.SoftKeyboardStateListener}\n */\n\n @Override\n public void onSoftKeyboardOpened(int keyboardHeight) {\n // 执行位移动画\n ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBodyLayout, \"translationY\", 0, -mCommitView.getHeight());\n objectAnimator.setDuration(mAnimTime);\n objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());\n objectAnimator.start();\n\n // 执行缩小动画\n mLogoView.setPivotX(mLogoView.getWidth() / 2f);\n mLogoView.setPivotY(mLogoView.getHeight());\n AnimatorSet animatorSet = new AnimatorSet();\n ObjectAnimator scaleX = ObjectAnimator.ofFloat(mLogoView, \"scaleX\", 1f, mLogoScale);\n ObjectAnimator scaleY = ObjectAnimator.ofFloat(mLogoView, \"scaleY\", 1f, mLogoScale);\n ObjectAnimator translationY = ObjectAnimator.ofFloat(mLogoView, \"translationY\", 0f, -mCommitView.getHeight());\n animatorSet.play(translationY).with(scaleX).with(scaleY);\n animatorSet.setDuration(mAnimTime);\n animatorSet.start();\n }\n\n @Override\n public void onSoftKeyboardClosed() {\n // 执行位移动画\n ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBodyLayout, \"translationY\", mBodyLayout.getTranslationY(), 0f);\n objectAnimator.setDuration(mAnimTime);\n objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());\n objectAnimator.start();\n\n if (mLogoView.getTranslationY() == 0) {\n return;\n }\n\n // 执行放大动画\n mLogoView.setPivotX(mLogoView.getWidth() / 2f);\n mLogoView.setPivotY(mLogoView.getHeight());\n AnimatorSet animatorSet = new AnimatorSet();\n ObjectAnimator scaleX = ObjectAnimator.ofFloat(mLogoView, \"scaleX\", mLogoScale, 1f);\n ObjectAnimator scaleY = ObjectAnimator.ofFloat(mLogoView, \"scaleY\", mLogoScale, 1f);\n ObjectAnimator translationY = ObjectAnimator.ofFloat(mLogoView, \"translationY\", mLogoView.getTranslationY(), 0f);\n animatorSet.play(translationY).with(scaleX).with(scaleY);\n animatorSet.setDuration(mAnimTime);\n animatorSet.start();\n }\n\n /**\n * {@link TextView.OnEditorActionListener}\n */\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE && mCommitView.isEnabled()) {\n // 模拟点击登录按钮\n onClick(mCommitView);\n return true;\n }\n return false;\n }\n\n @NonNull\n @Override\n protected ImmersionBar createStatusBarConfig() {\n return super.createStatusBarConfig()\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white);\n }\n}", "answers": [" startActivity(PhoneResetActivity.class);"], "length": 2305, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "4cdf78eb-1669-48ad-9e33-6e146daa0ea1", "reasoning": "In MineFragment's onClick method, each button ID case launches an activity via startActivity(SomeActivity.class). The case for R.id.btn_mine_change is opened but missing its body. Based on the imported activities, the logical activity to start for a \"change\" action is PhoneResetActivity (used to change/reset phone number). Therefore the next line should launch that activity.", "reasoning_model_answer": "startActivity(PhoneResetActivity.class);", "assistant_with_reasoning": "\nIn MineFragment's onClick method, each button ID case launches an activity via startActivity(SomeActivity.class). The case for R.id.btn_mine_change is opened but missing its body. Based on the imported activities, the logical activity to start for a \"change\" action is PhoneResetActivity (used to change/reset phone number). Therefore the next line should launch that activity.\n\nstartActivity(PhoneResetActivity.class);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.788, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 32323, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "startActivity(PhoneResetActivity.class);", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.infineon.esim.lpa.core.dtos.ActivationCode;\nimport com.infineon.esim.lpa.core.dtos.DeviceInformation;\nimport com.infineon.esim.lpa.core.dtos.EuiccInfo;\nimport com.infineon.esim.lpa.core.dtos.ProfileDownloadSession;\nimport com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata;\nimport com.infineon.esim.lpa.core.dtos.result.local.ClearNotificationsResult;\nimport com.infineon.esim.lpa.core.dtos.result.local.DeleteResult;\nimport com.infineon.esim.lpa.core.dtos.result.local.DisableResult;\nimport com.infineon.esim.lpa.core.dtos.result.local.EnableResult;\nimport com.infineon.esim.lpa.core.dtos.result.local.SetNicknameResult;\nimport com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult;\nimport com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult;\nimport com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult;\nimport com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult;\nimport com.infineon.esim.lpa.core.dtos.result.remote.RemoteError;\nimport com.infineon.esim.lpa.core.es10.Es10Interface;\nimport com.infineon.esim.lpa.core.es10.EuiccChannel;\nimport com.infineon.esim.lpa.core.es9plus.Es9PlusInterface;\nimport com.infineon.esim.lpa.core.worker.local.ClearAllNotificationsWorker;\nimport com.infineon.esim.lpa.core.worker.local.DeleteProfileWorker;\nimport com.infineon.esim.lpa.core.worker.local.DisableProfileWorker;\nimport com.infineon.esim.lpa.core.worker.local.EnableProfileWorker;\nimport com.infineon.esim.lpa.core.worker.local.GetEidWorker;\nimport com.infineon.esim.lpa.core.worker.local.GetEuiccInfo2Worker;\nimport com.infineon.esim.lpa.core.worker.local.ListProfilesWorker;\nimport com.infineon.esim.lpa.core.worker.local.SetNicknameWorker;\nimport com.infineon.esim.lpa.core.worker.remote.AuthenticateWorker;\nimport com.infineon.esim.lpa.core.worker.remote.CancelSessionWorker;\nimport com.infineon.esim.lpa.core.worker.remote.DownloadProfileWorker;\nimport com.infineon.esim.lpa.core.worker.remote.HandleNotificationsWorker;\nimport com.infineon.esim.util.Log;\nimport java.util.List;", "context": "core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCoreImpl.java\n/*\n * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED \"AS IS\". INFINEON\n * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,\n * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,\n * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES\n * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER\n * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR\n * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.\n *\n * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR\n * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR\n * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR\n * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE\n * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION\n * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR\n * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON\n * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.\n *\n * (C)Copyright INFINEON TECHNOLOGIES All rights reserved\n */\n\npackage com.infineon.esim.lpa.core;\n\n\n\npublic class LocalProfileAssistantCoreImpl implements LocalProfileAssistantCore {\n private static final String TAG = LocalProfileAssistantCoreImpl.class.getName();\n\n private ProfileDownloadSession profileDownloadSession = null;\n\n private Es10Interface es10Interface;\n private Es9PlusInterface es9PlusInterface;\n\n public LocalProfileAssistantCoreImpl() {\n }\n\n public void setEuiccChannel(EuiccChannel euiccChannel) {\n this.es10Interface = new Es10Interface(euiccChannel);\n }\n\n public void enableEs9PlusInterface() {\n this.es9PlusInterface = new Es9PlusInterface();\n }\n\n public void disableEs9PlusInterface() {\n this.es9PlusInterface = null;\n }\n\n // Local functions\n\n @Override\n public EnableResult enableProfile(String iccid, boolean refreshFlag) throws Exception {\n int result = new EnableProfileWorker(es10Interface).enable(iccid, refreshFlag);\n\n return new EnableResult(result);\n }\n\n @Override\n public DisableResult disableProfile(String iccid) throws Exception {\n int result = new DisableProfileWorker(es10Interface).disable(iccid);\n\n return new DisableResult(result);\n }\n\n @Override\n public DeleteResult deleteProfile(String iccid) throws Exception {\n int result = new DeleteProfileWorker(es10Interface).delete(iccid);\n\n return new DeleteResult(result);\n }\n\n @Override\n public SetNicknameResult setNickname(String iccid, String nicknameNew) throws Exception {\n int result = new SetNicknameWorker(es10Interface).setNickname(iccid,nicknameNew);\n\n return new SetNicknameResult(result);\n }\n\n @Override\n public List getProfiles() throws Exception {\n return new ListProfilesWorker(es10Interface).listProfiles();\n }\n\n @Override\n public String getEID() throws Exception {\n return new GetEidWorker(es10Interface).getEid();\n }\n\n @Override\n public EuiccInfo getEuiccInfo2() throws Exception {\n return new GetEuiccInfo2Worker(es10Interface).getEuiccInfo2();\n }\n\n // Remote functions\n\n @Override\n public AuthenticateResult authenticate(ActivationCode activationCode) throws Exception {\n if(isEs9PlusInterfaceUnavailable()) {\n Log.error(TAG, \"ES9+ interface is not available! Enable internet connection?\");\n throw new Exception(\"ES9+ interface is not available! Enable internet connection?\");\n }\n\n profileDownloadSession = new ProfileDownloadSession(activationCode, DeviceInformation.getDeviceInformation(), es10Interface, es9PlusInterface);\n\n boolean success = new AuthenticateWorker(profileDownloadSession).authenticate();\n\n if(success) {\n ProfileMetadata profileMetadata = new ProfileMetadata(profileDownloadSession.getProfileMetaData());\n return new AuthenticateResult(profileDownloadSession.isCcRequired(), profileMetadata);\n } else {\n return new AuthenticateResult(getLastEs9PlusError());\n }\n }\n\n @Override\n public DownloadResult downloadProfile(String confirmationCode) throws Exception {\n if(isEs9PlusInterfaceUnavailable()) {\n Log.error(TAG, \"ES9+ interface is not available! Enable internet connection?\");\n throw new Exception(\"ES9+ interface is not available! Enable internet connection?\");\n }\n\n boolean success = new DownloadProfileWorker(profileDownloadSession).downloadProfile(confirmationCode);\n\n if(success) {\n return new DownloadResult();\n } else {\n\ncore/src/main/java/com/infineon/esim/lpa/core/dtos/EuiccInfo.java\npublic class EuiccInfo {\n private static final String TAG = EuiccInfo.class.getName();\n\n private String eid;\n private final String profileVersion;\n private final String svn;\n private final String euiccFirmwareVer;\n private final String globalplatformVersion;\n private final String sasAcreditationNumber;\n private final List pkiIdsForSign;\n private final List pkiIdsForVerify;\n private final PprIds forbiddenProfilePolicyRules;\n private final BerOctetString extCardResource;\n\n public EuiccInfo(EUICCInfo2 euiccInfo2) {\n this(null, euiccInfo2);\n }\n\n public EuiccInfo(String eid, EUICCInfo2 euiccInfo2) {\n this.eid = eid;\n this.profileVersion = versionTypeToString(euiccInfo2.getProfileVersion());\n this.svn = versionTypeToString(euiccInfo2.getSvn());\n this.euiccFirmwareVer = versionTypeToString(euiccInfo2.getEuiccFirmwareVer());\n this.globalplatformVersion = versionTypeToString(euiccInfo2.getGlobalplatformVersion());\n\n this.sasAcreditationNumber = euiccInfo2.getSasAcreditationNumber().toString();\n\n this.pkiIdsForSign = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForSigning());\n this.pkiIdsForVerify = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForVerification());\n\n this.forbiddenProfilePolicyRules = euiccInfo2.getForbiddenProfilePolicyRules();\n\n this.extCardResource = euiccInfo2.getExtCardResource();\n }\n\n public void setEid(String eid) {\n this.eid = eid;\n }\n\n public String getEid() {\n return eid;\n }\n\n public String getProfileVersion() {\n return profileVersion;\n }\n\n public String getSvn() {\n return svn;\n }\n\n public String getEuiccFirmwareVer() {\n return euiccFirmwareVer;\n }\n\n\n public String getGlobalplatformVersion() {\n return globalplatformVersion;\n }\n\n public String getSasAcreditationNumber() {\n return sasAcreditationNumber;\n }\n\n public List getPkiIdsForSign() {\n return pkiIdsForSign;\n }\n\n public List getPkiIdsForVerify() {\n return pkiIdsForVerify;\n }\n\n public String getPkiIdsForSignAsString(){\n StringBuilder sb = new StringBuilder();\n if (!pkiIdsForSign.isEmpty()) {\n for(String pkiId : pkiIdsForSign) {\n sb.append(pkiId);\n sb.append(\"\\n\");\n }\n } else {\n return \"Not Found\";\n }\n return sb.subSequence(0, sb.length() - 1).toString();\n }\n\n public String getPkiIdsForVerifyAsString(){\n StringBuilder sb = new StringBuilder();\n if (!pkiIdsForVerify.isEmpty()) {\n for(String pkiId : pkiIdsForVerify) {\n sb.append(pkiId);\n sb.append(\"\\n\");\n }\n } else {\n return \"Not Found\";\n }\n return sb.subSequence(0, sb.length() - 1).toString();\n }\n\n public String getForbiddenProfilePolicyRules() {\n return forbiddenProfilePolicyRules.toString();\n }\n\n public String getExtCardResource() {\n return extCardResource.toString();\n }\n\n private static String versionTypeToString(VersionType versionType) {\n if(versionType != null) {\n String vts = versionType.toString();\n Log.debug(TAG, \"Raw version number: \\\"\" + vts + \"\\\".\" );\n if (vts.length() == 6) {\n int major = Integer.parseInt(vts.substring(0, 2));\n int middle = Integer.parseInt(vts.substring(2, 4));\n int minor = Integer.parseInt(vts.substring(4, 6));\n\n return major + \".\" + middle + \".\" + minor;\n }\n }\n\n return \"N/A\";\n }\n\n private static List euiccPkiIdList(EUICCInfo2.EuiccCiPKIdListForSigning pkiIdListIn) {\n List pkiIdList = new ArrayList<>();\n\n for(SubjectKeyIdentifier ski : pkiIdListIn.getSubjectKeyIdentifier()) {\n pkiIdList.add(ski.toString());\n }\n\n return pkiIdList;\n }\n\n private static List euiccPkiIdList(EUICCInfo2.EuiccCiPKIdListForVerification pkiIdListIn) {\n List pkiIdList = new ArrayList<>();\n\n for(SubjectKeyIdentifier ski : pkiIdListIn.getSubjectKeyIdentifier()) {\n pkiIdList.add(ski.toString());\n }\n\n return pkiIdList;\n }\n\n\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/es9plus/Es9PlusInterface.java\npublic class Es9PlusInterface {\n private static final String TAG = Es9PlusInterface.class.getName();\n\n private static final Gson GS = new GsonBuilder().disableHtmlEscaping().create();\n\n private static final String INITIATE_AUTHENTICATION_PATH = \"/gsma/rsp2/es9plus/initiateAuthentication\";\n private static final String AUTHENTICATE_CLIENT_PATH = \"/gsma/rsp2/es9plus/authenticateClient\";\n private static final String GET_BOUND_PROFILE_PACKAGE_PATH = \"/gsma/rsp2/es9plus/getBoundProfilePackage\";\n private static final String HANDLE_NOTIFICATION_PATH = \"/gsma/rsp2/es9plus/handleNotification\";\n private static final String CANCEL_SESSION_PATH = \"/gsma/rsp2/es9plus/cancelSession\";\n\n private final HttpsClient httpsClient;\n\n private String smdpAddress;\n\n private FunctionExecutionStatus lastFunctionExecutionStatus = null;\n\n public Es9PlusInterface() {\n this.httpsClient = new HttpsClient();\n }\n\n public void setSmdpAddress(String smdpAddress) {\n this.smdpAddress = smdpAddress;\n }\n\n public InitiateAuthenticationResponse initiateAuthentication(InitiateAuthenticationRequest initiateAuthenticationRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + initiateAuthenticationRequest);\n\n InitiateAuthenticationReq initiateAuthenticationReq = new InitiateAuthenticationReq();\n initiateAuthenticationReq.setRequest(initiateAuthenticationRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(initiateAuthenticationReq), smdpAddress, INITIATE_AUTHENTICATION_PATH, true);\n checkHttpStatusCode(\"InitiateAuthentication\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n InitiateAuthenticationResp initiateAuthenticationResp = GS.fromJson(httpResponse.getContent(), InitiateAuthenticationResp.class);\n checkFunctionExecutionStatus(\"InitiateAuthentication\", initiateAuthenticationResp);\n\n InitiateAuthenticationResponse initiateAuthenticationResponse = initiateAuthenticationResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + initiateAuthenticationResponse);\n\n return initiateAuthenticationResponse;\n }\n\n public AuthenticateClientResponseEs9 authenticateClient(AuthenticateClientRequest authenticateClientRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + authenticateClientRequest);\n\n AuthenticateClientReq authenticateClientReq = new AuthenticateClientReq();\n authenticateClientReq.setRequest(authenticateClientRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(authenticateClientReq), smdpAddress, AUTHENTICATE_CLIENT_PATH, true);\n checkHttpStatusCode(\"AuthenticateClient\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n AuthenticateClientResp authenticateClientResp = GS.fromJson(httpResponse.getContent(), AuthenticateClientResp.class);\n checkFunctionExecutionStatus(\"AuthenticateClient\", authenticateClientResp);\n\n AuthenticateClientResponseEs9 authenticateClientResponseEs9 = authenticateClientResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + authenticateClientResponseEs9);\n\n return authenticateClientResponseEs9;\n }\n\n public GetBoundProfilePackageResponse getBoundProfilePackage(GetBoundProfilePackageRequest getBoundProfilePackageRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + getBoundProfilePackageRequest);\n\n GetBoundProfilePackageReq getBoundProfilePackageReq = new GetBoundProfilePackageReq();\n getBoundProfilePackageReq.setRequest(getBoundProfilePackageRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(getBoundProfilePackageReq), smdpAddress, GET_BOUND_PROFILE_PACKAGE_PATH, true);\n checkHttpStatusCode(\"GetBoundProfilePackage\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n GetBoundProfilePackageResp getBoundProfilePackageResp = GS.fromJson(httpResponse.getContent(), GetBoundProfilePackageResp.class);\n checkFunctionExecutionStatus(\"GetBoundProfilePackage\", getBoundProfilePackageResp);\n\n GetBoundProfilePackageResponse getBoundProfilePackageResponse = getBoundProfilePackageResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + getBoundProfilePackageResponse);\n\n return getBoundProfilePackageResponse;\n }\n\n public CancelSessionResponseEs9 cancelSession(CancelSessionRequestEs9 cancelSessionRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + cancelSessionRequest);\n\n CancelSessionReq cancelSessionReq = new CancelSessionReq();\n cancelSessionReq.setRequest(cancelSessionRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(cancelSessionReq), smdpAddress, CANCEL_SESSION_PATH, true);\n checkHttpStatusCode(\"CancelSession\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n CancelSessionResp cancelSessionResp = GS.fromJson(httpResponse.getContent(), CancelSessionResp.class);\n checkFunctionExecutionStatus(\"CancelSession\", cancelSessionResp);\n\n CancelSessionResponseEs9 cancelSessionResponseEs9 = cancelSessionResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + cancelSessionResponseEs9);\n\n return cancelSessionResponseEs9;\n }\n\n public void handleNotification(PendingNotification pendingNotification) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + pendingNotification);\n\n HandleNotificationReq handleNotificationReq = new HandleNotificationReq();\n handleNotificationReq.setRequest(pendingNotification);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(handleNotificationReq), smdpAddress, HANDLE_NOTIFICATION_PATH, true);\n // No content for response\n\n checkHttpStatusCode(\"HandleNotification\", httpResponse, HttpsURLConnection.HTTP_NO_CONTENT);\n }\n\n public FunctionExecutionStatus getFunctionExecutionStatus() {\n return lastFunctionExecutionStatus;\n }\n\n private void ensureSmdpAddressIsAvailable() throws Exception {\n if(smdpAddress == null) {\n Log.error(TAG, \"SM-DP+ address is not available.\");\n throw new Exception(\"SM-DP+ address is not available.\");\n }\n }\n\n private void checkHttpStatusCode(String functionName, HttpResponse httpResponse, int expectedHttpStatusCode) {\n if(httpResponse.getStatusCode() != expectedHttpStatusCode) {\n throw new RuntimeException(\"Error in \" + functionName + \": wrong HTTP status code: \" + httpResponse.getStatusCode());\n }\n }\n\n private void checkFunctionExecutionStatus(String functionName, ResponseMsgBody responseMessage) {\n if((responseMessage.getHeader() != null) &&\n (responseMessage.getHeader().getFunctionExecutionStatus() != null)) {\n\n this.lastFunctionExecutionStatus = responseMessage.getHeader().getFunctionExecutionStatus();\n String status = lastFunctionExecutionStatus.getStatus();\n\n if(status.equals(FunctionExecutionStatus.EXECUTION_STATUS_SUCCESS) ||\n status.equals(FunctionExecutionStatus.EXECUTION_STATUS_WITH_WARNING)) {\n return;\n } else {\n throw new RuntimeException(\"Error in \" + functionName + \": FunctionExecutionStatus: \" + lastFunctionExecutionStatus.toString());\n }\n }\n\n throw new RuntimeException(\"Error in \" + functionName + \": FunctionExecutionStatus not found in response.\");\n }\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/RemoteError.java\npublic class RemoteError {\n private final String status;\n private final String subjectCode;\n private final String reasonCode;\n private final String message;\n\n public RemoteError() {\n this(\"No error\",null, null, null);\n }\n\n public RemoteError(FunctionExecutionStatus functionExecutionStatus) {\n if(functionExecutionStatus == null) {\n this.status = \"No error\";\n this.subjectCode = null;\n this.reasonCode = null;\n this.message = null;\n } else {\n this.status = functionExecutionStatus.getStatus();\n if(functionExecutionStatus.getStatusCodeData() != null) {\n this.subjectCode = functionExecutionStatus.getStatusCodeData().getSubjectCode();\n this.reasonCode = functionExecutionStatus.getStatusCodeData().getReasonCode();\n this.message = functionExecutionStatus.getStatusCodeData().getMessage();\n } else {\n this.subjectCode = null;\n this.reasonCode = null;\n this.message = null;\n }\n }\n }\n\n public RemoteError(String status, String subjectCode, String reasonCode, String message) {\n this.status = status;\n this.subjectCode = subjectCode;\n this.reasonCode = reasonCode;\n this.message = message;\n }\n\n public String getStatus() {\n return status;\n }\n\n public String getSubjectCode() {\n return subjectCode;\n }\n\n public String getReasonCode() {\n return reasonCode;\n }\n\n public String getMessage() {\n return message;\n }\n\n @Override\n @NonNull\n public String toString() {\n return \"RspError{\" +\n \"status='\" + status + '\\'' +\n \", subjectCode='\" + subjectCode + '\\'' +\n \", reasonCode='\" + reasonCode + '\\'' +\n \", message='\" + message + '\\'' +\n '}';\n }\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/ClearNotificationsResult.java\npublic class ClearNotificationsResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_NOT_FOUND = 1;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_NOT_FOUND, \"ICCID not found.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final List values;\n\n public ClearNotificationsResult(List results) {\n this.values = results;\n }\n\n @Override\n public boolean isOk() {\n for(Integer value : values) {\n if(value != OK) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean equals(int value) {\n for(Integer internalValue : values) {\n if(value == internalValue) {\n return true;\n }\n }\n\n return false;\n }\n\n @Override\n public String getDescription() {\n StringBuilder description = new StringBuilder();\n\n for(Integer value : values) {\n description.append(lookup.get(value)).append(\"\\n\");\n }\n\n return description.toString();\n }\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/EnableResult.java\npublic class EnableResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_OR_AID_NOT_FOUND = 1;\n public static final int PROFILE_NOT_IN_DISABLED_STATE = 2;\n public static final int DISALLOWED_BY_POLICY = 3;\n public static final int WRONG_PROFILE_REENABLING = 4;\n public static final int CAT_BUSY = 5;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_OR_AID_NOT_FOUND, \"ICCID or AID not found.\");\n lookup.put(PROFILE_NOT_IN_DISABLED_STATE, \"Profile not in disabled state.\");\n lookup.put(DISALLOWED_BY_POLICY, \"Disallowed by policy.\");\n lookup.put(WRONG_PROFILE_REENABLING, \"Wrong profile reenabling.\");\n lookup.put(CAT_BUSY, \"CAT busy.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public EnableResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/es10/EuiccChannel.java\npublic interface EuiccChannel {\n List transmitAPDUS(List apdus) throws Exception;\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/worker/remote/AuthenticateWorker.java\npublic class AuthenticateWorker {\n private static final String TAG = AuthenticateWorker.class.getName();\n\n private final ProfileDownloadSession profileDownloadSession;\n private final Es10Interface es10Interface;\n private final Es9PlusInterface es9PlusInterface;\n\n public AuthenticateWorker(ProfileDownloadSession profileDownloadSession) {\n this.profileDownloadSession = profileDownloadSession;\n this.es10Interface = profileDownloadSession.getEs10Interface();\n this.es9PlusInterface = profileDownloadSession.getEs9PlusInterface();\n }\n\n public boolean authenticate() throws Exception {\n Log.debug(TAG, \"Authenticating ...\");\n\n // Get required data from eUICC\n EUICCInfo1 euiccInfo1 = es10Interface.es10b_getEuiccInfo1();\n GetEuiccChallengeResponse euiccChallenge = es10Interface.es10b_getEuiccChallenge();\n\n profileDownloadSession.es10_processEuiccInfo1(euiccInfo1);\n profileDownloadSession.es10_processEuiccChallenge(euiccChallenge);\n\n // Send initiateAuthenticate to SM-DP+\n InitiateAuthenticationRequest initiateAuthenticationRequest = profileDownloadSession.es9Plus_getInitiateAuthenticationRequest();\n InitiateAuthenticationResponse initiateAuthenticationResponse = es9PlusInterface.initiateAuthentication(initiateAuthenticationRequest);\n profileDownloadSession.es9Plus_processInitiateAuthenticationResponse(es9PlusInterface.getFunctionExecutionStatus(), initiateAuthenticationResponse);\n\n // Send authenticateServer to eUICC\n AuthenticateServerRequest authenticateServerRequest = profileDownloadSession.es10_getAuthenticateServerRequest();\n AuthenticateServerResponse authenticateServerResponse = es10Interface.es10b_authenticateServer(authenticateServerRequest);\n profileDownloadSession.es10_processAuthenticateServerResponse(authenticateServerResponse);\n\n // Send authenticateClient to SM-DP+\n AuthenticateClientRequest authenticateClientRequest = profileDownloadSession.es9Plus_getAuthenticateClientRequest();\n AuthenticateClientResponseEs9 authenticateClientResponseEs9 = es9PlusInterface.authenticateClient(authenticateClientRequest);\n profileDownloadSession.es9Plus_processAuthenticateClientResponse(es9PlusInterface.getFunctionExecutionStatus(), authenticateClientResponseEs9);\n\n return profileDownloadSession.isClientAuthenticatedSuccessfully();\n }\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/worker/local/ListProfilesWorker.java\npublic class ListProfilesWorker {\n private static final String TAG = ListProfilesWorker.class.getName();\n\n private final Es10Interface es10Interface;\n\n public ListProfilesWorker(Es10Interface es10Interface) {\n this.es10Interface = es10Interface;\n }\n\n public List listProfiles() throws Exception {\n Log.debug(TAG, \"Getting list of all profiles...\");\n\n ProfileInfoListResponse profileInfoListResponse = es10Interface.es10c_getProfilesInfoAll();\n\n List profileMetadataList = new ArrayList<>();\n\n for (ProfileInfo profileInfo : profileInfoListResponse.getProfileInfoListOk().getProfileInfo()) {\n profileMetadataList.add(new ProfileMetadata(profileInfo));\n }\n\n return profileMetadataList;\n }\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/SetNicknameResult.java\npublic class SetNicknameResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_NOT_FOUND = 1;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_NOT_FOUND, \"ICCID not found.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public SetNicknameResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}", "answers": [" return new DownloadResult(getLastEs9PlusError());"], "length": 2085, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "4eb30760-c457-40a5-9603-7dfcae6da1ad", "reasoning": "The method downloadProfile ends with an if‑else checking the success of the DownloadProfileWorker. In the success branch it returns a new DownloadResult(). In the failure branch it should return a DownloadResult containing the remote error, mirroring the pattern used in the authenticate method (which returns new AuthenticateResult(getLastEs9PlusError()) on failure). Therefore the next line after the opening else brace is the return statement constructing a DownloadResult with the last ES9+ error.", "reasoning_model_answer": "return new DownloadResult(getLastEs9PlusError());", "assistant_with_reasoning": "\nThe method downloadProfile ends with an if‑else checking the success of the DownloadProfileWorker. In the success branch it returns a new DownloadResult(). In the failure branch it should return a DownloadResult containing the remote error, mirroring the pattern used in the authenticate method (which returns new AuthenticateResult(getLastEs9PlusError()) on failure). Therefore the next line after the opening else brace is the return statement constructing a DownloadResult with the last ES9+ error.\n\nreturn new DownloadResult(getLastEs9PlusError());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.635, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 28848, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return new DownloadResult(getLastEs9PlusError());", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.infineon.esim.util.Bytes;\nimport androidx.annotation.NonNull;\nimport com.gsma.sgp.messages.rspdefinitions.AuthenticateClientRequest;\nimport com.gsma.sgp.messages.rspdefinitions.AuthenticateServerResponse;\nimport com.gsma.sgp.messages.rspdefinitions.TransactionId;\nimport com.infineon.esim.lpa.core.es9plus.messages.request.base.RequestMsgBody;\nimport com.infineon.esim.messages.Ber;", "context": "core/src/main/java/com/infineon/esim/lpa/core/es9plus/messages/request/AuthenticateClientReq.java\n/*\n * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED \"AS IS\". INFINEON\n * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,\n * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,\n * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES\n * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER\n * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR\n * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.\n *\n * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR\n * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR\n * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR\n * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE\n * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION\n * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR\n * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON\n * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.\n *\n * (C)Copyright INFINEON TECHNOLOGIES All rights reserved\n */\n\npackage com.infineon.esim.lpa.core.es9plus.messages.request;\n\n\n\npublic class AuthenticateClientReq extends RequestMsgBody {\n private String transactionId;\n private String authenticateServerResponse;\n\n public String getTransactionId() {\n return transactionId;\n }\n\n public void setTransactionId(String transactionId) {\n this.transactionId = transactionId;\n }\n\n public String getAuthenticateServerResponse() {\n\nmessages/src/main/java/com/gsma/sgp/messages/rspdefinitions/TransactionId.java\npublic class TransactionId extends BerOctetString {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic TransactionId() {\n\t}\n\n\tpublic TransactionId(byte[] value) {\n\t\tsuper(value);\n\t}\n\n}\n\nmessages/src/main/java/com/gsma/sgp/messages/rspdefinitions/AuthenticateServerResponse.java\npublic class AuthenticateServerResponse implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic byte[] code = null;\n\tpublic static final BerTag tag = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 56);\n\n\tprivate AuthenticateResponseOk authenticateResponseOk = null;\n\tprivate AuthenticateResponseError authenticateResponseError = null;\n\t\n\tpublic AuthenticateServerResponse() {\n\t}\n\n\tpublic AuthenticateServerResponse(byte[] code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic void setAuthenticateResponseOk(AuthenticateResponseOk authenticateResponseOk) {\n\t\tthis.authenticateResponseOk = authenticateResponseOk;\n\t}\n\n\tpublic AuthenticateResponseOk getAuthenticateResponseOk() {\n\t\treturn authenticateResponseOk;\n\t}\n\n\tpublic void setAuthenticateResponseError(AuthenticateResponseError authenticateResponseError) {\n\t\tthis.authenticateResponseError = authenticateResponseError;\n\t}\n\n\tpublic AuthenticateResponseError getAuthenticateResponseError() {\n\t\treturn authenticateResponseError;\n\t}\n\n\tpublic int encode(OutputStream reverseOS) throws IOException {\n\t\treturn encode(reverseOS, true);\n\t}\n\n\tpublic int encode(OutputStream reverseOS, boolean withTag) throws IOException {\n\n\t\tif (code != null) {\n\t\t\tfor (int i = code.length - 1; i >= 0; i--) {\n\t\t\t\treverseOS.write(code[i]);\n\t\t\t}\n\t\t\tif (withTag) {\n\t\t\t\treturn tag.encode(reverseOS) + code.length;\n\t\t\t}\n\t\t\treturn code.length;\n\t\t}\n\n\t\tint codeLength = 0;\n\t\tif (authenticateResponseError != null) {\n\t\t\tcodeLength += authenticateResponseError.encode(reverseOS, false);\n\t\t\t// write tag: CONTEXT_CLASS, CONSTRUCTED, 1\n\t\t\treverseOS.write(0xA1);\n\t\t\tcodeLength += 1;\n\t\t\tcodeLength += BerLength.encodeLength(reverseOS, codeLength);\n\t\t\tif (withTag) {\n\t\t\t\tcodeLength += tag.encode(reverseOS);\n\t\t\t}\n\t\t\treturn codeLength;\n\t\t}\n\t\t\n\t\tif (authenticateResponseOk != null) {\n\t\t\tcodeLength += authenticateResponseOk.encode(reverseOS, false);\n\t\t\t// write tag: CONTEXT_CLASS, CONSTRUCTED, 0\n\t\t\treverseOS.write(0xA0);\n\t\t\tcodeLength += 1;\n\t\t\tcodeLength += BerLength.encodeLength(reverseOS, codeLength);\n\t\t\tif (withTag) {\n\t\t\t\tcodeLength += tag.encode(reverseOS);\n\t\t\t}\n\t\t\treturn codeLength;\n\t\t}\n\t\t\n\t\tthrow new IOException(\"Error encoding CHOICE: No element of CHOICE was selected.\");\n\t}\n\n\tpublic int decode(InputStream is) throws IOException {\n\t\treturn decode(is, true);\n\t}\n\n\tpublic int decode(InputStream is, boolean withTag) throws IOException {\n\t\tint codeLength = 0;\n\t\tBerLength length = new BerLength();\n\t\tBerTag berTag = new BerTag();\n\n\t\tif (withTag) {\n\t\t\tcodeLength += tag.decodeAndCheck(is);\n\t\t}\n\n\t\tcodeLength += length.decode(is);\n\t\tcodeLength += berTag.decode(is);\n\n\t\tif (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 0)) {\n\t\t\tauthenticateResponseOk = new AuthenticateResponseOk();\n\t\t\tcodeLength += authenticateResponseOk.decode(is, false);\n\t\t\treturn codeLength;\n\t\t}\n\n\t\tif (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 1)) {\n\t\t\tauthenticateResponseError = new AuthenticateResponseError();\n\t\t\tcodeLength += authenticateResponseError.decode(is, false);\n\t\t\treturn codeLength;\n\t\t}\n\n\t\tthrow new IOException(\"Error decoding CHOICE: Tag \" + berTag + \" matched to no item.\");\n\t}\n\n\tpublic void encodeAndSave(int encodingSizeGuess) throws IOException {\n\t\tReverseByteArrayOutputStream reverseOS = new ReverseByteArrayOutputStream(encodingSizeGuess);\n\t\tencode(reverseOS, false);\n\t\tcode = reverseOS.getArray();\n\t}\n\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendAsString(sb, 0);\n\t\treturn sb.toString();\n\t}\n\n\tpublic void appendAsString(StringBuilder sb, int indentLevel) {\n\n\t\tif (authenticateResponseOk != null) {\n\t\t\tsb.append(\"authenticateResponseOk: \");\n\t\t\tauthenticateResponseOk.appendAsString(sb, indentLevel + 1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (authenticateResponseError != null) {\n\t\t\tsb.append(\"authenticateResponseError: \");\n\t\t\tauthenticateResponseError.appendAsString(sb, indentLevel + 1);\n\t\t\treturn;\n\t\t}\n\n\t\tsb.append(\"\");\n\t}\n\n}\n\nmessages/src/main/java/com/infineon/esim/messages/Ber.java\n@SuppressWarnings(\"unused\")\npublic class Ber {\n private static final String TAG = Ber.class.getName();\n\n // Tags see: http://luca.ntop.org/Teaching/Appunti/asn1.html\n public static final BerTag BER_TAG_SEQUENCE_OF = new BerTag(BerTag.UNIVERSAL_CLASS, BerTag.CONSTRUCTED, 0x10); // 0x30\n public static final BerTag BER_TAG_TRANSACTION_ID = new BerTag(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 0x00); // 0x80\n public static final BerTag BER_TAG_CONTROL_REF_TEMPLATE = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 0x06); // 0xA6\n\n public static final BerTag BER_TAG_SIGNATURE = new BerTag(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 0x37); // 0x5F37\n public static final BerTag BER_TAG_OT_KEY = new BerTag(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 0x49); // 0x5F49\n\n\n public static final BerTag BER_TAG_FIRST_SEQ_OF_87_CONTAINER = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 0x00); // 0xA0\n public static final BerTag BER_TAG_SEQ_OF_88_CONTAINER = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 0x01); // 0xA1\n public static final BerTag BER_TAG_SECOND_SEQ_OF_87_CONTAINER = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 0x02); // 0xA2\n public static final BerTag BER_TAG_SEQ_OF_86_CONTAINER = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 0x03); // 0xA3\n\n public static final BerTag BER_TAG_SEQ_OF_86 = new BerTag(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 0x06); // 0x86\n public static final BerTag BER_TAG_SEQ_OF_87 = new BerTag(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 0x07); // 0x87\n public static final BerTag BER_TAG_SEQ_OF_88 = new BerTag(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 0x08); // 0x88\n\n private static final int ENCODING_SIZE_GUESS = 32; // Use standard ESG of ByteArrayOutputStream\n\n /**\n * Encodes a BER tag from a BerTag object to a byte array.\n * @param tag BerTag object to be encoded\n * @return Byte array representing the encoded BER tag\n */\n public static byte[] encodeTag(BerTag tag) {\n ReverseByteArrayOutputStream os = new ReverseByteArrayOutputStream(4);\n\n try {\n tag.encode(os);\n } catch (IOException e) {\n Log.error(TAG,\"Error: IOException during encoding of BerTag object: \" + tag + \".\", e);\n }\n\n return os.getArray();\n }\n\n /**\n * Encodes a BER length from an int to a byte array.\n * @param length BER length as int to be encoded\n * @return Byte array representing the encoded BER length\n */\n public static byte[] encodeLength(int length) {\n // Java int range is from -2147483648 to 2147483647 and uses 4 Byte.\n if (length < 0) {\n Log.error(TAG,\"Error: Negative length not supported: \" + length);\n throw new IllegalArgumentException(\"Negative length not supported.\");\n }\n\n final int BER_LENGTH_ESG = 4; // Assumption: length 0xFFFFFFFF because of int range. Resize if not...\n ReverseByteArrayOutputStream os = new ReverseByteArrayOutputStream(BER_LENGTH_ESG, true);\n\n try {\n BerLength.encodeLength(os, length);\n } catch (IOException e) {\n\n Log.error(TAG,\"Eror: IOException during length encoding: \", e);\n }\n\n return os.getArray();\n }\n\n /**\n * Encodes a list of elements in a BER sequence (\"SEQUENCE\" or \"SEQUENCE OF\") to a byte array.\n * @param data Elements to be encoded as BER sequence\n * @return Byte array representing the encoded list of elements in a BER sequence as byte array.\n */\n public static byte[] encodeSequence(List data) {\n byte[] output = null;\n\n for (byte[] dataElement : data) {\n output = Bytes.concatenate(output, dataElement);\n }\n\n return encodeElement(output, BER_TAG_SEQUENCE_OF);\n }\n\n /**\n * Encodes a BER element without a tag using only length and value (LV).\n * @param data Element to be encoded\n * @return Byte array representing the encoded LV BER element\n */\n public static byte[] encodeElementWithoutTag(byte[] data) {\n return encodeElement(data, (byte[]) null);\n }\n\n /**\n * Encodes a BER element with tag, length and value (TLV).\n * @param data Element to be encoded\n * @param tag BER tag to be used\n * @return Byte array representing the encoded TLV BER element.\n */\n public static byte[] encodeElement(byte[] data, BerTag tag) {\n return encodeElement(data, encodeTag(tag));\n }\n\n private static byte[] encodeElement(byte[] data, byte[] tag) {\n byte[] dataEncoded = null;\n\n // Check if a tag shall be written\n if (tag != null) {\n dataEncoded = tag;\n }\n\n // Encode length and data\n byte[] length = encodeLength(data.length);\n dataEncoded = Bytes.concatenate(dataEncoded, length, data);\n\n return dataEncoded;\n }\n\n /**\n * Swaps the BER tag of an BER element\n * @param input BER TLV element as byte array\n * @param newTag new BER tag as BerTag object\n * @return BER element with new tag\n */\n public static byte[] swapTag(byte[] input, BerTag newTag) {\n return Ber.encodeElement(Ber.stripTagAndLength(input), newTag);\n }\n\n /**\n * Strips the tag and length bytes from an encoded BER TLV element\n * @param input BER TLV element to be stripped\n * @return Byte array representing the value\n */\n public static byte[] stripTagAndLength(byte[] input) {\n byte[] output = null;\n InputStream is = new ByteArrayInputStream(input);\n\n try {\n // Decode tag (and throw away)\n BerTag tag = new BerTag();\n tag.decode(is);\n\n // Decode length (and throw away)\n BerLength length = new BerLength();\n length.decode(is);\n\n // Write content to output\n if (length.val != 0) {\n output = Bytes.toByteArray(is);\n }\n } catch (IOException e) {\n Log.error(TAG,\"Error: IOException during stripping of type and length of BER data.\", e);\n }\n\n return output;\n }\n\n public static byte[] getTag(byte[] input) {\n InputStream is = new ByteArrayInputStream(input);\n\n try {\n BerTag tag = new BerTag();\n tag.decode(is);\n return encodeTag(tag);\n } catch (IOException e) {\n Log.error(TAG,\"Error: IOException during stripping of type and length of BER data.\", e);\n }\n\n return null;\n }\n\n public static byte[] getLength(byte[] input) {\n InputStream is = new ByteArrayInputStream(input);\n\n try {\n // Decode tag (and throw away)\n BerTag tag = new BerTag();\n tag.decode(is);\n\n BerLength length = new BerLength();\n length.decode(is);\n return encodeLength(length.val);\n } catch (IOException e) {\n Log.error(TAG,\"Error: IOException during stripping of type and length of BER data.\", e);\n }\n\n return null;\n }\n\n /**\n * Creates a BerType object from an BER encoded byte array.\n * @param tClass Class object of the desired BerType\n * @param input BER encoded byte array as input\n * @param Class type of the desired BerType\n * @return BerType object of class T created from BER encoded byte array\n */\n public static T createFromEncodedByteArray(Class tClass, byte[] input) {\n T berObject = null;\n\n try {\n berObject = tClass.getDeclaredConstructor().newInstance();\n } catch (InstantiationException e) {\n Log.error(TAG,\"Error: InstantiationException for class \\\"\" + tClass.getName() + \"\\\" in while creating instance.\", e);\n } catch (IllegalAccessException e) {\n Log.error(TAG,\"Error: IllegalAccessException for class \\\"\" + tClass.getName() + \"\\\" in while creating instance.\", e);\n } catch (InvocationTargetException e) {\n Log.error(TAG,\"Error: InvocationTargetException for class \\\"\" + tClass.getName() + \"\\\" in while creating instance.\", e);\n } catch (NoSuchMethodException e) {\n Log.error(TAG,\"Error: NoSuchMethodException for class \\\"\" + tClass.getName() + \"\\\" in while creating instance.\", e);\n }\n\n InputStream inputStream = new ByteArrayInputStream(input);\n\n try {\n if(berObject != null) {\n berObject.decode(inputStream);\n } else {\n return null;\n }\n inputStream.close();\n } catch (IOException e) {\n Log.error(TAG,\"Error: IOException during ASN1 message encoding\", e);\n }\n\n Log.verbose(TAG,\"Decoded object of class \" + berObject.getClass().getName() + \": \" + berObject);\n\n return berObject;\n }\n\n /**\n * Creates a BerType object from an BER encoded Hex-String object.\n * @param tClass Class object of the desired BerType\n * @param input BER encoded Hex-String object as input\n * @param Class type of the desired BerType\n * @return BerType object of class T created from BER encoded Hex-String object\n */\n public static T createFromEncodedHexString(Class tClass, String input) {\n return createFromEncodedByteArray(tClass, Bytes.decodeHexString(input));\n }\n\n /**\n * Creates a BerType object from an BER encoded Base64-String object.\n * @param tClass Class object of the desired BerType\n * @param input BER encoded Base64-String object as input\n * @param Class type of the desired BerType\n * @return BerType object of class T created from BER encoded Base64-String object\n */\n public static T createFromEncodedBase64String(Class tClass, String input) {\n return createFromEncodedByteArray(tClass, Bytes.decodeBase64String(input));\n }\n\n /**\n * Creates a signature of class BerOctetString from a BER encoded Base64-String object.\n * @param input BER encoded Base64-String object as input\n * @return BerOctetString created from BER encoded Base64-String object\n */\n public static BerOctetString createSignatureFromEncodedBase64String(String input) {\n // 5F37 tag and length 40 has to be scrapped\n byte[] signatureRaw = Bytes.decodeBase64String(input);\n byte[] signatureRawTrunc = Bytes.sub(signatureRaw, 3, signatureRaw.length - 3);\n return new BerOctetString(signatureRawTrunc);\n }\n\n /**\n * Returns BerType object as BER encoded bytes represented by a byte array.\n * @param berObject BerType object as input\n * @return BER encoded BerType object as byte array\n */\n public static byte[] getEncodedAsByteArray(BerType berObject) {\n int codeLength = 0;\n ReverseByteArrayOutputStream reverseByteArrayOutputStream = new ReverseByteArrayOutputStream(ENCODING_SIZE_GUESS, true);\n\n if(berObject == null) {\n return reverseByteArrayOutputStream.getArray();\n }\n\n Log.verbose(TAG,\"Encoding object of class \" + berObject.getClass().getSimpleName() + \": \" + berObject);\n\n try {\n codeLength = berObject.encode(reverseByteArrayOutputStream);\n reverseByteArrayOutputStream.close();\n } catch (IOException e) {\n Log.error(TAG,\"Error: IOException during ASN1 message decoding\", e);\n }\n\n byte[] output = reverseByteArrayOutputStream.getArray();\n\n if (codeLength != output.length) {\n Log.error(TAG,\"Error: Decoding ASN1 message ended in code length mismatch: codeLength: \" + codeLength + \" output.length: \" + output.length + \".\");\n }\n\n return output;\n }\n\n /**\n * Returns BerType object as BER encoded bytes represented by a Hex-String object.\n * @param berObject BerType object as input\n * @return BER encoded BerType object as Hex-String object\n */\n public static String getEncodedAsHexString(BerType berObject) {\n return Bytes.encodeHexString(getEncodedAsByteArray(berObject));\n }\n\n /**\n * Returns BerType object as BER encoded bytes represented by a Base64-String object.\n * @param berObject BerType object as input\n * @return BER encoded BerType object as Base64-String object\n */\n public static String getEncodedAsBase64String(BerType berObject) {\n return Bytes.encodeBase64String(getEncodedAsByteArray(berObject));\n }\n\n /**\n * Returns BerType object as BER encoded value (without leading tag and length) represented by a byte array.\n *\n * NOTE: The value itself is BER encoded with tag and length as TLV.\n * @param berObject BerType object as input\n * @return BER encoded value BerType object as byte array\n */\n public static byte[] getEncodedValueAsByteArray(BerType berObject) {\n return stripTagAndLength(getEncodedAsByteArray(berObject));\n }\n\n /**\n * Returns BerType object as BER encoded value (without leading tag and length) represented by a Hex-String object.\n *\n * NOTE: The value itself is BER encoded with tag and length as TLV.\n * @param berObject BerType object as input\n * @return BER encoded value BerType object as Hex-String object\n */\n public static String getEncodedValueAsHexString(BerType berObject) {\n return Bytes.encodeHexString(getEncodedValueAsByteArray(berObject));\n }\n\n /**\n * Returns BerType object as BER encoded value (without leading tag and length) represented by a Base64-String object.\n *\n * NOTE: The value itself is BER encoded with tag and length as TLV.\n * @param berObject BerType object as input\n * @return BER encoded value BerType object as Base64-String object\n */\n public static String getEncodedValueAsBase64String(BerType berObject) {\n return Bytes.encodeBase64String(getEncodedValueAsByteArray(berObject));\n }\n\n public static String getEncodedTagAsHexString(BerType berObject) {\n return Bytes.encodeHexString(getTag(getEncodedAsByteArray(berObject)));\n }\n\n public static String getEncodedLengthAsHexString(BerType berObject) {\n return Bytes.encodeHexString(getLength(getEncodedAsByteArray(berObject)));\n }\n}", "answers": [" return authenticateServerResponse;"], "length": 2281, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "f831db29-2fef-478a-8389-a35ce0ab8635", "reasoning": "The class defines a private String field named authenticateServerResponse and is currently inside the getter method getAuthenticateServerResponse(). The typical implementation of a getter returns the field's value. Therefore the next line should be the return statement for that field.", "reasoning_model_answer": "return authenticateServerResponse;", "assistant_with_reasoning": "\nThe class defines a private String field named authenticateServerResponse and is currently inside the getter method getAuthenticateServerResponse(). The typical implementation of a getter returns the field's value. Therefore the next line should be the return statement for that field.\n\nreturn authenticateServerResponse;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.846, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20901, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return authenticateServerResponse;", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.List;\nimport java.util.Map;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;\nimport me.pepperbell.continuity.api.client.CTMLoader;\nimport me.pepperbell.continuity.api.client.CTMLoaderRegistry;\nimport me.pepperbell.continuity.api.client.CTMPropertiesFactory;\nimport me.pepperbell.continuity.client.event.AddBlockStateModelCallback;\nimport me.pepperbell.continuity.client.event.ModelsAddedCallback;\nimport me.pepperbell.continuity.client.handler.AddBlockStateModelCallbackHandler;\nimport me.pepperbell.continuity.client.handler.ClientPlayJoinHandler;\nimport me.pepperbell.continuity.client.handler.ClientStartedHandler;\nimport me.pepperbell.continuity.client.handler.ModelsAddedCallbackHandler;\nimport me.pepperbell.continuity.client.processor.CompactCTMQuadProcessor;\nimport me.pepperbell.continuity.client.processor.HorizontalQuadProcessor;\nimport me.pepperbell.continuity.client.processor.HorizontalVerticalQuadProcessor;\nimport me.pepperbell.continuity.client.processor.ProcessingDataKeys;\nimport me.pepperbell.continuity.client.processor.TopQuadProcessor;\nimport me.pepperbell.continuity.client.processor.VerticalHorizontalQuadProcessor;\nimport me.pepperbell.continuity.client.processor.VerticalQuadProcessor;\nimport me.pepperbell.continuity.client.processor.overlay.SimpleOverlayQuadProcessor;\nimport me.pepperbell.continuity.client.processor.overlay.StandardOverlayQuadProcessor;\nimport me.pepperbell.continuity.client.processor.simple.CTMSpriteProvider;\nimport me.pepperbell.continuity.client.processor.simple.FixedSpriteProvider;\nimport me.pepperbell.continuity.client.processor.simple.RandomSpriteProvider;\nimport me.pepperbell.continuity.client.processor.simple.RepeatSpriteProvider;\nimport me.pepperbell.continuity.client.processor.simple.SimpleQuadProcessor;\nimport me.pepperbell.continuity.client.properties.BaseCTMProperties;\nimport me.pepperbell.continuity.client.properties.CompactConnectingCTMProperties;\nimport me.pepperbell.continuity.client.properties.ConnectingCTMProperties;\nimport me.pepperbell.continuity.client.properties.RandomCTMProperties;\nimport me.pepperbell.continuity.client.properties.RepeatCTMProperties;\nimport me.pepperbell.continuity.client.properties.StandardConnectingCTMProperties;\nimport me.pepperbell.continuity.client.properties.TileAmountValidator;\nimport me.pepperbell.continuity.client.properties.overlay.BaseOverlayCTMProperties;\nimport me.pepperbell.continuity.client.properties.overlay.RandomOverlayCTMProperties;\nimport me.pepperbell.continuity.client.properties.overlay.RepeatOverlayCTMProperties;\nimport me.pepperbell.continuity.client.properties.overlay.StandardConnectingOverlayCTMProperties;\nimport me.pepperbell.continuity.client.properties.overlay.StandardOverlayCTMProperties;\nimport me.pepperbell.continuity.client.resource.CTMLoadingContainer;\nimport me.pepperbell.continuity.client.resource.CustomBlockLayers;\nimport me.pepperbell.continuity.client.util.biome.BiomeRetriever;\nimport net.fabricmc.api.ClientModInitializer;\nimport net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;\nimport net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;\nimport net.fabricmc.fabric.api.resource.ResourceManagerHelper;\nimport net.fabricmc.fabric.api.resource.ResourcePackActivationType;\nimport net.fabricmc.loader.api.FabricLoader;\nimport net.minecraft.block.BlockState;\nimport net.minecraft.client.util.ModelIdentifier;\nimport net.minecraft.util.Identifier;", "context": "src/main/java/me/pepperbell/continuity/client/ContinuityClient.java\npackage me.pepperbell.continuity.client;\n\n\n\n\npublic class ContinuityClient implements ClientModInitializer {\n\tpublic static final String ID = \"continuity\";\n\tpublic static final String NAME = \"Continuity\";\n\tpublic static final Logger LOGGER = LogManager.getLogger(NAME);\n\n\nsrc/main/java/me/pepperbell/continuity/client/processor/simple/FixedSpriteProvider.java\npublic class FixedSpriteProvider implements SpriteProvider {\n\tprotected Sprite sprite;\n\n\tpublic FixedSpriteProvider(Sprite sprite) {\n\t\tthis.sprite = sprite;\n\t}\n\n\t@Override\n\tpublic Sprite getSprite(QuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier randomSupplier, ProcessingDataProvider dataProvider) {\n\t\treturn this.sprite;\n\t}\n\n\tpublic static class Factory implements SpriteProvider.Factory {\n\t\t@Override\n\t\tpublic SpriteProvider createSpriteProvider(Sprite[] sprites, BaseCTMProperties properties) {\n\t\t\treturn new FixedSpriteProvider(sprites[0]);\n\t\t}\n\n\t\t@Override\n\t\tpublic int getTextureAmount(BaseCTMProperties properties) {\n\t\t\treturn 1;\n\t\t}\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/properties/CompactConnectingCTMProperties.java\npublic class CompactConnectingCTMProperties extends StandardConnectingCTMProperties {\n\tprotected Int2IntMap tileReplacementMap;\n\n\tpublic CompactConnectingCTMProperties(Properties properties, Identifier id, String packName, int packPriority, String method) {\n\t\tsuper(properties, id, packName, packPriority, method);\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\tsuper.init();\n\t\tparseTileReplacements();\n\t}\n\n\tprotected void parseTileReplacements() {\n\t\tfor (String key : properties.stringPropertyNames()) {\n\t\t\tif (key.startsWith(\"ctm.\")) {\n\t\t\t\tString indexStr = key.substring(4);\n\t\t\t\tint index;\n\t\t\t\ttry {\n\t\t\t\t\tindex = Integer.parseInt(indexStr);\n\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (index < 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tString valueStr = properties.getProperty(key);\n\t\t\t\tint value;\n\t\t\t\ttry {\n\t\t\t\t\tvalue = Integer.parseInt(valueStr);\n\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\tContinuityClient.LOGGER.warn(\"Invalid '\" + key + \"' value '\" + valueStr + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// TODO: deduplicate code\n\t\t\t\tif (value < 0) {\n\t\t\t\t\tContinuityClient.LOGGER.warn(\"Invalid '\" + key + \"' value '\" + valueStr + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (tileReplacementMap == null) {\n\t\t\t\t\ttileReplacementMap = new Int2IntArrayMap();\n\t\t\t\t}\n\t\t\t\ttileReplacementMap.put(index, value);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean isValidForMultipass() {\n\t\treturn false;\n\t}\n\n\tpublic Int2IntMap getTileReplacementMap() {\n\t\treturn tileReplacementMap;\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/properties/overlay/StandardConnectingOverlayCTMProperties.java\npublic class StandardConnectingOverlayCTMProperties extends StandardConnectingCTMProperties implements OverlayPropertiesSection.Provider {\n\tprotected OverlayPropertiesSection overlaySection;\n\n\tpublic StandardConnectingOverlayCTMProperties(Properties properties, Identifier id, String packName, int packPriority, String method) {\n\t\tsuper(properties, id, packName, packPriority, method);\n\t\toverlaySection = new OverlayPropertiesSection(properties, id, packName);\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\tsuper.init();\n\t\toverlaySection.init();\n\t}\n\n\t@Override\n\tpublic OverlayPropertiesSection getOverlayPropertiesSection() {\n\t\treturn overlaySection;\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/event/AddBlockStateModelCallback.java\npublic interface AddBlockStateModelCallback {\n\tEvent EVENT = EventFactory.createArrayBacked(AddBlockStateModelCallback.class,\n\t\t\tlisteners -> (id, state, model, modelLoader) -> {\n\t\t\t\tfor (AddBlockStateModelCallback callback : listeners) {\n\t\t\t\t\tcallback.onAddBlockStateModel(id, state, model, modelLoader);\n\t\t\t\t}\n\t\t\t}\n\t);\n\n\tvoid onAddBlockStateModel(ModelIdentifier id, BlockState state, UnbakedModel model, ModelLoader modelLoader);\n}\n\nsrc/main/java/me/pepperbell/continuity/client/properties/RepeatCTMProperties.java\npublic class RepeatCTMProperties extends BaseCTMProperties {\n\tprotected int width;\n\tprotected int height;\n\tprotected Symmetry symmetry = Symmetry.NONE;\n\n\tpublic RepeatCTMProperties(Properties properties, Identifier id, String packName, int packPriority, String method) {\n\t\tsuper(properties, id, packName, packPriority, method);\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\tsuper.init();\n\t\tparseWidth();\n\t\tparseHeight();\n\t\tparseSymmetry();\n\t}\n\n\tprotected void parseWidth() {\n\t\tString widthStr = properties.getProperty(\"width\");\n\t\tif (widthStr != null) {\n\t\t\twidthStr = widthStr.trim();\n\t\t\ttry {\n\t\t\t\tint width = Integer.parseInt(widthStr);\n\t\t\t\tif (width > 0) {\n\t\t\t\t\tthis.width = width;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t//\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.error(\"Invalid 'width' value '\" + widthStr + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t\tvalid = false;\n\t\t}\n\t}\n\n\tprotected void parseHeight() {\n\t\tString heightStr = properties.getProperty(\"height\");\n\t\tif (heightStr != null) {\n\t\t\theightStr = heightStr.trim();\n\t\t\ttry {\n\t\t\t\tint height = Integer.parseInt(heightStr);\n\t\t\t\tif (height > 0) {\n\t\t\t\t\tthis.height = height;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t//\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.error(\"Invalid 'height' value '\" + heightStr + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t\tvalid = false;\n\t\t}\n\t}\n\n\tprotected void parseSymmetry() {\n\t\tSymmetry symmetry = PropertiesParsingHelper.parseSymmetry(properties, \"symmetry\", id, packName);\n\t\tif (symmetry != null) {\n\t\t\tthis.symmetry = symmetry;\n\t\t}\n\t}\n\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn height;\n\t}\n\n\tpublic Symmetry getSymmetry() {\n\t\treturn symmetry;\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/api/client/CTMLoader.java\npublic interface CTMLoader {\n\tCTMPropertiesFactory getPropertiesFactory();\n\n\tQuadProcessorFactory getProcessorFactory();\n\n\tstatic CTMLoader of(CTMPropertiesFactory propertiesFactory, QuadProcessorFactory processorFactory) {\n\t\treturn new CTMLoader() {\n\t\t\t@Override\n\t\t\tpublic CTMPropertiesFactory getPropertiesFactory() {\n\t\t\t\treturn propertiesFactory;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic QuadProcessorFactory getProcessorFactory() {\n\t\t\t\treturn processorFactory;\n\t\t\t}\n\t\t};\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/processor/VerticalHorizontalQuadProcessor.java\npublic class VerticalHorizontalQuadProcessor extends VerticalQuadProcessor {\n\t// Indices for this array are formed from these bit values:\n\t// 32 16\n\t// 1 * 8\n\t// 2 4\n\tprotected static final int[] SPRITE_INDEX_MAP_1 = new int[] {\n\t\t\t3, 6, 3, 3, 3, 6, 3, 3, 4, 5, 4, 4, 3, 6, 3, 3,\n\t\t\t3, 6, 3, 3, 3, 6, 3, 3, 3, 6, 3, 3, 3, 6, 3, 3,\n\t\t\t3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3,\n\t\t\t3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n\t};\n\n\tpublic VerticalHorizontalQuadProcessor(Sprite[] sprites, ProcessingPredicate processingPredicate, ConnectionPredicate connectionPredicate) {\n\t\tsuper(sprites, processingPredicate, connectionPredicate);\n\t}\n\n\t@Override\n\tpublic ProcessingResult processQuadInner(MutableQuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier randomSupplier, int pass, int processorIndex, ProcessingContext context) {\n\t\tDirection[] directions = DirectionMaps.getDirections(quad);\n\t\tBlockPos.Mutable mutablePos = context.getData(ProcessingDataKeys.MUTABLE_POS_KEY);\n\t\tint connections = getConnections(directions, mutablePos, blockView, state, pos, quad.lightFace(), sprite);\n\t\tSprite newSprite;\n\t\tif (connections != 0) {\n\t\t\tnewSprite = sprites[SPRITE_INDEX_MAP[connections]];\n\t\t} else {\n\t\t\tconnections = getConnections1(directions, mutablePos, blockView, state, pos, quad.lightFace(), sprite);\n\t\t\tnewSprite = sprites[SPRITE_INDEX_MAP_1[connections]];\n\t\t}\n\t\treturn SimpleQuadProcessor.process(quad, sprite, newSprite);\n\t}\n\n\tprotected int getConnections1(Direction[] directions, BlockPos.Mutable mutablePos, BlockRenderView blockView, BlockState state, BlockPos pos, Direction face, Sprite quadSprite) {\n\t\tmutablePos.set(pos);\n\t\tint connections = 0;\n\t\tfor (int i = 0; i < 2; i++) {\n\t\t\tmutablePos.move(directions[i * 2]);\n\t\t\tif (connectionPredicate.shouldConnect(state, quadSprite, pos, mutablePos, face, blockView)) {\n\t\t\t\tconnections |= 1 << i * 3;\n\t\t\t}\n\t\t\tmutablePos.set(pos);\n\t\t}\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint shift = (i / 2) * 3;\n\t\t\tint index1 = i;\n\t\t\tint index2 = (i + 1) % 4;\n\t\t\tif (((connections >> shift) & 1) == 1) {\n\t\t\t\tmutablePos.move(directions[index1]).move(directions[index2]);\n\t\t\t\tif (connectionPredicate.shouldConnect(state, quadSprite, pos, mutablePos, face, blockView)) {\n\t\t\t\t\tconnections |= 1 << (shift + i % 2 + 1);\n\t\t\t\t}\n\t\t\t\tmutablePos.set(pos);\n\t\t\t}\n\t\t}\n\t\treturn connections;\n\t}\n\n\tpublic static class Factory extends AbstractQuadProcessorFactory {\n\t\t@Override\n\t\tpublic QuadProcessor createProcessor(ConnectingCTMProperties properties, Sprite[] sprites) {\n\t\t\treturn new VerticalHorizontalQuadProcessor(sprites, BaseProcessingPredicate.fromProperties(properties), properties.getConnectionPredicate());\n\t\t}\n\n\t\t@Override\n\t\tpublic int getTextureAmount(ConnectingCTMProperties properties) {\n\t\t\treturn 7;\n\t\t}\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/properties/StandardConnectingCTMProperties.java\npublic class StandardConnectingCTMProperties extends ConnectingCTMProperties {\n\tprotected boolean innerSeams = false;\n\n\tpublic StandardConnectingCTMProperties(Properties properties, Identifier id, String packName, int packPriority, String method) {\n\t\tsuper(properties, id, packName, packPriority, method);\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\tsuper.init();\n\t\tparseInnerSeams();\n\t}\n\n\tprotected void parseInnerSeams() {\n\t\tString innerSeamsStr = properties.getProperty(\"innerSeams\");\n\t\tif (innerSeamsStr != null) {\n\t\t\tinnerSeamsStr = innerSeamsStr.trim();\n\t\t\tinnerSeams = Boolean.parseBoolean(innerSeamsStr);\n\t\t}\n\t}\n\n\tpublic boolean getInnerSeams() {\n\t\treturn innerSeams;\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/handler/ModelsAddedCallbackHandler.java\npublic class ModelsAddedCallbackHandler implements ModelsAddedCallback {\n\tprivate final Map modelId2StateMap;\n\tprivate final Map>> modelId2ContainersMap;\n\n\tpublic ModelsAddedCallbackHandler(Map modelId2StateMap, Map>> modelId2ContainersMap) {\n\t\tthis.modelId2StateMap = modelId2StateMap;\n\t\tthis.modelId2ContainersMap = modelId2ContainersMap;\n\t}\n\n\t@Override\n\tpublic void onModelsAdded(ModelLoader modelLoader, ResourceManager resourceManager, Profiler profiler, Map unbakedModels, Map modelsToBake) {\n\t\tObject2ObjectOpenHashMap wrappedModels = new Object2ObjectOpenHashMap<>();\n\n\t\tUnbakedModel missingModel = unbakedModels.get(ModelLoader.MISSING_ID);\n\t\tFunction unbakedModelGetter = id -> {\n\t\t\tUnbakedModel model = unbakedModels.get(id);\n\t\t\tif (model == null) {\n\t\t\t\treturn missingModel;\n\t\t\t}\n\t\t\treturn model;\n\t\t};\n\t\tVoidSet> voidSet = VoidSet.get();\n\t\tCollectionBasedConsumer> reusableConsumer = new CollectionBasedConsumer<>();\n\n\t\t// Check which models should be wrapped\n\t\tfor (Map.Entry entry : unbakedModels.entrySet()) {\n\t\t\tif (entry.getKey() instanceof ModelIdentifier) {\n\t\t\t\tModelIdentifier id = (ModelIdentifier)entry.getKey();\n\n\t\t\t\t// Only wrap final block state models\n\t\t\t\tif (isBlockStateModelId(id)) {\n\t\t\t\t\tUnbakedModel model = entry.getValue();\n\t\t\t\t\tCollection dependencies = model.getTextureDependencies(unbakedModelGetter, voidSet);\n\t\t\t\t\tList> containerList = modelId2ContainersMap.get(id);\n\t\t\t\t\tif (containerList == null) {\n\t\t\t\t\t\tcontainerList = CTMPropertiesLoader.getAllAffecting(dependencies);\n\t\t\t\t\t\tif (containerList == null) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treusableConsumer.setCollection(containerList);\n\t\t\t\t\t\tCTMPropertiesLoader.consumeAllAffecting(dependencies, reusableConsumer);\n\t\t\t\t\t}\n\t\t\t\t\tcontainerList.sort(Collections.reverseOrder());\n\n\t\t\t\t\tSet> multipassContainerSet = null;\n\t\t\t\t\tint amount = containerList.size();\n\t\t\t\t\tfor (int i = 0; i < amount; i++) {\n\t\t\t\t\t\tCTMLoadingContainer container = containerList.get(i);\n\t\t\t\t\t\tSet> dependents = container.getRecursiveMultipassDependents();\n\t\t\t\t\t\tif (dependents != null) {\n\t\t\t\t\t\t\tif (multipassContainerSet == null) {\n\t\t\t\t\t\t\t\tmultipassContainerSet = new ObjectArraySet<>();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmultipassContainerSet.addAll(dependents);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tList> multipassContainerList = null;\n\t\t\t\t\tif (multipassContainerSet != null) {\n\t\t\t\t\t\tBlockState state = modelId2StateMap.get(id);\n\t\t\t\t\t\tfor (CTMLoadingContainer container : multipassContainerSet) {\n\t\t\t\t\t\t\tif (!container.getProperties().affectsBlockStates() || container.getProperties().affectsBlockState(state)) {\n\t\t\t\t\t\t\t\tif (multipassContainerList == null) {\n\t\t\t\t\t\t\t\t\tmultipassContainerList = new ObjectArrayList<>();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmultipassContainerList.add(container);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (multipassContainerList != null) {\n\t\t\t\t\t\t\tmultipassContainerList.sort(Collections.reverseOrder());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\twrappedModels.put(id, new CTMUnbakedModel(model, containerList, multipassContainerList));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tmodelId2StateMap.clear();\n\t\tmodelId2ContainersMap.clear();\n\n\t\t// Inject wrapped models\n\t\tObjectIterator> iterator = wrappedModels.object2ObjectEntrySet().fastIterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\tObject2ObjectMap.Entry entry = iterator.next();\n\t\t\tIdentifier id = entry.getKey();\n\t\t\tUnbakedModel wrapped = entry.getValue();\n\n\t\t\tunbakedModels.put(id, wrapped);\n\t\t\tif (modelsToBake.containsKey(id)) {\n\t\t\t\tmodelsToBake.put(id, wrapped);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate boolean isBlockStateModelId(ModelIdentifier id) {\n\t\treturn !id.getVariant().equals(\"inventory\");\n\t}\n\n\tprivate static class CollectionBasedConsumer implements Consumer {\n\t\tprivate Collection collection;\n\n\t\t@Override\n\t\tpublic void accept(T t) {\n\t\t\tcollection.add(t);\n\t\t}\n\n\t\tpublic void setCollection(Collection collection) {\n\t\t\tthis.collection = collection;\n\t\t}\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/properties/TileAmountValidator.java\npublic interface TileAmountValidator {\n\tboolean validateTileAmount(int amount, T properties);\n\n\tstatic CTMPropertiesFactory wrapFactory(CTMPropertiesFactory factory, TileAmountValidator validator) {\n\t\treturn (properties, id, packName, packPriority, method) -> {\n\t\t\tT ctmProperties = factory.createProperties(properties, id, packName, packPriority, method);\n\t\t\tif (ctmProperties == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (validator.validateTileAmount(ctmProperties.tiles.size(), ctmProperties)) {\n\t\t\t\treturn ctmProperties;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t}\n\n\tclass Exactly implements TileAmountValidator {\n\t\tprotected final int targetAmount;\n\n\t\tpublic Exactly(int targetAmount) {\n\t\t\tthis.targetAmount = targetAmount;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean validateTileAmount(int amount, T properties) {\n\t\t\tif (amount == targetAmount) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.error(\"Method '\" + properties.getMethod() + \"' requires exactly \" + targetAmount + \" tiles but \" + amount + \" were provided in file '\" + properties.getId() + \"' in pack '\" + properties.getPackName() + \"'\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tclass AtLeast implements TileAmountValidator {\n\t\tprotected final int targetAmount;\n\n\t\tpublic AtLeast(int targetAmount) {\n\t\t\tthis.targetAmount = targetAmount;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean validateTileAmount(int amount, T properties) {\n\t\t\tif (amount >= targetAmount) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.error(\"Method '\" + properties.getMethod() + \"' requires at least \" + targetAmount + \" tiles but only \" + amount + \" were provided in file '\" + properties.getId() + \"' in pack '\" + properties.getPackName() + \"'\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tclass Repeat implements TileAmountValidator {\n\t\t@Override\n\t\tpublic boolean validateTileAmount(int amount, T properties) {\n\t\t\tint targetAmount = properties.getWidth() * properties.getHeight();\n\t\t\tif (amount == targetAmount) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.error(\"Method '\" + properties.getMethod() + \"' requires exactly \" + targetAmount + \" tiles but \" + amount + \" were provided in file '\" + properties.getId() + \"' in pack '\" + properties.getPackName() + \"'\");\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/processor/HorizontalQuadProcessor.java\npublic class HorizontalQuadProcessor extends ConnectingQuadProcessor {\n\t// Indices for this array are formed from these bit values:\n\t// 1 * 2\n\tprotected static final int[] SPRITE_INDEX_MAP = new int[] {\n\t\t\t3, 2, 0, 1,\n\t};\n\n\tpublic HorizontalQuadProcessor(Sprite[] sprites, ProcessingPredicate processingPredicate, ConnectionPredicate connectionPredicate) {\n\t\tsuper(sprites, processingPredicate, connectionPredicate);\n\t}\n\n\t@Override\n\tpublic ProcessingResult processQuadInner(MutableQuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier randomSupplier, int pass, int processorIndex, ProcessingContext context) {\n\t\tDirection[] directions = DirectionMaps.getDirections(quad);\n\t\tBlockPos.Mutable mutablePos = context.getData(ProcessingDataKeys.MUTABLE_POS_KEY);\n\t\tint connections = getConnections(directions, mutablePos, blockView, state, pos, quad.lightFace(), sprite);\n\t\tSprite newSprite = sprites[SPRITE_INDEX_MAP[connections]];\n\t\treturn SimpleQuadProcessor.process(quad, sprite, newSprite);\n\t}\n\n\tprotected int getConnections(Direction[] directions, BlockPos.Mutable mutablePos, BlockRenderView blockView, BlockState state, BlockPos pos, Direction face, Sprite quadSprite) {\n\t\tmutablePos.set(pos);\n\t\tint connections = 0;\n\t\tfor (int i = 0; i < 2; i++) {\n\t\t\tmutablePos.move(directions[i * 2]);\n\t\t\tif (connectionPredicate.shouldConnect(state, quadSprite, pos, mutablePos, face, blockView)) {\n\t\t\t\tconnections |= 1 << i;\n\t\t\t}\n\t\t\tmutablePos.set(pos);\n\t\t}\n\t\treturn connections;\n\t}\n\n\tpublic static class Factory extends AbstractQuadProcessorFactory {\n\t\t@Override\n\t\tpublic QuadProcessor createProcessor(ConnectingCTMProperties properties, Sprite[] sprites) {\n\t\t\treturn new HorizontalQuadProcessor(sprites, BaseProcessingPredicate.fromProperties(properties), properties.getConnectionPredicate());\n\t\t}\n\n\t\t@Override\n\t\tpublic int getTextureAmount(ConnectingCTMProperties properties) {\n\t\t\treturn 4;\n\t\t}\n\t}\n}\n\nsrc/main/java/me/pepperbell/continuity/client/processor/overlay/StandardOverlayQuadProcessor.java\npublic class StandardOverlayQuadProcessor extends AbstractQuadProcessor {\n\tprotected Set matchTilesSet;\n\tprotected Predicate matchBlocksPredicate;\n\tprotected Set connectTilesSet;\n\tprotected Predicate connectBlocksPredicate;\n\tprotected ConnectionPredicate connectionPredicate;\n\n\tprotected int tintIndex;\n\tprotected BlockState tintBlock;\n\tprotected RenderMaterial material;\n\n\tpublic StandardOverlayQuadProcessor(Sprite[] sprites, ProcessingPredicate processingPredicate, Set matchTilesSet, Predicate matchBlocksPredicate, Set connectTilesSet, Predicate connectBlocksPredicate, ConnectionPredicate connectionPredicate, int tintIndex, BlockState tintBlock, BlendMode layer) {\n\t\tsuper(sprites, processingPredicate);\n\t\tthis.matchTilesSet = matchTilesSet;\n\t\tthis.matchBlocksPredicate = matchBlocksPredicate;\n\t\tthis.connectTilesSet = connectTilesSet;\n\t\tthis.connectBlocksPredicate = connectBlocksPredicate;\n\t\tthis.connectionPredicate = connectionPredicate;\n\n\t\tthis.tintIndex = tintIndex;\n\t\tthis.tintBlock = tintBlock;\n\t\tmaterial = RenderUtil.getMaterialFinder().blendMode(0, layer).find();\n\t}\n\n\t@Override\n\tpublic ProcessingResult processQuadInner(MutableQuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier randomSupplier, int pass, int processorIndex, ProcessingContext context) {\n\t\tDirection lightFace = quad.lightFace();\n\t\tOverlayRenderer renderer = getRenderer(blockView, pos, state, lightFace, sprite, DirectionMaps.getMap(lightFace)[0], context);\n\t\tif (renderer != null) {\n\t\t\tcontext.addEmitterConsumer(renderer);\n\t\t}\n\t\treturn ProcessingResult.CONTINUE;\n\t}\n\n\tprotected boolean appliesOverlay(BlockState other, BlockState state, Direction face, Sprite quadSprite, BlockPos pos, BlockRenderView blockView) {\n\t\tif (other.getBlock().hasDynamicBounds()) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!other.isFullCube(EmptyBlockView.INSTANCE, BlockPos.ORIGIN)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (connectBlocksPredicate != null) {\n\t\t\tif (!connectBlocksPredicate.test(other)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (connectTilesSet != null) {\n\t\t\tif (!connectTilesSet.contains(SpriteCalculator.getSprite(other, face).getId())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn !connectionPredicate.shouldConnect(state, quadSprite, pos, other, face, blockView);\n\t}\n\n\tprotected boolean hasSameOverlay(BlockState other, BlockState state, Direction face, Sprite quadSprite, BlockPos pos, BlockRenderView blockView) {\n\t\tif (matchBlocksPredicate != null) {\n\t\t\tif (!matchBlocksPredicate.test(other)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (matchTilesSet != null) {\n\t\t\tif (!matchTilesSet.contains(SpriteCalculator.getSprite(other, face).getId())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tprotected void appliesOverlayUnobscured(Direction direction0, BlockStateAndBoolean blockStateAndBoolean, BlockRenderView blockView, BlockPos pos, BlockState state, Direction lightFace, Sprite quadSprite, BlockPos.Mutable mutablePos) {\n\t\tmutablePos.move(direction0);\n\t\tBlockState state0 = blockView.getBlockState(mutablePos);\n\t\tboolean bool = appliesOverlay(state0, state, lightFace, quadSprite, pos, blockView);\n\t\tif (bool) {\n\t\t\tmutablePos.move(lightFace);\n\t\t\tif (blockView.getBlockState(mutablePos).isOpaqueFullCube(blockView, mutablePos)) {\n\t\t\t\tbool = false;\n\t\t\t}\n\t\t}\n\t\tmutablePos.set(pos);\n\t\tblockStateAndBoolean.state = state0;\n\t\tblockStateAndBoolean.bool = bool;\n\t}\n\n\tprotected boolean hasSameOverlayUnobscured(BlockState state0, Direction direction0, BlockRenderView blockView, BlockPos pos, BlockState state, Direction lightFace, Sprite quadSprite, BlockPos.Mutable mutablePos) {\n\t\tboolean s0 = hasSameOverlay(state0, state, lightFace, quadSprite, pos, blockView);\n\t\tif (s0) {\n\t\t\tmutablePos.move(direction0).move(lightFace);\n\t\t\tif (blockView.getBlockState(mutablePos).isOpaqueFullCube(blockView, mutablePos)) {\n\t\t\t\ts0 = false;\n\t\t\t}\n\t\t\tmutablePos.set(pos);\n\t\t}\n\t\treturn s0;\n\t}\n\n\tprotected boolean appliesOverlayCorner(Direction direction0, Direction direction1, BlockRenderView blockView, BlockPos pos, BlockState state, Direction lightFace, Sprite quadSprite, BlockPos.Mutable mutablePos) {\n\t\tmutablePos.move(direction0).move(direction1);\n\t\tboolean corner0 = appliesOverlay(blockView.getBlockState(mutablePos), state, lightFace, quadSprite, pos, blockView);\n\t\tif (corner0) {\n\t\t\tmutablePos.move(lightFace);\n\t\t\tif (blockView.getBlockState(mutablePos).isOpaqueFullCube(blockView, mutablePos)) {\n\t\t\t\tcorner0 = false;\n\t\t\t}\n\t\t}\n\t\tmutablePos.set(pos);\n\t\treturn corner0;\n\t}\n\n\tprotected OverlayRenderer fromCorner(Direction direction0, Direction direction1, int sprite0, int sprite1, OverlayRenderer renderer, BlockRenderView blockView, BlockPos pos, BlockState state, Direction lightFace, Sprite quadSprite, BlockPos.Mutable mutablePos) {\n\t\tSprite[] rendererSprites = prepareRenderer(renderer, lightFace, blockView, pos);\n\t\tmutablePos.move(direction0).move(direction1);\n\t\tif (appliesOverlay(blockView.getBlockState(mutablePos), state, lightFace, quadSprite, pos, blockView)) {\n\t\t\tmutablePos.move(lightFace);\n\t\t\tif (!blockView.getBlockState(mutablePos).isOpaqueFullCube(blockView, mutablePos)) {\n\t\t\t\trendererSprites[1] = sprites[sprite1];\n\t\t\t}\n\t\t}\n\t\trendererSprites[0] = sprites[sprite0];\n\t\treturn renderer;\n\t}\n\n\tprotected OverlayRenderer fromOneSide(BlockState state0, BlockState state1, BlockState state2, Direction direction0, Direction direction1, Direction direction2, int sprite0, int sprite1, int sprite2, OverlayRenderer renderer, BlockRenderView blockView, BlockPos pos, BlockState state, Direction lightFace, Sprite quadSprite, BlockPos.Mutable mutablePos) {\n\t\tboolean s0 = hasSameOverlayUnobscured(state0, direction0, blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tboolean s1 = hasSameOverlayUnobscured(state1, direction1, blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tboolean s2 = hasSameOverlayUnobscured(state2, direction2, blockView, pos, state, lightFace, quadSprite, mutablePos);\n\n\t\tSprite[] rendererSprites = prepareRenderer(renderer, lightFace, blockView, pos);\n\t\trendererSprites[0] = sprites[sprite0];\n\t\tif (s0 | s1) {\n\t\t\tif (appliesOverlayCorner(direction0, direction1, blockView, pos, state, lightFace, quadSprite, mutablePos)) {\n\t\t\t\trendererSprites[1] = sprites[sprite1];\n\t\t\t}\n\t\t}\n\t\tif (s1 | s2) {\n\t\t\tif (appliesOverlayCorner(direction1, direction2, blockView, pos, state, lightFace, quadSprite, mutablePos)) {\n\t\t\t\trendererSprites[2] = sprites[sprite2];\n\t\t\t}\n\t\t}\n\t\treturn renderer;\n\t}\n\n\tprotected static OverlayRenderer getRenderer(ProcessingDataProvider dataProvider) {\n\t\treturn dataProvider.getData(ProcessingDataKeys.STANDARD_OVERLAY_RENDERER_POOL_KEY).getRenderer();\n\t}\n\n\tprotected Sprite[] prepareRenderer(OverlayRenderer renderer, Direction face, BlockRenderView blockView, BlockPos pos) {\n\t\treturn renderer.prepare(face, RenderUtil.getTintColor(tintBlock, blockView, pos, tintIndex), material);\n\t}\n\n\tprotected OverlayRenderer prepareRenderer(OverlayRenderer renderer, Direction face, BlockRenderView blockView, BlockPos pos, int sprite1) {\n\t\tSprite[] rendererSprites = prepareRenderer(renderer, face, blockView, pos);\n\t\trendererSprites[0] = sprites[sprite1];\n\t\treturn renderer;\n\t}\n\n\tprotected OverlayRenderer prepareRenderer(OverlayRenderer renderer, Direction face, BlockRenderView blockView, BlockPos pos, int sprite1, int sprite2) {\n\t\tSprite[] rendererSprites = prepareRenderer(renderer, face, blockView, pos);\n\t\trendererSprites[0] = sprites[sprite1];\n\t\trendererSprites[1] = sprites[sprite2];\n\t\treturn renderer;\n\t}\n\n\t/*\n\t0:\tD R (CORNER)\n\t1:\tD\n\t2:\tL D (CORNER)\n\t3:\tD R\n\t4:\tL D\n\t5:\tL D R\n\t6:\tL D T\n\t7:\tR\n\t8:\tL D R U\n\t9:\tL\n\t10:\tR U\n\t11:\tL U\n\t12:\tD R U\n\t13:\tL R U\n\t14:\tR U (CORNER)\n\t15:\tU\n\t16:\tL U (CORNER)\n\t */\n\tprotected OverlayRenderer getRenderer(BlockRenderView blockView, BlockPos pos, BlockState state, Direction lightFace, Sprite quadSprite, Direction[] directions, ProcessingDataProvider dataProvider) {\n\t\tBlockPos.Mutable mutablePos = dataProvider.getData(ProcessingDataKeys.MUTABLE_POS_KEY).set(pos);\n\t\tBlockStateAndBoolean blockStateAndBoolean = dataProvider.getData(ProcessingDataKeys.BLOCK_STATE_AND_BOOLEAN_KEY);\n\n\t\t//\n\n\t\tappliesOverlayUnobscured(directions[0], blockStateAndBoolean, blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tBlockState state0 = blockStateAndBoolean.state;\n\t\tboolean left = blockStateAndBoolean.bool;\n\t\tappliesOverlayUnobscured(directions[1], blockStateAndBoolean, blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tBlockState state1 = blockStateAndBoolean.state;\n\t\tboolean down = blockStateAndBoolean.bool;\n\t\tappliesOverlayUnobscured(directions[2], blockStateAndBoolean, blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tBlockState state2 = blockStateAndBoolean.state;\n\t\tboolean right = blockStateAndBoolean.bool;\n\t\tappliesOverlayUnobscured(directions[3], blockStateAndBoolean, blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tBlockState state3 = blockStateAndBoolean.state;\n\t\tboolean up = blockStateAndBoolean.bool;\n\n\t\t//\n\n\t\tif (left & down & right & up) {\n\t\t\treturn prepareRenderer(getRenderer(dataProvider), lightFace, blockView, pos, 8);\n\t\t}\n\t\tif (left & down & right) {\n\t\t\treturn prepareRenderer(getRenderer(dataProvider), lightFace, blockView, pos, 5);\n\t\t}\n\t\tif (left & down & up) {\n\t\t\treturn prepareRenderer(getRenderer(dataProvider), lightFace, blockView, pos, 6);\n\t\t}\n\t\tif (left & right & up) {\n\t\t\treturn prepareRenderer(getRenderer(dataProvider), lightFace, blockView, pos, 13);\n\t\t}\n\t\tif (down & right & up) {\n\t\t\treturn prepareRenderer(getRenderer(dataProvider), lightFace, blockView, pos, 12);\n\t\t}\n\n\t\tif (left & right) {\n\t\t\treturn prepareRenderer(getRenderer(dataProvider), lightFace, blockView, pos, 9, 7);\n\t\t}\n\t\tif (up & down) {\n\t\t\treturn prepareRenderer(getRenderer(dataProvider), lightFace, blockView, pos, 15, 1);\n\t\t}\n\n\t\tif (left & down) {\n\t\t\treturn fromCorner(directions[2], directions[3], 4, 14, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (down & right) {\n\t\t\treturn fromCorner(directions[0], directions[3], 3, 16, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (right & up) {\n\t\t\treturn fromCorner(directions[0], directions[1], 10, 2, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (up & left) {\n\t\t\treturn fromCorner(directions[1], directions[2], 11, 0, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\n\t\t//\n\n\t\tif (left) {\n\t\t\treturn fromOneSide(state1, state2, state3, directions[1], directions[2], directions[3], 9, 0, 14, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (down) {\n\t\t\treturn fromOneSide(state2, state3, state0, directions[2], directions[3], directions[0], 1, 14, 16, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (right) {\n\t\t\treturn fromOneSide(state3, state0, state1, directions[3], directions[0], directions[1], 7, 16, 2, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (up) {\n\t\t\treturn fromOneSide(state0, state1, state2, directions[0], directions[1], directions[2], 15, 2, 0, getRenderer(dataProvider), blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\n\t\t//\n\n\t\tboolean s0 = hasSameOverlayUnobscured(state0, directions[0], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tboolean s1 = hasSameOverlayUnobscured(state1, directions[1], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tboolean s2 = hasSameOverlayUnobscured(state2, directions[2], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\tboolean s3 = hasSameOverlayUnobscured(state3, directions[3], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\n\t\tboolean corner0 = false;\n\t\tboolean corner1 = false;\n\t\tboolean corner2 = false;\n\t\tboolean corner3 = false;\n\t\tif (s0 | s1) {\n\t\t\tcorner0 = appliesOverlayCorner(directions[0], directions[1], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (s1 | s2) {\n\t\t\tcorner1 = appliesOverlayCorner(directions[1], directions[2], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (s2 | s3) {\n\t\t\tcorner2 = appliesOverlayCorner(directions[2], directions[3], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\t\tif (s3 | s0) {\n\t\t\tcorner3 = appliesOverlayCorner(directions[3], directions[0], blockView, pos, state, lightFace, quadSprite, mutablePos);\n\t\t}\n\n\t\tif (corner0 | corner1 | corner2 | corner3) {\n\t\t\tOverlayRenderer renderer = getRenderer(dataProvider);\n\t\t\tSprite[] rendererSprites = prepareRenderer(renderer, lightFace, blockView, pos);\n\t\t\tif (corner0) {\n\t\t\t\trendererSprites[0] = sprites[2];\n\t\t\t}\n\t\t\tif (corner1) {\n\t\t\t\trendererSprites[1] = sprites[0];\n\t\t\t}\n\t\t\tif (corner2) {\n\t\t\t\trendererSprites[2] = sprites[14];\n\t\t\t}\n\t\t\tif (corner3) {\n\t\t\t\trendererSprites[3] = sprites[16];\n\t\t\t}\n\t\t\treturn renderer;\n\t\t}\n\n\t\t//\n\n\t\treturn null;\n\t}\n\n\tpublic static class BlockStateAndBoolean {\n\t\tpublic BlockState state;\n\t\tpublic boolean bool;\n\t}\n\n\tpublic static class OverlayRenderer implements Consumer {\n\t\tprotected static final Sprite[] EMPTY_SPRITES = new Sprite[4];\n\n\t\tprotected Sprite[] sprites = new Sprite[4];\n\t\tprotected Direction face;\n\t\tprotected int color;\n\t\tprotected RenderMaterial material;\n\n\t\t@Override\n\t\tpublic void accept(QuadEmitter emitter) {\n\t\t\tfor (Sprite sprite : sprites) {\n\t\t\t\tif (sprite != null && !TextureUtil.isMissingSprite(sprite)) {\n\t\t\t\t\tQuadUtil.emitOverlayQuad(emitter, face, sprite, color, material);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic Sprite[] prepare(Direction face, int color, RenderMaterial material) {\n\t\t\tSystem.arraycopy(EMPTY_SPRITES, 0, sprites, 0, EMPTY_SPRITES.length);\n\t\t\tthis.face = face;\n\t\t\tthis.color = color;\n\t\t\tthis.material = material;\n\t\t\treturn sprites;\n\t\t}\n\t}\n\n\tpublic static class OverlayRendererPool {\n\t\tprotected final List list = new ObjectArrayList<>();\n\t\tprotected int nextIndex = 0;\n\n\t\tpublic OverlayRenderer getRenderer() {\n\t\t\tif (nextIndex >= list.size()) {\n\t\t\t\tlist.add(new OverlayRenderer());\n\t\t\t}\n\t\t\tOverlayRenderer renderer = list.get(nextIndex);\n\t\t\tnextIndex++;\n\t\t\treturn renderer;\n\t\t}\n\n\t\tpublic void reset() {\n\t\t\tnextIndex = 0;\n\t\t}\n\t}\n\n\tpublic static class Factory extends AbstractQuadProcessorFactory {\n\t\t@Override\n\t\tpublic QuadProcessor createProcessor(StandardOverlayCTMProperties properties, Sprite[] sprites) {\n\t\t\tOverlayPropertiesSection overlaySection = properties.getOverlayPropertiesSection();\n\t\t\treturn new StandardOverlayQuadProcessor(sprites, OverlayProcessingPredicate.fromProperties(properties), properties.getMatchTilesSet(), properties.getMatchBlocksPredicate(), properties.getConnectTilesSet(), properties.getConnectBlocksPredicate(), properties.getConnectionPredicate(), overlaySection.getTintIndex(), overlaySection.getTintBlock(), overlaySection.getLayer());\n\t\t}\n\n\t\t@Override\n\t\tpublic int getTextureAmount(StandardOverlayCTMProperties properties) {\n\t\t\treturn 17;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean supportsNullSprites(StandardOverlayCTMProperties properties) {\n\t\t\treturn false;\n\t\t}\n\t}\n}", "answers": ["\t@Override"], "length": 3364, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "95a6a535-accc-4549-8da1-41820c978b77", "reasoning": "The ContinuityClient class opened earlier and defined static fields. After the import statements, the next logical code is to start implementing the required ClientModInitializer method. The first line of that implementation is the @Override annotation before the method signature.", "reasoning_model_answer": "@Override", "assistant_with_reasoning": "\nThe ContinuityClient class opened earlier and defined static fields. After the import statements, the next logical code is to start implementing the required ClientModInitializer method. The first line of that implementation is the @Override annotation before the method signature.\n\n@Override", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.62, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 38054, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "@Override", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.infineon.esim.lpa.core.es9plus.Es9PlusInterface;\nimport com.infineon.esim.util.Log;\nimport com.gsma.sgp.messages.rspdefinitions.CancelSessionReason;\nimport com.gsma.sgp.messages.rspdefinitions.CancelSessionRequest;\nimport com.gsma.sgp.messages.rspdefinitions.CancelSessionRequestEs9;\nimport com.gsma.sgp.messages.rspdefinitions.CancelSessionResponse;\nimport com.gsma.sgp.messages.rspdefinitions.CancelSessionResponseEs9;\nimport com.infineon.esim.lpa.core.dtos.ProfileDownloadSession;\nimport com.infineon.esim.lpa.core.es10.Es10Interface;", "context": "core/src/main/java/com/infineon/esim/lpa/core/worker/remote/CancelSessionWorker.java\n/*\n * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED \"AS IS\". INFINEON\n * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,\n * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,\n * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES\n * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER\n * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR\n * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.\n *\n * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR\n * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR\n * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR\n * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE\n * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION\n * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR\n * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON\n * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.\n *\n * (C)Copyright INFINEON TECHNOLOGIES All rights reserved\n */\n\npackage com.infineon.esim.lpa.core.worker.remote;\n\n\npublic class CancelSessionWorker {\n private static final String TAG = CancelSessionWorker.class.getName();\n\n private final ProfileDownloadSession profileDownloadSession;\n\n private final Es10Interface es10Interface;\n private final Es9PlusInterface es9PlusInterface;\n\n public CancelSessionWorker(ProfileDownloadSession profileDownloadSession) {\n this.profileDownloadSession = profileDownloadSession;\n this.es10Interface = profileDownloadSession.getEs10Interface();\n\nmessages/src/main/java/com/gsma/sgp/messages/rspdefinitions/CancelSessionRequestEs9.java\npublic class CancelSessionRequestEs9 implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static final BerTag tag = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 65);\n\n\tpublic byte[] code = null;\n\tprivate TransactionId transactionId = null;\n\tprivate CancelSessionResponse cancelSessionResponse = null;\n\t\n\tpublic CancelSessionRequestEs9() {\n\t}\n\n\tpublic CancelSessionRequestEs9(byte[] code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic void setTransactionId(TransactionId transactionId) {\n\t\tthis.transactionId = transactionId;\n\t}\n\n\tpublic TransactionId getTransactionId() {\n\t\treturn transactionId;\n\t}\n\n\tpublic void setCancelSessionResponse(CancelSessionResponse cancelSessionResponse) {\n\t\tthis.cancelSessionResponse = cancelSessionResponse;\n\t}\n\n\tpublic CancelSessionResponse getCancelSessionResponse() {\n\t\treturn cancelSessionResponse;\n\t}\n\n\tpublic int encode(OutputStream reverseOS) throws IOException {\n\t\treturn encode(reverseOS, true);\n\t}\n\n\tpublic int encode(OutputStream reverseOS, boolean withTag) throws IOException {\n\n\t\tif (code != null) {\n\t\t\tfor (int i = code.length - 1; i >= 0; i--) {\n\t\t\t\treverseOS.write(code[i]);\n\t\t\t}\n\t\t\tif (withTag) {\n\t\t\t\treturn tag.encode(reverseOS) + code.length;\n\t\t\t}\n\t\t\treturn code.length;\n\t\t}\n\n\t\tint codeLength = 0;\n\t\tcodeLength += cancelSessionResponse.encode(reverseOS, false);\n\t\t// write tag: CONTEXT_CLASS, CONSTRUCTED, 1\n\t\treverseOS.write(0xA1);\n\t\tcodeLength += 1;\n\t\t\n\t\tcodeLength += transactionId.encode(reverseOS, false);\n\t\t// write tag: CONTEXT_CLASS, PRIMITIVE, 0\n\t\treverseOS.write(0x80);\n\t\tcodeLength += 1;\n\t\t\n\t\tcodeLength += BerLength.encodeLength(reverseOS, codeLength);\n\n\t\tif (withTag) {\n\t\t\tcodeLength += tag.encode(reverseOS);\n\t\t}\n\n\t\treturn codeLength;\n\n\t}\n\n\tpublic int decode(InputStream is) throws IOException {\n\t\treturn decode(is, true);\n\t}\n\n\tpublic int decode(InputStream is, boolean withTag) throws IOException {\n\t\tint codeLength = 0;\n\t\tint subCodeLength = 0;\n\t\tBerTag berTag = new BerTag();\n\n\t\tif (withTag) {\n\t\t\tcodeLength += tag.decodeAndCheck(is);\n\t\t}\n\n\t\tBerLength length = new BerLength();\n\t\tcodeLength += length.decode(is);\n\n\t\tint totalLength = length.val;\n\t\tcodeLength += totalLength;\n\n\t\tsubCodeLength += berTag.decode(is);\n\t\tif (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 0)) {\n\t\t\ttransactionId = new TransactionId();\n\t\t\tsubCodeLength += transactionId.decode(is, false);\n\t\t\tsubCodeLength += berTag.decode(is);\n\t\t}\n\t\telse {\n\t\t\tthrow new IOException(\"Tag does not match the mandatory sequence element tag.\");\n\t\t}\n\t\t\n\t\tif (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 1)) {\n\t\t\tcancelSessionResponse = new CancelSessionResponse();\n\t\t\tsubCodeLength += cancelSessionResponse.decode(is, false);\n\t\t\tif (subCodeLength == totalLength) {\n\t\t\t\treturn codeLength;\n\t\t\t}\n\t\t}\n\t\tthrow new IOException(\"Unexpected end of sequence, length tag: \" + totalLength + \", actual sequence length: \" + subCodeLength);\n\n\t\t\n\t}\n\n\tpublic void encodeAndSave(int encodingSizeGuess) throws IOException {\n\t\tReverseByteArrayOutputStream reverseOS = new ReverseByteArrayOutputStream(encodingSizeGuess);\n\t\tencode(reverseOS, false);\n\t\tcode = reverseOS.getArray();\n\t}\n\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendAsString(sb, 0);\n\t\treturn sb.toString();\n\t}\n\n\tpublic void appendAsString(StringBuilder sb, int indentLevel) {\n\n\t\tsb.append(\"{\");\n\t\tsb.append(\"\\n\");\n\t\tfor (int i = 0; i < indentLevel + 1; i++) {\n\t\t\tsb.append(\"\\t\");\n\t\t}\n\t\tif (transactionId != null) {\n\t\t\tsb.append(\"transactionId: \").append(transactionId);\n\t\t}\n\t\telse {\n\t\t\tsb.append(\"transactionId: \");\n\t\t}\n\t\t\n\t\tsb.append(\",\\n\");\n\t\tfor (int i = 0; i < indentLevel + 1; i++) {\n\t\t\tsb.append(\"\\t\");\n\t\t}\n\t\tif (cancelSessionResponse != null) {\n\t\t\tsb.append(\"cancelSessionResponse: \");\n\t\t\tcancelSessionResponse.appendAsString(sb, indentLevel + 1);\n\t\t}\n\t\telse {\n\t\t\tsb.append(\"cancelSessionResponse: \");\n\t\t}\n\t\t\n\t\tsb.append(\"\\n\");\n\t\tfor (int i = 0; i < indentLevel; i++) {\n\t\t\tsb.append(\"\\t\");\n\t\t}\n\t\tsb.append(\"}\");\n\t}\n\n}\n\nmessages/src/main/java/com/gsma/sgp/messages/rspdefinitions/CancelSessionReason.java\npublic class CancelSessionReason extends BerInteger {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic CancelSessionReason() {\n\t}\n\n\tpublic CancelSessionReason(byte[] code) {\n\t\tsuper(code);\n\t}\n\n\tpublic CancelSessionReason(BigInteger value) {\n\t\tsuper(value);\n\t}\n\n\tpublic CancelSessionReason(long value) {\n\t\tsuper(value);\n\t}\n\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/es10/Es10Interface.java\n@SuppressWarnings(\"unused\")\npublic class Es10Interface {\n private static final String TAG = Es10Interface.class.getName();\n\n private final EuiccChannel euiccChannel;\n\n public Es10Interface(EuiccChannel euiccChannel) {\n this.euiccChannel = euiccChannel;\n }\n\n // ES10a\n\n public EuiccConfiguredAddressesResponse es10a_getEuiccConfiguredAddresses() throws Exception {\n EuiccConfiguredAddressesRequest euiccConfiguredAddressesRequest = new EuiccConfiguredAddressesRequest();\n\n Log.debug(TAG, \"ES10 -> : \" + euiccConfiguredAddressesRequest);\n EuiccConfiguredAddressesResponse euiccConfiguredAddressesResponse = sendCommand(euiccConfiguredAddressesRequest, EuiccConfiguredAddressesResponse.class);\n Log.debug(TAG, \"ES10 <- : \" + euiccConfiguredAddressesResponse);\n\n return euiccConfiguredAddressesResponse;\n }\n\n public SetDefaultDpAddressResponse es10a_setDefaultDpAddress(BerUTF8String defaultDpAddress) throws Exception {\n SetDefaultDpAddressRequest setDefaultDpAddressRequest = new SetDefaultDpAddressRequest();\n setDefaultDpAddressRequest.setDefaultDpAddress(defaultDpAddress);\n\n Log.debug(TAG, \"ES10 -> : \" + setDefaultDpAddressRequest);\n SetDefaultDpAddressResponse setDefaultDpAddressResponse = sendCommand(setDefaultDpAddressRequest, SetDefaultDpAddressResponse.class);\n Log.debug(TAG, \"ES10 <- : \" + setDefaultDpAddressResponse);\n\n return setDefaultDpAddressResponse;\n }\n\n // ES10b\n\n public PrepareDownloadResponse es10b_prepareDownloadRequest(PrepareDownloadRequest prepareDownloadRequest) throws Exception {\n return sendCommand(prepareDownloadRequest, PrepareDownloadResponse.class);\n }\n\n public ProfileInstallationResult es10b_loadBoundProfilePackage(SegmentedBoundProfilePackage segmentedBoundProfilePackage) throws Exception {\n List> segments = segmentedBoundProfilePackage.getSegments();\n\n for(int i = 0; i < (segments.size() - 1); i++) {\n sendCommand(segments.get(i), null);\n }\n\n return sendCommand(segments.get(segments.size() - 1), ProfileInstallationResult.class);\n }\n\n public GetEuiccChallengeResponse es10b_getEuiccChallenge() throws Exception {\n GetEuiccChallengeRequest getEuiccChallengeRequest = new GetEuiccChallengeRequest();\n\n return sendCommand(getEuiccChallengeRequest, GetEuiccChallengeResponse.class);\n }\n\n public EUICCInfo1 es10b_getEuiccInfo1() throws Exception {\n GetEuiccInfo1Request getEuiccInfo1Request = new GetEuiccInfo1Request();\n\n return sendCommand(getEuiccInfo1Request, EUICCInfo1.class);\n }\n\n public EUICCInfo2 es10b_getEuiccInfo2() throws Exception {\n GetEuiccInfo2Request getEuiccInfo2Request = new GetEuiccInfo2Request();\n\n return sendCommand(getEuiccInfo2Request, EUICCInfo2.class);\n }\n\n public ListNotificationResponse es10b_listNotification(NotificationEvent notificationEvent) throws Exception {\n ListNotificationRequest listNotificationRequest = new ListNotificationRequest();\n listNotificationRequest.setProfileManagementOperation(notificationEvent);\n\n return sendCommand(listNotificationRequest, ListNotificationResponse.class);\n }\n\n public RetrieveNotificationsListResponse es10b_retrieveNotificationsListBySeqNumber(BerInteger seqNumber) throws Exception {\n RetrieveNotificationsListRequest.SearchCriteria searchCriteria = new RetrieveNotificationsListRequest.SearchCriteria();\n searchCriteria.setSeqNumber(seqNumber);\n\n return es10b_retrieveNotificationsListBySeqNumber(searchCriteria);\n }\n\n public RetrieveNotificationsListResponse es10b_retrieveNotificationsListByNotificationEvent(NotificationEvent notificationEvent) throws Exception {\n RetrieveNotificationsListRequest.SearchCriteria searchCriteria = new RetrieveNotificationsListRequest.SearchCriteria();\n searchCriteria.setProfileManagementOperation(notificationEvent);\n\n return es10b_retrieveNotificationsListBySeqNumber(searchCriteria);\n }\n\n private RetrieveNotificationsListResponse es10b_retrieveNotificationsListBySeqNumber(RetrieveNotificationsListRequest.SearchCriteria searchCriteria) throws Exception {\n RetrieveNotificationsListRequest retrieveNotificationsListRequest = new RetrieveNotificationsListRequest();\n retrieveNotificationsListRequest.setSearchCriteria(searchCriteria);\n\n return sendCommand(retrieveNotificationsListRequest, RetrieveNotificationsListResponse.class);\n }\n\n public NotificationSentResponse es10b_removeNotificationFromList(BerInteger seqNumber) throws Exception {\n NotificationSentRequest notificationSentRequest = new NotificationSentRequest();\n notificationSentRequest.setSeqNumber(seqNumber);\n\n return sendCommand(notificationSentRequest,NotificationSentResponse.class);\n }\n\n public AuthenticateServerResponse es10b_authenticateServer(AuthenticateServerRequest authenticateServerRequest) throws Exception {\n return sendCommand(authenticateServerRequest, AuthenticateServerResponse.class);\n }\n\n\n public CancelSessionResponse es10b_cancelSession(CancelSessionRequest cancelSessionRequest) throws Exception {\n return sendCommand(cancelSessionRequest, CancelSessionResponse.class);\n }\n\n // ES10c\n\n public ProfileInfoListResponse es10c_getProfilesInfoAll() throws Exception {\n ProfileInfoListRequest profileInfoListRequest = new ProfileInfoListRequest();\n\n return sendCommand(profileInfoListRequest, ProfileInfoListResponse.class);\n }\n\n public EnableProfileResponse es10c_enableProfileByIccid(Iccid iccid, BerBoolean refreshFlag) throws Exception {\n EnableProfileRequest.ProfileIdentifier profileIdentifier = new EnableProfileRequest.ProfileIdentifier();\n profileIdentifier.setIccid(iccid);\n\n return es10c_enableProfile(profileIdentifier,refreshFlag);\n }\n\n public EnableProfileResponse es10c_enableProfileByIsdpAid(OctetTo16 isdpAid, BerBoolean refreshFlag) throws Exception {\n EnableProfileRequest.ProfileIdentifier profileIdentifier = new EnableProfileRequest.ProfileIdentifier();\n profileIdentifier.setIsdpAid(isdpAid);\n\n return es10c_enableProfile(profileIdentifier, refreshFlag);\n }\n\n private EnableProfileResponse es10c_enableProfile(EnableProfileRequest.ProfileIdentifier profileIdentifier, BerBoolean refreshFlag) throws Exception {\n EnableProfileRequest enableProfileRequest = new EnableProfileRequest();\n enableProfileRequest.setProfileIdentifier(profileIdentifier);\n enableProfileRequest.setRefreshFlag(refreshFlag);\n\n return sendCommand(enableProfileRequest, EnableProfileResponse.class);\n }\n\n public DisableProfileResponse es10c_disableProfileByIccid(Iccid iccid, BerBoolean refreshFlag) throws Exception {\n DisableProfileRequest.ProfileIdentifier profileIdentifier = new DisableProfileRequest.ProfileIdentifier();\n profileIdentifier.setIccid(iccid);\n\n return es10c_disableProfile(profileIdentifier, refreshFlag);\n }\n\n public DisableProfileResponse es10c_disableProfileByIsdpAid(OctetTo16 isdpAid, BerBoolean refreshFlag) throws Exception {\n DisableProfileRequest.ProfileIdentifier profileIdentifier = new DisableProfileRequest.ProfileIdentifier();\n profileIdentifier.setIsdpAid(isdpAid);\n\n return es10c_disableProfile(profileIdentifier, refreshFlag);\n }\n\n private DisableProfileResponse es10c_disableProfile(DisableProfileRequest.ProfileIdentifier profileIdentifier, BerBoolean refreshFlag) throws Exception {\n DisableProfileRequest disableProfileRequest = new DisableProfileRequest();\n disableProfileRequest.setProfileIdentifier(profileIdentifier);\n disableProfileRequest.setRefreshFlag(refreshFlag);\n\n return sendCommand(disableProfileRequest, DisableProfileResponse.class);\n }\n\n public DeleteProfileResponse es10c_deleteProfileByIccid(Iccid iccid) throws Exception {\n DeleteProfileRequest deleteProfileRequest = new DeleteProfileRequest();\n deleteProfileRequest.setIccid(iccid);\n\n return sendCommand(deleteProfileRequest, DeleteProfileResponse.class);\n }\n\n public DeleteProfileResponse es10c_deleteProfileByIsdpAid(OctetTo16 isdpAid) throws Exception {\n DeleteProfileRequest deleteProfileRequest = new DeleteProfileRequest();\n deleteProfileRequest.setIsdpAid(isdpAid);\n\n return sendCommand(deleteProfileRequest, DeleteProfileResponse.class);\n }\n\n public EuiccMemoryResetResponse es10c_eUiccMemoryReset(BerBitString resetOptions) throws Exception {\n EuiccMemoryResetRequest euiccMemoryResetRequest = new EuiccMemoryResetRequest();\n euiccMemoryResetRequest.setResetOptions(resetOptions);\n\n return sendCommand(euiccMemoryResetRequest, EuiccMemoryResetResponse.class);\n }\n\n public GetEuiccDataResponse es10c_getEid() throws Exception {\n GetEuiccDataRequest getEuiccDataRequest = new GetEuiccDataRequest();\n getEuiccDataRequest.setTagList(new Octet1(Bytes.decodeHexString(\"5A\")));\n\n return sendCommand(getEuiccDataRequest, GetEuiccDataResponse.class);\n }\n\n public SetNicknameResponse es10c_setNickname(Iccid iccid, String nickname) throws Exception {\n SetNicknameRequest setNicknameRequest = new SetNicknameRequest();\n setNicknameRequest.setIccid(iccid);\n setNicknameRequest.setProfileNickname(new BerUTF8String(nickname));\n\n return sendCommand(setNicknameRequest, SetNicknameResponse.class);\n }\n\n public GetRatResponse es10c_getRat() throws Exception {\n GetRatRequest getRatRequest = new GetRatRequest();\n\n return sendCommand(getRatRequest, GetRatResponse.class);\n }\n\n // INTERNAL\n\n private T sendCommand(BerType berRequest, Class berResponseClass) throws Exception {\n List requests = TransportCommand.getTransportCommands(berRequest);\n\n Log.debug(TAG, \"ES10 -> : \" + berRequest.getClass().getSimpleName() + \"\\n\" + berRequest);\n String response = transmitApdus(requests);\n\n if(Apdu.isSuccessResponse(response)) {\n T berResponse = Ber.createFromEncodedHexString(berResponseClass, response);\n Log.debug(TAG, \"ES10 <- : \" + berResponse.getClass().getSimpleName() + \"\\n\" + berResponse);\n\n return berResponse;\n } else {\n throw new Exception(\"Error: APDU response is no success: \" + Apdu.getStatusWord(response));\n }\n }\n\n private T sendCommand(List encodedRequests, Class berResponseClass) throws Exception {\n List requests = TransportCommand.getTransportCommands(encodedRequests);\n\n String response = transmitApdus(requests);\n\n if(Apdu.isSuccessResponse(response)) {\n if(berResponseClass != null) {\n return Ber.createFromEncodedHexString(berResponseClass, response);\n } else {\n return null;\n }\n } else {\n throw new Exception(\"Error: APDU response is no success: \" + Apdu.getStatusWord(response));\n }\n }\n\n private String transmitApdus(List apduRequests) throws Exception {\n List apduResponses;\n String finalApduResponse = null;\n\n Log.debug(TAG, \"ES10 - Transmit APDUs requests: \" + apduRequests);\n apduResponses = euiccChannel.transmitAPDUS(apduRequests);\n Log.debug(TAG, \"ES10 - Transmit APDUs responses: \" + apduResponses);\n\n // Return first response APDU that contains data\n for (String apduResponse : apduResponses) {\n finalApduResponse = apduResponse;\n if (Apdu.doesResponseContainData(apduResponse)) {\n return apduResponse;\n }\n }\n\n return finalApduResponse;\n }\n}\n\nmessages/src/main/java/com/gsma/sgp/messages/rspdefinitions/CancelSessionResponseEs9.java\npublic class CancelSessionResponseEs9 implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic byte[] code = null;\n\tpublic static final BerTag tag = new BerTag(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 65);\n\n\tprivate CancelSessionOk cancelSessionOk = null;\n\tprivate BerInteger cancelSessionError = null;\n\t\n\tpublic CancelSessionResponseEs9() {\n\t}\n\n\tpublic CancelSessionResponseEs9(byte[] code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic void setCancelSessionOk(CancelSessionOk cancelSessionOk) {\n\t\tthis.cancelSessionOk = cancelSessionOk;\n\t}\n\n\tpublic CancelSessionOk getCancelSessionOk() {\n\t\treturn cancelSessionOk;\n\t}\n\n\tpublic void setCancelSessionError(BerInteger cancelSessionError) {\n\t\tthis.cancelSessionError = cancelSessionError;\n\t}\n\n\tpublic BerInteger getCancelSessionError() {\n\t\treturn cancelSessionError;\n\t}\n\n\tpublic int encode(OutputStream reverseOS) throws IOException {\n\t\treturn encode(reverseOS, true);\n\t}\n\n\tpublic int encode(OutputStream reverseOS, boolean withTag) throws IOException {\n\n\t\tif (code != null) {\n\t\t\tfor (int i = code.length - 1; i >= 0; i--) {\n\t\t\t\treverseOS.write(code[i]);\n\t\t\t}\n\t\t\tif (withTag) {\n\t\t\t\treturn tag.encode(reverseOS) + code.length;\n\t\t\t}\n\t\t\treturn code.length;\n\t\t}\n\n\t\tint codeLength = 0;\n\t\tif (cancelSessionError != null) {\n\t\t\tcodeLength += cancelSessionError.encode(reverseOS, false);\n\t\t\t// write tag: CONTEXT_CLASS, PRIMITIVE, 1\n\t\t\treverseOS.write(0x81);\n\t\t\tcodeLength += 1;\n\t\t\tcodeLength += BerLength.encodeLength(reverseOS, codeLength);\n\t\t\tif (withTag) {\n\t\t\t\tcodeLength += tag.encode(reverseOS);\n\t\t\t}\n\t\t\treturn codeLength;\n\t\t}\n\t\t\n\t\tif (cancelSessionOk != null) {\n\t\t\tcodeLength += cancelSessionOk.encode(reverseOS, false);\n\t\t\t// write tag: CONTEXT_CLASS, CONSTRUCTED, 0\n\t\t\treverseOS.write(0xA0);\n\t\t\tcodeLength += 1;\n\t\t\tcodeLength += BerLength.encodeLength(reverseOS, codeLength);\n\t\t\tif (withTag) {\n\t\t\t\tcodeLength += tag.encode(reverseOS);\n\t\t\t}\n\t\t\treturn codeLength;\n\t\t}\n\t\t\n\t\tthrow new IOException(\"Error encoding CHOICE: No element of CHOICE was selected.\");\n\t}\n\n\tpublic int decode(InputStream is) throws IOException {\n\t\treturn decode(is, true);\n\t}\n\n\tpublic int decode(InputStream is, boolean withTag) throws IOException {\n\t\tint codeLength = 0;\n\t\tBerLength length = new BerLength();\n\t\tBerTag berTag = new BerTag();\n\n\t\tif (withTag) {\n\t\t\tcodeLength += tag.decodeAndCheck(is);\n\t\t}\n\n\t\tcodeLength += length.decode(is);\n\t\tcodeLength += berTag.decode(is);\n\n\t\tif (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.CONSTRUCTED, 0)) {\n\t\t\tcancelSessionOk = new CancelSessionOk();\n\t\t\tcodeLength += cancelSessionOk.decode(is, false);\n\t\t\treturn codeLength;\n\t\t}\n\n\t\tif (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 1)) {\n\t\t\tcancelSessionError = new BerInteger();\n\t\t\tcodeLength += cancelSessionError.decode(is, false);\n\t\t\treturn codeLength;\n\t\t}\n\n\t\tthrow new IOException(\"Error decoding CHOICE: Tag \" + berTag + \" matched to no item.\");\n\t}\n\n\tpublic void encodeAndSave(int encodingSizeGuess) throws IOException {\n\t\tReverseByteArrayOutputStream reverseOS = new ReverseByteArrayOutputStream(encodingSizeGuess);\n\t\tencode(reverseOS, false);\n\t\tcode = reverseOS.getArray();\n\t}\n\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendAsString(sb, 0);\n\t\treturn sb.toString();\n\t}\n\n\tpublic void appendAsString(StringBuilder sb, int indentLevel) {\n\n\t\tif (cancelSessionOk != null) {\n\t\t\tsb.append(\"cancelSessionOk: \");\n\t\t\tcancelSessionOk.appendAsString(sb, indentLevel + 1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (cancelSessionError != null) {\n\t\t\tsb.append(\"cancelSessionError: \").append(cancelSessionError);\n\t\t\treturn;\n\t\t}\n\n\t\tsb.append(\"\");\n\t}\n\n}\n\napp/src/test/java/com/infineon/esim/util/Log.java\nfinal public class Log {\n\n // Ref:\n // https://stackoverflow.com/questions/8355632/how-do-you-usually-tag-log-entries-android\n public static String getFileLineNumber() {\n String info = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n if (ste[i].getMethodName().equals(\"getFileLineNumber\")) {\n info = \"(\"+ste[i + 1].getFileName() + \":\" + ste[i + 1].getLineNumber()+\")\";\n }\n }\n return info;\n }\n\n public static void verbose(final String tag, final String msg) {\n System.out.println(\"V - \" + tag + \": \" + msg);\n }\n\n public static void debug(final String tag, final String msg) {\n System.out.println(\"D - \" + tag + \": \" + msg);\n }\n\n public static void info(final String tag, final String msg) {\n System.out.println(\"I- \" + tag + \": \" + msg);\n }\n\n public static void error(final String msg) {\n System.out.println(\"E- \" + msg);\n }\n\n public static void error(final String tag, final String msg) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n }\n\n public static void error(final String tag, final String msg, final Throwable error) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n error.printStackTrace();\n }\n}\n\ncore/src/main/java/com/infineon/esim/lpa/core/es9plus/Es9PlusInterface.java\npublic class Es9PlusInterface {\n private static final String TAG = Es9PlusInterface.class.getName();\n\n private static final Gson GS = new GsonBuilder().disableHtmlEscaping().create();\n\n private static final String INITIATE_AUTHENTICATION_PATH = \"/gsma/rsp2/es9plus/initiateAuthentication\";\n private static final String AUTHENTICATE_CLIENT_PATH = \"/gsma/rsp2/es9plus/authenticateClient\";\n private static final String GET_BOUND_PROFILE_PACKAGE_PATH = \"/gsma/rsp2/es9plus/getBoundProfilePackage\";\n private static final String HANDLE_NOTIFICATION_PATH = \"/gsma/rsp2/es9plus/handleNotification\";\n private static final String CANCEL_SESSION_PATH = \"/gsma/rsp2/es9plus/cancelSession\";\n\n private final HttpsClient httpsClient;\n\n private String smdpAddress;\n\n private FunctionExecutionStatus lastFunctionExecutionStatus = null;\n\n public Es9PlusInterface() {\n this.httpsClient = new HttpsClient();\n }\n\n public void setSmdpAddress(String smdpAddress) {\n this.smdpAddress = smdpAddress;\n }\n\n public InitiateAuthenticationResponse initiateAuthentication(InitiateAuthenticationRequest initiateAuthenticationRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + initiateAuthenticationRequest);\n\n InitiateAuthenticationReq initiateAuthenticationReq = new InitiateAuthenticationReq();\n initiateAuthenticationReq.setRequest(initiateAuthenticationRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(initiateAuthenticationReq), smdpAddress, INITIATE_AUTHENTICATION_PATH, true);\n checkHttpStatusCode(\"InitiateAuthentication\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n InitiateAuthenticationResp initiateAuthenticationResp = GS.fromJson(httpResponse.getContent(), InitiateAuthenticationResp.class);\n checkFunctionExecutionStatus(\"InitiateAuthentication\", initiateAuthenticationResp);\n\n InitiateAuthenticationResponse initiateAuthenticationResponse = initiateAuthenticationResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + initiateAuthenticationResponse);\n\n return initiateAuthenticationResponse;\n }\n\n public AuthenticateClientResponseEs9 authenticateClient(AuthenticateClientRequest authenticateClientRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + authenticateClientRequest);\n\n AuthenticateClientReq authenticateClientReq = new AuthenticateClientReq();\n authenticateClientReq.setRequest(authenticateClientRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(authenticateClientReq), smdpAddress, AUTHENTICATE_CLIENT_PATH, true);\n checkHttpStatusCode(\"AuthenticateClient\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n AuthenticateClientResp authenticateClientResp = GS.fromJson(httpResponse.getContent(), AuthenticateClientResp.class);\n checkFunctionExecutionStatus(\"AuthenticateClient\", authenticateClientResp);\n\n AuthenticateClientResponseEs9 authenticateClientResponseEs9 = authenticateClientResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + authenticateClientResponseEs9);\n\n return authenticateClientResponseEs9;\n }\n\n public GetBoundProfilePackageResponse getBoundProfilePackage(GetBoundProfilePackageRequest getBoundProfilePackageRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + getBoundProfilePackageRequest);\n\n GetBoundProfilePackageReq getBoundProfilePackageReq = new GetBoundProfilePackageReq();\n getBoundProfilePackageReq.setRequest(getBoundProfilePackageRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(getBoundProfilePackageReq), smdpAddress, GET_BOUND_PROFILE_PACKAGE_PATH, true);\n checkHttpStatusCode(\"GetBoundProfilePackage\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n GetBoundProfilePackageResp getBoundProfilePackageResp = GS.fromJson(httpResponse.getContent(), GetBoundProfilePackageResp.class);\n checkFunctionExecutionStatus(\"GetBoundProfilePackage\", getBoundProfilePackageResp);\n\n GetBoundProfilePackageResponse getBoundProfilePackageResponse = getBoundProfilePackageResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + getBoundProfilePackageResponse);\n\n return getBoundProfilePackageResponse;\n }\n\n public CancelSessionResponseEs9 cancelSession(CancelSessionRequestEs9 cancelSessionRequest) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + cancelSessionRequest);\n\n CancelSessionReq cancelSessionReq = new CancelSessionReq();\n cancelSessionReq.setRequest(cancelSessionRequest);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(cancelSessionReq), smdpAddress, CANCEL_SESSION_PATH, true);\n checkHttpStatusCode(\"CancelSession\", httpResponse, HttpsURLConnection.HTTP_OK);\n\n CancelSessionResp cancelSessionResp = GS.fromJson(httpResponse.getContent(), CancelSessionResp.class);\n checkFunctionExecutionStatus(\"CancelSession\", cancelSessionResp);\n\n CancelSessionResponseEs9 cancelSessionResponseEs9 = cancelSessionResp.getResponse();\n Log.debug(TAG, \"ES9+ <- : \" + cancelSessionResponseEs9);\n\n return cancelSessionResponseEs9;\n }\n\n public void handleNotification(PendingNotification pendingNotification) throws Exception {\n ensureSmdpAddressIsAvailable();\n\n Log.debug(TAG, \"ES9+ -> : \" + pendingNotification);\n\n HandleNotificationReq handleNotificationReq = new HandleNotificationReq();\n handleNotificationReq.setRequest(pendingNotification);\n\n HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(handleNotificationReq), smdpAddress, HANDLE_NOTIFICATION_PATH, true);\n // No content for response\n\n checkHttpStatusCode(\"HandleNotification\", httpResponse, HttpsURLConnection.HTTP_NO_CONTENT);\n }\n\n public FunctionExecutionStatus getFunctionExecutionStatus() {\n return lastFunctionExecutionStatus;\n }\n\n private void ensureSmdpAddressIsAvailable() throws Exception {\n if(smdpAddress == null) {\n Log.error(TAG, \"SM-DP+ address is not available.\");\n throw new Exception(\"SM-DP+ address is not available.\");\n }\n }\n\n private void checkHttpStatusCode(String functionName, HttpResponse httpResponse, int expectedHttpStatusCode) {\n if(httpResponse.getStatusCode() != expectedHttpStatusCode) {\n throw new RuntimeException(\"Error in \" + functionName + \": wrong HTTP status code: \" + httpResponse.getStatusCode());\n }\n }\n\n private void checkFunctionExecutionStatus(String functionName, ResponseMsgBody responseMessage) {\n if((responseMessage.getHeader() != null) &&\n (responseMessage.getHeader().getFunctionExecutionStatus() != null)) {\n\n this.lastFunctionExecutionStatus = responseMessage.getHeader().getFunctionExecutionStatus();\n String status = lastFunctionExecutionStatus.getStatus();\n\n if(status.equals(FunctionExecutionStatus.EXECUTION_STATUS_SUCCESS) ||\n status.equals(FunctionExecutionStatus.EXECUTION_STATUS_WITH_WARNING)) {\n return;\n } else {\n throw new RuntimeException(\"Error in \" + functionName + \": FunctionExecutionStatus: \" + lastFunctionExecutionStatus.toString());\n }\n }\n\n throw new RuntimeException(\"Error in \" + functionName + \": FunctionExecutionStatus not found in response.\");\n }\n}", "answers": [" this.es9PlusInterface = profileDownloadSession.getEs9PlusInterface();"], "length": 2434, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "055e2350-0f9b-4a34-8cbb-5f2d8d9536ba", "reasoning": "The constructor of CancelSessionWorker initializes the session and the ES10 interface. Since the class also has a field es9PlusInterface, the next logical step is to initialize it from the provided ProfileDownloadSession, mirroring the ES10 initialization. The appropriate call is profileDownloadSession.getEs9PlusInterface().", "reasoning_model_answer": "this.es9PlusInterface = profileDownloadSession.getEs9PlusInterface();", "assistant_with_reasoning": "\nThe constructor of CancelSessionWorker initializes the session and the ES10 interface. Since the class also has a field es9PlusInterface, the next logical step is to initialize it from the provided ProfileDownloadSession, mirroring the ES10 initialization. The appropriate call is profileDownloadSession.getEs9PlusInterface().\n\nthis.es9PlusInterface = profileDownloadSession.getEs9PlusInterface();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.932, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 31856, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "this.es9PlusInterface = profileDownloadSession.getEs9PlusInterface();", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.alibaba.fastjson2.JSONObject;\nimport com.ly.ckibana.configure.web.route.HttpRoute;\nimport com.ly.ckibana.constants.Constants;\nimport com.ly.ckibana.model.compute.aggregation.bucket.TermsBucket;\nimport com.ly.ckibana.model.compute.indexpattern.IndexPattern;\nimport com.ly.ckibana.model.enums.AggType;\nimport com.ly.ckibana.model.exception.FallbackToEsException;\nimport com.ly.ckibana.model.request.CkRequestContext;\nimport com.ly.ckibana.model.request.ProxyConfig;\nimport com.ly.ckibana.model.request.RequestContext;\nimport com.ly.ckibana.model.response.Response;\nimport com.ly.ckibana.parser.ParamParser;\nimport com.ly.ckibana.parser.ResultParser;\nimport com.ly.ckibana.service.CkService;\nimport com.ly.ckibana.service.EsClientUtil;\nimport com.ly.ckibana.strategy.aggs.Aggregation;\nimport com.ly.ckibana.util.JSONUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.stereotype.Component;\nimport javax.annotation.Resource;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;", "context": "src/main/java/com/ly/ckibana/handlers/SearchHandler.java\n/*\n * Copyright (c) 2023 LY.com All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.ly.ckibana.handlers;\n\n\n\n@SuppressWarnings(\"rawtypes\")\n@Component\npublic class SearchHandler extends BaseHandler {\n\n @Resource\n private ParamParser paramParser;\n\n @Resource\n private CkService ckService;\n\n @Resource\n private ResultParser resultParseService;\n\n @Override\n public List routes() {\n return List.of(\n HttpRoute.newRoute().path(\"/_search\").methods(HttpMethod.GET, HttpMethod.POST),\n HttpRoute.newRoute().path(\"/{index}/_search\").methods(HttpMethod.GET, HttpMethod.POST),\n HttpRoute.newRoute().path(\"/{index}/{type}/_search\").methods(HttpMethod.GET, HttpMethod.POST)\n );\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public String doHandle(RequestContext context) throws Exception {\n String index = context.getIndex();\n // es6.x 查询索引列表时,传入index默认为 * 或 *:*,此时解析请求体,判断是否查询索引列表,如果是的话,就查询ck和es,merge后返回\n if (StringUtils.isEmpty(index)) {\n throw new FallbackToEsException();\n }\n if (!index.equals(Constants.MATCH_ALL) && !context.isCkIndex()) {\n throw new FallbackToEsException();\n }\n JSONObject searchQuery = JSONUtils.deserialize(context.getRequestInfo().getRequestBody(), JSONObject.class);\n\nsrc/main/java/com/ly/ckibana/model/compute/aggregation/bucket/TermsBucket.java\n@EqualsAndHashCode(callSuper = true)\n@Data\npublic class TermsBucket extends Bucket {\n\n}\n\nsrc/main/java/com/ly/ckibana/model/compute/indexpattern/IndexPattern.java\n@Data\npublic class IndexPattern {\n\n private String uiIndex;\n\n private String index;\n\n private String database;\n\n private String timeField;\n}\n\nsrc/main/java/com/ly/ckibana/service/CkService.java\n@Slf4j\n@Service\npublic class CkService {\n\n public static final int SOCKET_TIMEOUT = 120000;\n\n public static final int CONNECTION_TIMEOUT = 10000;\n\n public static final int SLOW_THREAD = 10000;\n\n @Resource\n private ProxyConfigLoader proxyConfigLoader;\n\n @Resource\n private CkResultCacheService ckResultCacheService;\n\n @Resource\n private BlackSqlService blackSqlService;\n\n @Resource\n private SqlMonitorService sqlMonitorService;\n\n public static String getJdbcUrl(String urlTemplate, String database) {\n return String.format(\"jdbc:clickhouse://%s/%s\", urlTemplate, database);\n }\n\n public static BalancedClickhouseDataSource initDatasource(CkProperty ckProperty) {\n ClickHouseProperties props = new ClickHouseProperties();\n props.setUseServerTimeZone(false);\n props.setUseTimeZone(\"Asia/Shanghai\");\n props.setSocketTimeout(SOCKET_TIMEOUT);\n props.setConnectionTimeout(CONNECTION_TIMEOUT);\n props.setUser(ckProperty.getUser());\n props.setPassword(ckProperty.getPass());\n String jdbcUrl = String.format(\"jdbc:clickhouse://%s/%s\", ckProperty.getUrl(), ckProperty.getDefaultCkDatabase());\n return new BalancedClickhouseDataSource(jdbcUrl, props);\n }\n\n /**\n * 获取jdbc,不同集群获取的地址不同.\n *\n * @param indexPattern 索引模式\n * @return jdbc地址\n */\n public String getJdbcUrl(IndexPattern indexPattern) {\n if (proxyConfigLoader.getKibanaProperty().getProxy().getCk() == null) {\n throw new DataSourceEmptyException(\"clickhouse数据源为空,请检查配置proxy.ck\");\n }\n String ckUrl = proxyConfigLoader.getKibanaProperty().getProxy().getCk().getUrl();\n //基于不同集群,用于读数据的ck\n return getJdbcUrl(ckUrl, indexPattern.getDatabase());\n }\n\n public ClickHouseConnectionImpl getLimitedConnection(String jdbcUrl) throws SQLException {\n return getConnection(jdbcUrl);\n }\n\n /**\n * 获取ck连接.\n *\n * @param jdbcUrl jdbc地址\n * @return ck连接\n * @throws SQLException sql异常\n */\n private ClickHouseConnectionImpl getConnection(String jdbcUrl) throws SQLException {\n CkProperty ckProperty = proxyConfigLoader.getKibanaProperty().getProxy().getCk();\n if (ckProperty == null) {\n throw new DataSourceEmptyException(\"clickhouse数据源为空,请检查配置proxy.ck\");\n }\n ClickHouseProperties props = new ClickHouseProperties();\n props.setUseServerTimeZone(false);\n props.setUseTimeZone(ZoneId.systemDefault().getId());\n props.setSocketTimeout(SOCKET_TIMEOUT);\n props.setConnectionTimeout(CONNECTION_TIMEOUT);\n props.setUser(ckProperty.getUser());\n props.setPassword(ckProperty.getPass());\n BalancedClickhouseDataSource dataSource = new BalancedClickhouseDataSource(jdbcUrl, props);\n return (ClickHouseConnectionImpl) dataSource.getConnection();\n }\n\n public List queryTables(ProxyConfig proxyConfig, String tableName) throws Exception {\n String tableCondition = String.format(\"name = '%s' \", tableName);\n return queryTablesWithCondition(proxyConfig, tableCondition);\n }\n\n public List queryAllTables(ProxyConfig proxyConfig) throws Exception {\n return queryTablesWithCondition(proxyConfig, null);\n }\n\n public List queryTables(ProxyConfig proxyConfig, List tablePrefixes) throws Exception {\n String tableCondition = tablePrefixes.stream().map(name -> String.format(\"'%s'\", name)).collect(Collectors.joining(\",\", \"name in (\", \")\"));\n return queryTablesWithCondition(proxyConfig, tableCondition);\n }\n\n private List queryTablesWithCondition(ProxyConfig proxyConfig, String tableCondition) throws Exception {\n String sql = String.format(\"SELECT name FROM system.tables WHERE database = '%s' \", proxyConfig.getCkDatabase());\n if (StringUtils.isNotEmpty(tableCondition)) {\n sql = String.format(\"%s AND %s \", sql, tableCondition);\n }\n List tables = queryData(proxyConfig, sql);\n return tables.stream().map(each -> each.getString(\"name\")).collect(Collectors.toList());\n }\n\n public Map queryColumns(BalancedClickhouseDataSource clickhouseDataSource, String table) throws Exception {\n Map result = new HashMap<>();\n String sql = String.format(\"desc `%s`\", table);\n try (ClickHouseConnection connection = clickhouseDataSource.getConnection()) {\n ResultSet results = query(connection, sql);\n ResultSetMetaData metaData = results.getMetaData();\n while (results.next()) {\n Map columnMap = new HashMap<>();\n for (int i = 1; i <= metaData.getColumnCount(); i++) {\n columnMap.put(metaData.getColumnName(i), results.getString(metaData.getColumnName(i)));\n }\n result.put(columnMap.get(\"name\"), columnMap.get(\"type\"));\n }\n return result;\n }\n }\n\n private List queryData(CkRequestContext ckRequestContext, String sql) throws Exception {\n String jdbcUrl = getJdbcUrl(ckRequestContext.getIndexPattern());\n try (ClickHouseConnectionImpl connection = getLimitedConnection(jdbcUrl)) {\n return formatObjectResult(query(connection, sql));\n }\n }\n\n private List queryData(ProxyConfig proxyConfig, String sql) throws Exception {\n try (ClickHouseConnection connection = proxyConfig.getCkDatasource().getConnection()) {\n return formatObjectResult(query(connection, sql));\n }\n }\n\n public Pair, Boolean> queryDataWithCacheAndStatus(CkRequestContext ckRequestContext, String sql) throws Exception {\n Pair, Boolean> resultAndStatus = Pair.of(new ArrayList<>(), false);\n Exception exception = null;\n\n if (ckRequestContext.getTimeRange() != null && blackSqlService.isBlackSql(ckRequestContext.getTimeRange().getDiffMillSeconds(), ckRequestContext.getQuerySqlWithoutTimeRange())) {\n throw new BlackSqlException(ckRequestContext.getQuerySqlWithoutTimeRange() + \"在黑名单中, 禁止执行\");\n }\n long startTime = System.currentTimeMillis();\n\n try {\n if (ckResultCacheService.containsKey(sql)) {\n resultAndStatus = Pair.of(ckResultCacheService.get(sql), true);\n } else {\n List result = queryData(ckRequestContext, sql);\n ckResultCacheService.put(sql, result);\n resultAndStatus = Pair.of(result, false);\n }\n } catch (Exception e) {\n exception = e;\n log.error(\"query data error, sql:{}, cost:{}\", sql,\n Duration.between(Instant.ofEpochMilli(startTime), Instant.ofEpochMilli(System.currentTimeMillis())).toMillis(), e);\n }\n\n long endTime = System.currentTimeMillis();\n try {\n long range = ckRequestContext.getTimeRange() == null ? 0L : ckRequestContext.getTimeRange().getDiffMillSeconds();\n sqlMonitorService.recordAsync(range, ckRequestContext.getQuerySqlWithoutTimeRange(), startTime, endTime);\n } catch (Exception e) {\n log.error(\"[monitor-add][{}ms] sql={}, startTime={}, endTime={}\", ckRequestContext.getQuerySqlWithoutTimeRange(),\n startTime, endTime,\n Duration.between(Instant.ofEpochMilli(startTime), Instant.ofEpochMilli(endTime)).toMillis());\n }\n\n if (exception != null) {\n throw exception;\n }\n return resultAndStatus;\n }\n\n public List queryDataWithoutCache(CkRequestContext ckRequestContext, String sql) throws Exception {\n return queryData(ckRequestContext, sql);\n }\n\n /**\n * 查询ck,拦截不同报错.\n */\n private ResultSet query(ClickHouseConnection connection, String sql) throws Exception {\n try {\n long begin = System.currentTimeMillis();\n Statement statement = connection.createStatement();\n ResultSet result = statement.executeQuery(sql);\n long cost = System.currentTimeMillis() - begin;\n if (cost >= SLOW_THREAD) {\n log.warn(\"[query][slowQuery][{}ms] sql={}\", cost, sql);\n } else {\n log.info(\"[query][{}ms] sql={}\", cost, sql);\n }\n return result;\n } catch (ClickHouseException ex) {\n log.error(\"[query] exception sql: {}\", sql, ex);\n if (isResourceExceed(ex.getErrorCode())) {\n throw new ResourceExceedException(ex.getMessage());\n } else if (ex.getErrorCode() == ClickHouseErrorCode.TOO_MUCH_SIMULTANEOUS_QUERIES.code) {\n throw new TooManySimultaneousException(ex.getMessage());\n } else if (ex.getErrorCode() == ClickHouseErrorCode.UNKNOWN_IDENTIFIER.code) {\n String field = ex.getCause().getMessage().split(\"while processing query\")[0];\n field = field.replace(\"Code: 47, e.displayText() = DB::Exception: Missing columns:\", \"\")\n .replace(\"'\", \"\").replace(\" \", \"\");\n throw new UnKnowFieldException(field);\n } else if (ex.getErrorCode() == ClickHouseErrorCode.UNKNOWN_TABLE.code) {\n throw new CKNotSupportException(ex.getMessage());\n } else {\n throw new CkSQLException(ex.getMessage());\n }\n } catch (Exception ex) {\n throw ex;\n }\n }\n\n /**\n * 检查ck结果行是否超过配置.\n *\n * @param rowCount 行数\n * @throws ResourceExceedException 资源超出异常。\n */\n private void isResultRowCountExceed(Integer rowCount) throws ResourceExceedException {\n if (rowCount >= proxyConfigLoader.getKibanaProperty().getQuery().getMaxResultRow()) {\n throw new ResourceExceedException(String.format(\"超过代理配置maxResultRow %s\", proxyConfigLoader.getKibanaProperty().getQuery().getMaxResultRow()));\n }\n }\n\n private boolean isResourceExceed(int errorCode) {\n return Arrays.asList(ClickHouseErrorCode.MEMORY_LIMIT_EXCEEDED.code, ClickHouseErrorCode.TOO_MUCH_BYTES.code,\n ClickHouseErrorCode.TOO_MANY_ROWS_OR_BYTES.code, ClickHouseErrorCode.QUOTA_EXPIRED.code).contains(errorCode);\n }\n\n /**\n * 将ck数据封装为list格式返回.\n */\n private List formatObjectResult(ResultSet resultSet) throws SQLException, ResourceExceedException {\n List result = new ArrayList<>();\n ResultSetMetaData metaData = resultSet.getMetaData();\n int columnCount = metaData.getColumnCount();\n while (resultSet.next()) {\n JSONObject rowData = new JSONObject();\n for (int i = 1; i <= columnCount; i++) {\n if (ProxyUtils.isArrayType(metaData.getColumnTypeName(i))) {\n rowData.put(metaData.getColumnName(i), JSONUtils.convert(resultSet.getArray(i).getArray(), List.class));\n } else {\n rowData.put(metaData.getColumnName(i), resultSet.getObject(i));\n }\n }\n result.add(rowData);\n isResultRowCountExceed(result.size());\n }\n return result;\n }\n\n}\n\nsrc/main/java/com/ly/ckibana/model/request/CkRequestContext.java\n@Data\npublic class CkRequestContext {\n\n private IndexPattern indexPattern;\n\n private String tableName;\n\n private Map columns = new HashMap<>();\n\n private int size;\n\n private String sort;\n\n /**\n * response hits使用 使用原始字段名.\n */\n private List docValues;\n\n private List sortingFields;\n\n private String querySqlWithoutTimeRange;\n\n private String query;\n\n /**\n * 聚合参数.\n */\n private List aggs;\n\n /**\n * 采样参数.\n */\n private SampleParam sampleParam;\n /**\n * 最大结果条数。若大于或等于此阈值,抛出异常,否则可能引发oom.\n */\n private int maxResultRow;\n\n /**\n * 时间范围参数.\n */\n private Range timeRange;\n\n /**\n * 记录耗时使用.\n */\n private long beginTime;\n\n private String database;\n\n private String clientIp;\n\n public CkRequestContext() {\n }\n\n public CkRequestContext(String clientIp, IndexPattern indexPattern, int maxResultRow) {\n this.clientIp = clientIp;\n this.indexPattern = indexPattern;\n this.maxResultRow = maxResultRow;\n database = indexPattern.getDatabase();\n beginTime = System.currentTimeMillis();\n }\n\n @Data\n @AllArgsConstructor\n public static class SampleParam {\n\n /**\n * 优化策略,一个msearch查询第一个的count,确定本次查询的采样参数.\n */\n private long sampleTotalCount;\n\n /**\n * sampleTotalCount数据量超过这个阈值,才会使用采样查询.\n */\n private int sampleCountMaxThreshold;\n\n }\n}\n\nsrc/main/java/com/ly/ckibana/model/response/Response.java\n@Data\npublic class Response {\n\n @JsonProperty(\"timed_out\")\n private boolean timedOut;\n\n @JsonProperty(\"_shards\")\n private Shards shards = new Shards();\n\n private Hits hits = new Hits();\n\n private int took;\n\n private boolean cache;\n\n /**\n * 聚合名-{buckets信息}.\n */\n private Map> aggregations;\n\n private Integer status;\n\n private Object error;\n\n private List sqls = new ArrayList<>();\n}\n\nsrc/main/java/com/ly/ckibana/util/JSONUtils.java\n@Slf4j\npublic final class JSONUtils {\n\n /**\n * 序列化.\n */\n public static String serialize(Object o) {\n try {\n ObjectMapper mapper = new ObjectMapper();\n return mapper.writeValueAsString(o);\n } catch (Exception ex) {\n log.error(\"serialize error\", ex);\n return \"{}\";\n }\n }\n\n /**\n * 反序列化.\n */\n public static T deserialize(String json, Class type) {\n try {\n return JSON.parseObject(json, type);\n } catch (Exception ex) {\n log.error(\"deserialize error, json:{}\", json, ex);\n throw ex;\n }\n }\n\n /**\n * 反序列化为list.\n */\n public static List deserializeToList(String json, Class tClass) {\n List result = new ArrayList<>();\n deserialize(json, List.class).stream().forEach(each -> result.add(convert(each, tClass)));\n return result;\n }\n\n /**\n * list转换.\n */\n public static List deserializeToList(List list, Class tClass) {\n if (list == null) {\n return new ArrayList<>();\n }\n return list.stream().map(o -> convert(o, tClass)).collect(Collectors.toList());\n }\n\n /**\n * object转换为map.\n */\n public static Map convertToMap(Object o) {\n return convert(o, Map.class);\n }\n\n /**\n * object转换为其他类型.\n */\n public static T convert(Object o, Class type) {\n try {\n if (o == null) {\n return null;\n }\n String json = JSON.toJSONString(o);\n return JSON.parseObject(json, type);\n } catch (Exception ex) {\n log.error(\"convert error\", ex);\n throw ex;\n }\n }\n\n /**\n * 拷贝生成同类新对象.\n */\n public static T copy(Object source) {\n Object result = new BeanWrapperImpl(source.getClass()).getWrappedInstance();\n BeanUtils.copyProperties(source, result);\n return (T) result;\n }\n}\n\nsrc/main/java/com/ly/ckibana/model/request/RequestContext.java\n@Data\n@SuperBuilder\n@AllArgsConstructor\n@NoArgsConstructor\n@Accessors(chain = true)\npublic class RequestContext {\n\n private HttpServletRequest httpRequest;\n\n private HttpServletResponse httpResponse;\n\n private Map urlParams;\n\n private ProxyConfig proxyConfig;\n\n private RequestInfo requestInfo;\n\n private String clientIp;\n\n private String targetUrl;\n\n private String requestUrl;\n\n /**\n * 去掉 originalIndex 中的 remote cluster,比如 remote_cluster_name:index_name -> index_name.\n */\n private String index;\n\n /**\n * url路径中的原始index,可能包含 remote cluster,比如 remote_cluster_name:index_name.\n */\n private String originalIndex;\n\n /**\n * 是否匹配 proxy config 的黑白名单,属于 ck 索引.\n */\n private boolean ckIndex;\n\n @Data\n @AllArgsConstructor\n public static class RequestInfo {\n private Map params;\n\n private Header[] headers;\n\n private String method;\n\n private String url;\n\n private String requestBody;\n }\n}\n\nsrc/main/java/com/ly/ckibana/model/exception/FallbackToEsException.java\npublic class FallbackToEsException extends RuntimeException {\n \n public FallbackToEsException() {\n }\n \n public FallbackToEsException(String msg) {\n super(msg);\n }\n}\n\nsrc/main/java/com/ly/ckibana/model/request/ProxyConfig.java\n@Data\n@SuperBuilder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class ProxyConfig {\n public static final Logger log = LoggerFactory.getLogger(ProxyConfig.class);\n\n private KibanaItemProperty kibanaItemProperty;\n\n private RestClient restClient;\n\n private EsProxyClientConsumer esClientBuffer;\n\n private BalancedClickhouseDataSource ckDatasource;\n\n public ProxyConfig(KibanaItemProperty kibanaItemProperty) {\n this.kibanaItemProperty = kibanaItemProperty;\n this.restClient = RestUtils.initEsResClient(kibanaItemProperty.getEs());\n this.esClientBuffer = new EsProxyClientConsumer();\n if (kibanaItemProperty.getCk() != null) {\n this.ckDatasource = CkService.initDatasource(kibanaItemProperty.getCk());\n } else {\n this.ckDatasource = null;\n }\n }\n\n public String getCkDatabase() {\n if (kibanaItemProperty.getCk() == null) {\n throw new DataSourceEmptyException(\"clickhouse数据源为空,请检查配置proxy.ck\");\n }\n return kibanaItemProperty.getCk().getDefaultCkDatabase();\n }\n\n public boolean shouldUpdateEsClient(KibanaItemProperty properties) {\n if (properties == null || properties.getEs() == null) {\n return false;\n }\n if (StringUtils.isEmpty(this.kibanaItemProperty.getEs().getHost()) && StringUtils.isEmpty(properties.getEs().getHost())) {\n return false;\n }\n boolean hostDiff = !Objects.equals(this.kibanaItemProperty.getEs().getHost(), properties.getEs().getHost());\n Map oldHeaders = this.kibanaItemProperty.getEs().getHeaders();\n Map newHeaders = properties.getEs().getHeaders();\n boolean headersDiff;\n if (oldHeaders != null && newHeaders != null) {\n headersDiff = !oldHeaders.toString().equals(newHeaders.toString());\n } else {\n headersDiff = !(oldHeaders == null && newHeaders == null);\n }\n return headersDiff || hostDiff;\n }\n\n public boolean shouldUpdateCkClient(KibanaItemProperty properties) {\n if (properties == null || properties.getCk() == null) {\n return false;\n }\n CkProperty oldProperty = this.kibanaItemProperty.getCk();\n CkProperty newProperty = properties.getCk();\n if (oldProperty == null && newProperty != null) {\n return true;\n }\n return !Objects.equals(newProperty, oldProperty);\n }\n\n public boolean isDirectToEs(String index) {\n if (StringUtils.isEmpty(index)) {\n return true;\n }\n if (CollectionUtils.isEmpty(kibanaItemProperty.getBlackIndexList()) && CollectionUtils.isEmpty(kibanaItemProperty.getWhiteIndexList())) {\n return true;\n }\n if (!CollectionUtils.isEmpty(kibanaItemProperty.getBlackIndexList())) {\n for (String each : kibanaItemProperty.getBlackIndexList()) {\n if (index.equals(each)) {\n return true;\n }\n }\n }\n if (!CollectionUtils.isEmpty(kibanaItemProperty.getWhiteIndexList())) {\n for (String each : kibanaItemProperty.getWhiteIndexList()) {\n if (index.equals(each)) {\n return false;\n }\n }\n }\n return true;\n }\n\n public IndexPattern buildIndexPattern(String originIndex) {\n String index = ProxyUtils.trimRemoteCluster(originIndex);\n return buildIndexPattern(index, index);\n }\n\n public IndexPattern buildIndexPattern(String uiIndex, String index) {\n IndexPattern indexPattern = new IndexPattern();\n String database = getCkDatabase();\n indexPattern.setUiIndex(uiIndex);\n indexPattern.setIndex(index);\n indexPattern.setDatabase(database);\n return indexPattern;\n }\n}\n\nsrc/main/java/com/ly/ckibana/parser/ParamParser.java\n@Slf4j\n@Service\npublic class ParamParser {\n\n private static final String KEYED = \"keyed\";\n\n private static final String FIELD = \"field\";\n\n @Resource\n private ProxyConfigLoader proxyConfigLoader;\n\n @Resource\n private CkService ckService;\n\n @Resource\n private List aggStrategyList;\n\n @Resource\n private FiltersAggsStrategyHelpler filtersAggsStrategyHelpler;\n\n @Setter\n private Map aggStrategyMap;\n\n\n @PostConstruct\n public void init() {\n aggStrategyMap = new HashMap<>(aggStrategyList.size());\n aggStrategyList.forEach(each -> aggStrategyMap.put(each.getAggType(), each));\n }\n\n /**\n * 基于入口参数,解析indexPattern信息.\n * 远程集群名(数据库__集群业务名称):索引名 如businesslog__log:anquan_dns-*\n * 兼容原有es业务,需要default库名\n */\n public IndexPattern buildIndexPattern(RequestContext context) {\n return context.getProxyConfig().buildIndexPattern(context.getOriginalIndex(), context.getIndex());\n }\n\n /**\n * 是否需要采样,部分index采样。默认不采样.\n *\n * @param uiIndex uiIndex\n * @return 是否需要采样\n */\n public boolean checkIfNeedSampleByIndex(String uiIndex) {\n QueryProperty queryProperty = proxyConfigLoader.getKibanaProperty().getQuery();\n if (queryProperty == null) {\n return false;\n }\n List sampleIndexPatterns = queryProperty.getSampleIndexPatterns();\n if (CollectionUtils.isEmpty(sampleIndexPatterns)) {\n return false;\n }\n for (String each : sampleIndexPatterns) {\n if (uiIndex.equals(each)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 将查询语句转换为对应的agg聚合策略.\n */\n public List parseAggs(int depth, CkRequestContext ckRequestContext, JSONObject searchQuery) {\n List result = null;\n if (searchQuery.containsKey(Constants.AGGS)) {\n result = new ArrayList<>();\n JSONObject aggs = searchQuery.getJSONObject(Constants.AGGS);\n for (String aggsKey : aggs.keySet()) {\n List subAggs = null;\n JSONObject aggsSettings = aggs.getJSONObject(aggsKey);\n if (aggsSettings.containsKey(Constants.AGGS)) {\n subAggs = parseAggs(depth + 1, ckRequestContext, aggsSettings);\n }\n List currentAggs = doParseAggs(depth, aggsKey, ckRequestContext, aggsSettings, subAggs);\n if (currentAggs.isEmpty()) {\n continue;\n }\n if (aggsSettings.containsKey(Constants.AGGS) && CollectionUtils.isNotEmpty(subAggs)) {\n for (Aggregation currentAgg : currentAggs) {\n currentAgg.setSubAggs(subAggs);\n }\n }\n result.addAll(currentAggs);\n }\n }\n return result;\n }\n\n /**\n * 基于agg类型解析出对应的object.\n */\n private List doParseAggs(int depth, String aggName, CkRequestContext ckRequestContext, JSONObject parentSetting, List subAggs) {\n List aggs = new ArrayList<>();\n AggsParam baseAggsParam = new AggsParam(aggName, depth, ckRequestContext.getQuery(), ckRequestContext.getColumns(), subAggs);\n for (String each : parentSetting.keySet()) {\n if (Constants.AGGS.equals(each)) {\n continue;\n }\n AggsParam aggsParam = buildAggParam(baseAggsParam, each, parentSetting.getJSONObject(each));\n AggType type = aggsParam.getAggType();\n Aggregation aggregation = aggStrategyMap.get(type);\n if (null == aggregation) {\n throw new UnSupportAggsTypeException(each, AggType.getAggTypes());\n }\n if (AggType.FILTERS.equals(type)) {\n aggs.add(filtersAggsStrategyHelpler.generate(aggsParam, ckRequestContext));\n } else {\n aggs.add(aggregation.generate(aggsParam));\n }\n }\n return aggs;\n }\n\n private AggsParam buildAggParam(AggsParam baseAggsParam, String aggType, JSONObject aggSetting) {\n AggsParam result = JSONUtils.copy(baseAggsParam);\n String aggField = aggSetting.getString(FIELD);\n Map supportColumns = baseAggsParam.getColumns();\n if (!validAggField(aggType, aggField, supportColumns)) {\n throw new UnSupportAggsTypeException(aggType.toUpperCase(), aggField, AggType.getAggTypes());\n }\n try {\n result.setAggType(AggType.valueOf(aggType.toUpperCase()));\n result.setAggBucketsName(getAggBucketsNameByAggType(result));\n } catch (Exception e) {\n throw new UnSupportAggsTypeException(aggType.toUpperCase(), aggField, AggType.getAggTypes());\n }\n String fieldType = supportColumns.get(aggField);\n result.setAggSetting(aggSetting);\n result.setField(aggField);\n result.setKeyed(aggSetting.getBooleanValue(KEYED));\n result.setFieldType(fieldType);\n return result;\n }\n\n private AggBucketsName getAggBucketsNameByAggType(AggsParam result) {\n return (AggType.PERCENTILES.equals(result.getAggType()) || AggType.PERCENTILE_RANKS.equals(result.getAggType()))\n ? AggBucketsName.VALUES : AggBucketsName.BUCKETS;\n }\n\n private boolean validAggField(String aggType, String aggField, Map supportColumns) {\n return isFiltersAgg(aggType) || !isMissAggField(aggField) && !isMissAggFieldColumn(aggField, supportColumns);\n }\n\n /**\n * 是否ck列中缺失aggField字段.\n *\n * @param aggField aggField\n * @param supportColumns supportColumns\n * @return 是否ck列中缺失的字段\n */\n private boolean isMissAggFieldColumn(String aggField, Map supportColumns) {\n return !Constants.ES_INDEX_QUERY_FIELD.equals(aggField) && !supportColumns.containsKey(aggField);\n }\n\n /**\n * 是否用户参数缺失aggField.\n *\n * @param aggField aggField\n * @return boolean\n */\n private boolean isMissAggField(String aggField) {\n return StringUtils.isEmpty(aggField);\n }\n\n /**\n * 是否为filters聚合.\n *\n * @param aggType aggType\n * @return boolean\n */\n private boolean isFiltersAgg(String aggType) {\n return AggType.FILTERS.name().toLowerCase().equals(aggType);\n }\n\n /**\n * 查询列信息.\n */\n public Map queryTableColumns(BalancedClickhouseDataSource clickhouseDataSource, String tableName) throws Exception {\n return ckService.queryColumns(clickhouseDataSource, tableName);\n }\n\n /**\n * 如果需要走 cache,cache 返回不为空再请求es.\n */\n public Map queryColumnsFromCache(Map> cache, String tableName) {\n Map result = null;\n //不为空不为*的table名称才需要查询列名\n if (Strings.isNullOrEmpty(tableName) || ProxyUtils.matchAllIndex(tableName)) {\n return new HashMap<>();\n }\n if (cache != null && cache.containsKey(tableName)) {\n result = cache.get(tableName);\n }\n return result;\n }\n\n /**\n * 基于indexPattern,查询其下的字段,包括名称和类型.\n *\n * @param requestContext 请求上下文\n * @param indexPattern 当前index pattern\n * @param isForSelectTimeField 是:代表为创建index pattern时间时选择时间字段列表场景,需要额外类型转换(规则参见ProxyUtils.isTimeFieldOptionByName)\n * 否:代表查询index pattern字段列表。无需额外类型转换\n */\n public Map queryIndexPatternFields(RequestContext requestContext, IndexPattern indexPattern,\n boolean isForSelectTimeField) throws Exception {\n Map result = new HashMap<>();\n String tableName = indexPattern.getIndex();\n Map columns = ckService.queryColumns(requestContext.getProxyConfig().getCkDatasource(), tableName);\n //特殊查询字段不存在,转为真实对应的ck字段\n for (Map.Entry each : columns.entrySet()) {\n String ckName = each.getKey();\n String ckType = each.getValue();\n //当isForSelectTimeField为true情况,若indexPattern已经设置时间字段,则非时间字段按原始类型返回即可。\n String esType = ProxyUtils.convertCkTypeToEsType(ckName, ckType,\n isNotIndexPatternTimeField(indexPattern, ckName) ? Boolean.FALSE : isForSelectTimeField);\n JSONObject jsonObjectType = new JSONObject();\n jsonObjectType.put(esType, new IndexPatternFields(ckName, esType));\n result.put(ckName, jsonObjectType);\n }\n return result;\n }\n\n /**\n * 是否命中已经被设置为时间字段的字段名.\n *\n * @param indexPattern 当前index pattern\n * @param ckName ck字段名\n * @return boolean\n */\n private boolean isNotIndexPatternTimeField(IndexPattern indexPattern, String ckName) {\n return StringUtils.isNotBlank(indexPattern.getTimeField()) && !ckName.equals(indexPattern.getTimeField());\n }\n\n /**\n * 计算用户选择的时间框间隔ms.\n *\n * @param timeRange range时间范围\n */\n public long getTimeIntervalMillSeconds(Range timeRange) {\n return timeRange == null ? 0L : timeRange.getDiffMillSeconds();\n }\n\n /**\n * 时间参数round.\n * 2分钟内数据不round, 默认round 10s\n * 返回ui\n */\n public Range getTimeRangeAfterRound(CkRequestContext ckRequestContext) {\n Range result = ckRequestContext.getTimeRange();\n KibanaItemProperty kibanaItemProperty = proxyConfigLoader.getKibanaProperty().getProxy();\n boolean isRoundAble = getTimeIntervalMillSeconds(result) > kibanaItemProperty.getRoundAbleMinPeriod();\n if (isRoundAble) {\n int realRound = kibanaItemProperty.getRound() > 0 ? kibanaItemProperty.getRound() : Constants.ROUND_SECOND;\n result.setHigh(DateUtils.roundToMSecond(Math.min(System.currentTimeMillis(), (Long) result.getHigh()), realRound));\n result.setLow(DateUtils.roundToMSecond((Long) result.getLow(), realRound));\n }\n return result;\n }\n\n /**\n * 查询代理配置MaxResultRow.\n *\n * @return MaxResultRow\n */\n public int getMaxResultRow() {\n return this.proxyConfigLoader.getKibanaProperty().getQuery().getMaxResultRow();\n }\n}", "answers": [" IndexPattern indexPattern = paramParser.buildIndexPattern(context);"], "length": 2562, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "db13d161-592d-45e5-ba28-2a0a3d8af340", "reasoning": "After deserializing the request body into a JSONObject named searchQuery, the handler will need to determine the ClickHouse index pattern for the request. The ParamParser provides a buildIndexPattern method that takes the RequestContext. So the next logical line creates an IndexPattern using that parser.", "reasoning_model_answer": "IndexPattern indexPattern = paramParser.buildIndexPattern(context);", "assistant_with_reasoning": "\nAfter deserializing the request body into a JSONObject named searchQuery, the handler will need to determine the ClickHouse index pattern for the request. The ParamParser provides a buildIndexPattern method that takes the RequestContext. So the next logical line creates an IndexPattern using that parser.\n\nIndexPattern indexPattern = paramParser.buildIndexPattern(context);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.183, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 34675, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "IndexPattern indexPattern = paramParser.buildIndexPattern(context);", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.google.gson.Gson;\nimport de.morihofi.acmeserver.certificate.acme.api.Provisioner;\nimport de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint;\nimport de.morihofi.acmeserver.certificate.acme.api.endpoints.objects.Identifier;\nimport de.morihofi.acmeserver.certificate.acme.api.endpoints.order.objects.ACMEOrderResponse;\nimport de.morihofi.acmeserver.certificate.acme.api.endpoints.order.objects.FinalizeOrderRequestPayload;\nimport de.morihofi.acmeserver.certificate.objects.ACMERequestBody;\nimport de.morihofi.acmeserver.database.Database;\nimport de.morihofi.acmeserver.database.objects.ACMEAccount;\nimport de.morihofi.acmeserver.database.objects.ACMEIdentifier;\nimport de.morihofi.acmeserver.exception.exceptions.ACMEBadCsrException;\nimport de.morihofi.acmeserver.tools.base64.Base64Tools;\nimport de.morihofi.acmeserver.tools.certificate.PemUtil;\nimport de.morihofi.acmeserver.tools.certificate.dataExtractor.CsrDataExtractor;\nimport de.morihofi.acmeserver.tools.crypto.Crypto;\nimport de.morihofi.acmeserver.tools.dateAndTime.DateTools;\nimport de.morihofi.acmeserver.tools.certificate.generator.ServerCertificateGenerator;\nimport edu.umd.cs.findbugs.annotations.SuppressFBWarnings;\nimport io.javalin.http.Context;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.bouncycastle.pkcs.PKCS10CertificationRequest;\nimport org.bouncycastle.util.io.pem.PemObject;\nimport java.math.BigInteger;\nimport java.security.cert.X509Certificate;\nimport java.sql.Timestamp;\nimport java.util.List;\nimport java.util.stream.Collectors;", "context": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/order/FinalizeOrderEndpoint.java\npackage de.morihofi.acmeserver.certificate.acme.api.endpoints.order;\n\n\n\n\npublic class FinalizeOrderEndpoint extends AbstractAcmeEndpoint {\n\n /**\n * Logger\n */\n public final Logger log = LogManager.getLogger(getClass());\n\n /**\n * ACME Endpoint for finalize an order\n *\n * @param provisioner Provisioner instance\n */\n @SuppressFBWarnings(\"EI_EXPOSE_REP2\")\n public FinalizeOrderEndpoint(Provisioner provisioner) {\n super(provisioner);\n }\n\n @Override\n public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception {\n String orderId = ctx.pathParam(\"orderId\");\n\n ACMEAccount account = Database.getAccountByOrderId(orderId);\n // Check signature and nonce\n assert account != null;\n performSignatureAndNonceCheck(ctx, account, acmeRequestBody);\n\n //After check parse payload\n FinalizeOrderRequestPayload reqBodyPayloadObj = gson.fromJson(acmeRequestBody.getDecodedPayload(), FinalizeOrderRequestPayload.class);\n String csr = reqBodyPayloadObj.getCsr();\n\n List csrDomainNames = CsrDataExtractor.getDomainsFromCSR(csr);\n if (csrDomainNames.isEmpty()) {\n\nsrc/main/java/de/morihofi/acmeserver/certificate/objects/ACMERequestBody.java\npublic class ACMERequestBody {\n @SerializedName(\"protected\")\n private String protectedHeader;\n @SerializedName(\"payload\")\n private String payload;\n @SerializedName(\"signature\")\n private String signature;\n\n /**\n * Retrieves the decoded value of the protected header.\n * The protected header is Base64-encoded and contains information about the request and the signature algorithm.\n *\n * @return The decoded protected header as a {@code String}.\n */\n public String getDecodedProtected() {\n return Base64Tools.decodeBase64(protectedHeader);\n }\n\n /**\n * Retrieves the raw, Base64-encoded value of the protected header.\n *\n * @return The Base64-encoded protected header as a {@code String}.\n */\n public String getProtected() {\n return protectedHeader;\n }\n\n /**\n * Retrieves the raw, Base64-encoded payload of the ACME request.\n * The payload contains the actual data of the request.\n *\n * @return The Base64-encoded payload as a {@code String}.\n */\n public String getPayload() {\n return payload;\n }\n\n /**\n * Retrieves the decoded value of the payload.\n * The payload is Base64-encoded and contains the actual data of the request.\n *\n * @return The decoded payload as a {@code String}.\n */\n public String getDecodedPayload() {\n return Base64Tools.decodeBase64(payload);\n }\n\n /**\n * Retrieves the raw, Base64-encoded signature of the ACME request.\n * The signature verifies the authenticity and integrity of the protected header and payload.\n *\n * @return The Base64-encoded signature as a {@code String}.\n */\n public String getSignature() {\n return signature;\n }\n}\n\nsrc/main/java/de/morihofi/acmeserver/tools/certificate/dataExtractor/CsrDataExtractor.java\npublic class CsrDataExtractor {\n\n /**\n * Extracts domain names from a Certificate Signing Request (CSR) in PEM format.\n *\n * @param csr The Certificate Signing Request in PEM format.\n * @return A list of domain names (Subject Alternative Names) extracted from the CSR.\n * @throws IOException If an error occurs while processing the CSR.\n */\n public static List getDomainsFromCSR(String csr) throws IOException {\n byte[] csrBytes = Base64Tools.decodeBase64URLAsBytes(csr);\n PKCS10CertificationRequest certRequest = new PKCS10CertificationRequest(csrBytes);\n\n List domainList = new ArrayList<>();\n\n // Extract the SAN extension\n Extension sanExtension = certRequest.getRequestedExtensions().getExtension(Extension.subjectAlternativeName);\n if (sanExtension != null) {\n GeneralNames san = GeneralNames.getInstance(sanExtension.getParsedValue());\n GeneralName[] names = san.getNames();\n\n // Loop through all names in the SAN\n for (GeneralName name : names) {\n if (name.getTagNo() == GeneralName.dNSName) {\n String dnsName = name.getName().toString();\n domainList.add(dnsName);\n }\n }\n }\n\n\n return domainList;\n }\n}\n\nsrc/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java\npublic class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this server\n */\n public String getApiURL() {\n return \"https://\" + Main.appConfig.getServer().getDnsName() + \":\" + Main.appConfig.getServer().getPorts().getHttps() + \"/\" + provisionerName;\n }\n\n /**\n * Retrieves the server URL constructed from the application's configuration.\n * This method combines the DNS name and HTTPS port specified in the app configuration\n * to form the complete server URL.\n *\n * @return a String representing the full HTTPS URL of the server\n */\n public String getServerURL() {\n return \"https://\" + Main.appConfig.getServer().getDnsName() + \":\" + Main.appConfig.getServer().getPorts().getHttps();\n }\n\n\n /**\n * The name of the provisioner. Immutable after initial assignment.\n */\n private final String provisionerName;\n\n /**\n * Configuration for ACME (Automated Certificate Management Environment) metadata.\n * This configuration can be changed during the lifecycle of the object.\n */\n private MetadataConfig acmeMetadataConfig;\n\n /**\n * Configuration for the expiration of generated certificates.\n * This configuration can be adjusted as needed.\n */\n private CertificateExpiration generatedCertificateExpiration;\n\n /**\n * Flag indicating whether wildcards are allowed in certificate requests.\n * Can be toggled to enable or disable wildcard support.\n */\n private boolean wildcardAllowed;\n\n /**\n * Manager for cryptographic store operations.\n * Provides functionality for managing cryptographic elements such as keys and certificates.\n */\n private final CryptoStoreManager cryptoStoreManager;\n\n /**\n * Configuration for domain name restrictions.\n * Defines the constraints and rules for domain names in the context of this provisioner.\n */\n private final DomainNameRestrictionConfig domainNameRestriction;\n\n\n /**\n * Constructs a new Provisioner object.\n * This constructor initializes the Provisioner with the specified settings and configurations.\n * It sets up various aspects like the provisioner's name, ACME metadata configuration, certificate expiration settings,\n * domain name restrictions, wildcard allowance, and the crypto store manager.\n *\n * @param provisionerName The name of the provisioner.\n * @param acmeMetadataConfig The ACME metadata configuration.\n * @param generatedCertificateExpiration The settings for the expiration of generated certificates.\n * @param domainNameRestriction The configuration for domain name restrictions.\n * @param wildcardAllowed A boolean value indicating whether wildcards are allowed.\n * @param cryptoStoreManager The manager for cryptographic store operations.\n */\n @SuppressFBWarnings(\"EI_EXPOSE_REP2\")\n public Provisioner(String provisionerName, MetadataConfig acmeMetadataConfig, CertificateExpiration generatedCertificateExpiration, DomainNameRestrictionConfig domainNameRestriction, boolean wildcardAllowed, CryptoStoreManager cryptoStoreManager) {\n this.provisionerName = provisionerName;\n this.acmeMetadataConfig = acmeMetadataConfig;\n this.generatedCertificateExpiration = generatedCertificateExpiration;\n this.domainNameRestriction = domainNameRestriction;\n this.wildcardAllowed = wildcardAllowed;\n this.cryptoStoreManager = cryptoStoreManager;\n }\n\n /**\n * Checks if wildcard is allowed in the configuration.\n * This method returns a boolean indicating whether wildcard usage is permitted.\n *\n * @return {@code true} if wildcard is allowed, otherwise {@code false}.\n */\n public boolean isWildcardAllowed() {\n return wildcardAllowed;\n }\n\n /**\n * Sets the wildcard allowance status.\n * This method allows enabling or disabling the usage of wildcards.\n *\n * @param wildcardAllowed A boolean value to set the wildcard allowance status.\n */\n public void setWildcardAllowed(boolean wildcardAllowed) {\n this.wildcardAllowed = wildcardAllowed;\n }\n\n /**\n * Retrieves the domain name restriction configuration.\n * This configuration dictates the constraints on domain names.\n * Note: The returned object is a direct reference and any changes will affect the original object.\n *\n * @return The {@link DomainNameRestrictionConfig} object representing domain name restrictions.\n */\n @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n public DomainNameRestrictionConfig getDomainNameRestriction() {\n return domainNameRestriction;\n }\n\n\n /**\n * Retrieves the configuration for generated certificate expiration.\n * This object provides details about the expiration settings for generated certificates.\n * Note: The returned object is a direct reference and any changes will affect the original object.\n *\n * @return The {@link CertificateExpiration} object representing the expiration settings.\n */\n @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n public CertificateExpiration getGeneratedCertificateExpiration() {\n return generatedCertificateExpiration;\n }\n\n\n /**\n * Sets the configuration for generated certificate expiration.\n * This method allows setting the expiration details for newly generated certificates.\n * Note: The input object is used as a direct reference, and changes to it will reflect in the system.\n *\n * @param generatedCertificateExpiration The {@link CertificateExpiration} object to set.\n */\n @SuppressFBWarnings(\"EI_EXPOSE_REP2\")\n public void setGeneratedCertificateExpiration(CertificateExpiration generatedCertificateExpiration) {\n this.generatedCertificateExpiration = generatedCertificateExpiration;\n }\n\n /**\n * Retrieves the name of the provisioner.\n * This method returns the name assigned to the provisioner, which is\n * used in various other operations within the system.\n *\n * @return A {@code String} representing the name of the provisioner.\n */\n public String getProvisionerName() {\n return provisionerName;\n }\n\n /**\n * Constructs and returns the path for the Certificate Revocation List (CRL).\n * This method creates a path string for the CRL using the provisioner's name.\n * The path is typically used to access or store the CRL file in a specific directory structure.\n *\n * @return A {@code String} representing the path for the CRL file, specific to the provisioner.\n */\n public String getCrlPath() {\n return \"/crl/\" + getProvisionerName() + \".crl\";\n }\n\n /**\n * Constructs and returns the path for the Online Certificate Status Protocol (OCSP) service.\n * This method generates the path used to access the OCSP service, incorporating the provisioner's name.\n * The path is usually part of the URL used to interact with the OCSP service.\n *\n * @return A {@code String} representing the OCSP service path, associated with the provisioner.\n */\n public String getOcspPath() {\n return \"/\" + getProvisionerName() + \"/ocsp\";\n }\n\n /**\n * Retrieves the intermediate Certificate Authority (CA) certificate.\n * This method fetches the X.509 certificate associated with the intermediate CA\n * from the KeyStore. It uses a specific alias to locate the certificate.\n *\n * @return The intermediate CA's {@link X509Certificate}.\n * @throws KeyStoreException If an error occurs while accessing the KeyStore.\n */\n public X509Certificate getIntermediateCaCertificate() throws KeyStoreException {\n\n String alias = CryptoStoreManager.getKeyStoreAliasForProvisionerIntermediate(provisionerName);\n KeyStore keyStore = cryptoStoreManager.getKeyStore();\n return (X509Certificate) keyStore.getCertificate(alias);\n }\n\n /**\n * Retrieves the KeyPair associated with the intermediate Certificate Authority (CA).\n * This method fetches both the public and private keys for the intermediate CA from the KeyStore.\n * It utilizes a specific alias to locate these keys.\n *\n * @return A {@link KeyPair} consisting of the intermediate CA's public and private keys.\n * @throws KeyStoreException If an error occurs while accessing the KeyStore.\n * @throws UnrecoverableKeyException If the key cannot be recovered (typically due to an incorrect password or corruption).\n * @throws NoSuchAlgorithmException If the algorithm for recovering the key is not available.\n */\n public KeyPair getIntermediateCaKeyPair() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {\n\n String alias = CryptoStoreManager.getKeyStoreAliasForProvisionerIntermediate(provisionerName);\n\n KeyStore keyStore = cryptoStoreManager.getKeyStore();\n\n return new KeyPair(\n keyStore.getCertificate(alias).getPublicKey(),\n (PrivateKey) keyStore.getKey(alias, \"\".toCharArray())\n );\n }\n\n\n public MetadataConfig getAcmeMetadataConfig() {\n return acmeMetadataConfig;\n }\n\n @SuppressFBWarnings(\"EI_EXPOSE_REP2\")\n public void setAcmeMetadataConfig(MetadataConfig acmeMetadataConfig) {\n this.acmeMetadataConfig = acmeMetadataConfig;\n }\n\n /**\n * Returns the full OCSP (Online Certificate Status Protocol) URL.\n * This method combines the server URL with the OCSP path to construct\n * the full OCSP URL.\n *\n * @return A {@code String} representing the full OCSP URL.\n */\n public String getFullOcspUrl() {\n return getServerURL() + getOcspPath();\n }\n\n /**\n * Returns the full CRL (Certificate Revocation List) URL.\n * This method concatenates the server URL with the CRL path to\n * create the full CRL URL.\n *\n * @return A {@code String} representing the full CRL URL.\n */\n public String getFullCrlUrl() {\n return getServerURL() + getCrlPath();\n }\n\n\n /**\n * Retrieves the instance of the CryptoStoreManager.\n * This manager is responsible for managing cryptographic elements\n * such as keys and certificates.\n *\n * @return The {@code CryptoStoreManager} instance currently in use.\n */\n public CryptoStoreManager getCryptoStoreManager() {\n return cryptoStoreManager;\n }\n\n}\n\nsrc/main/java/de/morihofi/acmeserver/tools/dateAndTime/DateTools.java\npublic class DateTools {\n\n private DateTools(){}\n\n /**\n * Formats a {@link Date} object as a string in the ACME date format.\n *\n * @param date The {@link Date} object to be formatted.\n * @return A string representing the formatted date in the \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\" format in UTC time zone.\n */\n public static String formatDateForACME(Date date) {\n // Set the date format\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n\n // Format the date and return it as a string\n return dateFormat.format(date);\n }\n}\n\nsrc/main/java/de/morihofi/acmeserver/certificate/acme/api/abstractclass/AbstractAcmeEndpoint.java\npublic abstract class AbstractAcmeEndpoint implements Handler {\n\n /**\n * Instance for accessing the current provisioner\n */\n private final Provisioner provisioner;\n\n /**\n * Gson for JSON to POJO and POJO to JSON conversion\n */\n private final Gson gson;\n\n public AbstractAcmeEndpoint(Provisioner provisioner) {\n this.provisioner = provisioner;\n this.gson = new Gson();\n }\n\n public Provisioner getProvisioner() {\n return provisioner;\n }\n\n public Gson getGson() {\n return gson;\n }\n\n @Override\n public void handle(@NotNull Context ctx) throws Exception {\n ACMERequestBody acmeRequestBody = gson.fromJson(ctx.body(), ACMERequestBody.class);\n\n handleRequest(ctx, provisioner, gson, acmeRequestBody);\n }\n\n public abstract void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception;\n\n public void performSignatureAndNonceCheck(Context ctx, String accountId, ACMERequestBody acmeRequestBody) throws NoSuchAlgorithmException, SignatureException, IOException, InvalidKeySpecException, InvalidKeyException, NoSuchProviderException {\n // Check signature and nonce\n SignatureCheck.checkSignature(ctx, accountId, gson);\n NonceManager.checkNonceFromDecodedProtected(acmeRequestBody.getDecodedProtected());\n }\n\n public void performSignatureAndNonceCheck(Context ctx, ACMEAccount account, ACMERequestBody acmeRequestBody) throws NoSuchAlgorithmException, SignatureException, IOException, InvalidKeySpecException, InvalidKeyException, NoSuchProviderException {\n performSignatureAndNonceCheck(ctx, account.getAccountId(), acmeRequestBody);\n }\n}\n\nsrc/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/objects/Identifier.java\npublic class Identifier {\n\n /**\n * Type of the DNS identifier, mostly dns\n */\n private String type;\n\n /**\n * Value of the identifier, so it is the DNS Name\n */\n private String value;\n\n /**\n * Constructs a new Identifier with specified type and value.\n * This constructor initializes the Identifier with a specific type (e.g., 'dns') and its corresponding value.\n *\n * @param type The type of the identifier (e.g., 'dns').\n * @param value The value of the identifier (e.g., a DNS name).\n */\n public Identifier(String type, String value) {\n this.type = type;\n this.value = value;\n }\n\n /**\n * Default constructor for Identifier.\n * Constructs an Identifier with default values for type and value.\n */\n public Identifier() {\n }\n\n /**\n * Retrieves the type of this identifier.\n * The type usually indicates the category of the identifier (e.g., 'dns' for DNS names).\n *\n * @return The type of the identifier as a {@code String}.\n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the type of this identifier.\n * This method allows changing the type of the identifier.\n *\n * @param type The new type of the identifier as a {@code String}.\n */\n public void setType(String type) {\n this.type = type;\n }\n\n /**\n * Retrieves the value of this identifier.\n * The value is specific to the type of the identifier (e.g., a DNS name for type 'dns').\n *\n * @return The value of the identifier as a {@code String}.\n */\n public String getValue() {\n return value;\n }\n\n /**\n * Sets the value of this identifier.\n * This method allows changing the value of the identifier.\n *\n * @param value The new value of the identifier as a {@code String}.\n */\n public void setValue(String value) {\n this.value = value;\n }\n}", "answers": [" throw new ACMEBadCsrException(\"CSR does not contain any domain names\");"], "length": 2207, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "6aef28d9-8c57-4f6a-acaf-9b714a38b309", "reasoning": "The method is parsing the CSR and extracting domain names. If the list is empty, the code should signal an error. The imported ACMEBadCsrException is intended for CSR-related errors, so the next line inside the if‑block should throw this exception with an appropriate message.", "reasoning_model_answer": "throw new ACMEBadCsrException(\"CSR does not contain any domain names\");", "assistant_with_reasoning": "\nThe method is parsing the CSR and extracting domain names. If the list is empty, the code should signal an error. The imported ACMEBadCsrException is intended for CSR-related errors, so the next line inside the if‑block should throw this exception with an appropriate message.\n\nthrow new ACMEBadCsrException(\"CSR does not contain any domain names\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.019, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21504, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "throw new ACMEBadCsrException(\"CSR does not contain any domain names\");", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.Collection;\nimport java.util.Map;\nimport org.eclipse.emf.common.EMFPlugin;\nimport org.eclipse.emf.common.notify.AdapterFactory;\nimport org.eclipse.emf.common.util.ResourceLocator;\nimport org.eclipse.emf.ecore.EClass;\nimport org.eclipse.emf.ecore.resource.ResourceSet;\nimport org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;\nimport org.eclipse.emf.edit.provider.ComposedAdapterFactory;\nimport org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;\nimport org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;\nimport org.osgi.framework.BundleContext;\nimport nl.esi.emf.properties.provider.PropertiesEditPlugin;\nimport nl.esi.emf.properties.provider.PropertiesItemProviderAdapterFactory;\nimport nl.esi.pps.architecture.deployed.provider.DeployedItemProviderAdapterFactory;\nimport nl.esi.pps.architecture.implemented.provider.ImplementedItemProviderAdapterFactory;\nimport nl.esi.pps.architecture.instantiated.provider.InstantiatedItemProviderAdapterFactory;\nimport nl.esi.pps.architecture.provider.ArchitectureEditPlugin;\nimport nl.esi.pps.architecture.provider.ArchitectureItemProviderAdapterFactory;\nimport nl.esi.pps.architecture.specified.provider.SpecifiedItemProviderAdapterFactory;\nimport nl.esi.pps.common.emf.common.PngEclipsePlugin;\nimport nl.esi.pps.tmsc.provider.dataanalysis.IDataAnalysisItemContentProvider;\nimport nl.esi.pps.tmsc.provider.dataanalysis.internal.DataAnalysisItemContentProviderRegistryReader;", "context": "plugins/nl.esi.pps.tmsc.edit/src-gen/nl/esi/pps/tmsc/provider/TmscEditPlugin.java\n/**\n */\npackage nl.esi.pps.tmsc.provider;\n\n\n\n\n/**\n * This is the central singleton for the Tmsc edit plugin.\n * \n * \n * @generated\n */\npublic final class TmscEditPlugin extends EMFPlugin {\n\t/**\n\t * Keep track of the singleton.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic static final TmscEditPlugin INSTANCE = new TmscEditPlugin();\n\n\t/**\n\t * Keep track of the singleton.\n\t * \n\t * \n\t * @generated\n\t */\n\tprivate static Implementation plugin;\n\n\t/**\n\t * Create the instance.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic TmscEditPlugin() {\n\t\tsuper(new ResourceLocator[] { ArchitectureEditPlugin.INSTANCE, PropertiesEditPlugin.INSTANCE, });\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * \n\t * \n\t * @return the singleton instance.\n\t * @generated\n\t */\n\t@Override\n\nplugins/nl.esi.pps.architecture.edit/src-gen/nl/esi/pps/architecture/deployed/provider/DeployedItemProviderAdapterFactory.java\npublic class DeployedItemProviderAdapterFactory extends DeployedAdapterFactory\n\t\timplements ComposeableAdapterFactory, IChangeNotifier, IDisposable {\n\t/**\n\t * This keeps track of the root adapter factory that delegates to this adapter factory.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected ComposedAdapterFactory parentAdapterFactory;\n\n\t/**\n\t * This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected IChangeNotifier changeNotifier = new ChangeNotifier();\n\n\t/**\n\t * This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected Collection supportedTypes = new ArrayList();\n\n\t/**\n\t * This constructs an instance.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic DeployedItemProviderAdapterFactory() {\n\t\tsupportedTypes.add(IEditingDomainItemProvider.class);\n\t\tsupportedTypes.add(IStructuredItemContentProvider.class);\n\t\tsupportedTypes.add(ITreeItemContentProvider.class);\n\t\tsupportedTypes.add(IItemLabelProvider.class);\n\t\tsupportedTypes.add(IItemPropertySource.class);\n\t}\n\n\t/**\n\t * This keeps track of the one adapter used for all {@link nl.esi.pps.architecture.deployed.Host} instances.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected HostItemProvider hostItemProvider;\n\n\t/**\n\t * This creates an adapter for a {@link nl.esi.pps.architecture.deployed.Host}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter createHostAdapter() {\n\t\tif (hostItemProvider == null) {\n\t\t\thostItemProvider = new HostItemProvider(this);\n\t\t}\n\n\t\treturn hostItemProvider;\n\t}\n\n\t/**\n\t * This returns the root adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic ComposeableAdapterFactory getRootAdapterFactory() {\n\t\treturn parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();\n\t}\n\n\t/**\n\t * This sets the composed adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {\n\t\tthis.parentAdapterFactory = parentAdapterFactory;\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic boolean isFactoryForType(Object type) {\n\t\treturn supportedTypes.contains(type) || super.isFactoryForType(type);\n\t}\n\n\t/**\n\t * This implementation substitutes the factory itself as the key for the adapter.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter adapt(Notifier notifier, Object type) {\n\t\treturn super.adapt(notifier, this);\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Object adapt(Object object, Object type) {\n\t\tif (isFactoryForType(type)) {\n\t\t\tObject adapter = super.adapt(object, type);\n\t\t\tif (!(type instanceof Class) || (((Class) type).isInstance(adapter))) {\n\t\t\t\treturn adapter;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * This adds a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void addListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.addListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This removes a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void removeListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.removeListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void fireNotifyChanged(Notification notification) {\n\t\tchangeNotifier.fireNotifyChanged(notification);\n\n\t\tif (parentAdapterFactory != null) {\n\t\t\tparentAdapterFactory.fireNotifyChanged(notification);\n\t\t}\n\t}\n\n\t/**\n\t * This disposes all of the item providers created by this factory. \n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void dispose() {\n\t\tif (hostItemProvider != null)\n\t\t\thostItemProvider.dispose();\n\t}\n\n}\n\nplugins/nl.esi.emf.properties.edit/src-gen/nl/esi/emf/properties/provider/PropertiesEditPlugin.java\npublic final class PropertiesEditPlugin extends EMFPlugin {\n\t/**\n\t * Keep track of the singleton.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic static final PropertiesEditPlugin INSTANCE = new PropertiesEditPlugin();\n\n\t/**\n\t * Keep track of the singleton.\n\t * \n\t * \n\t * @generated\n\t */\n\tprivate static Implementation plugin;\n\n\t/**\n\t * Create the instance.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic PropertiesEditPlugin() {\n\t\tsuper(new ResourceLocator[] {});\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * \n\t * \n\t * @return the singleton instance.\n\t * @generated\n\t */\n\t@Override\n\tpublic ResourceLocator getPluginResourceLocator() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * \n\t * \n\t * @return the singleton instance.\n\t * @generated\n\t */\n\tpublic static Implementation getPlugin() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * The actual implementation of the Eclipse Plugin.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic static class Implementation extends EclipsePlugin {\n\t\t/**\n\t\t * Creates an instance.\n\t\t * \n\t\t * \n\t\t * @generated\n\t\t */\n\t\tpublic Implementation() {\n\t\t\tsuper();\n\n\t\t\t// Remember the static instance.\n\t\t\t//\n\t\t\tplugin = this;\n\t\t}\n\t}\n\n}\n\nplugins/nl.esi.pps.architecture.edit/src-gen/nl/esi/pps/architecture/specified/provider/SpecifiedItemProviderAdapterFactory.java\npublic class SpecifiedItemProviderAdapterFactory extends SpecifiedAdapterFactory\n\t\timplements ComposeableAdapterFactory, IChangeNotifier, IDisposable {\n\t/**\n\t * This keeps track of the root adapter factory that delegates to this adapter factory.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected ComposedAdapterFactory parentAdapterFactory;\n\n\t/**\n\t * This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected IChangeNotifier changeNotifier = new ChangeNotifier();\n\n\t/**\n\t * This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected Collection supportedTypes = new ArrayList();\n\n\t/**\n\t * This constructs an instance.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic SpecifiedItemProviderAdapterFactory() {\n\t\tsupportedTypes.add(IEditingDomainItemProvider.class);\n\t\tsupportedTypes.add(IStructuredItemContentProvider.class);\n\t\tsupportedTypes.add(ITreeItemContentProvider.class);\n\t\tsupportedTypes.add(IItemLabelProvider.class);\n\t\tsupportedTypes.add(IItemPropertySource.class);\n\t}\n\n\t/**\n\t * This keeps track of the one adapter used for all {@link nl.esi.pps.architecture.specified.Component} instances.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected ComponentItemProvider componentItemProvider;\n\n\t/**\n\t * This creates an adapter for a {@link nl.esi.pps.architecture.specified.Component}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter createComponentAdapter() {\n\t\tif (componentItemProvider == null) {\n\t\t\tcomponentItemProvider = new ComponentItemProvider(this);\n\t\t}\n\n\t\treturn componentItemProvider;\n\t}\n\n\t/**\n\t * This keeps track of the one adapter used for all {@link nl.esi.pps.architecture.specified.Interface} instances.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected InterfaceItemProvider interfaceItemProvider;\n\n\t/**\n\t * This creates an adapter for a {@link nl.esi.pps.architecture.specified.Interface}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter createInterfaceAdapter() {\n\t\tif (interfaceItemProvider == null) {\n\t\t\tinterfaceItemProvider = new InterfaceItemProvider(this);\n\t\t}\n\n\t\treturn interfaceItemProvider;\n\t}\n\n\t/**\n\t * This keeps track of the one adapter used for all {@link nl.esi.pps.architecture.specified.Operation} instances.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected OperationItemProvider operationItemProvider;\n\n\t/**\n\t * This creates an adapter for a {@link nl.esi.pps.architecture.specified.Operation}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter createOperationAdapter() {\n\t\tif (operationItemProvider == null) {\n\t\t\toperationItemProvider = new OperationItemProvider(this);\n\t\t}\n\n\t\treturn operationItemProvider;\n\t}\n\n\t/**\n\t * This returns the root adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic ComposeableAdapterFactory getRootAdapterFactory() {\n\t\treturn parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();\n\t}\n\n\t/**\n\t * This sets the composed adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {\n\t\tthis.parentAdapterFactory = parentAdapterFactory;\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic boolean isFactoryForType(Object type) {\n\t\treturn supportedTypes.contains(type) || super.isFactoryForType(type);\n\t}\n\n\t/**\n\t * This implementation substitutes the factory itself as the key for the adapter.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter adapt(Notifier notifier, Object type) {\n\t\treturn super.adapt(notifier, this);\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Object adapt(Object object, Object type) {\n\t\tif (isFactoryForType(type)) {\n\t\t\tObject adapter = super.adapt(object, type);\n\t\t\tif (!(type instanceof Class) || (((Class) type).isInstance(adapter))) {\n\t\t\t\treturn adapter;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * This adds a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void addListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.addListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This removes a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void removeListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.removeListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void fireNotifyChanged(Notification notification) {\n\t\tchangeNotifier.fireNotifyChanged(notification);\n\n\t\tif (parentAdapterFactory != null) {\n\t\t\tparentAdapterFactory.fireNotifyChanged(notification);\n\t\t}\n\t}\n\n\t/**\n\t * This disposes all of the item providers created by this factory. \n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void dispose() {\n\t\tif (componentItemProvider != null)\n\t\t\tcomponentItemProvider.dispose();\n\t\tif (interfaceItemProvider != null)\n\t\t\tinterfaceItemProvider.dispose();\n\t\tif (operationItemProvider != null)\n\t\t\toperationItemProvider.dispose();\n\t}\n\n}\n\nplugins/nl.esi.pps.architecture.edit/src-gen/nl/esi/pps/architecture/provider/ArchitectureItemProviderAdapterFactory.java\npublic class ArchitectureItemProviderAdapterFactory extends ArchitectureAdapterFactory\n\t\timplements ComposeableAdapterFactory, IChangeNotifier, IDisposable {\n\t/**\n\t * This keeps track of the root adapter factory that delegates to this adapter factory.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected ComposedAdapterFactory parentAdapterFactory;\n\n\t/**\n\t * This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected IChangeNotifier changeNotifier = new ChangeNotifier();\n\n\t/**\n\t * This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected Collection supportedTypes = new ArrayList();\n\n\t/**\n\t * This constructs an instance.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic ArchitectureItemProviderAdapterFactory() {\n\t\tsupportedTypes.add(IEditingDomainItemProvider.class);\n\t\tsupportedTypes.add(IStructuredItemContentProvider.class);\n\t\tsupportedTypes.add(ITreeItemContentProvider.class);\n\t\tsupportedTypes.add(IItemLabelProvider.class);\n\t\tsupportedTypes.add(IItemPropertySource.class);\n\t}\n\n\t/**\n\t * This returns the root adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic ComposeableAdapterFactory getRootAdapterFactory() {\n\t\treturn parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();\n\t}\n\n\t/**\n\t * This sets the composed adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {\n\t\tthis.parentAdapterFactory = parentAdapterFactory;\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic boolean isFactoryForType(Object type) {\n\t\treturn supportedTypes.contains(type) || super.isFactoryForType(type);\n\t}\n\n\t/**\n\t * This implementation substitutes the factory itself as the key for the adapter.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter adapt(Notifier notifier, Object type) {\n\t\treturn super.adapt(notifier, this);\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Object adapt(Object object, Object type) {\n\t\tif (isFactoryForType(type)) {\n\t\t\tObject adapter = super.adapt(object, type);\n\t\t\tif (!(type instanceof Class) || (((Class) type).isInstance(adapter))) {\n\t\t\t\treturn adapter;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * This adds a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void addListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.addListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This removes a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void removeListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.removeListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void fireNotifyChanged(Notification notification) {\n\t\tchangeNotifier.fireNotifyChanged(notification);\n\n\t\tif (parentAdapterFactory != null) {\n\t\t\tparentAdapterFactory.fireNotifyChanged(notification);\n\t\t}\n\t}\n\n\t/**\n\t * This disposes all of the item providers created by this factory. \n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void dispose() {\n\t}\n\n}\n\nplugins/nl.esi.emf.properties.edit/src-gen/nl/esi/emf/properties/provider/PropertiesItemProviderAdapterFactory.java\npublic class PropertiesItemProviderAdapterFactory extends PropertiesAdapterFactory\n\t\timplements ComposeableAdapterFactory, IChangeNotifier, IDisposable {\n\t/**\n\t * This keeps track of the root adapter factory that delegates to this adapter factory.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected ComposedAdapterFactory parentAdapterFactory;\n\n\t/**\n\t * This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected IChangeNotifier changeNotifier = new ChangeNotifier();\n\n\t/**\n\t * This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected Collection supportedTypes = new ArrayList();\n\n\t/**\n\t * This constructs an instance.\n\t * \n\t * \n\t * @generated\n\t */\n\tpublic PropertiesItemProviderAdapterFactory() {\n\t\tsupportedTypes.add(IEditingDomainItemProvider.class);\n\t\tsupportedTypes.add(IStructuredItemContentProvider.class);\n\t\tsupportedTypes.add(ITreeItemContentProvider.class);\n\t\tsupportedTypes.add(IItemLabelProvider.class);\n\t\tsupportedTypes.add(IItemPropertySource.class);\n\t}\n\n\t/**\n\t * This keeps track of the one adapter used for all {@link java.util.Map.Entry} instances.\n\t * \n\t * \n\t * @generated\n\t */\n\tprotected PropertyMapEntryItemProvider propertyMapEntryItemProvider;\n\n\t/**\n\t * This creates an adapter for a {@link java.util.Map.Entry}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter createPropertyMapEntryAdapter() {\n\t\tif (propertyMapEntryItemProvider == null) {\n\t\t\tpropertyMapEntryItemProvider = new PropertyMapEntryItemProvider(this);\n\t\t}\n\n\t\treturn propertyMapEntryItemProvider;\n\t}\n\n\t/**\n\t * This returns the root adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic ComposeableAdapterFactory getRootAdapterFactory() {\n\t\treturn parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();\n\t}\n\n\t/**\n\t * This sets the composed adapter factory that contains this factory.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {\n\t\tthis.parentAdapterFactory = parentAdapterFactory;\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic boolean isFactoryForType(Object type) {\n\t\treturn supportedTypes.contains(type) || super.isFactoryForType(type);\n\t}\n\n\t/**\n\t * This implementation substitutes the factory itself as the key for the adapter.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Adapter adapt(Notifier notifier, Object type) {\n\t\treturn super.adapt(notifier, this);\n\t}\n\n\t/**\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic Object adapt(Object object, Object type) {\n\t\tif (isFactoryForType(type)) {\n\t\t\tObject adapter = super.adapt(object, type);\n\t\t\tif (!(type instanceof Class) || (((Class) type).isInstance(adapter))) {\n\t\t\t\treturn adapter;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * This adds a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void addListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.addListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This removes a listener.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void removeListener(INotifyChangedListener notifyChangedListener) {\n\t\tchangeNotifier.removeListener(notifyChangedListener);\n\t}\n\n\t/**\n\t * This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.\n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void fireNotifyChanged(Notification notification) {\n\t\tchangeNotifier.fireNotifyChanged(notification);\n\n\t\tif (parentAdapterFactory != null) {\n\t\t\tparentAdapterFactory.fireNotifyChanged(notification);\n\t\t}\n\t}\n\n\t/**\n\t * This disposes all of the item providers created by this factory. \n\t * \n\t * \n\t * @generated\n\t */\n\t@Override\n\tpublic void dispose() {\n\t\tif (propertyMapEntryItemProvider != null)\n\t\t\tpropertyMapEntryItemProvider.dispose();\n\t}\n\n}", "answers": ["\tpublic ResourceLocator getPluginResourceLocator() {"], "length": 2421, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "d47990aa-801e-476b-a896-33ee0d00fcc7", "reasoning": "The class TmscEditPlugin extends EMFPlugin and follows the typical pattern of EMF edit plugins. After the @Override annotation, the next method defined is getPluginResourceLocator(), which returns the static plugin instance. This matches the structure seen in similar generated plugins.", "reasoning_model_answer": "public ResourceLocator getPluginResourceLocator() {", "assistant_with_reasoning": "\nThe class TmscEditPlugin extends EMFPlugin and follows the typical pattern of EMF edit plugins. After the @Override annotation, the next method defined is getPluginResourceLocator(), which returns the static plugin instance. This matches the structure seen in similar generated plugins.\n\npublic ResourceLocator getPluginResourceLocator() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.87, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 23432, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public ResourceLocator getPluginResourceLocator() {", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "from dataclasses import dataclass, field\nfrom threestudio.models.geometry.base import (\n BaseExplicitGeometry,\n BaseGeometry,\n contract_to_unisphere,\n)\nfrom threestudio.models.geometry.implicit_sdf import ImplicitSDF\nfrom threestudio.models.geometry.implicit_volume import ImplicitVolume\nfrom threestudio.models.isosurface import MarchingTetrahedraHelper\nfrom threestudio.models.mesh import Mesh\nfrom threestudio.models.networks import get_encoding, get_mlp\nfrom threestudio.utils.ops import scale_tensor\nfrom threestudio.utils.typing import *\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport threestudio", "context": "threestudio/models/geometry/tetrahedra_sdf_grid.py\n\n\n\n\n@threestudio.register(\"tetrahedra-sdf-grid\")\nclass TetrahedraSDFGrid(BaseExplicitGeometry):\n @dataclass\n class Config(BaseExplicitGeometry.Config):\n isosurface_resolution: int = 128\n isosurface_deformable_grid: bool = True\n isosurface_remove_outliers: bool = False\n isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01\n\n n_input_dims: int = 3\n n_feature_dims: int = 3\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n shape_init: Optional[str] = None\n shape_init_params: Optional[Any] = None\n force_shape_init: bool = False\n geometry_only: bool = False\n fix_geometry: bool = False\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n\n # this should be saved to state_dict, register as buffer\n self.isosurface_bbox: Float[Tensor, \"2 3\"]\n self.register_buffer(\"isosurface_bbox\", self.bbox.clone())\n\n self.isosurface_helper = MarchingTetrahedraHelper(\n self.cfg.isosurface_resolution,\n f\"load/tets/{self.cfg.isosurface_resolution}_tets.npz\",\n )\n\n self.sdf: Float[Tensor, \"Nv 1\"]\n self.deformation: Optional[Float[Tensor, \"Nv 3\"]]\n\n if not self.cfg.fix_geometry:\n self.register_parameter(\n \"sdf\",\n nn.Parameter(\n torch.zeros(\n (self.isosurface_helper.grid_vertices.shape[0], 1),\n dtype=torch.float32,\n )\n ),\n )\n if self.cfg.isosurface_deformable_grid:\n self.register_parameter(\n \"deformation\",\n nn.Parameter(\n torch.zeros_like(self.isosurface_helper.grid_vertices)\n ),\n )\n else:\n self.deformation = None\n else:\n self.register_buffer(\n \"sdf\",\n torch.zeros(\n (self.isosurface_helper.grid_vertices.shape[0], 1),\n dtype=torch.float32,\n ),\n )\n if self.cfg.isosurface_deformable_grid:\n self.register_buffer(\n \"deformation\",\n torch.zeros_like(self.isosurface_helper.grid_vertices),\n )\n else:\n self.deformation = None\n\n if not self.cfg.geometry_only:\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n\n self.mesh: Optional[Mesh] = None\n\n def initialize_shape(self) -> None:\n raise NotImplementedError\n\n def isosurface(self) -> Mesh:\n # return cached mesh if fix_geometry is True to save computation\n if self.cfg.fix_geometry and self.mesh is not None:\n return self.mesh\n mesh = self.isosurface_helper(self.sdf, self.deformation)\n mesh.v_pos = scale_tensor(\n mesh.v_pos, self.isosurface_helper.points_range, self.isosurface_bbox\n )\n if self.cfg.isosurface_remove_outliers:\n\n\nthreestudio/models/geometry/base.py\nclass BaseGeometry(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n @staticmethod\n def create_from(\n other: \"BaseGeometry\", cfg: Optional[Union[dict, DictConfig]] = None, **kwargs\n ) -> \"BaseGeometry\":\n raise TypeError(\n f\"Cannot create {BaseGeometry.__name__} from {other.__class__.__name__}\"\n )\n\n def export(self, *args, **kwargs) -> Dict[str, Any]:\n return {}\n\nthreestudio/utils/ops.py\ndef scale_tensor(\n dat: Num[Tensor, \"... D\"], inp_scale: ValidScale, tgt_scale: ValidScale\n):\n if inp_scale is None:\n inp_scale = (0, 1)\n if tgt_scale is None:\n tgt_scale = (0, 1)\n if isinstance(tgt_scale, Tensor):\n assert dat.shape[-1] == tgt_scale.shape[-1]\n dat = (dat - inp_scale[0]) / (inp_scale[1] - inp_scale[0])\n dat = dat * (tgt_scale[1] - tgt_scale[0]) + tgt_scale[0]\n return dat\n\nthreestudio/models/networks.py\ndef get_mlp(n_input_dims, n_output_dims, config) -> nn.Module:\n network: nn.Module\n if config.otype == \"VanillaMLP\":\n network = VanillaMLP(n_input_dims, n_output_dims, config_to_primitive(config))\n elif config.otype == \"SphereInitVanillaMLP\":\n network = SphereInitVanillaMLP(\n n_input_dims, n_output_dims, config_to_primitive(config)\n )\n else:\n assert (\n config.get(\"sphere_init\", False) is False\n ), \"sphere_init=True only supported by VanillaMLP\"\n network = TCNNNetwork(n_input_dims, n_output_dims, config_to_primitive(config))\n return network\n\nthreestudio/models/geometry/implicit_volume.py\nclass ImplicitVolume(BaseImplicitGeometry):\n @dataclass\n class Config(BaseImplicitGeometry.Config):\n n_input_dims: int = 3\n n_feature_dims: int = 3\n density_activation: Optional[str] = \"softplus\"\n density_bias: Union[float, str] = \"blob_magic3d\"\n density_blob_scale: float = 10.0\n density_blob_std: float = 0.5\n pos_encoding_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"HashGrid\",\n \"n_levels\": 16,\n \"n_features_per_level\": 2,\n \"log2_hashmap_size\": 19,\n \"base_resolution\": 16,\n \"per_level_scale\": 1.447269237440378,\n }\n )\n mlp_network_config: dict = field(\n default_factory=lambda: {\n \"otype\": \"VanillaMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"none\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n normal_type: Optional[\n str\n ] = \"finite_difference\" # in ['pred', 'finite_difference', 'finite_difference_laplacian']\n finite_difference_normal_eps: float = 0.01\n\n # automatically determine the threshold\n isosurface_threshold: Union[float, str] = 25.0\n\n cfg: Config\n\n def configure(self) -> None:\n super().configure()\n self.encoding = get_encoding(\n self.cfg.n_input_dims, self.cfg.pos_encoding_config\n )\n self.density_network = get_mlp(\n self.encoding.n_output_dims, 1, self.cfg.mlp_network_config\n )\n if self.cfg.n_feature_dims > 0:\n self.feature_network = get_mlp(\n self.encoding.n_output_dims,\n self.cfg.n_feature_dims,\n self.cfg.mlp_network_config,\n )\n if self.cfg.normal_type == \"pred\":\n self.normal_network = get_mlp(\n self.encoding.n_output_dims, 3, self.cfg.mlp_network_config\n )\n\n def get_activated_density(\n self, points: Float[Tensor, \"*N Di\"], density: Float[Tensor, \"*N 1\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Float[Tensor, \"*N 1\"]]:\n density_bias: Union[float, Float[Tensor, \"*N 1\"]]\n if self.cfg.density_bias == \"blob_dreamfusion\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * torch.exp(\n -0.5 * (points**2).sum(dim=-1) / self.cfg.density_blob_std**2\n )[..., None]\n )\n elif self.cfg.density_bias == \"blob_magic3d\":\n # pre-activation density bias\n density_bias = (\n self.cfg.density_blob_scale\n * (\n 1\n - torch.sqrt((points**2).sum(dim=-1)) / self.cfg.density_blob_std\n )[..., None]\n )\n elif isinstance(self.cfg.density_bias, float):\n density_bias = self.cfg.density_bias\n else:\n raise ValueError(f\"Unknown density bias {self.cfg.density_bias}\")\n raw_density: Float[Tensor, \"*N 1\"] = density + density_bias\n density = get_activation(self.cfg.density_activation)(raw_density)\n return raw_density, density\n\n def forward(\n self, points: Float[Tensor, \"*N Di\"], output_normal: bool = False\n ) -> Dict[str, Float[Tensor, \"...\"]]:\n grad_enabled = torch.is_grad_enabled()\n assert self.unbounded\n\n if output_normal and self.cfg.normal_type == \"analytic\":\n torch.set_grad_enabled(True)\n points.requires_grad_(True)\n\n points_unscaled = points # points in the original scale\n points = contract_to_unisphere(\n points, self.bbox, self.unbounded\n ) # points normalized to (0, 1)\n\n enc = self.encoding(points.view(-1, self.cfg.n_input_dims))\n density = self.density_network(enc).view(*points.shape[:-1], 1)\n raw_density, density = self.get_activated_density(points_unscaled, density)\n\n output = {\n \"density\": density,\n }\n\n if self.cfg.n_feature_dims > 0:\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n output.update({\"features\": features})\n\n if output_normal:\n if (\n self.cfg.normal_type == \"finite_difference\"\n or self.cfg.normal_type == \"finite_difference_laplacian\"\n ):\n # TODO: use raw density\n eps = self.cfg.finite_difference_normal_eps\n if self.cfg.normal_type == \"finite_difference_laplacian\":\n offsets: Float[Tensor, \"6 3\"] = torch.as_tensor(\n [\n [eps, 0.0, 0.0],\n [-eps, 0.0, 0.0],\n [0.0, eps, 0.0],\n [0.0, -eps, 0.0],\n [0.0, 0.0, eps],\n [0.0, 0.0, -eps],\n ]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 6 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 6 1\"] = self.forward_density(\n points_offset\n )\n normal = (\n -0.5\n * (density_offset[..., 0::2, 0] - density_offset[..., 1::2, 0])\n / eps\n )\n else:\n offsets: Float[Tensor, \"3 3\"] = torch.as_tensor(\n [[eps, 0.0, 0.0], [0.0, eps, 0.0], [0.0, 0.0, eps]]\n ).to(points_unscaled)\n points_offset: Float[Tensor, \"... 3 3\"] = (\n points_unscaled[..., None, :] + offsets\n ).clamp(-self.cfg.radius, self.cfg.radius)\n density_offset: Float[Tensor, \"... 3 1\"] = self.forward_density(\n points_offset\n )\n normal = -(density_offset[..., 0::1, 0] - density) / eps\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"pred\":\n normal = self.normal_network(enc).view(*points.shape[:-1], 3)\n normal = F.normalize(normal, dim=-1)\n elif self.cfg.normal_type == \"analytic\":\n normal = -torch.autograd.grad(\n density,\n points_unscaled,\n grad_outputs=torch.ones_like(density),\n create_graph=True,\n )[0]\n normal = F.normalize(normal, dim=-1)\n if not grad_enabled:\n normal = normal.detach()\n else:\n raise AttributeError(f\"Unknown normal type {self.cfg.normal_type}\")\n output.update({\"normal\": normal, \"shading_normal\": normal})\n\n torch.set_grad_enabled(grad_enabled)\n return output\n\n def forward_density(self, points: Float[Tensor, \"*N Di\"]) -> Float[Tensor, \"*N 1\"]:\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n\n density = self.density_network(\n self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n ).reshape(*points.shape[:-1], 1)\n\n _, density = self.get_activated_density(points_unscaled, density)\n return density\n\n def forward_field(\n self, points: Float[Tensor, \"*N Di\"]\n ) -> Tuple[Float[Tensor, \"*N 1\"], Optional[Float[Tensor, \"*N 3\"]]]:\n if self.cfg.isosurface_deformable_grid:\n threestudio.warn(\n f\"{self.__class__.__name__} does not support isosurface_deformable_grid. Ignoring.\"\n )\n density = self.forward_density(points)\n return density, None\n\n def forward_level(\n self, field: Float[Tensor, \"*N 1\"], threshold: float\n ) -> Float[Tensor, \"*N 1\"]:\n return -(field - threshold)\n\n def export(self, points: Float[Tensor, \"*N Di\"], **kwargs) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.cfg.n_feature_dims == 0:\n return out\n points_unscaled = points\n points = contract_to_unisphere(points_unscaled, self.bbox, self.unbounded)\n enc = self.encoding(points.reshape(-1, self.cfg.n_input_dims))\n features = self.feature_network(enc).view(\n *points.shape[:-1], self.cfg.n_feature_dims\n )\n out.update(\n {\n \"features\": features,\n }\n )\n return out\n\n @staticmethod\n @torch.no_grad()\n def create_from(\n other: BaseGeometry,\n cfg: Optional[Union[dict, DictConfig]] = None,\n copy_net: bool = True,\n **kwargs,\n ) -> \"ImplicitVolume\":\n if isinstance(other, ImplicitVolume):\n instance = ImplicitVolume(cfg, **kwargs)\n instance.encoding.load_state_dict(other.encoding.state_dict())\n instance.density_network.load_state_dict(other.density_network.state_dict())\n if copy_net:\n if (\n instance.cfg.n_feature_dims > 0\n and other.cfg.n_feature_dims == instance.cfg.n_feature_dims\n ):\n instance.feature_network.load_state_dict(\n other.feature_network.state_dict()\n )\n if (\n instance.cfg.normal_type == \"pred\"\n and other.cfg.normal_type == \"pred\"\n ):\n instance.normal_network.load_state_dict(\n other.normal_network.state_dict()\n )\n return instance\n else:\n raise TypeError(\n f\"Cannot create {ImplicitVolume.__name__} from {other.__class__.__name__}\"\n )\n\nthreestudio/models/isosurface.py\nclass MarchingTetrahedraHelper(IsosurfaceHelper):\n def __init__(self, resolution: int, tets_path: str):\n super().__init__()\n self.resolution = resolution\n self.tets_path = tets_path\n\n self.triangle_table: Float[Tensor, \"...\"]\n self.register_buffer(\n \"triangle_table\",\n torch.as_tensor(\n [\n [-1, -1, -1, -1, -1, -1],\n [1, 0, 2, -1, -1, -1],\n [4, 0, 3, -1, -1, -1],\n [1, 4, 2, 1, 3, 4],\n [3, 1, 5, -1, -1, -1],\n [2, 3, 0, 2, 5, 3],\n [1, 4, 0, 1, 5, 4],\n [4, 2, 5, -1, -1, -1],\n [4, 5, 2, -1, -1, -1],\n [4, 1, 0, 4, 5, 1],\n [3, 2, 0, 3, 5, 2],\n [1, 3, 5, -1, -1, -1],\n [4, 1, 2, 4, 3, 1],\n [3, 0, 4, -1, -1, -1],\n [2, 0, 1, -1, -1, -1],\n [-1, -1, -1, -1, -1, -1],\n ],\n dtype=torch.long,\n ),\n persistent=False,\n )\n self.num_triangles_table: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"num_triangles_table\",\n torch.as_tensor(\n [0, 1, 1, 2, 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 1, 0], dtype=torch.long\n ),\n persistent=False,\n )\n self.base_tet_edges: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"base_tet_edges\",\n torch.as_tensor([0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3], dtype=torch.long),\n persistent=False,\n )\n\n tets = np.load(self.tets_path)\n self._grid_vertices: Float[Tensor, \"...\"]\n self.register_buffer(\n \"_grid_vertices\",\n torch.from_numpy(tets[\"vertices\"]).float(),\n persistent=False,\n )\n self.indices: Integer[Tensor, \"...\"]\n self.register_buffer(\n \"indices\", torch.from_numpy(tets[\"indices\"]).long(), persistent=False\n )\n\n self._all_edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n\n def normalize_grid_deformation(\n self, grid_vertex_offsets: Float[Tensor, \"Nv 3\"]\n ) -> Float[Tensor, \"Nv 3\"]:\n return (\n (self.points_range[1] - self.points_range[0])\n / (self.resolution) # half tet size is approximately 1 / self.resolution\n * torch.tanh(grid_vertex_offsets)\n ) # FIXME: hard-coded activation\n\n @property\n def grid_vertices(self) -> Float[Tensor, \"Nv 3\"]:\n return self._grid_vertices\n\n @property\n def all_edges(self) -> Integer[Tensor, \"Ne 2\"]:\n if self._all_edges is None:\n # compute edges on GPU, or it would be VERY SLOW (basically due to the unique operation)\n edges = torch.tensor(\n [0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3],\n dtype=torch.long,\n device=self.indices.device,\n )\n _all_edges = self.indices[:, edges].reshape(-1, 2)\n _all_edges_sorted = torch.sort(_all_edges, dim=1)[0]\n _all_edges = torch.unique(_all_edges_sorted, dim=0)\n self._all_edges = _all_edges\n return self._all_edges\n\n def sort_edges(self, edges_ex2):\n with torch.no_grad():\n order = (edges_ex2[:, 0] > edges_ex2[:, 1]).long()\n order = order.unsqueeze(dim=1)\n\n a = torch.gather(input=edges_ex2, index=order, dim=1)\n b = torch.gather(input=edges_ex2, index=1 - order, dim=1)\n\n return torch.stack([a, b], -1)\n\n def _forward(self, pos_nx3, sdf_n, tet_fx4):\n with torch.no_grad():\n occ_n = sdf_n > 0\n occ_fx4 = occ_n[tet_fx4.reshape(-1)].reshape(-1, 4)\n occ_sum = torch.sum(occ_fx4, -1)\n valid_tets = (occ_sum > 0) & (occ_sum < 4)\n occ_sum = occ_sum[valid_tets]\n\n # find all vertices\n all_edges = tet_fx4[valid_tets][:, self.base_tet_edges].reshape(-1, 2)\n all_edges = self.sort_edges(all_edges)\n unique_edges, idx_map = torch.unique(all_edges, dim=0, return_inverse=True)\n\n unique_edges = unique_edges.long()\n mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1\n mapping = (\n torch.ones(\n (unique_edges.shape[0]), dtype=torch.long, device=pos_nx3.device\n )\n * -1\n )\n mapping[mask_edges] = torch.arange(\n mask_edges.sum(), dtype=torch.long, device=pos_nx3.device\n )\n idx_map = mapping[idx_map] # map edges to verts\n\n interp_v = unique_edges[mask_edges]\n edges_to_interp = pos_nx3[interp_v.reshape(-1)].reshape(-1, 2, 3)\n edges_to_interp_sdf = sdf_n[interp_v.reshape(-1)].reshape(-1, 2, 1)\n edges_to_interp_sdf[:, -1] *= -1\n\n denominator = edges_to_interp_sdf.sum(1, keepdim=True)\n\n edges_to_interp_sdf = torch.flip(edges_to_interp_sdf, [1]) / denominator\n verts = (edges_to_interp * edges_to_interp_sdf).sum(1)\n\n idx_map = idx_map.reshape(-1, 6)\n\n v_id = torch.pow(2, torch.arange(4, dtype=torch.long, device=pos_nx3.device))\n tetindex = (occ_fx4[valid_tets] * v_id.unsqueeze(0)).sum(-1)\n num_triangles = self.num_triangles_table[tetindex]\n\n # Generate triangle indices\n faces = torch.cat(\n (\n torch.gather(\n input=idx_map[num_triangles == 1],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 1]][:, :3],\n ).reshape(-1, 3),\n torch.gather(\n input=idx_map[num_triangles == 2],\n dim=1,\n index=self.triangle_table[tetindex[num_triangles == 2]][:, :6],\n ).reshape(-1, 3),\n ),\n dim=0,\n )\n\n return verts, faces\n\n def forward(\n self,\n level: Float[Tensor, \"N3 1\"],\n deformation: Optional[Float[Tensor, \"N3 3\"]] = None,\n ) -> Mesh:\n if deformation is not None:\n grid_vertices = self.grid_vertices + self.normalize_grid_deformation(\n deformation\n )\n else:\n grid_vertices = self.grid_vertices\n\n v_pos, t_pos_idx = self._forward(grid_vertices, level, self.indices)\n\n mesh = Mesh(\n v_pos=v_pos,\n t_pos_idx=t_pos_idx,\n # extras\n grid_vertices=grid_vertices,\n tet_edges=self.all_edges,\n grid_level=level,\n grid_deformation=deformation,\n )\n\n return mesh\n\nthreestudio/models/mesh.py\nclass Mesh:\n def __init__(\n self, v_pos: Float[Tensor, \"Nv 3\"], t_pos_idx: Integer[Tensor, \"Nf 3\"], **kwargs\n ) -> None:\n self.v_pos: Float[Tensor, \"Nv 3\"] = v_pos\n self.t_pos_idx: Integer[Tensor, \"Nf 3\"] = t_pos_idx\n self._v_nrm: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tng: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._v_tex: Optional[Float[Tensor, \"Nt 3\"]] = None\n self._t_tex_idx: Optional[Float[Tensor, \"Nf 3\"]] = None\n self._v_rgb: Optional[Float[Tensor, \"Nv 3\"]] = None\n self._edges: Optional[Integer[Tensor, \"Ne 2\"]] = None\n self.extras: Dict[str, Any] = {}\n for k, v in kwargs.items():\n self.add_extra(k, v)\n\n def add_extra(self, k, v) -> None:\n self.extras[k] = v\n\n def remove_outlier(self, outlier_n_faces_threshold: Union[int, float]) -> Mesh:\n if self.requires_grad:\n threestudio.debug(\"Mesh is differentiable, not removing outliers\")\n return self\n\n # use trimesh to first split the mesh into connected components\n # then remove the components with less than n_face_threshold faces\n import trimesh\n\n # construct a trimesh object\n mesh = trimesh.Trimesh(\n vertices=self.v_pos.detach().cpu().numpy(),\n faces=self.t_pos_idx.detach().cpu().numpy(),\n )\n\n # split the mesh into connected components\n components = mesh.split(only_watertight=False)\n # log the number of faces in each component\n threestudio.debug(\n \"Mesh has {} components, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n\n n_faces_threshold: int\n if isinstance(outlier_n_faces_threshold, float):\n # set the threshold to the number of faces in the largest component multiplied by outlier_n_faces_threshold\n n_faces_threshold = int(\n max([c.faces.shape[0] for c in components]) * outlier_n_faces_threshold\n )\n else:\n # set the threshold directly to outlier_n_faces_threshold\n n_faces_threshold = outlier_n_faces_threshold\n\n # log the threshold\n threestudio.debug(\n \"Removing components with less than {} faces\".format(n_faces_threshold)\n )\n\n # remove the components with less than n_face_threshold faces\n components = [c for c in components if c.faces.shape[0] >= n_faces_threshold]\n\n # log the number of faces in each component after removing outliers\n threestudio.debug(\n \"Mesh has {} components after removing outliers, with faces: {}\".format(\n len(components), [c.faces.shape[0] for c in components]\n )\n )\n # merge the components\n mesh = trimesh.util.concatenate(components)\n\n # convert back to our mesh format\n v_pos = torch.from_numpy(mesh.vertices).to(self.v_pos)\n t_pos_idx = torch.from_numpy(mesh.faces).to(self.t_pos_idx)\n\n clean_mesh = Mesh(v_pos, t_pos_idx)\n # keep the extras unchanged\n\n if len(self.extras) > 0:\n clean_mesh.extras = self.extras\n threestudio.debug(\n f\"The following extra attributes are inherited from the original mesh unchanged: {list(self.extras.keys())}\"\n )\n return clean_mesh\n\n @property\n def requires_grad(self):\n return self.v_pos.requires_grad\n\n @property\n def v_nrm(self):\n if self._v_nrm is None:\n self._v_nrm = self._compute_vertex_normal()\n return self._v_nrm\n\n @property\n def v_tng(self):\n if self._v_tng is None:\n self._v_tng = self._compute_vertex_tangent()\n return self._v_tng\n\n @property\n def v_tex(self):\n if self._v_tex is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._v_tex\n\n @property\n def t_tex_idx(self):\n if self._t_tex_idx is None:\n self._v_tex, self._t_tex_idx = self._unwrap_uv()\n return self._t_tex_idx\n\n @property\n def v_rgb(self):\n return self._v_rgb\n\n @property\n def edges(self):\n if self._edges is None:\n self._edges = self._compute_edges()\n return self._edges\n\n def _compute_vertex_normal(self):\n i0 = self.t_pos_idx[:, 0]\n i1 = self.t_pos_idx[:, 1]\n i2 = self.t_pos_idx[:, 2]\n\n v0 = self.v_pos[i0, :]\n v1 = self.v_pos[i1, :]\n v2 = self.v_pos[i2, :]\n\n face_normals = torch.cross(v1 - v0, v2 - v0)\n\n # Splat face normals to vertices\n v_nrm = torch.zeros_like(self.v_pos)\n v_nrm.scatter_add_(0, i0[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i1[:, None].repeat(1, 3), face_normals)\n v_nrm.scatter_add_(0, i2[:, None].repeat(1, 3), face_normals)\n\n # Normalize, replace zero (degenerated) normals with some default value\n v_nrm = torch.where(\n dot(v_nrm, v_nrm) > 1e-20, v_nrm, torch.as_tensor([0.0, 0.0, 1.0]).to(v_nrm)\n )\n v_nrm = F.normalize(v_nrm, dim=1)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(v_nrm))\n\n return v_nrm\n\n def _compute_vertex_tangent(self):\n vn_idx = [None] * 3\n pos = [None] * 3\n tex = [None] * 3\n for i in range(0, 3):\n pos[i] = self.v_pos[self.t_pos_idx[:, i]]\n tex[i] = self.v_tex[self.t_tex_idx[:, i]]\n # t_nrm_idx is always the same as t_pos_idx\n vn_idx[i] = self.t_pos_idx[:, i]\n\n tangents = torch.zeros_like(self.v_nrm)\n tansum = torch.zeros_like(self.v_nrm)\n\n # Compute tangent space for each triangle\n uve1 = tex[1] - tex[0]\n uve2 = tex[2] - tex[0]\n pe1 = pos[1] - pos[0]\n pe2 = pos[2] - pos[0]\n\n nom = pe1 * uve2[..., 1:2] - pe2 * uve1[..., 1:2]\n denom = uve1[..., 0:1] * uve2[..., 1:2] - uve1[..., 1:2] * uve2[..., 0:1]\n\n # Avoid division by zero for degenerated texture coordinates\n tang = nom / torch.where(\n denom > 0.0, torch.clamp(denom, min=1e-6), torch.clamp(denom, max=-1e-6)\n )\n\n # Update all 3 vertices\n for i in range(0, 3):\n idx = vn_idx[i][:, None].repeat(1, 3)\n tangents.scatter_add_(0, idx, tang) # tangents[n_i] = tangents[n_i] + tang\n tansum.scatter_add_(\n 0, idx, torch.ones_like(tang)\n ) # tansum[n_i] = tansum[n_i] + 1\n tangents = tangents / tansum\n\n # Normalize and make sure tangent is perpendicular to normal\n tangents = F.normalize(tangents, dim=1)\n tangents = F.normalize(tangents - dot(tangents, self.v_nrm) * self.v_nrm)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(tangents))\n\n return tangents\n\n def _unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n threestudio.info(\"Using xatlas to perform UV unwrapping, may take a while ...\")\n\n import xatlas\n\n atlas = xatlas.Atlas()\n atlas.add_mesh(\n self.v_pos.detach().cpu().numpy(),\n self.t_pos_idx.cpu().numpy(),\n )\n co = xatlas.ChartOptions()\n po = xatlas.PackOptions()\n for k, v in xatlas_chart_options.items():\n setattr(co, k, v)\n for k, v in xatlas_pack_options.items():\n setattr(po, k, v)\n atlas.generate(co, po)\n vmapping, indices, uvs = atlas.get_mesh(0)\n vmapping = (\n torch.from_numpy(\n vmapping.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n uvs = torch.from_numpy(uvs).to(self.v_pos.device).float()\n indices = (\n torch.from_numpy(\n indices.astype(np.uint64, casting=\"same_kind\").view(np.int64)\n )\n .to(self.v_pos.device)\n .long()\n )\n return uvs, indices\n\n def unwrap_uv(\n self, xatlas_chart_options: dict = {}, xatlas_pack_options: dict = {}\n ):\n self._v_tex, self._t_tex_idx = self._unwrap_uv(\n xatlas_chart_options, xatlas_pack_options\n )\n\n def set_vertex_color(self, v_rgb):\n assert v_rgb.shape[0] == self.v_pos.shape[0]\n self._v_rgb = v_rgb\n\n def _compute_edges(self):\n # Compute edges\n edges = torch.cat(\n [\n self.t_pos_idx[:, [0, 1]],\n self.t_pos_idx[:, [1, 2]],\n self.t_pos_idx[:, [2, 0]],\n ],\n dim=0,\n )\n edges = edges.sort()[0]\n edges = torch.unique(edges, dim=0)\n return edges\n\n def normal_consistency(self) -> Float[Tensor, \"\"]:\n edge_nrm: Float[Tensor, \"Ne 2 3\"] = self.v_nrm[self.edges]\n nc = (\n 1.0 - torch.cosine_similarity(edge_nrm[:, 0], edge_nrm[:, 1], dim=-1)\n ).mean()\n return nc\n\n def _laplacian_uniform(self):\n # from stable-dreamfusion\n # https://github.com/ashawkey/stable-dreamfusion/blob/8fb3613e9e4cd1ded1066b46e80ca801dfb9fd06/nerf/renderer.py#L224\n verts, faces = self.v_pos, self.t_pos_idx\n\n V = verts.shape[0]\n F = faces.shape[0]\n\n # Neighbor indices\n ii = faces[:, [1, 2, 0]].flatten()\n jj = faces[:, [2, 0, 1]].flatten()\n adj = torch.stack([torch.cat([ii, jj]), torch.cat([jj, ii])], dim=0).unique(\n dim=1\n )\n adj_values = torch.ones(adj.shape[1]).to(verts)\n\n # Diagonal indices\n diag_idx = adj[0]\n\n # Build the sparse matrix\n idx = torch.cat((adj, torch.stack((diag_idx, diag_idx), dim=0)), dim=1)\n values = torch.cat((-adj_values, adj_values))\n\n # The coalesce operation sums the duplicate indices, resulting in the\n # correct diagonal\n return torch.sparse_coo_tensor(idx, values, (V, V)).coalesce()\n\n def laplacian(self) -> Float[Tensor, \"\"]:\n with torch.no_grad():\n L = self._laplacian_uniform()\n loss = L.mm(self.v_pos)\n loss = loss.norm(dim=1)\n loss = loss.mean()\n return loss", "answers": [" mesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold)"], "length": 2654, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "4ced9e3e-1998-4371-9ecd-df38441162d7", "reasoning": "The isosurface method builds a mesh, scales its vertices, then checks cfg.isosurface_remove_outliers. The next logical step is to remove outlier faces using the mesh's remove_outlier method with the configured threshold, assigning the result back to mesh before returning it.", "reasoning_model_answer": "mesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold)", "assistant_with_reasoning": "\nThe isosurface method builds a mesh, scales its vertices, then checks cfg.isosurface_remove_outliers. The next logical step is to remove outlier faces using the mesh's remove_outlier method with the configured threshold, assigning the result back to mesh before returning it.\n\nmesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.295, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33634, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "mesh = mesh.remove_outlier(self.cfg.isosurface_outlier_n_faces_threshold)", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import cc.polyfrost.oneconfig.utils.Multithreading;\nimport com.github.may2beez.mayobees.config.MayOBeesConfig;\nimport com.github.may2beez.mayobees.event.ClickEvent;\nimport com.github.may2beez.mayobees.module.IModule;\nimport net.minecraft.block.state.IBlockState;\nimport net.minecraft.client.Minecraft;\nimport net.minecraft.item.ItemStack;\nimport net.minecraft.util.BlockPos;\nimport net.minecraftforge.event.world.WorldEvent;\nimport net.minecraftforge.fml.common.eventhandler.SubscribeEvent;\nimport java.util.concurrent.CopyOnWriteArrayList;\nimport java.util.concurrent.TimeUnit;", "context": "src/main/java/com/github/may2beez/mayobees/module/impl/other/GhostBlocks.java\npackage com.github.may2beez.mayobees.module.impl.other;\n\n\n\npublic class GhostBlocks implements IModule {\n private final Minecraft mc = Minecraft.getMinecraft();\n private static GhostBlocks instance;\n private final CopyOnWriteArrayList clickedBlocks = new CopyOnWriteArrayList<>();\n\n public static GhostBlocks getInstance() {\n if (instance == null) {\n instance = new GhostBlocks();\n }\n return instance;\n }\n\n @Override\n public String getName() {\n return \"Ghost Blocks\";\n }\n\n @Override\n public boolean isRunning() {\n return MayOBeesConfig.enableGhostBlocks;\n }\n\n @SubscribeEvent\n public void onMiddleClick(ClickEvent.Middle event) {\n if (event.block == null) return;\n if (!isRunning()) return;\n\n if (MayOBeesConfig.ghostBlocksOnlyWhileHoldingStonk) {\n ItemStack heldItem = mc.thePlayer.getHeldItem();\n if (heldItem == null || !heldItem.getDisplayName().contains(\"Stonk\")) return;\n }\n\n if (clickedBlocks.stream().noneMatch(ghostBlock -> ghostBlock.pos.equals(event.blockPos))) {\n GhostBlock gb = new GhostBlock(event.blockPos, mc.theWorld.getBlockState(event.blockPos));\n clickedBlocks.add(gb);\n mc.theWorld.setBlockToAir(event.blockPos);\n Multithreading.schedule(() -> {\n if (!clickedBlocks.contains(gb)) return;\n mc.theWorld.setBlockState(gb.pos, gb.previousBlockState);\n clickedBlocks.remove(gb);\n }, MayOBeesConfig.ghostBlocksDuration, TimeUnit.MILLISECONDS);\n }\n }\n\n @SubscribeEvent\n public void onWorldChange(WorldEvent.Unload event) {\n clickedBlocks.clear();\n }\n\n private static class GhostBlock {\n\nsrc/main/java/com/github/may2beez/mayobees/event/ClickEvent.java\npublic class ClickEvent extends Event {\n public Entity entity;\n public BlockPos blockPos;\n public Block block;\n\n protected ClickEvent() {\n }\n\n protected ClickEvent(Entity entity) {\n this.entity = entity;\n }\n\n protected ClickEvent(BlockPos blockPos) {\n this.blockPos = blockPos;\n this.block = Minecraft.getMinecraft().theWorld.getBlockState(blockPos).getBlock();\n }\n\n public static class Left extends ClickEvent {\n public Left(Entity entity) {\n super(entity);\n }\n public Left(BlockPos blockPos) {\n super(blockPos);\n }\n public Left() {\n super();\n }\n }\n\n public static class Right extends ClickEvent {\n public Right(Entity entity) {\n super(entity);\n }\n public Right(BlockPos blockPos) {\n super(blockPos);\n }\n public Right() {\n super();\n }\n }\n\n public static class Middle extends ClickEvent {\n public Middle(Entity entity) {\n super(entity);\n }\n public Middle(BlockPos blockPos) {\n super(blockPos);\n }\n public Middle() {\n super();\n }\n }\n}\n\nsrc/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java\npublic class MayOBeesConfig extends Config {\n\n //\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatically shoots arrows at nearby enemies\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static OneKeyBind shortBowAuraKeybind = new OneKeyBind(Keyboard.KEY_O);\n\n @Text(\n name = \"Shortbow Aura Item's Name\",\n description = \"The name of the item to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2\n )\n public static String shortBowAuraItemName = \"Shortbow\";\n\n @Switch(\n name = \"Shortbow Aura Attack Animals\",\n description = \"Whether or not to attack mobs\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static boolean shortBowAuraAttackMobs = true;\n\n @Switch(\n name = \"Shortbow Aura Attack Until Dead\",\n description = \"Whether or not to attack mobs until they are dead\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static boolean shortBowAuraAttackUntilDead = false;\n\n @DualOption(\n name = \"Shortbow Aura Rotation Type\",\n description = \"The type of rotation to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n left = \"Silent\",\n right = \"Client\",\n size = 2\n )\n public static boolean shortBowAuraRotationType = false;\n\n @DualOption(\n name = \"Shortbow Aura Mouse Button\",\n description = \"The mouse button to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n left = \"Left\",\n right = \"Right\",\n size = 2\n )\n public static boolean shortBowAuraMouseButton = false;\n\n @DualOption(\n name = \"Shortbow Aura Rotation Mode\",\n description = \"The mode of rotation to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n left = \"Bow Rotation\",\n right = \"Straight Rotation\"\n )\n public static boolean shortBowAuraRotationMode = false;\n\n @Info(\n text = \"The range of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2,\n type = InfoType.INFO\n )\n public static String shortBowAuraRangeInfo = \"The range of the shortbow aura\";\n\n @Slider(\n name = \"Shortbow Aura Range\",\n description = \"The range of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 4,\n max = 30\n )\n public static int shortBowAuraRange = 15;\n\n @Slider(\n name = \"Shortbow Aura FOV\",\n description = \"The FOV of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 360\n )\n public static int shortBowAuraFOV = 120;\n\n @Info(\n text = \"The speed of the shortbow aura's rotation\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2,\n type = InfoType.INFO\n )\n public static String shortBowAuraRotationSpeedInfo = \"The speed of the shortbow aura's rotation\";\n\n @Slider(\n name = \"Shortbow Aura Rotation Speed\",\n description = \"The speed of the shortbow aura's rotation\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 50,\n max = 800\n )\n public static int shortBowAuraRotationSpeed = 300;\n\n @Slider(\n name = \"Shortbow Aura Rotation Speed Randomizer\",\n description = \"The speed of the shortbow aura's rotation\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 500\n )\n public static int shortBowAuraRotationSpeedRandomizer = 100;\n\n public static long getRandomizedRotationSpeed() {\n return (long) (shortBowAuraRotationSpeed + Math.random() * shortBowAuraRotationSpeedRandomizer);\n }\n\n @Info(\n text = \"The speed of the shortbow aura's attack\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2,\n type = InfoType.INFO\n )\n public static String shortBowAuraAttackSpeedInfo = \"The speed of the shortbow aura's attack\";\n\n @Slider(\n name = \"Shortbow Aura Cooldown (ms)\",\n description = \"The cooldown of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 1000\n )\n public static int shortBowAuraCooldown = 500;\n\n @Slider(\n name = \"Shortbow Aura Cooldown Randomizer (ms)\",\n description = \"The randomizer of the shortbow aura cooldown\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 1000\n )\n public static int shortBowAuraCooldownRandomizer = 100;\n\n public static long getRandomizedCooldown() {\n return (long) (shortBowAuraCooldown + Math.random() * shortBowAuraCooldownRandomizer);\n }\n\n @Color(\n name = \"Shortbow Aura Target Color\",\n description = \"The color of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static OneColor shortBowAuraTargetColor = new OneColor(255, 0, 0, 100);\n\n //\n\n //\n //\n @Switch(\n name = \"Chest ESP\",\n description = \"Highlights chests\",\n category = \"Render\",\n subcategory = \"Chest ESP\"\n )\n public static boolean chestESP = false;\n\n @Color(\n name = \"Chest ESP Color\",\n description = \"The color of the chest ESP\",\n category = \"Render\",\n subcategory = \"Chest ESP\"\n )\n public static OneColor chestESPColor = new OneColor(194, 91, 12, 100);\n\n @Switch(\n name = \"Chest ESP Tracers\",\n description = \"Draws lines to chests\",\n category = \"Render\",\n subcategory = \"Chest ESP\"\n )\n public static boolean chestESPTracers = false;\n //\n\n //\n @Switch(\n name = \"Fairy Soul ESP\",\n description = \"Highlights fairy souls\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESP = false;\n\n @Color(\n name = \"Fairy Soul ESP Color\",\n description = \"The color of the fairy soul ESP\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static OneColor fairySoulESPColor = new OneColor(147, 8, 207, 100);\n\n @Switch(\n name = \"Fairy Soul ESP Tracers\",\n description = \"Draws lines to fairy souls\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESPTracers = false;\n\n @Switch(\n name = \"Fairy Soul ESP Show Only Closest\",\n description = \"Only shows the closest fairy soul\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESPShowOnlyClosest = false;\n\n @Switch(\n name = \"Fairy Soul ESP Show Distance\",\n description = \"Shows the distance to the fairy soul\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESPShowDistance = false;\n\n @Button(\n name = \"Fairy Soul ESP Reset\",\n text = \"Reset\",\n description = \"Resets the fairy soul ESP\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\",\n size = 2\n )\n public static void fairySoulESPReset() {\n ESP.getInstance().resetClickedFairySouls();\n }\n\n @Button(\n name = \"Fairy Souls ESP reset only current island\",\n text = \"Reset only current island\",\n description = \"Resets the fairy soul ESP only for the current island\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\",\n size = 2\n )\n public static void fairySoulESPResetOnlyCurrentIsland() {\n ESP.getInstance().resetClickedFairySoulsOnlyCurrentIsland();\n }\n\n @Button(\n name = \"Fairy Souls ESP Add all visible souls to clicked list\",\n text = \"Add all visible souls to clicked list\",\n description = \"Adds all visible fairy souls to the clicked list\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\",\n size = 2\n )\n public static void fairySoulESPAddAllVisibleSoulsToClickedList() {\n ESP.getInstance().addAllVisibleFairySoulsToClickedList();\n }\n\n //\n\n //\n @Switch(\n name = \"Gift ESP\",\n description = \"Highlights gifts\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESP = false;\n\n @Color(\n name = \"Gift ESP Color\",\n description = \"The color of the gift ESP\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static OneColor giftESPColor = new OneColor(230, 230, 230, 100);\n\n @Switch(\n name = \"Gift ESP Tracers\",\n description = \"Draws lines to gifts\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESPTracers = false;\n\n @Switch(\n name = \"Gift ESP Show Only on Jerry Workshop\",\n description = \"Only shows the gift on jerry workshop\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESPShowOnlyOnJerryWorkshop = false;\n\n @Switch(\n name = \"Gift ESP Show Distance\",\n description = \"Shows the distance to the closest gift\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESPShowDistance = false;\n\n @Button(\n name = \"Gift ESP Reset\",\n text = \"Reset\",\n description = \"Resets the gift ESP\",\n category = \"Render\",\n subcategory = \"Gift ESP\",\n size = 2\n )\n public static void giftESPReset() {\n ESP.getInstance().resetClickedGifts();\n }\n\n //\n //\n\n //\n @Info(\n text = \"Smart Toggle activates the appropriate macro depending on the situation\",\n size = 2,\n category = \"Misc\",\n type = InfoType.WARNING\n )\n public boolean infoSmartToggle1 = false;\n\n @Info(\n text = \"Gift Aura - Be at Jerry Workshop\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle3 = false;\n\n @Info(\n text = \"Fishing Macro - Hold Rod\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle4 = false;\n\n @Info(\n text = \"Shortbow Aura - Hold Your Item\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle5 = false;\n\n @Info(\n text = \"Foraging Macro - Hold Treecapitator or Sappling on private island\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle2 = false;\n\n @Info(\n text = \"Fill Chests with Sapplings Macro - Hold Abiphone and have Treecap in hotbar\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle6 = false;\n\n @KeyBind(\n name = \"SmartToggle keybind\",\n category = \"Misc\"\n )\n public static OneKeyBind smartToggleKeybind = new OneKeyBind(Keyboard.KEY_NONE);\n @Switch(\n name = \"Ungrab Mouse\",\n category = \"Misc\"\n )\n public static boolean mouseUngrab = false;\n //\n\n //\n //\n @Switch(\n name = \"Alchemy Helper\",\n description = \"Automatically brews potions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper\",\n size = 2\n )\n public static boolean alchemyHelper = false;\n\n @Switch(\n name = \"Auto put water bottles\",\n description = \"Automatically puts water bottles in the brewing stand\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoPutWaterBottles = false;\n\n @Switch(\n name = \"Auto put ingredients\",\n description = \"Automatically puts ingredients in the brewing stand\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoPutIngredients = false;\n\n @Dropdown(\n name = \"Max ingredient type\",\n description = \"The max ingredient type to use\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\",\n options = {\"None\", \"Enchanted Sugar Cane\", \"Enchanted Blaze Rod\"},\n size = 2\n )\n public static int alchemyHelperMaxIngredientType = 0;\n\n @Switch(\n name = \"Auto pick up finish potions\",\n description = \"Automatically picks up finish potions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoPickUpFinishPotions = false;\n\n @Switch(\n name = \"Auto close GUI after picking up potions\",\n description = \"Automatically closes the GUI after picking up potions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoCloseGUIAfterPickingUpPotions = false;\n\n @Slider(\n name = \"Delay between potion gui actions (ms)\",\n description = \"The delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionGuiActions = 300;\n\n @Slider(\n name = \"Delay between gui potion actions randomizer (ms)\",\n description = \"The randomizer of the delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionGuiActionsRandomizer = 100;\n\n public static long getRandomizedDelayBetweenPotionGuiActions() {\n return (long) (alchemyHelperDelayBetweenPotionGuiActions + Math.random() * alchemyHelperDelayBetweenPotionGuiActionsRandomizer);\n }\n\n @Slider(\n name = \"Delay between ingredients gui actions (ms)\",\n description = \"The delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenIngredientsGuiActions = 300;\n\n @Slider(\n name = \"Delay between gui ingredients actions randomizer (ms)\",\n description = \"The randomizer of the delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenIngredientsGuiActionsRandomizer = 100;\n\n public static long getRandomizedDelayBetweenIngredientsGuiActions() {\n return (long) (alchemyHelperDelayBetweenIngredientsGuiActions + Math.random() * alchemyHelperDelayBetweenIngredientsGuiActionsRandomizer);\n }\n\n @Slider(\n name = \"Delay between potion sell actions (ms)\",\n description = \"The delay between potion sell actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionSellActions = 300;\n\n @Slider(\n name = \"Delay between potion sell actions randomizer (ms)\",\n description = \"The randomizer of the delay between potion sell actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionSellActionsRandomizer = 100;\n\n public static long getRandomizedDelayBetweenPotionSellActions() {\n return (long) (alchemyHelperDelayBetweenPotionSellActions + Math.random() * alchemyHelperDelayBetweenPotionSellActionsRandomizer);\n }\n\n @KeyBind(\n name = \"Auto sell potions to NPC\",\n description = \"Automatically sells potions to NPC\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Additions\"\n )\n public static OneKeyBind alchemyHelperAutoSellPotionsToNPCKeybind = new OneKeyBind(Keyboard.KEY_NONE);\n\n //\n \n //\n @Switch(name = \"Use Fishing Rod\", category = \"Skills\",\n subcategory = \"Foraging\")\n public static boolean foragingUseRod = false;\n\n @Dropdown(name = \"Fill Chest With Sapling Type\", category = \"Skills\",\n subcategory = \"Foraging\", options = {\"Spruce\",\"Jungle\", \"Dark Oak\"})\n public static int fillChestSaplingType = 0;\n\n @DualOption(\n name = \"Foraging Mode\",\n description = \"The mode of foraging\",\n category = \"Skills\",\n subcategory = \"Foraging\",\n left = \"Camera rotations\",\n right = \"Skulls and moving\",\n size = 2\n )\n public static boolean foragingMode = false;\n\n @DualOption(\n name = \"Dirt Detection Mode\",\n description = \"The mode of dirt detection. Blocks Scanner won't make the proper Vec3's for now. Doesn't really matter in skull mode\",\n category = \"Skills\",\n subcategory = \"Foraging\",\n left = \"Relative Blocks\",\n right = \"Blocks Scanner\"\n )\n public static boolean dirtDetectionMode = false;\n\n @Slider(\n name = \"Foraging Macro Base Rotation Speed\",\n description = \"The base rotation speed of the foraging macro\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 50,\n max = 800\n )\n public static int foragingMacroBaseRotationSpeed = 150;\n\n @Slider(\n name = \"Foraging Macro Rotation Speed Randomizer\",\n description = \"The randomizer of the rotation speed of the foraging macro\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 0,\n max = 500\n )\n public static int foragingMacroRotationSpeedRandomizer = 50;\n\n public static long getRandomizedForagingMacroRotationSpeed() {\n return (long) (foragingMacroBaseRotationSpeed + Math.random() * foragingMacroRotationSpeedRandomizer);\n }\n\n @Slider(name = \"Foraging Macro Delay\", category = \"Skills\",\n subcategory = \"Foraging - Options\", max = 500, min = 0.0F, step = 10)\n public static int foragingDelay = 50;\n\n @Slider(\n name = \"Foraging Macro Extra Break Delay\",\n description = \"The extra delay between breaking blocks. Most of the time, it's your ping\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 0,\n max = 800\n )\n public static int foragingMacroExtraBreakDelay = 100;\n\n @Slider(name = \"Stuck timeout\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n max = 2500, min = 0.0F, step = 100\n )\n public static int stuckTimeout = 1500;\n\n @Slider(\n name = \"Monkey level\",\n description = \"The monkey level to calculate delay\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 0,\n max = 100\n )\n public static int monkeyLevel = 0;\n\n //\n \n //\n @Switch(\n name = \"Fishing\",\n description = \"Automatically fishes\",\n category = \"Skills\",\n subcategory = \"Fishing\"\n )\n public static boolean fishing = false;\n @Switch(\n name = \"Sneak while fishing\",\n description = \"Sneaks while fishing\",\n category = \"Skills\",\n subcategory = \"Fishing\"\n )\n public static boolean sneakWhileFishing = false;\n @Switch(\n name = \"Anti AFK\",\n description = \"Anti AFK\",\n category = \"Skills\",\n subcategory = \"Fishing\"\n )\n public static boolean antiAfkWhileFishing = false;\n //\n //\n\n //\n @Switch(\n name = \"Debug Mode\",\n description = \"Enables debug mode\",\n category = \"Debug\"\n )\n public static boolean debugMode = false;\n\n //\n @DualOption(\n name = \"Save Tablist\",\n description = \"Saves the tablist to a file\",\n category = \"Debug\",\n subcategory = \"Tablist\",\n left = \"Print\",\n right = \"Save\"\n )\n public static boolean saveTablistToFile = false;\n @Switch(\n name = \"Transposed Tablist\",\n description = \"Transposes the tablist\",\n category = \"Debug\",\n subcategory = \"Tablist\"\n )\n public static boolean transposedTablist = false;\n @Button(\n name = \"Get Tablist\",\n text = \"Get Tablist\",\n description = \"Gets the tablist\",\n category = \"Debug\",\n subcategory = \"Tablist\"\n )\n public static void getTablist() {\n Dev.getInstance().getTablist();\n }\n //\n\n //\n @DualOption(\n name = \"Save Inventory\",\n description = \"Saves the inventory to a file\",\n category = \"Debug\",\n subcategory = \"Inventory\",\n left = \"Print\",\n right = \"Save\"\n )\n public static boolean saveInventoryToFile = false;\n @Button(\n name = \"Get Inventory\",\n text = \"Get Inventory\",\n description = \"Gets the inventory\",\n category = \"Debug\",\n subcategory = \"Inventory\"\n )\n public static void getInventory() {\n Dev.getInstance().getInventory();\n }\n //\n\n //\n @DualOption(\n name = \"Save Item Lore\",\n description = \"Saves the item lore of specific slot to a file\",\n category = \"Debug\",\n subcategory = \"Item Lore\",\n left = \"Print\",\n right = \"Save\"\n )\n public static boolean saveItemLoreToFile = false;\n @Number(\n name = \"Item Lore Slot\",\n description = \"The slot to get the item lore from\",\n category = \"Debug\",\n subcategory = \"Item Lore\",\n min = 0,\n max = 44\n )\n public static int itemLoreSlot = 0;\n @Button(\n name = \"Get Item Lore\",\n text = \"Get Item Lore\",\n description = \"Gets the item lore of specific slot\",\n category = \"Debug\",\n subcategory = \"Item Lore\"\n )\n public static void getItemLore() {\n Dev.getInstance().getItemLore(itemLoreSlot);\n }\n //\n //\n\n //\n //\n @Switch(\n name = \"Enable Ghost Blocks\",\n description = \"Middle clicks turns blocks into air for a short period of time\",\n category = \"Other\",\n subcategory = \"Ghost Blocks\"\n )\n public static boolean enableGhostBlocks = false;\n\n @Switch(\n name = \"Ghost Blocks only while holding Stonk\",\n description = \"Middle clicks turns blocks into air for a short period of time\",\n category = \"Other\",\n subcategory = \"Ghost Blocks\"\n )\n public static boolean ghostBlocksOnlyWhileHoldingStonk = false;\n\n @Slider(\n name = \"Ghost Blocks Duration (ms)\",\n description = \"The duration of the ghost blocks\",\n category = \"Other\",\n subcategory = \"Ghost Blocks\",\n min = 500,\n max = 5000\n )\n public static int ghostBlocksDuration = 1000;\n\n @Dropdown(\n name = \"Failsafe sound\",\n description = \"The sound to play when the failsafe is triggered\",\n category = \"Other\",\n subcategory = \"Failsafe\",\n options = {\"Exp Orbs\", \"Anvil\"},\n size = 2\n )\n public static int failsafeSoundSelected = 0;\n\n @Switch(\n name = \"Stop active modules on rotation/teleport packet\",\n description = \"Stops all active modules when a rotation packet is received\",\n category = \"Other\",\n subcategory = \"Failsafe\"\n )\n public static boolean stopMacrosOnRotationTeleportCheck = false;\n\n @Switch(\n name = \"Stop active modules on world change\",\n description = \"Stops all active modules when a world change is detected\",\n category = \"Other\",\n subcategory = \"Failsafe\"\n )\n public static boolean stopMacrosOnWorldChange = false;\n\n //\n\n //\n @Switch(\n name = \"Gift Aura\",\n description = \"Automatically opens gifts\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAura = false;\n @Button(\n name = \"Gift Aura Reset\",\n text = \"Reset\",\n description = \"Resets the Gift Aura\",\n category = \"Other\",\n subcategory = \"Gift Aura\",\n size = 2\n )\n public static void giftAuraReset() {\n GiftAura.getInstance().reset();\n }\n @DualOption(\n name = \"Gift Aura Rotation Type\",\n description = \"The type of rotation to use for the gift aura\",\n category = \"Other\",\n subcategory = \"Gift Aura\",\n left = \"Silent\",\n right = \"Client\",\n size = 2\n )\n public static boolean giftAuraRotationType = true;\n\n @Color(\n name = \"Gift Aura ESP Color\",\n description = \"The color of the gift aura ESP\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static OneColor giftAuraESPColor = new OneColor(240, 93, 94, 100);\n @Switch(\n name = \"Open default gifts at Jerry's Workshop\",\n description = \"Automatically opens gifts hidden throughout Jerry's Workshop\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraOpenDefaultGiftsAtJerryWorkshop = false;\n @Switch(\n name = \"Open player gifts\",\n description = \"Automatically opens gifts from other players\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraOpenPlayerGifts = false;\n @Switch(\n name = \"Open gifts outside of Jerry's Workshop\",\n description = \"Automatically opens gifts outside of Jerry's Workshop\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraOpenGiftsOutsideOfJerryWorkshop = false;\n @Switch(\n name = \"Don't check for visibility\",\n description = \"Don't check if the gift is visible before opening it\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraDontCheckForVisibility = false;\n @Slider(\n name = \"Delay (ms)\",\n description = \"The delay between opening gifts\",\n category = \"Other\",\n subcategory = \"Gift Aura\",\n min = 150,\n max = 2000\n )\n public static int giftAuraDelay = 750;\n\n //\n //\n\n public MayOBeesConfig() {\n super(new Mod(\"MayOBees\", ModType.HYPIXEL), \"/mayobees/config.json\");\n initialize();\n\n registerKeyBind(smartToggleKeybind, () -> {\n ModuleManager.getInstance().smartToggle();\n });\n\n registerKeyBind(alchemyHelperAutoSellPotionsToNPCKeybind, () -> {\n LogUtils.info(\"[Alchemy Helper] Selling to NPC: \" + (!AlchemyHelper.getInstance().isSellingPotions() ? \"Enabled\" : \"Disabled\"));\n AlchemyHelper.getInstance().setSellingPotions(!AlchemyHelper.getInstance().isSellingPotions());\n });\n }\n}", "answers": [" private final BlockPos pos;"], "length": 3446, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "4c4860fb-9f92-4626-b655-86d98da97a3f", "reasoning": "The file defines an inner class GhostBlock after the imports. The class needs fields that are later accessed as gb.pos and gb.previousBlockState. The first field declaration should be the position field. Therefore the next line is the declaration of the pos field.", "reasoning_model_answer": "private final BlockPos pos;", "assistant_with_reasoning": "\nThe file defines an inner class GhostBlock after the imports. The class needs fields that are later accessed as gb.pos and gb.previousBlockState. The first field declaration should be the position field. Therefore the next line is the declaration of the pos field.\n\nprivate final BlockPos pos;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.441, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 33250, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private final BlockPos pos;", "score": 0.87, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport javax.servlet.http.HttpServletResponse;\nimport cn.hutool.core.bean.BeanUtil;\nimport com.baomidou.mybatisplus.core.metadata.IPage;\nimport com.metax.common.core.constant.HttpStatus;\nimport com.metax.common.core.context.SecurityContextHolder;\nimport com.metax.common.log.enums.BusinessType;\nimport com.metax.common.log.annotation.Log;\nimport com.metax.web.domain.MessageTemplate;\nimport com.metax.web.dto.MessageTemplateDto;\nimport com.metax.web.service.SendMessageService;\nimport com.metax.web.util.ContentHolderUtil;\nimport com.metax.web.util.DataUtil;\nimport com.metax.web.vo.MessageTemplateVo;\nimport com.metax.web.dto.SendForm;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PutMapping;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\nimport com.metax.common.security.annotation.RequiresPermissions;\nimport com.metax.web.service.IMessageTemplateService;\nimport com.metax.common.core.web.controller.BaseController;\nimport com.metax.common.core.web.domain.AjaxResult;\nimport com.metax.common.core.utils.poi.ExcelUtil;\nimport com.metax.common.core.web.page.TableDataInfo;\nimport static com.metax.common.core.constant.MetaxDataConstants.REAL_TIME;", "context": "metax-web/src/main/java/com/metax/web/controller/MessageTemplateController.java\npackage com.metax.web.controller;\n\n\n\n\n\n/**\n * 消息模板Controller\n *\n * @author hanabi\n * @date 2023-09-08\n */\n@RestController\n@RequestMapping(\"/message_template\")\npublic class MessageTemplateController extends BaseController {\n @Autowired\n private IMessageTemplateService messageTemplateService;\n @Autowired\n private SendMessageService sendMessageService;\n @Autowired\n private DataUtil dataUtil;\n @Autowired\n private ContentHolderUtil contentHolderUtil;\n\n /**\n * 查询消息模板列表\n */\n @RequiresPermissions(\"web:message_template:list\")\n @GetMapping(\"/list\")\n public TableDataInfo list(MessageTemplateDto messageTemplate,Long pageNum, Long pageSize) {\n IPage iPage = messageTemplateService.selectMessageTemplateList(messageTemplate, pageNum, pageSize);\n List messageTemplateDtos = getTemplateDtos(iPage.getRecords());\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(HttpStatus.SUCCESS);\n rspData.setRows(messageTemplateDtos);\n rspData.setMsg(\"查询成功\");\n rspData.setTotal(iPage.getTotal());\n return rspData;\n }\n\n /**\n * 查询消息模板列表\n */\n @RequiresPermissions(\"web:message_template:list\")\n @GetMapping(\"/audit/list\")\n public TableDataInfo auditList(MessageTemplateDto messageTemplate,Long pageNum, Long pageSize) {\n IPage iPage = messageTemplateService.selectAuditMessageTemplateList(messageTemplate, pageNum, pageSize);\n List messageTemplateDtos = getTemplateDtos(iPage.getRecords());\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(HttpStatus.SUCCESS);\n rspData.setRows(messageTemplateDtos);\n rspData.setMsg(\"查询成功\");\n rspData.setTotal(iPage.getTotal());\n return rspData;\n }\n\n /**\n * 查询所有占位符名称集合\n */\n @RequiresPermissions(\"web:message_template:list\")\n @GetMapping(\"/variables/{id}\")\n public TableDataInfo listVariables(@PathVariable Long id) {\n MessageTemplate messageTemplate = messageTemplateService.getById(id);\n List variables = contentHolderUtil.getVariables(messageTemplate);\n return getDataTable(variables);\n }\n\n /**\n * 导出消息模板列表\n */\n @RequiresPermissions(\"web:message_template:export\")\n @Log(title = \"消息模板\", businessType = BusinessType.EXPORT)\n @PostMapping(\"/export\")\n public void export(HttpServletResponse response, MessageTemplate messageTemplate) {\n List list = messageTemplateService.lambdaQuery().eq(MessageTemplate::getCreator, SecurityContextHolder.getUserName()).list();\n ExcelUtil util = new ExcelUtil(MessageTemplate.class);\n util.exportExcel(response, list, \"消息模板数据\");\n }\n\n /**\n * 获取消息模板详细信息\n */\n @RequiresPermissions(\"web:message_template:query\")\n @GetMapping(value = \"/{id}\")\n public AjaxResult getInfo(@PathVariable(\"id\") Long id) {\n MessageTemplateVo messageTemplateVo = BeanUtil.copyProperties(messageTemplateService.getById(id), MessageTemplateVo.class);\n return success(messageTemplateVo);\n }\n\n /**\n * 新增消息模板\n */\n @RequiresPermissions(\"web:message_template:add\")\n @Log(title = \"消息模板\", businessType = BusinessType.INSERT)\n @PostMapping\n public AjaxResult add(@RequestBody MessageTemplate messageTemplate) {\n return messageTemplateService.add(messageTemplate) ? AjaxResult.success():AjaxResult.error(\"存在未通过校验字段\");\n }\n\n /**\n * 修改消息模板\n */\n @RequiresPermissions(\"web:message_template:edit\")\n @Log(title = \"消息模板\", businessType = BusinessType.UPDATE)\n @PutMapping\n public AjaxResult edit(@RequestBody MessageTemplate messageTemplate) {\n return toAjax(messageTemplateService.edit(messageTemplate));\n }\n\n /**\n * 删除消息模板\n */\n @RequiresPermissions(\"web:message_template:remove\")\n @Log(title = \"消息模板\", businessType = BusinessType.DELETE)\n @DeleteMapping(\"/{ids}\")\n public AjaxResult remove(@PathVariable Long[] ids) {\n\n return toAjax(messageTemplateService.delete(ids));\n }\n\n /**\n * 发送消息\n * @param sendForm\n * @return\n */\n @RequiresPermissions(\"web:message_template:send\")\n @Log(title = \"消息模板\", businessType = BusinessType.SEND)\n @PostMapping(\"/send\")\n public AjaxResult send(@RequestBody SendForm sendForm) {\n return sendMessageService.send(sendForm);\n }\n\n\n /**\n * 启动消息\n * @param id\n * @return\n */\n @RequiresPermissions(\"web:message_template:start\")\n @Log(title = \"消息模板\", businessType = BusinessType.START)\n @GetMapping(\"/start/{id}\")\n public AjaxResult start(@PathVariable Long id) {\n return sendMessageService.start(id);\n }\n\n /**\n * 暂停消息\n * @param id\n * @return\n */\n\nmetax-web/src/main/java/com/metax/web/vo/MessageTemplateVo.java\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MessageTemplateVo {\n\n /**\n * 主键\n */\n private Long id;\n\n /**\n * 标题\n */\n private String name;\n\n /**\n * 推送类型:10.实时 20.定时\n */\n private Integer pushType;\n\n /**\n * 消息类型 10.通知类消息 20.营销类消息 30.验证码类消息\n */\n private Integer msgType;\n\n\n /**\n * 定时发送人群的文件路径\n */\n private String cronCrowdPath;\n\n /**\n * 期望发送时间\n */\n private String expectPushTime;\n\n /**\n * 消息发送渠道\n */\n private Integer sendChannel;\n\n /**\n * 消息内容 占位符用{$var}表示\n */\n private String msgContent;\n\n /**\n * 发送账号\n */\n private Integer sendAccount;\n}\n\nmetax-web/src/main/java/com/metax/web/domain/MessageTemplate.java\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"message_template\")\npublic class MessageTemplate{\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 标题\n */\n @Excel(name = \"标题\")\n private String name;\n\n /**\n * 当前消息状态:0.新建 20.停用 30.启用 40.发送中 50.发送成功 60.发送失败\n */\n private Integer msgStatus;\n\n /**\n * 审核状态 10.待审核 20.审核成功 30.审核不通过\n */\n private Integer auditStatus;\n\n /**\n * 推送类型:10.实时 20.定时\n */\n @Excel(name = \"推送类型:10.实时 20.定时\")\n private Integer pushType;\n\n /**\n * 定时任务Id (xxl-job-admin返回)\n */\n private Integer cronTaskId;\n\n /**\n * 定时发送人群的文件路径\n */\n @Excel(name = \"定时发送人群的文件路径\")\n private String cronCrowdPath;\n\n /**\n * 期望发送时间\n */\n @Excel(name = \"期望发送时间\")\n private String expectPushTime;\n\n /**\n * 消息发送渠道 10.Email 20.短信 30.钉钉机器人 40.微信服务号 50.push通知栏 60.飞书机器人\n */\n @Excel(name = \"消息发送渠道\")\n private Integer sendChannel;\n\n /**\n * 消息类型 10.通知类消息 20.营销类消息 30.验证码类消息\n */\n @Excel(name = \" 消息类型\")\n private Integer msgType;\n\n /**\n * 消息内容 占位符用${var}表示\n */\n @Excel(name = \"消息内容 占位符用${var}表示\")\n private String msgContent;\n\n /**\n * 发送账号\n */\n @Excel(name = \"发送账号 \")\n private Long sendAccount;\n\n /**\n * 创建者\n */\n @Excel(name = \"创建者\")\n private String creator;\n\n /**\n * 更新者\n */\n private String updator;\n\n /**\n * 创建时间\n */\n @JsonFormat( pattern = \"yyyy-MM-dd\")\n private LocalDateTime createTime;\n\n /**\n * 更新时间\n */\n @JsonFormat( pattern = \"yyyy-MM-dd\")\n private LocalDateTime updateTime;\n\n /**\n * 发送日志 如发送失败可存储报错信息 发送成功将返回第三方服务返回的消息id\n */\n @Excel(name = \"发送日志\")\n @TableField(exist = false)\n private String sendLogs;\n\n /**\n * 定时模板当前使用用户\n */\n private Long currentId;\n\n}\n\nmetax-web/src/main/java/com/metax/web/util/DataUtil.java\n@Component\n@Slf4j\n@Data\npublic class DataUtil {\n\n @Autowired\n public ChannelConfig channelConfig;\n @Autowired\n private StringRedisTemplate stringRedisTemplate;\n @Autowired\n public ISysUserService sysUserService;\n @Autowired\n private RedissonClient redissonClient;\n\n public Map statusMapping;\n\n public Map sendTypeMapping;\n //初始化当天渠道发送次数\n public Map channelCount = new HashMap<>();\n\n\n /**\n * 渠道映射 Integer to String\n *\n * @return\n */\n public Map channelMapping() {\n Map map = new HashMap<>();\n for (int i = 0; i < channelConfig.channels.size(); i++) {\n map.put(channelConfig.channels.get(i), channelConfig.channelNames.get(i));\n }\n return map;\n }\n\n /**\n * 渠道映射 String to Integer\n *\n * @return\n */\n public Map channelMappingToInteger() {\n Map map = new HashMap<>();\n for (int i = 0; i < channelConfig.channels.size(); i++) {\n map.put(channelConfig.channelCNNames.get(i), channelConfig.channels.get(i));\n }\n return map;\n }\n\n /**\n * 渠道中文映射\n *\n * @return\n */\n public Map channelCNMapping() {\n Map map = new HashMap<>();\n for (int i = 0; i < channelConfig.channels.size(); i++) {\n map.put(channelConfig.channels.get(i), channelConfig.channelCNNames.get(i));\n }\n return map;\n }\n\n /**\n * 类型映射集合\n *\n * @return\n */\n @PostConstruct\n public void typeMapping() {\n Map statusMap = new HashMap<>();\n Map sendTypeMap = new HashMap<>();\n\n statusMap.put(MSG_NEW, \"正常\");\n statusMap.put(MSG_STOP, \"已停用\");\n statusMap.put(MSG_START, \"已启用\");\n statusMap.put(MSG_SENDING, \"发送中\");\n statusMap.put(MSG_FAIL, \"发送失败\");\n statusMap.put(MSG_SUCCESS, \"发送成功\");\n sendTypeMap.put(TEXT, TEXT_NAME);\n sendTypeMap.put(LINK, LINK_NAME);\n sendTypeMap.put(MARKDOWN, MARKDOWN_NAME);\n sendTypeMap.put(ACTION_CARD, ACTION_CARD_NAME);\n sendTypeMap.put(FEED_CARD, FEED_CARD_NAME);\n\n //初始化当天渠道发送次数\n initChannelCount();\n this.statusMapping = statusMap;\n this.sendTypeMapping = sendTypeMap;\n }\n\n public void initChannelCount() {\n //初始化当天渠道发送次数\n channelConfig.channels.forEach(channel -> channelCount.put(channel, 0));\n }\n\n /**\n * 记录定时任务模板最近一次发送状态\n *\n * @param nextStatus\n * @param messageTemplateId\n * @param log\n */\n public void recordCronTaskStatus(String nextStatus, Long messageTemplateId, Long sender, String log) {\n CronTaskCords cronTaskCords = JSONUtil.toBean(stringRedisTemplate\n .opsForValue().get(CRON_TASK_STATUS_KEY + sender + \":\" + messageTemplateId), CronTaskCords.class);\n\n if (Objects.isNull(cronTaskCords)) {\n throw new ServiceException(\"非法操作用户\");\n }\n LocalDateTime now = LocalDateTime.now();\n if (CRON_TASK_SCHEDULING.equals(nextStatus)) {\n //调度开始 开始启动阶段\n cronTaskCords.setSchedulingTime(now);\n //将上一次任务的信息删除\n cronTaskCords.setSendTakeTime(0);\n cronTaskCords.setStartTakeTime(0);\n cronTaskCords.setSendingTime(null);\n cronTaskCords.setFailTime(null);\n cronTaskCords.setTotalTakeTime(new BigInteger(\"0\"));\n cronTaskCords.setSuccessTime(null);\n }\n\n if (CRON_TASK_SENDING.equals(nextStatus)) {\n //开始发送阶段 计算启动阶段花费时间=调度开始时间-当前时间\n cronTaskCords.setStartTakeTime(Duration.between(cronTaskCords.getSchedulingTime(), now).toMillis());\n cronTaskCords.setSendingTime(now);\n }\n\n if (CRON_TASK_SUCCESS.equals(nextStatus)) {\n //发送完成阶段 计算发送阶段花费时间 发送任务可能有多条消息会把同一发送任务的其他消息成功状况覆盖\n cronTaskCords.setSendTakeTime(Duration.between(cronTaskCords.getSendingTime(), now).toMillis());\n cronTaskCords.setSuccessTime(now);\n //计算总耗时\n BigInteger total = new BigInteger(Long.toString(cronTaskCords.getStartTakeTime())).add(new BigInteger(Long.toString(cronTaskCords.getSendTakeTime())));\n cronTaskCords.setTotalTakeTime(total);\n }\n\n if (CRON_TASK_FAIL.equals(nextStatus)) {\n //发送失败清除发送花费时间\n cronTaskCords.setFailTime(now);\n }\n\n if (CRON_TASK_STOP.equals(nextStatus)) {\n //暂停\n cronTaskCords.setStopTime(now);\n }\n\n //设置阶段状态\n cronTaskCords.setStatus(nextStatus);\n if (StrUtil.isNotBlank(log)) {\n cronTaskCords.setLog(log);\n }\n //存进redis\n stringRedisTemplate.opsForValue()\n .set(CRON_TASK_STATUS_KEY + cronTaskCords.getSender() + \":\" + messageTemplateId, JSON.toJSONString(cronTaskCords));\n }\n\n\n /**\n * 确认发送任务的某一组消息的发送状态\n *\n * @param sendId\n * @param messageId\n */\n public synchronized void confirmSend(String sendId, Long messageId, String messageRedisKey, Long sendTaskId, Exception ex) {\n //获取本次发送任务的redisKey\n if (StrUtil.isBlank(messageRedisKey)) {\n throw new ServiceException(SEND_MESSAGE_KEY + \"is null\");\n }\n RLock rLock = redissonClient.getLock(SEND_CONTENT_LOCK + sendTaskId);\n try {\n rLock.lock();\n List list = stringRedisTemplate.opsForList().range(messageRedisKey, 0, -1);\n if (Objects.isNull(list)) {\n throw new ServiceException(\"消息数据丢失!\");\n }\n List sendContexts = stringConvertSendContext(list);\n updateMsgStatus(sendContexts, messageId, sendId, messageRedisKey, sendTaskId, ex);\n } catch (Exception e) {\n log.error(\"发送流程出现异常\", e);\n } finally {\n rLock.unlock();\n }\n }\n\n /**\n * 更新消息发送状态\n *\n * @param sendContexts\n * @param messageId\n * @param sendId\n */\n public void updateMsgStatus(List sendContexts, Long messageId, String sendId, String messageRedisKey, Long sendTaskId, Exception ex) {\n if (sendTaskId == null || sendTaskId == 0) {\n throw new ServiceException(SEND_TASK_ID + \"is null\");\n }\n //从数组尾部开始遍历\n for (int i = sendContexts.size() - 1; i >= 0; i--) {\n //从当天发送任务集合中筛选出本次发送任务\n if (Objects.equals(sendContexts.get(i).getSendTaskId(), sendTaskId)) {\n //获取当前子任务\n List sendTasks = sendContexts.get(i).getSendTasks();\n for (SendTaskInfo sendTask : sendTasks) {\n if (Objects.equals(sendTask.getMessageId(), messageId)) {\n MessageTemplate messageTemplate = sendTask.getMessageTemplate();\n //如果不是待确认状态就退出本次消息确认\n if (!MSG_SENDING.equals(messageTemplate.getMsgStatus())) {\n return;\n }\n //修改发送状态\n if (StrUtil.isNotBlank(sendId)) {\n //成功\n messageTemplate.setMsgStatus(MSG_SUCCESS);\n messageTemplate.setSendLogs(\"消息发送成功,返回信息:\" + sendId);\n LocalDateTime now = LocalDateTime.now();\n sendTask.setSendEndTime(now);\n sendTask.setTakeTime(Duration.between(sendTask.getSendStartTime(), now).toMillis());\n if (TIMING.equals(messageTemplate.getPushType())) {\n //定时任务完成记录\n recordCronTaskStatus(CRON_TASK_SUCCESS, messageTemplate.getId(), sendContexts.get(i).getSender(), \"消息发送成功,返回信息:\" + sendId);\n }\n sendTask.setMessageTemplate(messageTemplate);\n } else {\n //失败\n messageTemplate.setMsgStatus(MSG_FAIL);\n messageTemplate.setSendLogs(\"消息发送失败,返回信息:\" + ex.getMessage());\n LocalDateTime now = LocalDateTime.now();\n sendTask.setSendEndTime(now);\n sendTask.setTakeTime(Duration.between(sendTask.getSendStartTime(), now).toMillis());\n if (TIMING.equals(messageTemplate.getPushType())) {\n //定时任务冗余失败记录\n recordCronTaskStatus(CRON_TASK_FAIL, messageTemplate.getId(), sendContexts.get(i).getSender(), ex.getMessage());\n }\n sendTask.setMessageTemplate(messageTemplate);\n }\n }\n }\n //按照下标重新存进redis\n stringRedisTemplate.opsForList().set(messageRedisKey, i, JSON.toJSONString(sendContexts.get(i)));\n }\n }\n }\n\n /**\n * 将redis取出来的string类型集合转换成SendContext类型\n *\n * @param list\n * @return\n */\n public List stringConvertSendContext(List list) {\n return list.stream().map(s -> JSONUtil.toBean(s, SendContent.class)).collect(Collectors.toList());\n }\n\n /**\n * 转换成String类型\n *\n * @param list\n * @return\n */\n public List sendContextConvertString(List list) {\n return list.stream().map(JSON::toJSONString).collect(Collectors.toList());\n }\n\n /**\n * 出现未知问题废弃,别处已实现\n * 记录用户发送失败消息(人数)数量\n */\n public void RecordingFail(String userName, SendTaskInfo sendTask) {\n Long userId = getSender(userName);\n String total = stringRedisTemplate.opsForValue().get(USER_SEND_TOTAL_FAIL + userId);\n int num = 0;\n if (StrUtil.isBlank(total)) {\n //如果是第一次记录\n num += sendTask.getReceivers().size();\n } else {\n num = Integer.parseInt(total);\n num += sendTask.getReceivers().size();\n }\n stringRedisTemplate.opsForValue().set(USER_SEND_TOTAL_FAIL + userId, String.valueOf(num));\n }\n\n /**\n * 出现未知问题废弃,别处已实现\n * 记录用户发送成功消息(人数)数量\n */\n public void RecordingSuccess(String userName, SendTaskInfo sendTask) {\n Long userId = getSender(userName);\n String total = stringRedisTemplate.opsForValue().get(USER_SEND_TOTAL_SUCCESS + userId);\n int num = 0;\n if (StrUtil.isBlank(total)) {\n //如果是第一次记录\n num += sendTask.getReceivers().size();\n } else {\n num = Integer.parseInt(total);\n num += sendTask.getReceivers().size();\n }\n stringRedisTemplate.opsForValue().set(USER_SEND_TOTAL_SUCCESS + userId, String.valueOf(num));\n }\n\n public Long getSender(String userName) {\n return sysUserService.lambdaQuery().eq(SysUser::getUserName, userName).one().getUserId();\n\n }\n\n public Integer countSendNumber(SendContent sendContext) {\n //本次任务发送总人数\n Integer sendNumber = 0;\n for (SendTaskInfo sendTask : sendContext.getSendTasks()) {\n sendNumber += sendTask.getReceivers().size();\n }\n return sendNumber;\n }\n\n\n}\n\nmetax-web/src/main/java/com/metax/web/service/SendMessageService.java\npublic interface SendMessageService {\n\n public AjaxResult send(ProcessContent sendForm);\n\n public AjaxResult start(Long id);\n\n public AjaxResult stop(Long id);\n}\n\nmetax-web/src/main/java/com/metax/web/dto/MessageTemplateDto.java\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MessageTemplateDto {\n\n\n private Long id;\n\n\n private String name;\n\n /**\n * 当前消息状态:0.新建 20.停用 30.启用 40.发送中 50.发送成功 60.发送失败\n */\n private String msgStatus;\n\n /**\n * 与messageTemplate的区别\n */\n private String pushType;\n\n /**\n * 消息类型 10.通知类消息 20.营销类消息 30.验证码类消息\n */\n private Integer msgType;\n\n /**\n * 审核状态 10.待审核 20.审核成功 30.审核不通过\n */\n private Integer auditStatus;\n\n /**\n * 定时发送人群的文件路径\n */\n private String cronCrowdPath;\n\n /**\n * 期望发送时间\n */\n private String expectPushTime;\n\n /**\n * 与messageTemplate的区别\n */\n private String sendChannel;\n\n /**\n * 消息内容 占位符用{$var}表示\n */\n private String msgContent;\n\n /**\n * 发送账号\n */\n private Integer sendAccount;\n\n /**\n * 创建者\n */\n private String creator;\n\n /**\n * 更新者\n */\n private String updator;\n\n /**\n * 创建时间\n */\n private String createTime;\n\n}\n\nmetax-common/metax-common-log/src/main/java/com/metax/common/log/enums/BusinessType.java\npublic enum BusinessType\n{\n /**\n * 其它\n */\n OTHER,\n\n /**\n * 新增\n */\n INSERT,\n\n /**\n * 修改\n */\n UPDATE,\n\n /**\n * 删除\n */\n DELETE,\n\n /**\n * 授权\n */\n GRANT,\n\n /**\n * 导出\n */\n EXPORT,\n\n /**\n * 导入\n */\n IMPORT,\n\n /**\n * 强退\n */\n FORCE,\n\n /**\n * 生成代码\n */\n GENCODE,\n\n /**\n * 清空数据\n */\n CLEAN,\n\n /**\n * 发送\n */\n SEND,\n\n /**\n * 启动\n */\n START,\n\n /**\n * 停止\n */\n STOP,\n}\n\nmetax-common/metax-common-core/src/main/java/com/metax/common/core/web/page/TableDataInfo.java\npublic class TableDataInfo implements Serializable\n{\n private static final long serialVersionUID = 1L;\n\n /** 总记录数 */\n private long total;\n\n /** 列表数据 */\n private List rows;\n\n /** 消息状态码 */\n private int code;\n\n /** 消息内容 */\n private String msg;\n\n /**\n * 表格数据对象\n */\n public TableDataInfo()\n {\n }\n\n /**\n * 分页\n * \n * @param list 列表数据\n * @param total 总记录数\n */\n public TableDataInfo(List list, int total)\n {\n this.rows = list;\n this.total = total;\n }\n\n public long getTotal()\n {\n return total;\n }\n\n public void setTotal(long total)\n {\n this.total = total;\n }\n\n public List getRows()\n {\n return rows;\n }\n\n public void setRows(List rows)\n {\n this.rows = rows;\n }\n\n public int getCode()\n {\n return code;\n }\n\n public void setCode(int code)\n {\n this.code = code;\n }\n\n public String getMsg()\n {\n return msg;\n }\n\n public void setMsg(String msg)\n {\n this.msg = msg;\n }\n}\n\nmetax-common/metax-common-core/src/main/java/com/metax/common/core/web/controller/BaseController.java\npublic class BaseController\n{\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @InitBinder\n public void initBinder(WebDataBinder binder)\n {\n // Date 类型转换\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport()\n {\n @Override\n public void setAsText(String text)\n {\n setValue(DateUtils.parseDate(text));\n }\n });\n }\n\n /**\n * 设置请求分页数据\n */\n protected void startPage()\n {\n PageUtils.startPage();\n }\n\n /**\n * 清理分页的线程变量\n */\n protected void clearPage()\n {\n PageUtils.clearPage();\n }\n\n /**\n * 响应请求分页数据\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n protected TableDataInfo getDataTable(List list)\n {\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(HttpStatus.SUCCESS);\n rspData.setRows(list);\n rspData.setMsg(\"查询成功\");\n rspData.setTotal(new PageInfo(list).getTotal());\n return rspData;\n }\n\n /**\n * 返回成功\n */\n public AjaxResult success()\n {\n return AjaxResult.success();\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(String message)\n {\n return AjaxResult.success(message);\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(Object data)\n {\n return AjaxResult.success(data);\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error()\n {\n return AjaxResult.error();\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error(String message)\n {\n return AjaxResult.error(message);\n }\n\n /**\n * 返回警告消息\n */\n public AjaxResult warn(String message)\n {\n return AjaxResult.warn(message);\n }\n\n /**\n * 响应返回结果\n * \n * @param rows 影响行数\n * @return 操作结果\n */\n protected AjaxResult toAjax(int rows)\n {\n return rows > 0 ? AjaxResult.success() : AjaxResult.error();\n }\n\n /**\n * 响应返回结果\n * \n * @param result 结果\n * @return 操作结果\n */\n protected AjaxResult toAjax(boolean result)\n {\n return result ? success() : error();\n }\n}\n\nmetax-common/metax-common-core/src/main/java/com/metax/common/core/constant/HttpStatus.java\npublic class HttpStatus\n{\n /**\n * 操作成功\n */\n public static final int SUCCESS = 200;\n\n /**\n * 对象创建成功\n */\n public static final int CREATED = 201;\n\n /**\n * 请求已经被接受\n */\n public static final int ACCEPTED = 202;\n\n /**\n * 操作已经执行成功,但是没有返回数据\n */\n public static final int NO_CONTENT = 204;\n\n /**\n * 资源已被移除\n */\n public static final int MOVED_PERM = 301;\n\n /**\n * 重定向\n */\n public static final int SEE_OTHER = 303;\n\n /**\n * 资源没有被修改\n */\n public static final int NOT_MODIFIED = 304;\n\n /**\n * 参数列表错误(缺少,格式不匹配)\n */\n public static final int BAD_REQUEST = 400;\n\n /**\n * 未授权\n */\n public static final int UNAUTHORIZED = 401;\n\n /**\n * 访问受限,授权过期\n */\n public static final int FORBIDDEN = 403;\n\n /**\n * 资源,服务未找到\n */\n public static final int NOT_FOUND = 404;\n\n /**\n * 不允许的http方法\n */\n public static final int BAD_METHOD = 405;\n\n /**\n * 资源冲突,或者资源被锁\n */\n public static final int CONFLICT = 409;\n\n /**\n * 不支持的数据,媒体类型\n */\n public static final int UNSUPPORTED_TYPE = 415;\n\n /**\n * 系统内部错误\n */\n public static final int ERROR = 500;\n\n /**\n * 接口未实现\n */\n public static final int NOT_IMPLEMENTED = 501;\n\n /**\n * 系统警告消息\n */\n public static final int WARN = 601;\n}", "answers": [" @RequiresPermissions(\"web:message_template:stop\")"], "length": 2149, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ab6b27ae-d615-4eaa-a34d-c60f30311128", "reasoning": "The code snippet ends with the Javadoc comment for the pause (stop) message method. Following the pattern used for the start method, the next line should be the permission annotation for the stop endpoint.", "reasoning_model_answer": "@RequiresPermissions(\"web:message_template:stop\")", "assistant_with_reasoning": "\nThe code snippet ends with the Javadoc comment for the pause (stop) message method. Following the pattern used for the start method, the next line should be the permission annotation for the stop endpoint.\n\n@RequiresPermissions(\"web:message_template:stop\")", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.565, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 27725, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "@RequiresPermissions(\"web:message_template:stop\")", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "from typing import Any, Optional, cast\nfrom zerolink import settings\nfrom zerolink.exc import APIError, AuthenticationError\nfrom zerolink_client import Client\nfrom zerolink_client.api.default import finetune, get_models_models_get\nfrom zerolink_client.api.entity import (\n desc_entity_id,\n desc_entity_ontology,\n lookup_entity,\n lookup_relation,\n search_entity,\n)\nfrom zerolink_client.api.extract import extract_text\nfrom zerolink_client.api.fact import (\n create_userattribute,\n create_userentity,\n create_userrule,\n create_usertriple,\n)\nfrom zerolink_client.api.kg import get_triple\nfrom zerolink_client.api.question import post_question\nfrom zerolink_client.api.session import (\n create_session,\n get_session_entities,\n get_session_facts,\n get_user_session,\n)\nfrom zerolink_client.api.user import create_user\nfrom zerolink_client.models import (\n ChatSession,\n CreateAttribute,\n CreateEntity,\n CreateRule,\n CreateRuleResponse,\n CreateTriple,\n CreateTuneJobResponse,\n Entity,\n HTTPValidationError,\n Question,\n QuestionResponse,\n TextExtract,\n)\nfrom zerolink_client.types import File, UNSET", "context": "zerolink/req.py\n\n\n# ------------------------------------------------------------------------\n# Endpoints\n# ------------------------------------------------------------------------\n\nclient = Client(\n base_url=settings.server_url,\n raise_on_unexpected_status=False,\n)\n\n\ndef check_api_key() -> None:\n \"\"\"\n Check if the API key is set.\n \"\"\"\n if settings.api_key is None:\n raise AuthenticationError()\n else:\n pass\n\n\ndef get_user_id() -> str:\n \"\"\"\n Get the user ID from the server. Only used for Demo server.\n \"\"\"\n client._headers[\"Authorization\"] = settings.api_key\n rep = create_user.sync(client=client)\n if rep is None:\n raise Exception(\"Failed to authenticate.\")\n settings.api_key = rep.user_id\n if isinstance(rep, HTTPValidationError):\n raise APIError(str(rep))\n return rep.user_id\n\n\ndef post_session(user_id: str, **kwargs) -> Optional[ChatSession]:\n \"\"\"\n Create a new session.\n \"\"\"\n check_api_key()\n if user_id is None:\n user_id = settings.api_key\n rep = create_session.sync(client=client, user_id=user_id, **kwargs)\n if isinstance(rep, HTTPValidationError):\n raise APIError(str(rep))\n return rep\n\n\ndef get_session_name(user_id: str, session_name: str, **kwargs):\n \"\"\"\n Lookup a session by user and name.\n \"\"\"\n check_api_key()\n rep = get_user_session.sync_detailed(user_id, session_name, client=client, **kwargs)\n if rep.status_code == 200:\n return rep.parsed\n elif rep.status_code == 404:\n return None\n else:\n err = rep.content.decode(\"utf-8\")\n print(err)\n raise APIError(err)\n\n\ndef get_session_entities_list(session_id: int, **kwargs):\n \"\"\"\n Get the entities of a session.\n \"\"\"\n check_api_key()\n rep = get_session_entities.sync_detailed(session_id, client=client, **kwargs)\n if rep.status_code == 200:\n return rep.parsed\n else:\n err = rep.content.decode(\"utf-8\")\n print(err)\n raise APIError(err)\n\n\ndef get_session_facts_list(session_id: int, **kwargs):\n \"\"\"\n Get the facts of a session.\n \"\"\"\n check_api_key()\n\n\nzerolink_client/api/entity/search_entity.py\ndef _get_kwargs(\n name: str,\n *,\n limit: Union[Unset, int] = 10,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Match\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Match\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Response[Union[HTTPValidationError, List[\"Match\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Optional[Union[HTTPValidationError, List[\"Match\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Response[Union[HTTPValidationError, List[\"Match\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n) -> Optional[Union[HTTPValidationError, List[\"Match\"]]]:\n\nzerolink_client/api/fact/create_usertriple.py\ndef _get_kwargs(\n *,\n body: CreateTriple,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[CreateFactResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[CreateFactResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Response[Union[CreateFactResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Optional[Union[CreateFactResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Response[Union[CreateFactResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateTriple,\n session_id: int,\n) -> Optional[Union[CreateFactResponse, HTTPValidationError]]:\n\nzerolink_client/api/entity/lookup_entity.py\ndef _get_kwargs(\n name: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Entity\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Entity\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Entity\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Entity\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Entity\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Entity\"]]]:\n\nzerolink_client/api/extract/extract_text.py\ndef _get_kwargs(\n *,\n body: TextExtract,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[AssertionResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[AssertionResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Response[Union[AssertionResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Optional[Union[AssertionResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Response[Union[AssertionResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: TextExtract,\n session_id: int,\n) -> Optional[Union[AssertionResponse, HTTPValidationError]]:\n\nzerolink_client/api/session/get_session_entities.py\ndef _get_kwargs(\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\ndef sync_detailed(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\ndef sync(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\nasync def asyncio_detailed(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\nasync def asyncio(\n session_id: int,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"GenericEntity\"]]]:\n\nzerolink_client/api/question/post_question.py\ndef _get_kwargs(\n *,\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, QuestionResponse]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, QuestionResponse]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Response[Union[HTTPValidationError, QuestionResponse]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Optional[Union[HTTPValidationError, QuestionResponse]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Response[Union[HTTPValidationError, QuestionResponse]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: Question,\n session_id: Union[Unset, int] = UNSET,\n) -> Optional[Union[HTTPValidationError, QuestionResponse]]:\n\nzerolink_client/api/entity/desc_entity_ontology.py\ndef _get_kwargs(\n id: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[Any, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[Any, HTTPValidationError]]:\ndef sync_detailed(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[Any, HTTPValidationError]]:\ndef sync(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[Any, HTTPValidationError]]:\nasync def asyncio_detailed(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[Any, HTTPValidationError]]:\nasync def asyncio(\n id: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[Any, HTTPValidationError]]:\n\nzerolink_client/models/question_response.py\nclass QuestionResponse:\n \"\"\"A response to a question request.\n\n Attributes:\n id (int): The ID of the question\n msg (str): A message describing the result of the question\n status (ResultStatus): The status of a result.\n answers (List[str]): The answers to the question\n methods (List[str]): The methods used to answer the question\n reasoners (List[str]): The reasoners used to answer the question\n query (Union[Unset, QuestionResponseQuery]): The query used to answer the question\n \"\"\"\n\n id: int\n msg: str\n status: ResultStatus\n answers: List[str]\n methods: List[str]\n reasoners: List[str]\n query: Union[Unset, \"QuestionResponseQuery\"] = UNSET\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.question_response_query import QuestionResponseQuery\n\n id = self.id\n\n msg = self.msg\n\n status = self.status.value\n\n answers = self.answers\n\n methods = self.methods\n\n reasoners = self.reasoners\n\n query: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.query, Unset):\n query = self.query.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"id\": id,\n \"msg\": msg,\n \"status\": status,\n \"answers\": answers,\n \"methods\": methods,\n \"reasoners\": reasoners,\n }\n )\n if query is not UNSET:\n field_dict[\"query\"] = query\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.question_response_query import QuestionResponseQuery\n\n d = src_dict.copy()\n id = d.pop(\"id\")\n\n msg = d.pop(\"msg\")\n\n status = ResultStatus(d.pop(\"status\"))\n\n answers = cast(List[str], d.pop(\"answers\"))\n\n methods = cast(List[str], d.pop(\"methods\"))\n\n reasoners = cast(List[str], d.pop(\"reasoners\"))\n\n _query = d.pop(\"query\", UNSET)\n query: Union[Unset, QuestionResponseQuery]\n if isinstance(_query, Unset):\n query = UNSET\n else:\n query = QuestionResponseQuery.from_dict(_query)\n\n question_response = cls(\n id=id,\n msg=msg,\n status=status,\n answers=answers,\n methods=methods,\n reasoners=reasoners,\n query=query,\n )\n\n question_response.additional_properties = d\n return question_response\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n\nzerolink_client/api/entity/lookup_relation.py\ndef _get_kwargs(\n name: str,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Relation\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Relation\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Relation\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Relation\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Response[Union[HTTPValidationError, List[\"Relation\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n) -> Optional[Union[HTTPValidationError, List[\"Relation\"]]]:\n\nzerolink_client/api/kg/get_triple.py\ndef _get_kwargs(\n name: str,\n *,\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[HTTPValidationError, List[\"Triple\"]]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[HTTPValidationError, List[\"Triple\"]]]:\ndef sync_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Response[Union[HTTPValidationError, List[\"Triple\"]]]:\ndef sync(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Optional[Union[HTTPValidationError, List[\"Triple\"]]]:\nasync def asyncio_detailed(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Response[Union[HTTPValidationError, List[\"Triple\"]]]:\nasync def asyncio(\n name: str,\n *,\n client: Union[AuthenticatedClient, Client],\n limit: Union[Unset, int] = 10,\n threshold: Union[Unset, float] = 0.3,\n) -> Optional[Union[HTTPValidationError, List[\"Triple\"]]]:\n\nzerolink_client/api/fact/create_userentity.py\ndef _get_kwargs(\n *,\n body: CreateEntity,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[CreateEntityResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[CreateEntityResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Response[Union[CreateEntityResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Optional[Union[CreateEntityResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Response[Union[CreateEntityResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateEntity,\n session_id: int,\n) -> Optional[Union[CreateEntityResponse, HTTPValidationError]]:\n\nzerolink_client/api/fact/create_userattribute.py\ndef _get_kwargs(\n *,\n body: CreateAttribute,\n session_id: int,\n) -> Dict[str, Any]:\ndef _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Union[GenericResponse, HTTPValidationError]]:\ndef _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Union[GenericResponse, HTTPValidationError]]:\ndef sync_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Response[Union[GenericResponse, HTTPValidationError]]:\ndef sync(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Optional[Union[GenericResponse, HTTPValidationError]]:\nasync def asyncio_detailed(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Response[Union[GenericResponse, HTTPValidationError]]:\nasync def asyncio(\n *,\n client: Union[AuthenticatedClient, Client],\n body: CreateAttribute,\n session_id: int,\n) -> Optional[Union[GenericResponse, HTTPValidationError]]:\n\nzerolink_client/models/create_attribute.py\nclass CreateAttribute:\n \"\"\"\n Attributes:\n subject (str): EID of a builtin entity\n predicate (str): Name of attribute\n attribute (Attribute):\n \"\"\"\n\n subject: str\n predicate: str\n attribute: \"Attribute\"\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n from ..models.attribute import Attribute\n\n subject = self.subject\n\n predicate = self.predicate\n\n attribute = self.attribute.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"subject\": subject,\n \"predicate\": predicate,\n \"attribute\": attribute,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.attribute import Attribute\n\n d = src_dict.copy()\n subject = d.pop(\"subject\")\n\n predicate = d.pop(\"predicate\")\n\n attribute = Attribute.from_dict(d.pop(\"attribute\"))\n\n create_attribute = cls(\n subject=subject,\n predicate=predicate,\n attribute=attribute,\n )\n\n create_attribute.additional_properties = d\n return create_attribute\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n\nzerolink/exc.py\nclass APIError(Exception):\n def __init__(self, message: str) -> None:\n self.message = message\n\n def __str__(self) -> str:\n return self.message\n\nzerolink_client/models/question.py\nclass Question:\n \"\"\"A question to be answered by querying the knowledge graph and reasoner.\n\n Attributes:\n body (str): The body of the question\n world (Union[Unset, WorldAssumption]): The world assumption is the assumption about the world that the reasoner\n makes. This is used to determine the answer to a query. For example, if\n the world assumption is \"closed\" then the reasoner will assume that the\n answer to the query is \"no\" if it cannot find a triple to satisfy the\n query. Default: WorldAssumption.CLOSED.\n spatial (Union[Unset, SpatialAssumption]): The spatial assumption is the assumption about space that the\n reasoner\n makes. This is used to determine the answer to a query. For example, if the\n spatial assumption is \"earth\" then the reasoner will only consider\n geographic locations on Earth and will assume all instances of 'location'\n are on Earth. If the spatial assumption is \"universe\" then the reasoner\n then this restriction is lifted and the reasoner will consider all\n locations in the universe. Default: SpatialAssumption.EARTH.\n temporal (Union[Unset, TemporalAssumption]): The temporal assumption is the assumption about time that the\n reasoner\n makes. This is used to determine the answer to a query. For example, if\n the temporal assumption is \"current\" then the reasoner will only consider\n triples that refer to entities that are non-historical. Excluding things\n like the Roman Empire and Francoist Spain. Default: TemporalAssumption.CURRENT.\n context (Union[Unset, ContextAssumption]): The context assumption is the assumption about the context that the\n reasoner makes. This is used to determine the answer to a query. For\n example, if the context assumption is \"none\" then the reasoner will only\n consider basic triples like instance_of and subclass_of. If the context\n assumption is \"local\" then the reasoner will consider triples that are\n defined by the user. If the context assumption is \"global\" then the\n reasoner will consider all queryable triples. Default: ContextAssumption.GLOBAL.\n \"\"\"\n\n body: str\n world: Union[Unset, WorldAssumption] = WorldAssumption.CLOSED\n spatial: Union[Unset, SpatialAssumption] = SpatialAssumption.EARTH\n temporal: Union[Unset, TemporalAssumption] = TemporalAssumption.CURRENT\n context: Union[Unset, ContextAssumption] = ContextAssumption.GLOBAL\n additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n body = self.body\n\n world: Union[Unset, str] = UNSET\n if not isinstance(self.world, Unset):\n world = self.world.value\n\n spatial: Union[Unset, str] = UNSET\n if not isinstance(self.spatial, Unset):\n spatial = self.spatial.value\n\n temporal: Union[Unset, str] = UNSET\n if not isinstance(self.temporal, Unset):\n temporal = self.temporal.value\n\n context: Union[Unset, str] = UNSET\n if not isinstance(self.context, Unset):\n context = self.context.value\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"body\": body,\n }\n )\n if world is not UNSET:\n field_dict[\"world\"] = world\n if spatial is not UNSET:\n field_dict[\"spatial\"] = spatial\n if temporal is not UNSET:\n field_dict[\"temporal\"] = temporal\n if context is not UNSET:\n field_dict[\"context\"] = context\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n d = src_dict.copy()\n body = d.pop(\"body\")\n\n _world = d.pop(\"world\", UNSET)\n world: Union[Unset, WorldAssumption]\n if isinstance(_world, Unset):\n world = UNSET\n else:\n world = WorldAssumption(_world)\n\n _spatial = d.pop(\"spatial\", UNSET)\n spatial: Union[Unset, SpatialAssumption]\n if isinstance(_spatial, Unset):\n spatial = UNSET\n else:\n spatial = SpatialAssumption(_spatial)\n\n _temporal = d.pop(\"temporal\", UNSET)\n temporal: Union[Unset, TemporalAssumption]\n if isinstance(_temporal, Unset):\n temporal = UNSET\n else:\n temporal = TemporalAssumption(_temporal)\n\n _context = d.pop(\"context\", UNSET)\n context: Union[Unset, ContextAssumption]\n if isinstance(_context, Unset):\n context = UNSET\n else:\n context = ContextAssumption(_context)\n\n question = cls(\n body=body,\n world=world,\n spatial=spatial,\n temporal=temporal,\n context=context,\n )\n\n question.additional_properties = d\n return question\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties", "answers": [" rep = get_session_facts.sync_detailed(session_id, client=client, **kwargs)"], "length": 2320, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "0d025c8a-c65b-4a3e-87d4-0e21bcbcd83a", "reasoning": "The function get_session_facts_list mirrors get_session_entities_list. After checking the API key, it should call the appropriate client method to fetch facts. The imported function is get_session_facts, and the pattern uses .sync_detailed with session_id, client, and **kwargs. Hence the next line is the call assigning the response to rep.", "reasoning_model_answer": "rep = get_session_facts.sync_detailed(session_id, client=client, **kwargs)", "assistant_with_reasoning": "\nThe function get_session_facts_list mirrors get_session_entities_list. After checking the API key, it should call the appropriate client method to fetch facts. The imported function is get_session_facts, and the pattern uses .sync_detailed with session_id, client, and **kwargs. Hence the next line is the call assigning the response to rep.\n\nrep = get_session_facts.sync_detailed(session_id, client=client, **kwargs)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.588, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 26805, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "rep = get_session_facts.sync_detailed(session_id, client=client, **kwargs)", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import torch\nimport argparse\nfrom nerf.provider import NeRFDataset_Test\nfrom nerf.gui import NeRFGUI\nfrom nerf.utils import *\n from nerf.network import NeRFNetwork, R2TalkerNeRF, GeneNeRFNetwork", "context": "test.py\n\n\n# torch.autograd.set_detect_anomaly(True)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--pose', type=str, help=\"transforms.json, pose source\")\n parser.add_argument('--aud', type=str, default=None, help=\"aud.npy, audio source\")\n parser.add_argument('--cond_type', type=str, default=None, help=\"type of driving condition: eo, ds, idexp\")\n parser.add_argument('--method', type=str, default='r2talker', help=\"r2talker, genefaceDagger, rad-nerf\")\n parser.add_argument('--bg_img', type=str, default='white', help=\"bg.jpg, background image source\")\n\n parser.add_argument('-O', action='store_true', help=\"equals --fp16 --cuda_ray --exp_eye\")\n # parser.add_argument('--test', action='store_true', help=\"test mode (load model and test dataset)\")\n # parser.add_argument('--test_train', action='store_true', help=\"test mode (load model and train dataset)\")\n parser.add_argument('--data_range', type=int, nargs='*', default=[0, -1], help=\"data range to use\")\n parser.add_argument('--workspace', type=str, default='workspace')\n parser.add_argument('--seed', type=int, default=0)\n\n ### training options\n # parser.add_argument('--iters', type=int, default=200000, help=\"training iters\")\n # parser.add_argument('--lr', type=float, default=5e-3, help=\"initial learning rate\")\n # parser.add_argument('--lr_net', type=float, default=5e-4, help=\"initial learning rate\")\n parser.add_argument('--ckpt', type=str, default='latest')\n parser.add_argument('--num_rays', type=int, default=4096 * 16, help=\"num rays sampled per image for each training step\")\n parser.add_argument('--cuda_ray', action='store_true', help=\"use CUDA raymarching instead of pytorch\")\n parser.add_argument('--max_steps', type=int, default=16, help=\"max num steps sampled per ray (only valid when using --cuda_ray)\")\n parser.add_argument('--num_steps', type=int, default=16, help=\"num steps sampled per ray (only valid when NOT using --cuda_ray)\")\n parser.add_argument('--upsample_steps', type=int, default=0, help=\"num steps up-sampled per ray (only valid when NOT using --cuda_ray)\")\n parser.add_argument('--update_extra_interval', type=int, default=16, help=\"iter interval to update extra status (only valid when using --cuda_ray)\")\n parser.add_argument('--max_ray_batch', type=int, default=4096, help=\"batch size of rays at inference to avoid OOM (only valid when NOT using --cuda_ray)\")\n\n\n ### network backbone options\n parser.add_argument('--fp16', action='store_true', help=\"use amp mixed precision training\")\n \n parser.add_argument('--lambda_amb', type=float, default=0.1, help=\"lambda for ambient loss\")\n \n parser.add_argument('--fbg', action='store_true', help=\"frame-wise bg\")\n parser.add_argument('--exp_eye', action='store_true', help=\"explicitly control the eyes\")\n parser.add_argument('--fix_eye', type=float, default=-1, help=\"fixed eye area, negative to disable, set to 0-0.3 for a reasonable eye\")\n parser.add_argument('--smooth_eye', action='store_true', help=\"smooth the eye area sequence\")\n\n parser.add_argument('--torso_shrink', type=float, default=0.8, help=\"shrink bg coords to allow more flexibility in deform\")\n\n ### dataset options\n parser.add_argument('--color_space', type=str, default='srgb', help=\"Color space, supports (linear, srgb)\")\n # parser.add_argument('--preload', action='store_true', help=\"preload all data into GPU, accelerate training but use more GPU memory\")\n # (the default value is for the fox dataset)\n parser.add_argument('--bound', type=float, default=1, help=\"assume the scene is bounded in box[-bound, bound]^3, if > 1, will invoke adaptive ray marching.\")\n parser.add_argument('--scale', type=float, default=4, help=\"scale camera location into box[-bound, bound]^3\")\n parser.add_argument('--offset', type=float, nargs='*', default=[0, 0, 0], help=\"offset of camera location\")\n parser.add_argument('--dt_gamma', type=float, default=1/256, help=\"dt_gamma (>=0) for adaptive ray marching. set to 0 to disable, >0 to accelerate rendering (but usually with worse quality)\")\n parser.add_argument('--min_near', type=float, default=0.05, help=\"minimum near distance for camera\")\n parser.add_argument('--density_thresh', type=float, default=10, help=\"threshold for density grid to be occupied (sigma)\")\n parser.add_argument('--density_thresh_torso', type=float, default=0.01, help=\"threshold for density grid to be occupied (alpha)\")\n parser.add_argument('--patch_size', type=int, default=1, help=\"[experimental] render patches in training, so as to apply LPIPS loss. 1 means disabled, use [64, 32, 16] to enable\")\n\n parser.add_argument('--finetune_lips', action='store_true', help=\"use LPIPS and landmarks to fine tune lips region\")\n parser.add_argument('--smooth_lips', action='store_true', help=\"smooth the enc_a in a exponential decay way...\")\n\n parser.add_argument('--torso', action='store_true', help=\"fix head and train torso\")\n parser.add_argument('--head_ckpt', type=str, default='', help=\"head model\")\n\n ### GUI options\n parser.add_argument('--gui', action='store_true', help=\"start a GUI\")\n parser.add_argument('--W', type=int, default=450, help=\"GUI width\")\n parser.add_argument('--H', type=int, default=450, help=\"GUI height\")\n parser.add_argument('--radius', type=float, default=3.35, help=\"default GUI camera radius from center\")\n parser.add_argument('--fovy', type=float, default=21.24, help=\"default GUI camera fovy\")\n parser.add_argument('--max_spp', type=int, default=1, help=\"GUI rendering max sample per pixel\")\n\n ### else\n parser.add_argument('--att', type=int, default=2, help=\"audio attention mode (0 = turn off, 1 = left-direction, 2 = bi-direction)\")\n parser.add_argument('--emb', action='store_true', help=\"use audio class + embedding instead of logits\")\n\n parser.add_argument('--ind_dim', type=int, default=4, help=\"individual code dim, 0 to turn off\")\n parser.add_argument('--ind_num', type=int, default=10000, help=\"number of individual codes, should be larger than training dataset size\")\n\n parser.add_argument('--ind_dim_torso', type=int, default=8, help=\"individual code dim, 0 to turn off\")\n\n parser.add_argument('--amb_dim', type=int, default=2, help=\"ambient dimension\")\n parser.add_argument('--part', action='store_true', help=\"use partial training data (1/10)\")\n parser.add_argument('--part2', action='store_true', help=\"use partial training data (first 15s)\")\n\n parser.add_argument('--train_camera', action='store_true', help=\"optimize camera pose\")\n parser.add_argument('--smooth_path', action='store_true', help=\"brute-force smooth camera pose trajectory with a window size\")\n parser.add_argument('--smooth_path_window', type=int, default=7, help=\"smoothing window size\")\n\n # asr\n parser.add_argument('--asr', action='store_true', help=\"load asr for real-time app\")\n parser.add_argument('--asr_wav', type=str, default='', help=\"load the wav and use as input\")\n parser.add_argument('--asr_play', action='store_true', help=\"play out the audio\")\n\n parser.add_argument('--asr_model', type=str, default='cpierse/wav2vec2-large-xlsr-53-esperanto')\n # parser.add_argument('--asr_model', type=str, default='facebook/wav2vec2-large-960h-lv60-self')\n\n parser.add_argument('--asr_save_feats', action='store_true')\n # audio FPS\n parser.add_argument('--fps', type=int, default=50)\n # sliding window left-middle-right length (unit: 20ms)\n parser.add_argument('-l', type=int, default=10)\n parser.add_argument('-m', type=int, default=50)\n parser.add_argument('-r', type=int, default=10)\n\n\n\nnerf/gui.py\nclass NeRFGUI:\n def __init__(self, opt, trainer, data_loader, debug=True):\n self.opt = opt # shared with the trainer's opt to support in-place modification of rendering parameters.\n self.W = opt.W\n self.H = opt.H\n self.cam = OrbitCamera(opt.W, opt.H, r=opt.radius, fovy=opt.fovy)\n self.debug = debug\n self.training = False\n self.step = 0 # training step \n\n self.trainer = trainer\n self.data_loader = data_loader\n\n # override with dataloader's intrinsics\n self.W = data_loader._data.W\n self.H = data_loader._data.H\n self.cam.update_intrinsics(data_loader._data.intrinsics)\n\n # use dataloader's pose\n pose_init = data_loader._data.poses[0]\n self.cam.update_pose(pose_init.detach().cpu().numpy())\n\n # use dataloader's bg\n bg_img = data_loader._data.bg_img #.view(1, -1, 3)\n if self.H != bg_img.shape[0] or self.W != bg_img.shape[1]:\n bg_img = F.interpolate(bg_img.permute(2, 0, 1).unsqueeze(0).contiguous(), (self.H, self.W), mode='bilinear').squeeze(0).permute(1, 2, 0).contiguous()\n self.bg_color = bg_img.view(1, -1, 3)\n\n # audio features (from dataloader, only used in non-playing mode)\n self.audio_features = data_loader._data.auds # [N, 29, 16]\n self.audio_idx = 0\n\n # control eye\n self.eye_area = None if not self.opt.exp_eye else data_loader._data.eye_area.mean().item()\n\n # playing seq from dataloader, or pause.\n self.playing = False\n self.loader = iter(data_loader)\n\n self.render_buffer = np.zeros((self.W, self.H, 3), dtype=np.float32)\n self.need_update = True # camera moved, should reset accumulation\n self.spp = 1 # sample per pixel\n self.mode = 'image' # choose from ['image', 'depth']\n\n self.dynamic_resolution = False # assert False!\n self.downscale = 1\n self.train_steps = 16\n\n self.ind_index = 0\n self.ind_num = trainer.model.individual_codes.shape[0]\n\n # build asr\n if self.opt.asr:\n self.asr = ASR(opt)\n \n dpg.create_context()\n self.register_dpg()\n self.test_step()\n \n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if self.opt.asr:\n self.asr.stop() \n dpg.destroy_context()\n\n def train_step(self):\n\n starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)\n starter.record()\n\n outputs = self.trainer.train_gui(self.data_loader, step=self.train_steps)\n\n ender.record()\n torch.cuda.synchronize()\n t = starter.elapsed_time(ender)\n\n self.step += self.train_steps\n self.need_update = True\n\n dpg.set_value(\"_log_train_time\", f'{t:.4f}ms ({int(1000/t)} FPS)')\n dpg.set_value(\"_log_train_log\", f'step = {self.step: 5d} (+{self.train_steps: 2d}), loss = {outputs[\"loss\"]:.4f}, lr = {outputs[\"lr\"]:.5f}')\n\n # dynamic train steps\n # max allowed train time per-frame is 500 ms\n full_t = t / self.train_steps * 16\n train_steps = min(16, max(4, int(16 * 500 / full_t)))\n if train_steps > self.train_steps * 1.2 or train_steps < self.train_steps * 0.8:\n self.train_steps = train_steps\n\n def prepare_buffer(self, outputs):\n if self.mode == 'image':\n return outputs['image']\n else:\n return np.expand_dims(outputs['depth'], -1).repeat(3, -1)\n\n def test_step(self):\n\n if self.need_update or self.spp < self.opt.max_spp:\n \n starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)\n starter.record()\n\n if self.playing:\n try:\n data = next(self.loader)\n except StopIteration:\n self.loader = iter(self.data_loader)\n data = next(self.loader)\n \n if self.opt.asr:\n # use the live audio stream\n data['auds'] = self.asr.get_next_feat()\n\n outputs = self.trainer.test_gui_with_data(data, self.W, self.H)\n\n # sync local camera pose\n self.cam.update_pose(data['poses_matrix'][0].detach().cpu().numpy())\n \n else:\n if self.audio_features is not None:\n auds = get_audio_features(self.audio_features, self.opt.att, self.audio_idx)\n else:\n auds = None\n outputs = self.trainer.test_gui(self.cam.pose, self.cam.intrinsics, self.W, self.H, auds, self.eye_area, self.ind_index, self.bg_color, self.spp, self.downscale)\n\n ender.record()\n torch.cuda.synchronize()\n t = starter.elapsed_time(ender)\n\n # update dynamic resolution\n if self.dynamic_resolution:\n # max allowed infer time per-frame is 200 ms\n full_t = t / (self.downscale ** 2)\n downscale = min(1, max(1/4, math.sqrt(200 / full_t)))\n if downscale > self.downscale * 1.2 or downscale < self.downscale * 0.8:\n self.downscale = downscale\n\n if self.need_update:\n self.render_buffer = self.prepare_buffer(outputs)\n self.spp = 1\n self.need_update = False\n else:\n self.render_buffer = (self.render_buffer * self.spp + self.prepare_buffer(outputs)) / (self.spp + 1)\n self.spp += 1\n \n if self.playing:\n self.need_update = True\n\n dpg.set_value(\"_log_infer_time\", f'{t:.4f}ms ({int(1000/t)} FPS)')\n dpg.set_value(\"_log_resolution\", f'{int(self.downscale * self.W)}x{int(self.downscale * self.H)}')\n dpg.set_value(\"_log_spp\", self.spp)\n dpg.set_value(\"_texture\", self.render_buffer)\n\n \n def register_dpg(self):\n\n ### register texture \n\n with dpg.texture_registry(show=False):\n dpg.add_raw_texture(self.W, self.H, self.render_buffer, format=dpg.mvFormat_Float_rgb, tag=\"_texture\")\n\n ### register window\n\n # the rendered image, as the primary window\n with dpg.window(tag=\"_primary_window\", width=self.W, height=self.H):\n\n # add the texture\n dpg.add_image(\"_texture\")\n\n # dpg.set_primary_window(\"_primary_window\", True)\n\n dpg.show_tool(dpg.mvTool_Metrics)\n\n # control window\n with dpg.window(label=\"Control\", tag=\"_control_window\", width=400, height=300):\n\n # button theme\n with dpg.theme() as theme_button:\n with dpg.theme_component(dpg.mvButton):\n dpg.add_theme_color(dpg.mvThemeCol_Button, (23, 3, 18))\n dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (51, 3, 47))\n dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (83, 18, 83))\n dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 5)\n dpg.add_theme_style(dpg.mvStyleVar_FramePadding, 3, 3)\n\n # time\n if not self.opt.test:\n with dpg.group(horizontal=True):\n dpg.add_text(\"Train time: \")\n dpg.add_text(\"no data\", tag=\"_log_train_time\") \n\n with dpg.group(horizontal=True):\n dpg.add_text(\"Infer time: \")\n dpg.add_text(\"no data\", tag=\"_log_infer_time\")\n \n with dpg.group(horizontal=True):\n dpg.add_text(\"SPP: \")\n dpg.add_text(\"1\", tag=\"_log_spp\")\n\n # train button\n if not self.opt.test:\n with dpg.collapsing_header(label=\"Train\", default_open=True):\n\n # train / stop\n with dpg.group(horizontal=True):\n dpg.add_text(\"Train: \")\n\n def callback_train(sender, app_data):\n if self.training:\n self.training = False\n dpg.configure_item(\"_button_train\", label=\"start\")\n else:\n self.training = True\n dpg.configure_item(\"_button_train\", label=\"stop\")\n\n dpg.add_button(label=\"start\", tag=\"_button_train\", callback=callback_train)\n dpg.bind_item_theme(\"_button_train\", theme_button)\n\n def callback_reset(sender, app_data):\n @torch.no_grad()\n def weight_reset(m: nn.Module):\n reset_parameters = getattr(m, \"reset_parameters\", None)\n if callable(reset_parameters):\n m.reset_parameters()\n self.trainer.model.apply(fn=weight_reset)\n self.trainer.model.reset_extra_state() # for cuda_ray density_grid and step_counter\n self.need_update = True\n\n dpg.add_button(label=\"reset\", tag=\"_button_reset\", callback=callback_reset)\n dpg.bind_item_theme(\"_button_reset\", theme_button)\n\n # save ckpt\n with dpg.group(horizontal=True):\n dpg.add_text(\"Checkpoint: \")\n\n def callback_save(sender, app_data):\n self.trainer.save_checkpoint(full=True, best=False)\n dpg.set_value(\"_log_ckpt\", \"saved \" + os.path.basename(self.trainer.stats[\"checkpoints\"][-1]))\n self.trainer.epoch += 1 # use epoch to indicate different calls.\n\n dpg.add_button(label=\"save\", tag=\"_button_save\", callback=callback_save)\n dpg.bind_item_theme(\"_button_save\", theme_button)\n\n dpg.add_text(\"\", tag=\"_log_ckpt\")\n \n # save mesh\n with dpg.group(horizontal=True):\n dpg.add_text(\"Marching Cubes: \")\n\n def callback_mesh(sender, app_data):\n self.trainer.save_mesh(resolution=256, threshold=10)\n dpg.set_value(\"_log_mesh\", \"saved \" + f'{self.trainer.name}_{self.trainer.epoch}.ply')\n self.trainer.epoch += 1 # use epoch to indicate different calls.\n\n dpg.add_button(label=\"mesh\", tag=\"_button_mesh\", callback=callback_mesh)\n dpg.bind_item_theme(\"_button_mesh\", theme_button)\n\n dpg.add_text(\"\", tag=\"_log_mesh\")\n\n with dpg.group(horizontal=True):\n dpg.add_text(\"\", tag=\"_log_train_log\")\n\n \n # rendering options\n with dpg.collapsing_header(label=\"Options\", default_open=True):\n \n # playing\n with dpg.group(horizontal=True):\n dpg.add_text(\"Play: \")\n\n def callback_play(sender, app_data):\n \n if self.playing:\n self.playing = False\n dpg.configure_item(\"_button_play\", label=\"start\")\n else:\n self.playing = True\n dpg.configure_item(\"_button_play\", label=\"stop\")\n if self.opt.asr:\n self.asr.warm_up()\n self.need_update = True\n\n dpg.add_button(label=\"start\", tag=\"_button_play\", callback=callback_play)\n dpg.bind_item_theme(\"_button_play\", theme_button)\n\n # set asr\n if self.opt.asr:\n\n # clear queue button\n def callback_clear_queue(sender, app_data):\n \n self.asr.clear_queue()\n self.need_update = True\n\n dpg.add_button(label=\"clear\", tag=\"_button_clear_queue\", callback=callback_clear_queue)\n dpg.bind_item_theme(\"_button_clear_queue\", theme_button)\n\n # dynamic rendering resolution\n with dpg.group(horizontal=True):\n\n def callback_set_dynamic_resolution(sender, app_data):\n if self.dynamic_resolution:\n self.dynamic_resolution = False\n self.downscale = 1\n else:\n self.dynamic_resolution = True\n self.need_update = True\n\n # Disable dynamic resolution for face.\n # dpg.add_checkbox(label=\"dynamic resolution\", default_value=self.dynamic_resolution, callback=callback_set_dynamic_resolution)\n dpg.add_text(f\"{self.W}x{self.H}\", tag=\"_log_resolution\")\n\n # mode combo\n def callback_change_mode(sender, app_data):\n self.mode = app_data\n self.need_update = True\n \n dpg.add_combo(('image', 'depth'), label='mode', default_value=self.mode, callback=callback_change_mode)\n\n\n # bg_color picker\n def callback_change_bg(sender, app_data):\n self.bg_color = torch.tensor(app_data[:3], dtype=torch.float32) # only need RGB in [0, 1]\n self.need_update = True\n\n dpg.add_color_edit((255, 255, 255), label=\"Background Color\", width=200, tag=\"_color_editor\", no_alpha=True, callback=callback_change_bg)\n\n # audio index slider\n if not self.opt.asr:\n def callback_set_audio_index(sender, app_data):\n self.audio_idx = app_data\n self.need_update = True\n\n dpg.add_slider_int(label=\"Audio\", min_value=0, max_value=self.audio_features.shape[0] - 1, format=\"%d\", default_value=self.audio_idx, callback=callback_set_audio_index)\n\n # ind code index slider\n if self.opt.ind_dim > 0:\n def callback_set_individual_code(sender, app_data):\n self.ind_index = app_data\n self.need_update = True\n\n dpg.add_slider_int(label=\"Individual\", min_value=0, max_value=self.ind_num - 1, format=\"%d\", default_value=self.ind_index, callback=callback_set_individual_code)\n\n # eye area slider\n if self.opt.exp_eye:\n def callback_set_eye(sender, app_data):\n self.eye_area = app_data\n self.need_update = True\n\n dpg.add_slider_float(label=\"eye area\", min_value=0, max_value=0.5, format=\"%.2f percent\", default_value=self.eye_area, callback=callback_set_eye)\n\n # fov slider\n def callback_set_fovy(sender, app_data):\n self.cam.fovy = app_data\n self.need_update = True\n\n dpg.add_slider_int(label=\"FoV (vertical)\", min_value=1, max_value=120, format=\"%d deg\", default_value=self.cam.fovy, callback=callback_set_fovy)\n\n # dt_gamma slider\n def callback_set_dt_gamma(sender, app_data):\n self.opt.dt_gamma = app_data\n self.need_update = True\n\n dpg.add_slider_float(label=\"dt_gamma\", min_value=0, max_value=0.1, format=\"%.5f\", default_value=self.opt.dt_gamma, callback=callback_set_dt_gamma)\n\n # max_steps slider\n def callback_set_max_steps(sender, app_data):\n self.opt.max_steps = app_data\n self.need_update = True\n\n dpg.add_slider_int(label=\"max steps\", min_value=1, max_value=1024, format=\"%d\", default_value=self.opt.max_steps, callback=callback_set_max_steps)\n\n # aabb slider\n def callback_set_aabb(sender, app_data, user_data):\n # user_data is the dimension for aabb (xmin, ymin, zmin, xmax, ymax, zmax)\n self.trainer.model.aabb_infer[user_data] = app_data\n\n # also change train aabb ? [better not...]\n #self.trainer.model.aabb_train[user_data] = app_data\n\n self.need_update = True\n\n dpg.add_separator()\n dpg.add_text(\"Axis-aligned bounding box:\")\n\n with dpg.group(horizontal=True):\n dpg.add_slider_float(label=\"x\", width=150, min_value=-self.opt.bound, max_value=0, format=\"%.2f\", default_value=-self.opt.bound, callback=callback_set_aabb, user_data=0)\n dpg.add_slider_float(label=\"\", width=150, min_value=0, max_value=self.opt.bound, format=\"%.2f\", default_value=self.opt.bound, callback=callback_set_aabb, user_data=3)\n\n with dpg.group(horizontal=True):\n dpg.add_slider_float(label=\"y\", width=150, min_value=-self.opt.bound, max_value=0, format=\"%.2f\", default_value=-self.opt.bound, callback=callback_set_aabb, user_data=1)\n dpg.add_slider_float(label=\"\", width=150, min_value=0, max_value=self.opt.bound, format=\"%.2f\", default_value=self.opt.bound, callback=callback_set_aabb, user_data=4)\n\n with dpg.group(horizontal=True):\n dpg.add_slider_float(label=\"z\", width=150, min_value=-self.opt.bound, max_value=0, format=\"%.2f\", default_value=-self.opt.bound, callback=callback_set_aabb, user_data=2)\n dpg.add_slider_float(label=\"\", width=150, min_value=0, max_value=self.opt.bound, format=\"%.2f\", default_value=self.opt.bound, callback=callback_set_aabb, user_data=5)\n \n\n # debug info\n if self.debug:\n with dpg.collapsing_header(label=\"Debug\"):\n # pose\n dpg.add_separator()\n dpg.add_text(\"Camera Pose:\")\n dpg.add_text(str(self.cam.pose), tag=\"_log_pose\")\n\n\n ### register camera handler\n\n def callback_camera_drag_rotate(sender, app_data):\n\n if not dpg.is_item_focused(\"_primary_window\"):\n return\n\n dx = app_data[1]\n dy = app_data[2]\n\n self.cam.orbit(dx, dy)\n self.need_update = True\n\n if self.debug:\n dpg.set_value(\"_log_pose\", str(self.cam.pose))\n\n\n def callback_camera_wheel_scale(sender, app_data):\n\n if not dpg.is_item_focused(\"_primary_window\"):\n return\n\n delta = app_data\n\n self.cam.scale(delta)\n self.need_update = True\n\n if self.debug:\n dpg.set_value(\"_log_pose\", str(self.cam.pose))\n\n\n def callback_camera_drag_pan(sender, app_data):\n\n if not dpg.is_item_focused(\"_primary_window\"):\n return\n\n dx = app_data[1]\n dy = app_data[2]\n\n self.cam.pan(dx, dy)\n self.need_update = True\n\n if self.debug:\n dpg.set_value(\"_log_pose\", str(self.cam.pose))\n\n\n with dpg.handler_registry():\n dpg.add_mouse_drag_handler(button=dpg.mvMouseButton_Left, callback=callback_camera_drag_rotate)\n dpg.add_mouse_wheel_handler(callback=callback_camera_wheel_scale)\n dpg.add_mouse_drag_handler(button=dpg.mvMouseButton_Middle, callback=callback_camera_drag_pan)\n\n \n dpg.create_viewport(title='RAD-NeRF', width=1080, height=720, resizable=True)\n\n ### global theme\n with dpg.theme() as theme_no_padding:\n with dpg.theme_component(dpg.mvAll):\n # set all padding to 0 to avoid scroll bar\n dpg.add_theme_style(dpg.mvStyleVar_WindowPadding, 0, 0, category=dpg.mvThemeCat_Core)\n dpg.add_theme_style(dpg.mvStyleVar_FramePadding, 0, 0, category=dpg.mvThemeCat_Core)\n dpg.add_theme_style(dpg.mvStyleVar_CellPadding, 0, 0, category=dpg.mvThemeCat_Core)\n \n dpg.bind_item_theme(\"_primary_window\", theme_no_padding)\n\n dpg.setup_dearpygui()\n\n #dpg.show_metrics()\n\n dpg.show_viewport()\n\n\n def render(self):\n\n while dpg.is_dearpygui_running():\n # update texture every frame\n if self.training:\n self.train_step()\n # audio stream thread...\n if self.opt.asr and self.playing:\n # run 2 ASR steps (audio is at 50FPS, video is at 25FPS)\n for _ in range(2):\n self.asr.run_step()\n self.test_step()\n dpg.render_dearpygui_frame()\n\nnerf/provider.py\nclass NeRFDataset_Test:\n def __init__(self, opt, device, downscale=1):\n super().__init__()\n \n self.opt = opt\n self.device = device\n self.downscale = downscale\n self.scale = opt.scale # camera radius scale to make sure camera are inside the bounding box.\n self.offset = opt.offset # camera offset\n self.bound = opt.bound # bounding box half length, also used as the radius to random sample poses.\n self.fp16 = opt.fp16\n\n self.start_index = opt.data_range[0]\n self.end_index = opt.data_range[1]\n\n self.training = False\n self.num_rays = -1\n\n # load nerf-compatible format data.\n \n with open(opt.pose, 'r') as f:\n transform = json.load(f)\n\n # load image size\n self.H = int(transform['cy']) * 2 // downscale\n self.W = int(transform['cx']) * 2 // downscale\n \n # read images\n frames = transform[\"frames\"]\n\n # use a slice of the dataset\n if self.end_index == -1: # abuse...\n self.end_index = len(frames)\n\n frames = frames[self.start_index:self.end_index]\n\n print(f'[INFO] load {len(frames)} frames.')\n\n # only load pre-calculated aud features when not live-streaming\n if not self.opt.asr:\n\n aud_features = np.load(self.opt.aud)\n\n if self.opt.cond_type == 'idexp':\n aud_features = aud_features.reshape(-1, 68, 3)\n aud_features = torch.from_numpy(aud_features)\n\n idexp_lm3d_mean = aud_features.mean(axis=0).reshape([1,68,3])\n idexp_lm3d_std = aud_features.std(axis=0).reshape([1,68,3])\n idexp_lm3d_normalized = (aud_features.reshape([-1,68,3]) - idexp_lm3d_mean)/idexp_lm3d_std\n\n # step1. clamp the lm3d, to regularize apparent outliers\n lm3d_clamp_std = 2.3 # typically 1.~5., reduce it when blurry or bad cases occurs\n idexp_lm3d_normalized[:,0:17] = torch.clamp(idexp_lm3d_normalized[:,0:17], -lm3d_clamp_std, lm3d_clamp_std) # yaw_x_y_z\n idexp_lm3d_normalized[:,17:27,0:2] = torch.clamp(idexp_lm3d_normalized[:,17:27,0:2], -lm3d_clamp_std/2, lm3d_clamp_std/2) # brow_x_y\n idexp_lm3d_normalized[:,17:27,2] = torch.clamp(idexp_lm3d_normalized[:,17:27,2], -lm3d_clamp_std, lm3d_clamp_std) # brow_z\n idexp_lm3d_normalized[:,27:36] = torch.clamp(idexp_lm3d_normalized[:,27:36], -lm3d_clamp_std, lm3d_clamp_std) # nose\n idexp_lm3d_normalized[:,36:48,0:2] = torch.clamp(idexp_lm3d_normalized[:,36:48,0:2], -lm3d_clamp_std/2, lm3d_clamp_std/2) # eye_x_y\n idexp_lm3d_normalized[:,36:48,2] = torch.clamp(idexp_lm3d_normalized[:,36:48,2], -lm3d_clamp_std, lm3d_clamp_std) # eye_z\n idexp_lm3d_normalized[:,48:68] = torch.clamp(idexp_lm3d_normalized[:,48:68], -lm3d_clamp_std, lm3d_clamp_std) # mouth\n\n aud_features = idexp_lm3d_normalized*idexp_lm3d_std + idexp_lm3d_mean\n\n\n # _lambda_other = 0.4\n # _lambda_lip = 0.2\n # moving_lm = aud_features[0].clone()\n # print(aud_features[0,:48].shape)\n # for i in range(aud_features.size()[0]):\n # aud_features[i,0:17] = 2.0*_lambda_other * moving_lm[0:17] + (1 - 2.0*_lambda_other) * aud_features[i,0:17] # yaw\n # aud_features[i,17:27] = 2.0*_lambda_other * moving_lm[17:27] + (1 - 2.0*_lambda_other) * aud_features[i,17:27] # brow\n # aud_features[i,27:36] = 2.0*_lambda_other * moving_lm[27:36] + (1 - 2.0*_lambda_other) * aud_features[i,27:36] # nose\n # aud_features[i,36:48] = _lambda_other * moving_lm[36:48] + (1 - _lambda_other) * aud_features[i,36:48] # eye\n # aud_features[i,:48] = moving_lm[:48]\n # aud_features[i,48:68] = _lambda_lip * moving_lm[48:68] + (1 - _lambda_lip) * aud_features[i,48:68]\n else:\n aud_features = torch.from_numpy(aud_features)\n\n aud_features = aud_features.reshape(-1, 68, 3)\n\n if self.opt.method == 'genefaceDagger':\n video_idexp_lm3d_mean = aud_features.mean(axis=0).reshape([1,68,3])\n video_idexp_lm3d_std = aud_features.std(axis=0).reshape([1,68,3])\n aud_features = (aud_features - video_idexp_lm3d_mean) / video_idexp_lm3d_std\n\n # support both [N, 16] labels and [N, 16, K] logits\n if len(aud_features.shape) == 3:\n # if self.opt.cond_type in ['eo','ds']:\n # aud_features = aud_features.float().permute(0, 2, 1) # [N, 16, 29] --> [N, 29, 16] \n \n\n if self.opt.emb:\n print(f'[INFO] argmax to aud features {aud_features.shape} for --emb mode')\n aud_features = aud_features.argmax(1) # [N, 16]\n \n else:\n assert self.opt.emb, \"aud only provide labels, must use --emb\"\n aud_features = aud_features.long()\n\n print(f'[INFO] load {self.opt.aud} aud_features: {aud_features.shape}')\n\n self.poses = []\n self.auds = []\n self.eye_area = []\n\n for f in tqdm.tqdm(frames, desc=f'Loading data'):\n \n pose = np.array(f['transform_matrix'], dtype=np.float32) # [4, 4]\n pose = nerf_matrix_to_ngp(pose, scale=self.scale, offset=self.offset)\n self.poses.append(pose)\n\n # find the corresponding audio to the image frame\n if not self.opt.asr and self.opt.aud == '':\n aud = aud_features[min(f['aud_id'], aud_features.shape[0] - 1)] # careful for the last frame...\n self.auds.append(aud)\n\n if self.opt.exp_eye:\n \n if 'eye_ratio' in f:\n area = f['eye_ratio']\n else:\n area = 0.25 # default value for opened eye\n \n self.eye_area.append(area)\n \n # load pre-extracted background image (should be the same size as training image...)\n\n if self.opt.bg_img == 'white': # special\n bg_img = np.ones((self.H, self.W, 3), dtype=np.float32)\n elif self.opt.bg_img == 'black': # special\n bg_img = np.zeros((self.H, self.W, 3), dtype=np.float32)\n else: # load from file\n bg_img = cv2.imread(self.opt.bg_img, cv2.IMREAD_UNCHANGED) # [H, W, 3]\n if bg_img.shape[0] != self.H or bg_img.shape[1] != self.W:\n bg_img = cv2.resize(bg_img, (self.W, self.H), interpolation=cv2.INTER_AREA)\n bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGR2RGB)\n bg_img = bg_img.astype(np.float32) / 255 # [H, W, 3/4]\n\n self.bg_img = bg_img\n\n self.poses = np.stack(self.poses, axis=0)\n\n # smooth camera path...\n if self.opt.smooth_path:\n self.poses = smooth_camera_path(self.poses, self.opt.smooth_path_window)\n \n self.poses = torch.from_numpy(self.poses) # [N, 4, 4]\n \n if self.opt.asr:\n # live streaming, no pre-calculated auds\n self.auds = None\n else:\n # auds corresponding to images\n if self.opt.aud == '':\n self.auds = torch.stack(self.auds, dim=0) # eo: [N, 32, 16], idexp_lm3ds: [N, 68, 3]\n # auds is novel, may have a different length with images\n else:\n self.auds = aud_features\n \n self.bg_img = torch.from_numpy(self.bg_img)\n\n if self.opt.exp_eye:\n self.eye_area = np.array(self.eye_area, dtype=np.float32) # [N]\n print(f'[INFO] eye_area: {self.eye_area.min()} - {self.eye_area.max()}')\n\n if self.opt.smooth_eye:\n\n # naive 5 window average\n ori_eye = self.eye_area.copy()\n for i in range(ori_eye.shape[0]):\n start = max(0, i - 1)\n end = min(ori_eye.shape[0], i + 2)\n self.eye_area[i] = ori_eye[start:end].mean()\n\n self.eye_area = torch.from_numpy(self.eye_area).view(-1, 1) # [N, 1]\n\n # always preload\n self.poses = self.poses.to(self.device)\n\n if self.auds is not None:\n self.auds = self.auds.to(self.device)\n\n self.bg_img = self.bg_img.to(torch.half).to(self.device)\n \n if self.opt.exp_eye:\n self.eye_area = self.eye_area.to(self.device)\n\n # load intrinsics\n \n fl_x = fl_y = transform['focal_len']\n\n cx = (transform['cx'] / downscale)\n cy = (transform['cy'] / downscale)\n\n self.intrinsics = np.array([fl_x, fl_y, cx, cy])\n\n # directly build the coordinate meshgrid in [-1, 1]^2\n self.bg_coords = get_bg_coords(self.H, self.W, self.device) # [1, H*W, 2] in [-1, 1]\n \n def mirror_index(self, index):\n size = self.poses.shape[0]\n turn = index // size\n res = index % size\n if turn % 2 == 0:\n return res\n else:\n return size - res - 1\n\n def collate(self, index):\n\n B = len(index) # a list of length 1\n # assert B == 1\n\n results = {}\n\n # audio use the original index\n if self.auds is not None:\n if self.opt.cond_type == 'idexp':\n auds = get_audio_features(self.auds, self.opt.att, index[0], smooth_win_size=5).to(self.device)\n else:\n auds = get_audio_features(self.auds, self.opt.att, index[0]).to(self.device)\n \n results['auds'] = auds\n\n # head pose and bg image may mirror (replay --> <-- --> <--).\n index[0] = self.mirror_index(index[0])\n\n poses = self.poses[index].to(self.device) # [B, 4, 4]\n \n rays = get_rays(poses, self.intrinsics, self.H, self.W, self.num_rays, self.opt.patch_size)\n\n results['index'] = index # for ind. code\n results['H'] = self.H\n results['W'] = self.W\n results['rays_o'] = rays['rays_o']\n results['rays_d'] = rays['rays_d']\n\n if self.opt.exp_eye:\n results['eye'] = self.eye_area[index].to(self.device) # [1]\n else:\n results['eye'] = None\n\n bg_img = self.bg_img.view(1, -1, 3).repeat(B, 1, 1).to(self.device)\n\n results['bg_color'] = bg_img\n\n bg_coords = self.bg_coords # [1, N, 2]\n results['bg_coords'] = bg_coords\n\n results['poses'] = convert_poses(poses) # [B, 6]\n results['poses_matrix'] = poses # [B, 4, 4]\n \n return results\n\n def dataloader(self):\n\n \n # test with novel auds, then use its length\n if self.auds is not None:\n size = self.auds.shape[0]\n # live stream test, use 2 * len(poses), so it naturally mirrors.\n else:\n size = 2 * self.poses.shape[0]\n\n loader = DataLoader(list(range(size)), batch_size=1, collate_fn=self.collate, shuffle=False, num_workers=0)\n loader._data = self # an ugly fix... we need poses in trainer.\n\n # do evaluate if has gt images and use self-driven setting\n loader.has_gt = False\n\n return loader", "answers": [" opt = parser.parse_args()"], "length": 2976, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "4656fd4e-f941-4cdd-8249-20c330ff402f", "reasoning": "The script defines an argument parser inside the main block. After the necessary imports at the end, the next logical step is to actually parse the command‑line arguments using that parser. Therefore the next line should call parser.parse_args() and store the result, typically in a variable like opt.", "reasoning_model_answer": "opt = parser.parse_args()", "assistant_with_reasoning": "\nThe script defines an argument parser inside the main block. After the necessary imports at the end, the next logical step is to actually parse the command‑line arguments using that parser. Therefore the next line should call parser.parse_args() and store the result, typically in a variable like opt.\n\nopt = parser.parse_args()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.309, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 36224, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "opt = parser.parse_args()", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.net.URLDecoder;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport javax.annotation.PostConstruct;\nimport javax.servlet.ServletOutputStream;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport javax.validation.Valid;\nimport org.apache.commons.io.IOUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.PageRequest;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.util.ResourceUtils;\nimport org.springframework.validation.BindingResult;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.SessionAttribute;\nimport org.springframework.web.multipart.MultipartFile;\nimport com.github.pagehelper.util.StringUtil;\nimport cn.gson.oasys.model.dao.attendcedao.AttendceDao;\nimport cn.gson.oasys.model.dao.notedao.AttachmentDao;\nimport cn.gson.oasys.model.dao.plandao.TrafficDao;\nimport cn.gson.oasys.model.dao.processdao.BursementDao;\nimport cn.gson.oasys.model.dao.processdao.DetailsBurseDao;\nimport cn.gson.oasys.model.dao.processdao.EvectionDao;\nimport cn.gson.oasys.model.dao.processdao.EvectionMoneyDao;\nimport cn.gson.oasys.model.dao.processdao.HolidayDao;\nimport cn.gson.oasys.model.dao.processdao.OvertimeDao;\nimport cn.gson.oasys.model.dao.processdao.ProcessListDao;\nimport cn.gson.oasys.model.dao.processdao.RegularDao;\nimport cn.gson.oasys.model.dao.processdao.ResignDao;\nimport cn.gson.oasys.model.dao.processdao.ReviewedDao;\nimport cn.gson.oasys.model.dao.processdao.StayDao;\nimport cn.gson.oasys.model.dao.processdao.SubjectDao;\nimport cn.gson.oasys.model.dao.system.StatusDao;\nimport cn.gson.oasys.model.dao.system.TypeDao;\nimport cn.gson.oasys.model.dao.user.UserDao;\nimport cn.gson.oasys.model.entity.attendce.Attends;\nimport cn.gson.oasys.model.entity.note.Attachment;\nimport cn.gson.oasys.model.entity.process.AubUser;\nimport cn.gson.oasys.model.entity.process.Bursement;\nimport cn.gson.oasys.model.entity.process.DetailsBurse;\nimport cn.gson.oasys.model.entity.process.Evection;\nimport cn.gson.oasys.model.entity.process.EvectionMoney;\nimport cn.gson.oasys.model.entity.process.Holiday;\nimport cn.gson.oasys.model.entity.process.Overtime;\nimport cn.gson.oasys.model.entity.process.ProcessList;\nimport cn.gson.oasys.model.entity.process.Regular;\nimport cn.gson.oasys.model.entity.process.Resign;\nimport cn.gson.oasys.model.entity.process.Reviewed;\nimport cn.gson.oasys.model.entity.process.Stay;\nimport cn.gson.oasys.model.entity.process.Subject;\nimport cn.gson.oasys.model.entity.process.Traffic;\nimport cn.gson.oasys.model.entity.system.SystemStatusList;\nimport cn.gson.oasys.model.entity.system.SystemTypeList;\nimport cn.gson.oasys.model.entity.user.User;\nimport cn.gson.oasys.services.process.ProcessService;", "context": "src/main/java/cn/gson/oasys/controller/process/ProcedureController.java\n\t\t\t\t\t\t\ttraffic.setUser(u);\n\t\t\t\t\t\t\ttraffic.setEvection(eve);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\tList mm=eve.getStay();\n\t\t\t\t\t\tfor (Stay stay : mm) {\n\t\t\t\t\t\t\tallmoney+=stay.getStayMoney()*stay.getDay();\n\t\t\t\t\t\t\tUser u=udao.findByUserName(stay.getNameuser());\n\t\t\t\t\t\t\tstay.setUser(u);\n\t\t\t\t\t\t\tstay.setEvemoney(eve);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\teve.setMoney(allmoney);\n\t\t\t\t\t\t//set主表\n\t\t\t\t\t\tProcessList pro=eve.getProId();\n\t\t\t\t\t\tSystem.out.println(pro+\"mmmmmm\");\n\t\t\t\t\t\tproservice.index5(pro, val, lu, filePath,shen.getUserName());\n\t\t\t\t\t\temdao.save(eve);\n\t\t\t\t\t\t//存审核表\n\t\t\t\t\t\tproservice.index7(shen, pro);\n\t\t\t\t\t}else{\n\t\t\t\t\t\treturn \"common/proce\";\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\treturn \"redirect:/flowmanage\";\n\t\t\n\t}\n\t//出差申请\n\t@RequestMapping(\"evection\")\n\tpublic String evection(Model model, @SessionAttribute(\"userId\") Long userId,HttpServletRequest request,\n\t\t\t@RequestParam(value = \"page\", defaultValue = \"0\") int page,\n\t\t\t@RequestParam(value = \"size\", defaultValue = \"10\") int size){\n\t\t//查找类型\n\t\tList outtype=tydao.findByTypeModel(\"aoa_evection\");\n\t\tproservice.index6(model, userId, page, size);\n\t\tmodel.addAttribute(\"outtype\", outtype);\n\t\treturn \"process/evection\";\n\t}\n\t/**\n\t * 出差申请表单接收\n\t * @param model\n\t * @param session\n\t * @param request\n\t * @param page\n\t * @param size\n\t * @return\n\t * @throws IOException \n\t * @throws IllegalStateException \n\t */\n\t@RequestMapping(\"evec\")\n\tpublic String evec(@RequestParam(\"filePath\")MultipartFile filePath,HttpServletRequest req,@Valid Evection eve,BindingResult br,\n\t\t\t@SessionAttribute(\"userId\") Long userId) throws IllegalStateException, IOException{\n\t\tUser lu=udao.findOne(userId);//申请人\n\t\tUser shen=udao.findByUserName(eve.getNameuser());//审核人\n\t\tLong roleid=lu.getRole().getRoleId();//申请人角色id\n\t\tLong fatherid=lu.getFatherId();//申请人父id\n\t\tLong userid=shen.getUserId();//审核人userid\n\t\tString val=req.getParameter(\"val\");\n\t\tif(roleid>=3L && Objects.equals(fatherid, userid)){\n\t\t\t//set主表\n\t\t\tProcessList pro=eve.getProId();\n\t\t\tproservice.index5(pro, val, lu, filePath,shen.getUserName());\n\t\t\tedao.save(eve);\n\t\t\t//存审核表\n\t\t\tproservice.index7(shen, pro);\n\t\t}else{\n\t\t\treturn \"common/proce\";\n\t\t}\n\t\t\n\t\treturn \"redirect:/xinxeng\";\n\t}\n\t//加班申请\n\t\t@RequestMapping(\"overtime\")\n\t\tpublic String overtime(Model model, @SessionAttribute(\"userId\") Long userId,HttpServletRequest request,\n\t\t\t\t@RequestParam(value = \"page\", defaultValue = \"0\") int page,\n\t\t\t\t@RequestParam(value = \"size\", defaultValue = \"10\") int size){\n\t\t\t//查找类型\n\t\t\tList overtype=tydao.findByTypeModel(\"aoa_overtime\");\n\t\t\tproservice.index6(model, userId, page, size);\n\t\t\tmodel.addAttribute(\"overtype\", overtype);\n\t\t\treturn \"process/overtime\";\n\t\t}\n\t/**\n\t * 加班申请接收\n\t * @param model\n\t * @param session\n\t * @param request\n\t * @param page\n\t * @param size\n\t * @return\n\t */\n\t\t@RequestMapping(\"over\")\n\t\tpublic String over(HttpServletRequest req,@Valid Overtime eve,BindingResult br,\n\t\t\t\t@SessionAttribute(\"userId\") Long userId) throws IllegalStateException, IOException{\n\t\t\tUser lu=udao.findOne(userId);//申请人\n\t\t\tUser shen=udao.findByUserName(eve.getNameuser());//审核人\n\t\t\tLong roleid=lu.getRole().getRoleId();//申请人角色id\n\t\t\tLong fatherid=lu.getFatherId();//申请人父id\n\t\t\tLong userid=shen.getUserId();//审核人userid\n\t\t\tString val=req.getParameter(\"val\");\n\t\t\tif(roleid>=3L && Objects.equals(fatherid, userid)){\n\t\t\t\t//set主表\n\t\t\t\tProcessList pro=eve.getProId();\n\t\t\t\tproservice.index8(pro, val, lu,shen.getUserName());\n\t\t\t\todao.save(eve);\n\t\t\t\t//存审核表\n\t\t\t\tproservice.index7(shen, pro);\n\t\t\t}else{\n\t\t\t\treturn \"common/proce\";\n\t\t\t}\n\t\t\t\n\t\t\treturn \"redirect:/xinxeng\";\n\t\t\t\n\t\t}\n\t//请假申请\n\t@RequestMapping(\"holiday\")\n\tpublic String holiday(Model model, @SessionAttribute(\"userId\") Long userId,HttpServletRequest request,\n\t\t\t@RequestParam(value = \"page\", defaultValue = \"0\") int page,\n\t\t\t@RequestParam(value = \"size\", defaultValue = \"10\") int size){\n\t\t//查找类型\n\nsrc/main/java/cn/gson/oasys/model/dao/system/StatusDao.java\n@Repository\npublic interface StatusDao extends PagingAndSortingRepository{\n\t\n\t//根据模块名和名字查找到唯一对象\n\tSystemStatusList findByStatusModelAndStatusName(String statusModel,String statusName);\n\t\n\t//根据模块名查找到状态集合\n\tList findByStatusModel(String statusModel);\n\t\n\tList findByStatusNameLikeOrStatusModelLike(String name,String name2);\n\t\n\t\n\t\n\t@Query(\"select sl.statusName from SystemStatusList sl where sl.statusId=:id\")\n\tString findname(@Param(\"id\")Long id);\n\t\n\t@Query(\"select sl.statusColor from SystemStatusList sl where sl.statusId=:id\")\n\tString findcolor(@Param(\"id\")Long id);\n\t\n\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/HolidayDao.java\npublic interface HolidayDao extends PagingAndSortingRepository{\n\n\tHoliday findByProId(ProcessList pro);\n\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/process/Traffic.java\n@Entity\n@Table(name=\"aoa_traffic\")\n//交通费用明细表\npublic class Traffic {\n\n\t@Id\n\t@Column(name=\"traffic_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long trafficId;\n\t\n\t@OneToOne\n\t@JoinColumn(name=\"user_name\")\n\tprivate User user;//出差人员\n\t\n\t@Column(name=\"depart_time\")\n\tprivate Date departTime;//出发时间\n\t\n\t@Column(name=\"depart_name\")\n\tprivate String departName;//出发城市\n\t\n\t@Column(name=\"reach_name\")\n\tprivate String reachName;//到达城市\n\t\n\t@Column(name=\"traffic_name\")\n\tprivate String trafficName;//交通工具\n\t\n\t@Column(name=\"seat_type\")\n\tprivate String seatType;//座位类型\n\t\n\t@Column(name=\"traffic_money\")\n\tprivate Double trafficMoney;//交通标准\n\t\n\t@ManyToOne()\n\t@JoinColumn(name=\"evection_id\")\n\tprivate EvectionMoney evection;\n\t\n\t@Transient\n\tprivate String username;\n\t\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic Long getTrafficId() {\n\t\treturn trafficId;\n\t}\n\n\tpublic void setTrafficId(Long trafficId) {\n\t\tthis.trafficId = trafficId;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Date getDepartTime() {\n\t\treturn departTime;\n\t}\n\n\tpublic void setDepartTime(Date departTime) {\n\t\tthis.departTime = departTime;\n\t}\n\n\tpublic String getDepartName() {\n\t\treturn departName;\n\t}\n\n\tpublic void setDepartName(String departName) {\n\t\tthis.departName = departName;\n\t}\n\n\tpublic String getReachName() {\n\t\treturn reachName;\n\t}\n\n\tpublic void setReachName(String reachName) {\n\t\tthis.reachName = reachName;\n\t}\n\n\tpublic String getTrafficName() {\n\t\treturn trafficName;\n\t}\n\n\tpublic void setTrafficName(String trafficName) {\n\t\tthis.trafficName = trafficName;\n\t}\n\n\tpublic String getSeatType() {\n\t\treturn seatType;\n\t}\n\n\tpublic void setSeatType(String seatType) {\n\t\tthis.seatType = seatType;\n\t}\n\n\tpublic Double getTrafficMoney() {\n\t\treturn trafficMoney;\n\t}\n\n\tpublic void setTrafficMoney(Double trafficMoney) {\n\t\tthis.trafficMoney = trafficMoney;\n\t}\n\n\tpublic EvectionMoney getEvection() {\n\t\treturn evection;\n\t}\n\n\tpublic void setEvection(EvectionMoney evection) {\n\t\tthis.evection = evection;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Traffic [trafficId=\" + trafficId + \", departTime=\" + departTime + \", departName=\" + departName\n\t\t\t\t+ \", reachName=\" + reachName + \", trafficName=\" + trafficName + \", seatType=\" + seatType\n\t\t\t\t+ \", evection=\" + evection + \", username=\" + username + \"]\";\n\t}\n\n\t\n\t\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/DetailsBurseDao.java\npublic interface DetailsBurseDao extends PagingAndSortingRepository{\n\n\tList findByBurs(Bursement bu);\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/ReviewedDao.java\npublic interface ReviewedDao extends PagingAndSortingRepository{\n\n\t//根据审核人查找流程\n\t@Query(\"select new cn.gson.oasys.model.entity.process.AubUser(pro.processId,pro.typeNmae,pro.deeply,pro.processName,pro.userId.userName,pro.applyTime,rev.statusId) \"\n\t\t\t+ \"from ProcessList as pro,Reviewed as rev where rev.proId.processId=pro.processId and rev.userId=?1 and rev.del=?2 order by rev.statusId\")\n\tPage findByUserIdOrderByStatusId(User user,Boolean bo,Pageable pa);\n\t\n\t//根据申请人和审核人查找流程\n\t@Query(\"select new cn.gson.oasys.model.entity.process.AubUser(pro.processId,pro.typeNmae,pro.deeply,pro.processName,pro.userId.userName,pro.applyTime,rev.statusId) \"\n\t\t\t+ \"from ProcessList as pro,Reviewed as rev where rev.proId.processId=pro.processId and rev.userId=?1 and pro.userId=?2 and rev.del=?3 order by rev.statusId\")\n\tPage findprocesslist(User user,User u,Boolean bo,Pageable pa);\n\t\n\t//根据状态和审核人查找流程\n\t@Query(\"select new cn.gson.oasys.model.entity.process.AubUser(pro.processId,pro.typeNmae,pro.deeply,pro.processName,pro.userId.userName,pro.applyTime,rev.statusId) \"\n\t\t\t+ \"from ProcessList as pro,Reviewed as rev where rev.proId.processId=pro.processId and rev.userId=?1 and rev.statusId=?2 and rev.del=?3 order by rev.statusId\")\n\tPage findbystatusprocesslist(User user,Long statusid,Boolean bo,Pageable pa);\n\t\n\t//根据类型名和审核人查找流程\n\t@Query(\"select new cn.gson.oasys.model.entity.process.AubUser(pro.processId,pro.typeNmae,pro.deeply,pro.processName,pro.userId.userName,pro.applyTime,rev.statusId) \"\n\t\t\t+ \"from ProcessList as pro,Reviewed as rev where rev.proId.processId=pro.processId and rev.userId=?1 and pro.typeNmae=?2 and rev.del=?3 order by rev.statusId\")\n\tPage findbytypenameprocesslist(User user,String typename,Boolean bo,Pageable pa);\n\t\n\t//根据标题和审核人查找流程\n\t@Query(\"select new cn.gson.oasys.model.entity.process.AubUser(pro.processId,pro.typeNmae,pro.deeply,pro.processName,pro.userId.userName,pro.applyTime,rev.statusId) \"\n\t\t\t+ \"from ProcessList as pro,Reviewed as rev where rev.proId.processId=pro.processId and rev.userId=?1 and pro.processName like %?2% and rev.del=?3 order by rev.statusId\")\n\tPage findbyprocessnameprocesslist(User user,String processname,Boolean bo,Pageable pa);\n\t\n\tList findByReviewedTimeNotNullAndProId(ProcessList pro);\n\t\n\t@Query(\" select re from Reviewed as re where re.proId.processId=?1 and re.userId=?2\")\n\tReviewed findByProIdAndUserId(Long pro,User u);\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/process/Resign.java\n@Table\n@Entity(name=\"aoa_resign\")\n//离职表\npublic class Resign {\n\t\n\t@Id\n\t@Column(name=\"resign_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long resignId;\n\t\n\tprivate String suggest;//申请人的意见及建议\n\t\n\t@Column(name=\"is_finish\")\n\tprivate Boolean finish=false;//是否还有费用报销未完成\n\t\n\t@OneToOne\n\t@JoinColumn(name=\"hand_user\")\n\tprivate User handUser; //工作交接人员\n\t\n\tprivate String nofinish;//未完成事宜\n\t\n\t@Column(name=\"financial_advice\")\n\tprivate String financialAdvice;//财务部意见及说明\n\t\n\t@Column(name=\"personnel_advice\")\n\tprivate String personnelAdvice;//人事部意见及说明\n\t\n\t@Column(name=\"manager_advice\")\n\tprivate String managerAdvice;//经理意见及说明\n\t\n\t@OneToOne(cascade=CascadeType.ALL)\n\t@JoinColumn(name=\"pro_id\")\n\tprivate ProcessList proId;\n\t\n\t@Transient\n\tprivate String nameuser;//审核人员\n\t\n\t@Transient\n\tprivate String handuser;//交接人员\n\t\n\t\n\n\tpublic String getManagerAdvice() {\n\t\treturn managerAdvice;\n\t}\n\n\tpublic void setManagerAdvice(String managerAdvice) {\n\t\tthis.managerAdvice = managerAdvice;\n\t}\n\n\tpublic String getNameuser() {\n\t\treturn nameuser;\n\t}\n\n\tpublic void setNameuser(String nameuser) {\n\t\tthis.nameuser = nameuser;\n\t}\n\n\tpublic String getHanduser() {\n\t\treturn handuser;\n\t}\n\n\tpublic void setHanduser(String handuser) {\n\t\tthis.handuser = handuser;\n\t}\n\n\tpublic ProcessList getProId() {\n\t\treturn proId;\n\t}\n\n\tpublic void setProId(ProcessList proId) {\n\t\tthis.proId = proId;\n\t}\n\n\tpublic Long getResignId() {\n\t\treturn resignId;\n\t}\n\n\tpublic void setResignId(Long resignId) {\n\t\tthis.resignId = resignId;\n\t}\n\n\tpublic String getSuggest() {\n\t\treturn suggest;\n\t}\n\n\tpublic void setSuggest(String suggest) {\n\t\tthis.suggest = suggest;\n\t}\n\n\tpublic Boolean getFinish() {\n\t\treturn finish;\n\t}\n\n\tpublic void setFinish(Boolean finish) {\n\t\tthis.finish = finish;\n\t}\n\n\tpublic User getHandUser() {\n\t\treturn handUser;\n\t}\n\n\tpublic void setHandUser(User handUser) {\n\t\tthis.handUser = handUser;\n\t}\n\n\tpublic String getNofinish() {\n\t\treturn nofinish;\n\t}\n\n\tpublic void setNofinish(String nofinish) {\n\t\tthis.nofinish = nofinish;\n\t}\n\n\tpublic String getFinancialAdvice() {\n\t\treturn financialAdvice;\n\t}\n\n\tpublic void setFinancialAdvice(String financialAdvice) {\n\t\tthis.financialAdvice = financialAdvice;\n\t}\n\n\tpublic String getPersonnelAdvice() {\n\t\treturn personnelAdvice;\n\t}\n\n\tpublic void setPersonnelAdvice(String personnelAdvice) {\n\t\tthis.personnelAdvice = personnelAdvice;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Resign [resignId=\" + resignId + \", suggest=\" + suggest + \", finish=\" + finish + \", handUser=\" + handUser\n\t\t\t\t+ \", nofinish=\" + nofinish + \", financialAdvice=\" + financialAdvice + \", personnelAdvice=\"\n\t\t\t\t+ personnelAdvice + \", managerAdvice=\" + managerAdvice + \", nameuser=\" + nameuser + \", handuser=\"\n\t\t\t\t+ handuser + \"]\";\n\t}\n\n\t\n\t\n\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/StayDao.java\npublic interface StayDao extends PagingAndSortingRepository{\n \n\tList findByEvemoney(EvectionMoney money);\n}\n\nsrc/main/java/cn/gson/oasys/services/process/ProcessService.java\n@Service\n@Transactional\npublic class ProcessService {\n\t@Autowired\n\tprivate UserDao udao;\n\t@Autowired\n\tprivate DeptDao ddao;\n\t@Autowired\n\tprivate RoleDao rdao;\n\t@Autowired\n\tprivate PositionDao pdao;\n\t@Autowired\n\tprivate SubjectDao sudao;\n\t@Autowired\n\tprivate StatusDao sdao;\n\t@Autowired\n\tprivate TypeDao tydao;\n\t@Autowired\n\tprivate ReviewedDao redao;\n\t@Autowired\n\tprivate AttachmentDao AttDao;\n\t@Autowired\n\tprivate BursementDao budao;\n\t@Autowired\n\tprivate MailServices mservice;\n\t@Autowired\n\tprivate ProcessListDao prodao;\n\t /**\n * 汉语中数字大写\n */\n private static final String[] CN_UPPER_NUMBER = { \"零\", \"壹\", \"贰\", \"叁\", \"肆\",\n \"伍\", \"陆\", \"柒\", \"捌\", \"玖\" };\n /**\n * 汉语中货币单位大写,这样的设计类似于占位符\n */\n private static final String[] CN_UPPER_MONETRAY_UNIT = { \"分\", \"角\", \"元\",\n \"拾\", \"佰\", \"仟\", \"万\", \"拾\", \"佰\", \"仟\", \"亿\", \"拾\", \"佰\", \"仟\", \"兆\", \"拾\",\n \"佰\", \"仟\" };\n /**\n * 特殊字符:整\n */\n private static final String CN_FULL = \"整\";\n /**\n * 特殊字符:负\n */\n private static final String CN_NEGATIVE = \"负\";\n /**\n * 金额的精度,默认值为2\n */\n private static final int MONEY_PRECISION = 2;\n /**\n * 特殊字符:零元整\n */\n private static final String CN_ZEOR_FULL = \"零元\" + CN_FULL;\n \n\n\t/**\n\t * 写文件 方法\n\t * \n\t * @param response\n\t * @param file\n\t * @throws IOException \n\t */\n\tpublic void writefile(HttpServletResponse response, File file) {\n\t\tServletOutputStream sos = null;\n\t\tFileInputStream aa = null;\n\t\ttry {\n\t\t\taa = new FileInputStream(file);\n\t\t\tsos = response.getOutputStream();\n\t\t\t// 读取文件问字节码\n\t\t\tbyte[] data = new byte[(int) file.length()];\n\t\t\tIOUtils.readFully(aa, data);\n\t\t\t// 将文件流输出到浏览器\n\t\t\tIOUtils.write(data, sos);\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}finally{\n\t\t\ttry {\n\t\t\t\tsos.close();\n\t\t\t\taa.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\n\t}\n /**\n * 用户封装\n * @param user\n * @param page\n * @param size\n * @param val\n * @return\n */\n\tpublic void user(int page,int size,Model model){\n\t\tPageable pa=new PageRequest(page, size);\n\t\t//查看用户并分页\n\t\tPage pageuser=udao.findAll(pa);\n\t\tList userlist=pageuser.getContent();\n\t\t// 查询部门表\n\t\tIterable deptlist = ddao.findAll();\n\t\t// 查职位表\n\t\tIterable poslist = pdao.findAll();\n\t\tmodel.addAttribute(\"page\", pageuser);\n\t\tmodel.addAttribute(\"emplist\", userlist);\n\t\tmodel.addAttribute(\"deptlist\", deptlist);\n\t\tmodel.addAttribute(\"poslist\", poslist);\n\t\tmodel.addAttribute(\"url\", \"names\");\n\t}\n\t\n\t\n\tpublic Page index(User user,int page,int size,String val,Model model){\n\t\tPageable pa=new PageRequest(page, size);\n\t\tPage pagelist=null;\n\t\tPage pagelist2=null;\n\t\tList orders = new ArrayList<>();\n\t\tUser u=udao.findByUserName(val);//找用户\n\t\tSystemStatusList status=sdao.findByStatusModelAndStatusName(\"aoa_process_list\", val);\n\t\tif(StringUtil.isEmpty(val)){\n\t\t\torders.add(new Order(Direction.DESC, \"applyTime\"));\n\t\t\tSort sort = new Sort(orders);\n\t\t\tpa=new PageRequest(page, size,sort);\n\t\t\tpagelist=redao.findByUserIdOrderByStatusId(user,false, pa);\n\t\t}else if(!Objects.isNull(u)){\n\t\t\tpagelist=redao.findprocesslist(user,u,false,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}else if(!Objects.isNull(status)){\n\t\t\tpagelist=redao.findbystatusprocesslist(user,status.getStatusId(),false,pa);\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t}else{\n\t\t\tpagelist2=redao.findbytypenameprocesslist(user, val,false, pa);\n\t\t\tif(!pagelist2.hasContent()){\n\t\t\t\tpagelist2=redao.findbyprocessnameprocesslist(user, val,false, pa);\n\t\t\t}\n\t\t\tmodel.addAttribute(\"sort\", \"&val=\"+val);\n\t\t\treturn pagelist2;\n\t\t}\n\t\treturn pagelist;\n\t}\n\n\tpublic List> index2(Page page,User user){\n\t\tList> list = new ArrayList<>();\n\t\tList prolist=page.getContent();\n\t\tfor (int i = 0; i < prolist.size(); i++) {\n\t\t\tString harryname=tydao.findname(prolist.get(i).getDeeply());\n\t\t\tSystemStatusList status=sdao.findOne(prolist.get(i).getStatusId());\n\t\t\tMap result=new HashMap<>();\n\t\t\tresult.put(\"typename\", prolist.get(i).getTypeNmae());\n\t\t\tresult.put(\"title\", prolist.get(i).getProcessName());\n\t\t\tresult.put(\"pushuser\", prolist.get(i).getUserName());\n\t\t\tresult.put(\"applytime\", prolist.get(i).getApplyTime());\n\t\t\tresult.put(\"harry\", harryname);\n\t\t\tresult.put(\"statusname\", status.getStatusName());\n\t\t\tresult.put(\"statuscolor\", status.getStatusColor());\n\t\t\tresult.put(\"proid\", prolist.get(i).getProcessId());\n\t\t\tlist.add(result);\n\t\t\t\n\t\t}\n\t\treturn list;\n\t}\n\t/**\n\t * 审核人封装\n\t */\n\tpublic List> index4(ProcessList process){\n\t\tList> relist=new ArrayList<>();\n\t\tList revie=redao.findByReviewedTimeNotNullAndProId(process);\n\t\tfor (int i = 0; i result=new HashMap<>();\n\t\t\tUser u=udao.findOne(revie.get(i).getUserId().getUserId());\n\t\t\tPosition po=pdao.findOne(u.getPosition().getId());\n\t\t\tSystemStatusList status=sdao.findOne(revie.get(i).getStatusId());\n\t\t\tresult.put(\"poname\", po.getName());\n\t\t\tresult.put(\"username\", u.getUserName());\n\t\t\tresult.put(\"retime\",revie.get(i).getReviewedTime());\n\t\t\tresult.put(\"restatus\",status.getStatusName());\n\t\t\tresult.put(\"statuscolor\",status.getStatusColor());\n\t\t\tresult.put(\"des\", revie.get(i).getAdvice());\n\t\t\tresult.put(\"img\",u.getImgPath());\n\t\t\tresult.put(\"positionid\",u.getPosition().getId());\n\t\t\trelist.add(result);\n\t\t}\n\t\treturn relist;\n\t}\n\t/**\n\t * process数据封装\n\t */\n\t\n\tpublic Map index3(String name,User user,String typename,ProcessList process){\n\t\tSystem.out.println(name);\n\t\tMap result=new HashMap<>();\n\t\tString harryname=tydao.findname(process.getDeeply());\n\t\tresult.put(\"proId\", process.getProcessId());\n\t\tresult.put(\"harryname\", harryname);\n\t\tresult.put(\"processName\", process.getProcessName());\n\t\tresult.put(\"processDescribe\",process.getProcessDescribe());\n\t\tif((\"审核\").equals(name)){\n\t\t\tresult.put(\"username\", process.getUserId().getUserName());//提单人员\n\t\t\tresult.put(\"deptname\", ddao.findname(process.getUserId().getDept().getDeptId()));//部门\n\t\t}else if((\"申请\").equals(name)){\n\t\t\tresult.put(\"username\", user.getUserName());\n\t\t\tresult.put(\"deptname\", ddao.findname(process.getUserId().getDept().getDeptId()));\n\t\t}\n\t\tresult.put(\"applytime\", process.getApplyTime());\n\t\tif(!Objects.isNull(process.getProFileid())){\n\t\t\tresult.put(\"file\", process.getProFileid());\n\t\t}else{\n\t\t\tresult.put(\"file\", \"file\");\n\t\t}\n\t\tresult.put(\"name\", name);\n\t\tresult.put(\"typename\", process.getTypeNmae());\n\t\tresult.put(\"startime\", process.getStartTime());\n\t\tresult.put(\"endtime\", process.getEndTime());\n\t\tresult.put(\"tianshu\", process.getProcseeDays());\n\t\tresult.put(\"statusid\", process.getStatusId());\n\t\tif( process.getProFileid()!=null){\n\t\t result.put(\"filepath\", process.getProFileid().getAttachmentPath());\n\t\t\tif(process.getProFileid().getAttachmentType().startsWith(\"image\")){\n\t\t\t\tresult.put(\"filetype\", \"img\");\n\t\t\t}else{\n\t\t\t\tresult.put(\"filetype\", \"appli\");\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t * 公用\n\t */\n\tpublic void index6(Model model,Long id,int page,int size){\n\t\tUser lu=udao.findOne(id);//申请人\n\t\tPageable pa=new PageRequest(page, size);\n\t\tList harrylist=tydao.findByTypeModel(\"aoa_process_list\");\n\t\t//查看用户并分页\n\t\tPage pageuser=udao.findAll(pa);\n\t\tList userlist=pageuser.getContent();\n\t\t// 查询部门表\n\t\tIterable deptlist = ddao.findAll();\n\t\t// 查职位表\n\t\tIterable poslist = pdao.findAll();\n\t\tmodel.addAttribute(\"page\", pageuser);\n\t\tmodel.addAttribute(\"emplist\", userlist);\n\t\tmodel.addAttribute(\"deptlist\", deptlist);\n\t\tmodel.addAttribute(\"poslist\", poslist);\n\t\tmodel.addAttribute(\"url\", \"names\");\n\t\tmodel.addAttribute(\"username\", lu.getUserName());\n\t\tmodel.addAttribute(\"harrylist\", harrylist);\n\t}\n\t/**\n\t * 存表\n\t * @throws IOException \n\t * @throws IllegalStateException \n\t */\n\tpublic void index5(ProcessList pro,String val,User lu,MultipartFile filePath,String name) throws IllegalStateException, IOException{\n\t\t\n\t\tpro.setTypeNmae(val);\n\t\tpro.setApplyTime(new Date());\n\t\tpro.setUserId(lu);\n\t\tpro.setStatusId(23L);\n\t\tpro.setShenuser(name);\n\t\tAttachment attaid=null;\n\t\tif(!StringUtil.isEmpty(filePath.getOriginalFilename())){\n\t\t\tattaid=mservice.upload(filePath, lu);\n\t\t\tattaid.setModel(\"aoa_bursement\");\n\t\t\tAttDao.save(attaid);\n\t\t\tpro.setProFileid(attaid);\n\t\t}\n\t}\n\tpublic void index8(ProcessList pro,String val,User lu,String name) {\n\t\tpro.setTypeNmae(val);\n\t\tpro.setApplyTime(new Date());\n\t\tpro.setUserId(lu);\n\t\tpro.setStatusId(23L);\n\t\tpro.setShenuser(name);\n\t}\n\t/**\n\t * 存主表\n\t */\n\tpublic void save(Long proid,User u,Reviewed reviewed,ProcessList pro,User u2){\n\t\tReviewed re=redao.findByProIdAndUserId(proid,u);\n\t\tre.setAdvice(reviewed.getAdvice());\n\t\tre.setStatusId(reviewed.getStatusId());\n\t\tre.setReviewedTime(new Date());\n\t\tre.setStatusId(reviewed.getStatusId());\n\t\tredao.save(re);\n\t\t\n\t\t\n\t\tReviewed re2=new Reviewed();\n\t\tre2.setProId(pro);\n\t\tre2.setUserId(u2);\n\t\tre2.setStatusId(23L);\n\t\tredao.save(re2);\n\t\t\n\t\tpro.getShenuser();\n\t\tpro.setShenuser(pro.getShenuser()+\";\"+u2.getUserName());\n\t\tpro.setStatusId(24L);//改变主表的状态\n\t\tprodao.save(pro);\n\t}\n\t/**\n\t * 存审核表\n\t */\n\tpublic void index7(User reuser,ProcessList pro){\n\t\tReviewed revie=new Reviewed();\n\t\trevie.setUserId(reuser);\n\t\trevie.setStatusId(23L);\n\t\trevie.setProId(pro);\n\t\tredao.save(revie);\n\t}\n\t/**\n\t * 把输入的金额转换为汉语中人民币的大写\n\t * \n\t * @param numberOfMoney\n\t * 输入的金额\n\t * @return 对应的汉语大写\n\t */\n\t public static String number2CNMontrayUnit(BigDecimal numberOfMoney) {\n\t StringBuffer sb = new StringBuffer();\n\t // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or\n\t // positive.\n\t int signum = numberOfMoney.signum();\n\t // 零元整的情况\n\t if (signum == 0) {\n\t return CN_ZEOR_FULL;\n\t }\n\t //这里会进行金额的四舍五入\n\t long number = numberOfMoney.movePointRight(MONEY_PRECISION)\n\t .setScale(0, 4).abs().longValue();\n\t // 得到小数点后两位值\n\t long scale = number % 100;\n\t int numUnit = 0;\n\t int numIndex = 0;\n\t boolean getZero = false;\n\t // 判断最后两位数,一共有四中情况:00 = 0, 01 = 1, 10, 11\n\t if (!(scale > 0)) {\n\t numIndex = 2;\n\t number = number / 100;\n\t getZero = true;\n\t }\n\t if ((scale > 0) && (!(scale % 10 > 0))) {\n\t numIndex = 1;\n\t number = number / 10;\n\t getZero = true;\n\t }\n\t int zeroSize = 0;\n\t while (true) {\n\t if (number <= 0) {\n\t break;\n\t }\n\t // 每次获取到最后一个数\n\t numUnit = (int) (number % 10);\n\t if (numUnit > 0) {\n\t if ((numIndex == 9) && (zeroSize >= 3)) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);\n\t }\n\t if ((numIndex == 13) && (zeroSize >= 3)) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);\n\t }\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);\n\t sb.insert(0, CN_UPPER_NUMBER[numUnit]);\n\t getZero = false;\n\t zeroSize = 0;\n\t } else {\n\t ++zeroSize;\n\t if (!(getZero)) {\n\t sb.insert(0, CN_UPPER_NUMBER[numUnit]);\n\t }\n\t if (numIndex == 2) {\n\t if (number > 0) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);\n\t }\n\t } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {\n\t sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);\n\t }\n\t getZero = true;\n\t }\n\t // 让number每次都去掉最后一个数\n\t number = number / 10;\n\t ++numIndex;\n\t }\n\t // 如果signum == -1,则说明输入的数字为负数,就在最前面追加特殊字符:负\n\t if (signum == -1) {\n\t sb.insert(0, CN_NEGATIVE);\n\t }\n\t // 输入的数字小数点后两位为\"00\"的情况,则要在最后追加特殊字符:整\n\t if (!(scale > 0)) {\n\t sb.append(CN_FULL);\n\t }\n\t return sb.toString();\n\t }\n\t \n\t public static String numbertocn(Double money){\n\t \tBigDecimal numberOfMoney = new BigDecimal(money);\n\t String s = number2CNMontrayUnit(numberOfMoney);\n\t System.out.println(\"你输入的金额为:【\"+ money +\"】 #--# [\" +s.toString()+\"]\");\n\t return s.toString();\n\t }\t\n\n\t\n\t\n}", "answers": ["\t\tList overtype=tydao.findByTypeModel(\"aoa_holiday\");"], "length": 2200, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "1bce8284-cba5-4da3-9e3a-d074922c30a0", "reasoning": "The method holiday begins similarly to evection and overtime: it needs to retrieve the list of system types for holiday requests. The pattern is to call tydao.findByTypeModel with the appropriate type model string and store it in a List variable. For holiday the type model is likely \"aoa_holiday\" and the variable follows the naming convention used earlier (e.g., outtype, overtype). Therefore the next line should retrieve this list.", "reasoning_model_answer": "List holtype = tydao.findByTypeModel(\"aoa_holiday\");", "assistant_with_reasoning": "\nThe method holiday begins similarly to evection and overtime: it needs to retrieve the list of system types for holiday requests. The pattern is to call tydao.findByTypeModel with the appropriate type model string and store it in a List variable. For holiday the type model is likely \"aoa_holiday\" and the variable follows the naming convention used earlier (e.g., outtype, overtype). Therefore the next line should retrieve this list.\n\nList holtype = tydao.findByTypeModel(\"aoa_holiday\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 8.275, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 28725, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "List holtype = tydao.findByTypeModel(\"aoa_holiday\");", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.badlogic.gdx.Gdx;\nimport com.badlogic.gdx.graphics.Texture;\nimport com.badlogic.gdx.graphics.g2d.Animation;\nimport com.badlogic.gdx.graphics.g2d.Batch;\nimport com.badlogic.gdx.graphics.g2d.TextureRegion;\nimport com.badlogic.gdx.math.MathUtils;\nimport com.badlogic.gdx.scenes.scene2d.Actor;\nimport com.senetboom.game.SenetBoom;\nimport static com.senetboom.game.SenetBoom.*;", "context": "core/src/com/senetboom/game/backend/Stick.java\npackage com.senetboom.game.backend;\n\n\n\npublic class Stick {\n\n private StickRoll[] stickRolls;\n private int stickValue;\n private static float maxTime = 1.5f;\n private static float elapsedTime = 0;\n\n // every time a new Stick is created, we need to create a new RollingSticks actor and add it to the stage\n // also save the value of the stick in the stickValue variable\n\n public Stick() {\n // rolling Sticks\n this.stickRolls = new StickRoll[4];\n this.stickValue = 0;\n for (int i = 0; i < 4; i++) {\n this.stickRolls[i] = new StickRoll();\n this.stickValue += this.stickRolls[i].getStickRoll();\n }\n if(stickValue == 0){ // 4 blacks equal value 6\n stickValue = 6;\n }\n\n // create RollingsSticks actor and add to stage\n RollingSticks rollingSticks = new RollingSticks();\n SenetBoom.stickStage.addActor(rollingSticks);\n\n // set sticksTumbling to true\n\ncore/src/com/senetboom/game/SenetBoom.java\npublic class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTexture;\n\n\t// for the empty variables (the tiles that are currently moved by a bot)\n\tpublic static int emptyVariable;\n\n\t// for the possible moves that the bot uses for decision-making\n\t// Array of int values\n\tpublic static ArrayList possibleMoves;\n\tpublic static int possibleMove;\n\n\t// for the batch\n\tSpriteBatch batch;\n\n\t// for the background\n\tTexture background;\n\n\t// for the currentStage\n\tstatic Stage currentStage;\n\n\t// stage options\n\tpublic static boolean showOptions;\n\tStage OptionsStage;\n\n\t// stage credit\n\tboolean showCredits;\n\tStage CreditsStage;\n\n\t// stick stage\n\tpublic static Stage stickStage;\n\n\t// typeWriterStage\n\tpublic static Stage typeWriterStage;\n\n\t// hitStage\n\tStage hitStage;\n\tAnimation hitAnimation;\n\n\t// helpOverlayStage\n\tstatic Stage helpOverlayStage;\n\tTexture help;\n\tpublic static boolean displayHelp;\n\tTexture hand;\n\t// for the pieces textures unselected\n\tpublic static Texture blackpiece;\n\tpublic static Texture whitepiece;\n\n\t// for the turn constant\n\tstatic Turn gameState;\n\n\t// for the game boolean value of it having just started\n\tpublic static boolean gameStarted;\n\n\t// for the tileSize relative to screenSize from RelativeResizer\n\tpublic static float tileSize;\n\n\t// textures for special state\n\tpublic static Texture happy;\n\tpublic static Texture water;\n\tpublic static Texture safe;\n\tpublic static Texture rebirth;\n\n\t// boolean determining if the game is in progress\n\tpublic static boolean inGame;\n\n\t// typewriter\n\tpublic static Typewriter typeWriter;\n\n\t// for knowing when to skip the Turn\n\tpublic static boolean skipTurn;\n\n\tpublic static Texture logo;\n\n\t// for the textbutton skin\n\tpublic static Skin skin;\n\n\t// if the Sticks are Tumbling\n\tpublic static boolean sticksTumbling;\n\n\t// current Stick value\n\tpublic static int currentStickValue;\n\t// Sticks\n\tpublic static Stick gameSticks;\n\n\t//Game End Stage\n\tpublic static Stage gameEndStage;\n\n\t// legitMove boolean\n\tpublic static boolean legitMove;\n\n\t// rebirth protection\n\tpublic static Texture rebirthProtection;\n\n\t// for the music volume\n\tpublic static float volume;\n\n\t// texture for the tile\n\tpublic static Texture tileTexture;\n\n\t// map stage\n\tpublic static Stage mapStage;\n\n\t// boolean for an extra turn\n\tpublic static boolean extraTurn;\n\t// texture\n\tpublic static Texture extraTurnTexture;\n\n\t//stage for extra turn\n\tpublic static Stage extraTurnStage;\n\n\t// stick value Stage\n\tprivate static Stage stickValueStage;\n\n\t// textures for the sticks\n\tpublic static Texture blackStick;\n\tpublic static Texture whiteStick;\n\n\t// number textures\n\tpublic static Texture number0;\n\tpublic static Texture number1;\n\tpublic static Texture number2;\n\tpublic static Texture number3;\n\tpublic static Texture number4;\n\tpublic static Texture number6;\n\n\t// for the game start\n\tpublic static boolean startUndecided;\n\tpublic static Stage deciderStage;\n\n\t// textures of starter\n\tpublic static Texture whiteStarts;\n\tpublic static Texture blackStarts;\n\n\t// boolean for the decider\n\tpublic static boolean deciderStarted;\n\n\t// for when a turn has not been checked yet\n\tpublic static boolean gameUnchecked;\n\n\t// hint stage\n\tpublic static Stage hintStage;\n\n\t// for displaying the current Turn\n\tpublic static Stage currentTurnStage;\n\n\t// turn play textures\n\tpublic static Texture whitePlays;\n\tpublic static Texture blackPlays;\n\n\t// texture for the help\n\tpublic static Texture helpTexture;\n\n\t// no moves texture\n\tpublic static Texture noMovesTexture;\n\n\tpublic static boolean displayHint = false;\n\n\tpublic static Texture possibleMoveTexture;\n\n\tpublic static boolean needRender;\n\n\t// for the arms\n\tpublic static Image armFromBelow;\n\tpublic static Image armFromAbove;\n\n\t// for the advanced arm stages and their respective boolean\n\n\tpublic static Stage armFromBelowStage;\n\tpublic static Stage armFromAboveStage;\n\tpublic static boolean showArmFromBelowStage;\n\tpublic static boolean showArmFromAboveStage;\n\n\tpublic static MusicPlaylist musicPlaylist;\n\n\t// enum of turn\n\tprivate enum Turn {\n\t\tPLAYERWHITE,\n\t\tPLAYERBLACK,\n\t}\n\n\t@Override\n\tpublic void create () {\n\t\tbatch = new SpriteBatch();\n\t\tbackground = new Texture(\"textures/background.png\");\n\n\t\t// from scene2dUi\n\t\tcurrentStage = new Stage();\n\t\tshowOptions = false;\n\t\tOptionsStage = new Stage();\n\t\tshowCredits = false;\n\t\tCreditsStage = new Stage();\n\t\tinGame = false;\n\t\tgameStarted = false;\n\t\tgameEndStage = new Stage();\n\t\tstickStage = new Stage();\n\t\ttypeWriterStage = new Stage();\n\t\thitStage = new Stage();\n\t\thelpOverlayStage = new Stage();\n\t\tmapStage = new Stage();\n\t\textraTurnStage = new Stage();\n\t\tstickValueStage = new Stage();\n\t\tdeciderStage = new Stage();\n\t\thintStage = new Stage();\n\t\tcurrentTurnStage = new Stage();\n\n\t\t// for the arms\n\n\t\tarmFromBelowStage = new Stage();\n\t\tarmFromAboveStage = new Stage();\n\t\tshowArmFromBelowStage = false;\n\t\tshowArmFromAboveStage = false;\n\n\t\t// possible Moves is a ArrayList of int values\n\t\tpossibleMoves = new ArrayList();\n\n\t\tdisplayHelp = false;\n\t\tskipTurn = false;\n\t\tsticksTumbling = false;\n\t\tlegitMove = false;\n\n\t\t// loading the skin\n\t\tskin = new Skin(Gdx.files.internal(\"menu.commodore64/uiskin.json\"));\n\n\t\t// loading all textures\n\t\tblackpiece = new Texture(\"textures/blackpiece.png\");\n\t\twhitepiece = new Texture(\"textures/whitepiece.png\");\n\t\thappy = new Texture(\"textures/happy.png\");\n\t\twater = new Texture(\"textures/water.png\");\n\t\tsafe = new Texture(\"textures/safe.png\");\n\t\trebirth = new Texture(\"textures/rebirth.png\");\n\t\trebirthProtection = new Texture(\"textures/rebirthprotection.png\");\n\t\tlogo = new Texture(\"logoSenet.png\");\n\t\ttileTexture = new Texture(\"textures/tile.png\");\n\t\temptyTexture = new Texture(\"textures/empty.png\");\n\t\textraTurnTexture = new Texture(\"textures/extraTurn.png\");\n\t\twhiteStarts = new Texture(\"textures/whiteStart.png\");\n\t\tblackStarts = new Texture(\"textures/blackStarts.png\");\n\n\t\t// arms\n\n\t\tarmFromAboveStage = new Stage();\n\t\tarmFromBelowStage = new Stage();\n\n\t\tarmFromAbove = new Image(new Texture(\"textures/armabovein.png\"));\n\t\tarmFromBelow = new Image(new Texture(\"textures/armbelowin.png\"));\n\n\t\tarmFromAboveStage.addActor(armFromAbove);\n\t\tarmFromBelowStage.addActor(armFromBelow);\n\n\t\t// for the sticks\n\t\tblackStick = new Texture(\"textures/blackStick.png\");\n\t\twhiteStick = new Texture(\"textures/whiteStick.png\");\n\n\t\t// for the numbers\n\t\tnumber0 = new Texture(\"textures/0.png\");\n\t\tnumber1 = new Texture(\"textures/1.png\");\n\t\tnumber2 = new Texture(\"textures/2.png\");\n\t\tnumber3 = new Texture(\"textures/3.png\");\n\t\tnumber4 = new Texture(\"textures/4.png\");\n\t\tnumber6 = new Texture(\"textures/6.png\");\n\n\t\t// possible Move Texture\n\t\tpossibleMoveTexture = new Texture(\"textures/possibleMove.png\");\n\n\t\t// no moves texture\n\t\tnoMovesTexture = new Texture(\"textures/noMovesTexture.png\");\n\n\t\t// help texture\n\t\thelpTexture = new Texture(\"textures/rules.png\");\n\n\t\t// for the turn plays textures\n\t\twhitePlays = new Texture(\"textures/whitePlays.png\");\n\t\tblackPlays = new Texture(\"textures/blackPlays.png\");\n\n\t\t// for the empty tile texture\n\t\temptyTexture = new Texture(\"textures/empty.png\");\n\n\t\t// music Playlist\n\n\t\tvolume = 0.5f;\n\n\t\tmusicPlaylist = new MusicPlaylist();\n\n\t\t// from youtube: https://www.youtube.com/watch?v=nBmWXmn11YE\n\t\tmusicPlaylist.addSong(\"music/egyptreconstruct.mp3\");\n\t\t// from youtube: https://www.youtube.com/watch?v=mECTRQ0VEyU\n\t\tmusicPlaylist.addSong(\"music/egyptianmusic.mp3\");\n\t\t// from youtube: https://www.youtube.com/watch?v=d7jKP_JngC8\n\t\tmusicPlaylist.addSong(\"music/egyptianmusic2.mp3\");\n\n\t\tmusicPlaylist.play();\n\n\t\t// for the empty variable (the tile that is currently moved by a bot)\n\t\temptyVariable = -1;\n\n\t\t// for the tileSize relative to screenSize from RelativeResizer\n\t\ttileSize = 80;\n\n\t\tgameState = Turn.PLAYERWHITE;\n\n\t\tresize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n\n\t\tGdx.input.setInputProcessor(currentStage);\n\n\t\tcreateHelpStage(); // for the help overlay that can be activated\n\n\t\tcreateMenu();\n\t}\n\n\t@Override\n\tpublic void render () {\n\t\tScreenUtils.clear(1, 0, 0, 1);\n\n\t\tbatch.begin();\n\t\tbatch.draw(background, 0, 0);\n\t\tbatch.end();\n\n\t\tif(needRender){\n\t\t\trenderBoard();\n\t\t\tneedRender = false;\n\t\t}\n\n\t\tif(inGame){\n\t\t\tmapStage.act();\n\t\t\tmapStage.draw();\n\t\t}\n\n\t\t// from scene2dUi\n\t\tcurrentStage.act();\n\t\tcurrentStage.draw();\n\n\t\tif(displayHelp){\n\t\t\thelpOverlayStage.act();\n\t\t\thelpOverlayStage.draw();\n\t\t}\n\n\t\tif (showOptions) {\n\t\t\tOptionsStage.act();\n\t\t\tOptionsStage.draw();\n\t\t}\n\n\t\tif (showCredits) {\n\t\t\tCreditsStage.act();\n\t\t\tCreditsStage.draw();\n\t\t}\n\n\t\tif(inGame){\n\t\t\t// all stages affiliated with the game ongoing\n\n\t\t\tif(gameStarted){\n\t\t\t\t// decide who starts!\n\t\t\t\tif(startUndecided){\n\t\t\t\t\tif(!(deciderStarted)) {\n\t\t\t\t\t\t// randomly decides the first turn state + displays this deciding on the screen\n\t\t\t\t\t\tdecideStarter();\n\t\t\t\t\t}\n\n\t\t\t\t\t// gets called till the timer in deciderStarter is up, then it sets startUndecided to false\n\t\t\t\t\tdeciderStage.act();\n\t\t\t\t\tdeciderStage.draw();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tupdateLogoStage();\n\t\t\t\t// first act of a new game:\n\t\t\t\t// throw the sticks!\n\t\t\t\tgameSticks = new Stick();\n\t\t\t\tcurrentStickValue = gameSticks.getValue();\n\t\t\t\tsticksTumbling = true;\n\t\t\t\t// add the stickValueStage\n\t\t\t\tstickValueStage = SenetBoom.drawStickValue(currentStickValue);\n\t\t\t\tgameStarted = false;\n\t\t\t}\n\n\t\t\t// stick animation\n\t\t\tstickStage.act();\n\t\t\tstickStage.draw();\n\n\t\t\t// for the explicit typewriter\n\t\t\ttypeWriterStage.act();\n\t\t\ttypeWriterStage.draw();\n\n\t\t\t// for the switch animation (kinda like hit)\n\t\t\thitStage.act();\n\t\t\thitStage.draw();\n\n\t\t\t// for the hints if displayHint turned on\n\t\t\tif(displayHint) {\n\t\t\t\thintStage.act();\n\t\t\t\thintStage.draw();\n\t\t\t}\n\n\t\t\t// for the extra turn symbol\n\t\t\textraTurnStage.act();\n\t\t\textraTurnStage.draw();\n\n\t\t\t// current turn stage\n\t\t\tcurrentTurnStage.act();\n\t\t\tcurrentTurnStage.draw();\n\n\t\t\tif(!(sticksTumbling)) {\n\t\t\t\t// display the current stick value if the sticks are not tumbling\n\t\t\t\tstickValueStage.act();\n\t\t\t\tstickValueStage.draw();\n\t\t\t} else{\n\t\t\t\t// waiting for the sticks to end tumbling ( its animation )\n\t\t\t\tStick.update(Gdx.graphics.getDeltaTime());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for the arms\n\t\t\tif(showArmFromBelowStage) {\n\t\t\t\tarmFromBelowStage.act();\n\t\t\t\tarmFromBelowStage.draw();\n\t\t\t}\n\n\t\t\tif(showArmFromAboveStage) {\n\t\t\t\tarmFromAboveStage.act();\n\t\t\t\tarmFromAboveStage.draw();\n\t\t\t}\n\n\t\t\t// for the display of the game having ended\n\t\t\tgameEndStage.act();\n\t\t\tgameEndStage.draw();\n\n\t\t\t// only if the sticks have stopped tumbling, and if the turn hasn't skipped,\n\t\t\t// we can let a turn be processed\n\t\t\tif (skipTurn) { // skip turn gets set to true if player pushed the skipTurn button\n\n\t\t\t\t// add a typewriter of ANGER or CONFUSED or SAD\n\t\t\t\t/* TODO\n\t\t\t\tif (gameState == Turn.PLAYERWHITE)\n\t\t\t\t\ttypeWriter.makeSpeech(Typewriter.Emotion.ANGRY, Typewriter.Character.WHITE);\n\t\t\t\telse\n\t\t\t\t\ttypeWriter.makeSpeech(Typewriter.Emotion.ANGRY, Typewriter.Character.BLACK);\n\t\t\t \t*/\n\n\t\t\t\t// other players turn\n\t\t\t\tswitchTurn();\n\n\t\t\t\tskipTurn = false;\n\t\t\t}\n\n\t\t\tprocessTurn();\n\t\t}\n\t}\n\n\tpublic void processTurn() {\n\n\t\t// ----------------- legit Move part\n\n\t\t// wait for a legitMove from a player of gameState\n\t\tif(legitMove) {\n\t\t\t// resets the legitMove check\n\t\t\tlegitMove = false;\n\n\t\t\t// if not legitMove, waits for a legitMove switch around\n\t\t\t// if legitMove, moves the piece in its respective dragStop Listener\n\t\t\t// check if the game is over\n\t\t\tcheckForGameEnd();\n\t\t\t// switch turn after completing the move\n\t\t\tswitchTurn();\n\t\t}\n\t}\n\n\tprivate void switchTurn() {\n\t\t// switch the turn\n\n\n\t\tif(extraTurn){ // if extraTurn is true, do not switch turn\n\t\t\t// player has an extra turn\n\t\t\textraTurn = false;\n\t\t}\n\t\telse { // switch turn\n\t\t\tif (gameState == Turn.PLAYERWHITE) {\n\t\t\t\tgameState = Turn.PLAYERBLACK;\n\t\t\t} else {\n\t\t\t\tgameState = Turn.PLAYERWHITE;\n\t\t\t}\n\t\t}\n\n\t\tpossibleMoves = new ArrayList();\n\n\t\tgameSticks = new Stick();\n\n\t\tcurrentStickValue = gameSticks.getValue();\n\n\t\t// ----------------- help part\n\t\t// after thrown, check if any moves are even possible with the stick(dice) number\n\t\t// if the next player has no moves possible, a slight hint gets added to the screen\n\t\t// we run calculateMove on any piece of the player and if it returns null,\n\t\t// the next player has no moves possible\n\n\t\tif (gameState == Turn.PLAYERWHITE) {\n\t\t\t// check if any moves are possible for the white player\n\t\t\t// if not, add a hint to the screen\n\t\t\tcheckForNoMoves(Turn.PLAYERWHITE);\n\t\t\t// if yes, remove the hint from the screen\n\t\t} else {\n\t\t\t// check if any moves are possible for the black player\n\t\t\t// if not, add a hint to the screen\n\t\t\t// if yes, remove the hint from the screen\n\t\t\tcheckForNoMoves(Turn.PLAYERBLACK);\n\t\t}\n\n\t\t// ----------------- end of help part\n\n\t\trenderBoard();\n\n\t\t// update move logo\n\t\tupdateLogoStage();\n\n\t\trenderBoard();\n\t\tGdx.input.setInputProcessor(currentStage);\n\t}\n\n\tprivate static void checkForNoMoves(Turn turn) {\n\n\t\thintStage.clear();\n\t\t// this method checks if the player has any moves possible\n\t\t// if not, it adds a \"No moves possible\" Actor to the hint screen\n\t\tboolean noMoves = true;\n\t\tTile[] gameBoard = Board.getBoard();\n\t\tPiece.Color currentTurn = turn == Turn.PLAYERWHITE ? Piece.Color.WHITE : Piece.Color.BLACK;\n\t\tfor(Tile tiles: gameBoard){\n\t\t\tif(tiles.hasPiece()){\n\t\t\t\tif(tiles.getPiece().getColour() == currentTurn){\n\t\t\t\t\t// if the piece is of the current turn\n\t\t\t\t\t// check if it has any moves possible\n\t\t\t\t\tif(tiles.isMoveValid(tiles.getPosition(), currentStickValue)){\n\t\t\t\t\t\t// if yes, set noMoves to false\n\t\t\t\t\t\tnoMoves = false;\n\t\t\t\t\t\tpossibleMoves.add(tiles.getPosition()+currentStickValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(noMoves){\n\t\t\t// if noMoves is true, add a hint to the screen\n\t\t\tImage noMove = new Image(noMovesTexture);\n\t\t\t// add at Position middle low\n\t\t\tnoMove.setPosition((float) Gdx.graphics.getWidth() /2, tileSize*2);\n\t\t\thintStage.addActor(noMove);\n\n\t\t\t// add a typewriter of ANGER or CONFUSED or SAD\n\t\t\t// TODO\n\n\t\t\t// render the board so that the possible Moves can be displayed on the screen\n\t\t\trenderBoard();\n\t\t}\n\t}\n\n\t// resize override\n\t@Override\n\tpublic void resize(int width, int height) {\n\t\t// from scene2dUi\n\t\tcurrentStage.getViewport().update(width, height, true);\n\t\tif (showOptions) {\n\t\t\tOptionsStage.getViewport().update(width, height, true);\n\t\t}\n\t\tif (showCredits) {\n\t\t\tCreditsStage.getViewport().update(width, height, true);\n\t\t}\n\t\tif(inGame){\n\t\t\tmapStage.getViewport().update(width, height, true);\n\t\t\tstickStage.getViewport().update(width, height, true);\n\t\t\ttypeWriterStage.getViewport().update(width, height, true);\n\t\t\thitStage.getViewport().update(width, height, true);\n\t\t\thelpOverlayStage.getViewport().update(width, height, true);\n\t\t\tgameEndStage.getViewport().update(width, height, true);\n\t\t\textraTurnStage.getViewport().update(width, height, true);\n\t\t\tstickValueStage.getViewport().update(width, height, true);\n\t\t\tdeciderStage.getViewport().update(width, height, true);\n\t\t\thintStage.getViewport().update(width, height, true);\n\t\t\tcurrentTurnStage.getViewport().update(width, height, true);\n\t\t\tarmFromAboveStage.getViewport().update(width, height, true);\n\t\t\tarmFromBelowStage.getViewport().update(width, height, true);\n\t\t}\n\t}\n\n\tprivate void updateLogoStage() {\n\t\t// updates the logo according to the turn constant\n\n\t\t// remove the old logo\n\t\tcurrentTurnStage.clear();\n\n\t\tImage currentTurner;\n\t\t// add the new logo\n\t\tif(gameState == Turn.PLAYERWHITE){\n\t\t\tcurrentTurner = new Image(whitePlays);\n\t\t} else {\n\t\t\tcurrentTurner = new Image(blackPlays);\n\t\t}\n\t\t// upper left corner\n\t\tcurrentTurner.setSize(tileSize*3, tileSize*2);\n\t\tcurrentTurner.setPosition(tileSize*2, tileSize * 8);\n\t\tcurrentTurnStage.addActor(currentTurner);\n\n\t}\n\n\tprivate void decideStarter() {\n\n\t\tdeciderStarted = true;\n\n\t\t// random decide if turn White or black\n\t\tint random = (int) (Math.random() * 2);\n\t\tif(random == 0){\n\t\t\tgameState = Turn.PLAYERWHITE;\n\t\t} else {\n\t\t\tgameState = Turn.PLAYERBLACK;\n\t\t}\n\t\t// adds the Decider to the stage\n\t\tDecider decider = new Decider(gameState);\n\t\tdeciderStage.addActor(decider);\n\t}\n\n\tprivate class Decider extends Actor{\n\t\t// after 2 seconds, it will set startDecided to true\n\t\tfloat X;\n\t\tfloat Y;\n\t\t// elapsed time since addition to stage\n\t\tfloat elapsed = 0;\n\t\t// this is the maximum duration that the bubble will be on the screen\n\t\tfinal float MAX_DURATION = 2f;\n\t\t// this is the stack of the bubble\n\t\tStack stack;\n\n\t\tpublic Decider(Turn turn){\n\t\t\tthis.stack = new Stack();\n\t\t\tstack.setSize(tileSize*4, tileSize*2);\n\n\t\t\tif(turn == Turn.PLAYERWHITE){\n\t\t\t\tstack.addActor(new Image(whiteStarts));\n\t\t\t} else {\n\t\t\t\tstack.addActor(new Image(blackStarts));\n\t\t\t}\n\n\t\t\tthis.X = tileSize*8;\n\t\t\tthis.Y = tileSize*8;\n\t\t}\n\n\t\t@Override\n\t\tpublic void act(float delta) {\n\t\t\t/*\n\t\t\t * this method is called every frame to update the Actor\n\t\t\t */\n\t\t\tsuper.act(delta);\n\t\t\telapsed += delta;\n\t\t\tif (elapsed > MAX_DURATION) {\n\t\t\t\tstartUndecided = false;\n\t\t\t\tremove(); // This will remove the actor from the stage\n\t\t\t}\n\t\t}\n\n\t\t// Override the draw method to add the stack at the correct position\n\t\t@Override\n\t\tpublic void draw(Batch batch, float parentAlpha) {\n\t\t\t/*\n\t\t\tThis method is called every frame to draw the starter indicator\n\t\t\t */\n\t\t\tsuper.draw(batch, parentAlpha);\n\t\t\tstack.setPosition(X, Y);\n\t\t\tstack.draw(batch, parentAlpha);\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void dispose () {\n\t\tbatch.dispose();\n\t\tbackground.dispose();\n\t\t// dispose of all textures\n\t\tblackpiece.dispose();\n\t\twhitepiece.dispose();\n\t\thappy.dispose();\n\t\twater.dispose();\n\t\tsafe.dispose();\n\t\trebirth.dispose();\n\t\trebirthProtection.dispose();\n\t\tlogo.dispose();\n\t\ttileTexture.dispose();\n\t\temptyTexture.dispose();\n\t\textraTurnTexture.dispose();\n\t\tblackStick.dispose();\n\t\twhiteStick.dispose();\n\t\tnumber0.dispose();\n\t\tnumber1.dispose();\n\t\tnumber2.dispose();\n\t\tnumber3.dispose();\n\t\tnumber4.dispose();\n\t\tnumber6.dispose();\n\t\twhiteStarts.dispose();\n\t\tblackStarts.dispose();\n\t}\n\n\tpublic static Coordinate calculatePXbyTile(int x) {\n\t\t// the screen is 1536 to 896. The board is 3x10 tiles and each tile is 80x80px.\n\t\t// the board is centered on the screen\n\t\tint screenWidth = 1536;\n\t\tint screenHeight = 896;\n\t\tint boardWidth = (int) (tileSize * 10);\n\t\tint boardHeight = (int) (tileSize * 3);\n\n\t\t// Calculate starting position (upper left corner) of the board\n\t\tint boardStartX = (screenWidth - boardWidth) / 2;\n\t\tint boardStartY = (screenHeight - boardHeight) / 2;\n\n\t\tint yCoord;\n\t\tint xCoord;\n\n\t\t// Calculate the tile's position\n\t\tif(x <= 9){\n\t\t\tyCoord = boardStartY + 80;\n\t\t\txCoord = boardStartX + (x * 80);\n\t\t} else if (x <= 19){\n\t\t\tyCoord = boardStartY;\n\t\t\txCoord = boardStartX + (10*80) - ((x-9)*80);\n\t\t} else {\n\t\t\tyCoord = boardStartY - (80);\n\t\t\txCoord = boardStartY * ((x-19) * 80);\n\t\t}\n\n\t\treturn new Coordinate(xCoord, yCoord);\n\t}\n\n\tpublic static int calculateTilebyPx(int x, int y) {\n\t\tint screenWidth = 1536;\n\t\tint screenHeight = 896;\n\t\tint inFuncTileSize = (int) tileSize;\n\t\tint boardWidth = (inFuncTileSize * 10);\n\t\tint boardHeight = (inFuncTileSize * 3);\n\n\t\t// Calculate starting position (upper left corner) of the board\n\t\tint boardStartX = (screenWidth - boardWidth) / 2;\n\t\tint boardStartY = (screenHeight - boardHeight) / 2;\n\n\t\t// Adjust the y-coordinate to reflect libGDX's bottom-left origin\n\t\tint adjustedY = screenHeight - y;\n\n\t\t// Calculate which tile\n\t\tint tileX = (int) ((x - boardStartX) / inFuncTileSize);\n\t\tint tileY = (int) ((adjustedY - boardStartY) / inFuncTileSize);\n\n\t\tint tile;\n\t\tif (tileY == 0) { // Top row\n\t\t\ttile = tileX; // Tiles 0 to 9\n\t\t} else if (tileY == 1) { // Middle row (reversed)\n\t\t\ttile = 19 - tileX; // Tiles 19 to 10, in reverse\n\t\t} else if (tileY == 2) { // Bottom row\n\t\t\ttile = 20 + tileX; // Tiles 20 to 29\n\t\t} else {\n\t\t\t// Handle the case where the coordinates are outside the board\n\t\t\ttile = -1;\n\t\t}\n\n\t\treturn tile;\n\t}\n\n\n\tpublic static void createHelpStage() {\n\t\t// load texture help\n\t\tImage help = new Image(helpTexture);\n\t\thelp.setPosition(tileSize*13.1f, tileSize*2.7f);\n\t\thelp.setSize(tileSize*7, tileSize*9);\n\t\t// add it to help stage\n\t\thelpOverlayStage.addActor(help);\n\t}\n\n\tpublic static void createOptionsStage() {\n\t}\n\n\tpublic static Skin getSkin() {\n\t\treturn skin;\n\t}\n\n\tpublic static void renderBoard() {\n\n\t\tstickValueStage.clear();\n\t\tstickValueStage = SenetBoom.drawStickValue(currentStickValue);\n\n\t\tmapStage.clear();\n\t\tmapStage = GameStage.drawMap();\n\n\t\tcurrentStage.clear();\n\t\tcurrentStage = GameStage.drawBoard();\n\n\t\tGdx.input.setInputProcessor(currentStage);\n\t}\n\n\tprivate static Stage drawStickValue(int currentStickValue) {\n\n\t\tStage stage = new Stage();\n\n\t\t// scene 2D UI stuff\n\t\tStack rawValue = new Stack();\n\t\tTable sticks = new Table();\n\n\t\tImage number;\n\t\t// switch statement for currentStickValue 1,2,3,4,6\n\t\tswitch(currentStickValue){\n\t\t\tcase 1:\n\t\t\t\t// draw 3 black sticks\n\t\t\t\t// draw 1 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number1);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t// draw 2 black sticks\n\t\t\t\t// draw 2 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number2);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t// draw 1 black sticks\n\t\t\t\t// draw 3 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number3);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\t// draw 0 black sticks\n\t\t\t\t// draw 4 white sticks\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tsticks.add(new Image(whiteStick));\n\t\t\t\tnumber = new Image(number4);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\t// draw 4 black sticks\n\t\t\t\t// draw 0 white sticks\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tsticks.add(new Image(blackStick));\n\t\t\t\tnumber = new Image(number6);\n\t\t\t\trawValue.add(number);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tsticks.setPosition(tileSize, tileSize*2);\n\t\tsticks.setSize(tileSize*2, tileSize*2);\n\t\tstage.addActor(sticks);\n\n\t\trawValue.setPosition(tileSize, tileSize*2.25f);\n\t\tstage.addActor(rawValue);\n\t\treturn stage;\n\t}\n\n\tpublic static void createMenu() {\n\t\tcurrentStage = MainMenu.createMenu();\n\t\tGdx.input.setInputProcessor(currentStage);\n\t\tinGame = false;\n\t}\n\n\tprivate void checkForGameEnd() {\n\t\t// goes over the gameBoard and counts, if someone has no pieces at all left\n\t\t// if so, the game ends and the winner is displayed\n\t\t// if not, the game continues\n\n\t\tTile[] gameBoard = Board.getBoard();\n\t\tint whitePieces = 0;\n\t\tint blackPieces = 0;\n\t\tfor(Tile tile : gameBoard){\n\t\t\tif(tile.hasPiece()){\n\t\t\t\tif(tile.getPiece().getColour() == Piece.Color.WHITE){\n\t\t\t\t\twhitePieces++;\n\t\t\t\t} else {\n\t\t\t\t\tblackPieces++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(whitePieces == 0){\n\t\t\tcreateGameEnd(Piece.Color.WHITE);\n\t\t}\n\t\tif(blackPieces == 0){\n\t\t\tcreateGameEnd(Piece.Color.BLACK);\n\t\t}\n\t}\n\n\tprivate void createGameEnd(Piece.Color color) {\n\t\t/*\n\t\tcreats a stage that displays the winner\n\t\t */\n\n\t\t// TODO\n\t}\n\n\tpublic static Piece.Color getTurn(){\n\t\treturn gameState == Turn.PLAYERWHITE ? Piece.Color.WHITE : Piece.Color.BLACK;\n\t}\n\n\tpublic static void addExtraTurnActor(){\n\t\tExtraTurnActor newTurn = new ExtraTurnActor();\n\t\textraTurnStage.addActor(newTurn);\n\t\tSystem.out.println(\"Added ExtraTurn Actor to Screen\\n\");\n\t}\n}", "answers": [" SenetBoom.sticksTumbling = true;"], "length": 2877, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "13eb313f-4145-4ca2-8bdd-8d253c9fd739", "reasoning": "In Stick.java's constructor, after adding the RollingSticks actor to the stage, the comment indicates we need to set the global flag that sticks are tumbling. The SenetBoom class defines a static boolean 'sticksTumbling'. So the next line should assign true to that field.", "reasoning_model_answer": "SenetBoom.sticksTumbling = true;", "assistant_with_reasoning": "\nIn Stick.java's constructor, after adding the RollingSticks actor to the stage, the comment indicates we need to set the global flag that sticks are tumbling. The SenetBoom class defines a static boolean 'sticksTumbling'. So the next line should assign true to that field.\n\nSenetBoom.sticksTumbling = true;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.202, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25071, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "SenetBoom.sticksTumbling = true;", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "import cloud.commandframework.context.CommandContext;\nimport cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;\nimport java.awt.Graphics2D;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Stream;\nimport net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;\nimport net.pl3x.map.core.command.CommandHandler;\nimport net.pl3x.map.core.command.Pl3xMapCommand;\nimport net.pl3x.map.core.command.Sender;\nimport net.pl3x.map.core.command.argument.RendererArgument;\nimport net.pl3x.map.core.command.argument.WorldArgument;\nimport net.pl3x.map.core.command.argument.ZoomArgument;\nimport net.pl3x.map.core.configuration.Config;\nimport net.pl3x.map.core.configuration.Lang;\nimport net.pl3x.map.core.image.io.IO;\nimport net.pl3x.map.core.markers.Point;\nimport net.pl3x.map.core.renderer.Renderer;\nimport net.pl3x.map.core.world.World;\nimport org.jetbrains.annotations.NotNull;\nimport static net.pl3x.map.core.world.World.PNG_MATCHER;", "context": "core/src/main/java/net/pl3x/map/core/command/commands/StitchCommand.java\n/*\n * MIT License\n *\n * Copyright (c) 2020-2023 William Blake Galbreath\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\npackage net.pl3x.map.core.command.commands;\n\n\npublic class StitchCommand extends Pl3xMapCommand {\n public StitchCommand(@NotNull CommandHandler handler) {\n super(handler);\n }\n\n @Override\n public void register() {\n getHandler().registerSubcommand(builder -> builder.literal(\"stitch\")\n .argument(WorldArgument.of(\"world\"), description(Lang.COMMAND_ARGUMENT_REQUIRED_WORLD_DESCRIPTION))\n .argument(RendererArgument.of(\"renderer\"), description(Lang.COMMAND_ARGUMENT_REQUIRED_RENDERER_DESCRIPTION))\n .argument(ZoomArgument.optional(\"zoom\"), description(Lang.COMMAND_ARGUMENT_OPTIONAL_ZOOM_DESCRIPTION))\n .meta(MinecraftExtrasMetaKeys.DESCRIPTION, Lang.parse(Lang.COMMAND_STITCH_DESCRIPTION))\n .permission(\"pl3xmap.command.stitch\")\n .handler(this::execute));\n }\n\n private void execute(@NotNull CommandContext<@NotNull Sender> context) {\n CompletableFuture.runAsync(() -> executeAsync(context));\n }\n\n private void executeAsync(@NotNull CommandContext<@NotNull Sender> context) {\n Sender sender = context.getSender();\n World world = context.get(\"world\");\n\ncore/src/main/java/net/pl3x/map/core/command/argument/ZoomArgument.java\npublic class ZoomArgument extends CommandArgument<@NotNull C, @NotNull Integer> {\n protected ZoomArgument(boolean required, @NotNull String name, @NotNull String defaultValue, @NotNull BiFunction<@NotNull CommandContext<@NotNull C>, @NotNull String, @NotNull List<@NotNull String>> suggestionsProvider, @NotNull ArgumentDescription defaultDescription) {\n super(required, name, new ZoomParser<>(), defaultValue, Integer.class, suggestionsProvider, defaultDescription);\n }\n\n /**\n * Create a new {@link ZoomArgument} builder.\n *\n * @param name argument name\n * @return new player argument builder\n */\n public static CommandArgument.@NotNull Builder<@NotNull C, @NotNull Integer> newBuilder(@NotNull String name) {\n return new Builder<>(name);\n }\n\n /**\n * Create a required {@link ZoomArgument}.\n *\n * @param name argument name\n * @return constructed player argument\n */\n public static @NotNull CommandArgument<@NotNull C, @NotNull Integer> of(@NotNull String name) {\n return ZoomArgument.<@NotNull C>newBuilder(name).asRequired().build();\n }\n\n /**\n * Create an optional {@link ZoomArgument}.\n *

\n * All arguments prior to any other required argument must also be required.\n *\n * @param name argument name\n * @return constructed player argument\n */\n public static @NotNull CommandArgument<@NotNull C, @NotNull Integer> optional(@NotNull String name) {\n return ZoomArgument.<@NotNull C>newBuilder(name).asOptional().build();\n }\n\n /**\n * Create an optional {@link ZoomArgument} with a default value.\n *

\n * All arguments prior to any other required argument must also be required.\n *\n * @param name argument name\n * @param defaultValue default value that will be used if none was supplied\n * @return constructed player argument\n */\n public static @NotNull CommandArgument<@NotNull C, @NotNull Integer> optional(@NotNull String name, @NotNull String defaultValue) {\n return ZoomArgument.<@NotNull C>newBuilder(name).asOptionalWithDefault(defaultValue).build();\n }\n\n /**\n * Mutable builder for {@link ZoomArgument} instances.\n *\n * @param command sender type\n */\n public static class Builder extends CommandArgument.Builder<@NotNull C, @NotNull Integer> {\n private Builder(@NotNull String name) {\n super(Integer.class, name);\n }\n\n @Override\n public @NotNull CommandArgument<@NotNull C, @NotNull Integer> build() {\n return new ZoomArgument<>(isRequired(), getName(), getDefaultValue(), getSuggestionsProvider(), getDefaultDescription());\n }\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/image/io/IO.java\npublic abstract class IO {\n private static final Registry<@NotNull Type> TYPES = new Registry<>();\n\n public static void register() {\n IO.register(\"bmp\", new Bmp());\n IO.register(\"gif\", new Gif());\n IO.register(\"jpg\", new Jpg());\n IO.register(\"jpeg\", get(\"jpg\"));\n IO.register(\"png\", new Png());\n }\n\n public static void register(@NotNull String name, @NotNull Type type) {\n if (TYPES.has(name)) {\n throw new IllegalStateException(String.format(\"IO type %s already registered\", name));\n }\n TYPES.register(name, type);\n }\n\n public static void unregister() {\n TYPES.unregister();\n }\n\n public static void unregister(@NotNull String name) {\n TYPES.unregister(name);\n }\n\n public static @NotNull Type get(@NotNull String format) {\n Type type = TYPES.get(format.toLowerCase(Locale.ROOT));\n if (type == null) {\n throw new IllegalStateException(\"Unknown or unsupported image format\");\n }\n return type;\n }\n\n public abstract static class Type extends Keyed {\n public Type(@NotNull String key) {\n super(key);\n }\n\n public @NotNull BufferedImage createBuffer() {\n return new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);\n }\n\n public int color(int argb) {\n return argb;\n }\n\n public @Nullable BufferedImage read(@NotNull Path path) {\n BufferedImage buffer = null;\n ImageReader reader = null;\n try (ImageInputStream in = ImageIO.createImageInputStream(Files.newInputStream(path))) {\n reader = ImageIO.getImageReadersBySuffix(getKey()).next();\n reader.setInput(in, false, true);\n buffer = reader.read(0);\n in.flush();\n } catch (IOException e) {\n Logger.warn(\"Could not read tile image: \" + path);\n e.printStackTrace();\n } finally {\n if (reader != null) {\n reader.dispose();\n }\n }\n return buffer;\n }\n\n public void write(@NotNull Path path, @NotNull BufferedImage buffer) {\n Path tmp = FileUtil.tmp(path);\n ImageWriter writer = null;\n try (ImageOutputStream out = ImageIO.createImageOutputStream(tmp.toFile())) {\n writer = ImageIO.getImageWritersBySuffix(getKey()).next();\n ImageWriteParam param = writer.getDefaultWriteParam();\n if (param.canWriteCompressed()) {\n param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n if (param.getCompressionType() == null) {\n param.setCompressionType(param.getCompressionTypes()[0]);\n }\n param.setCompressionQuality((float) Config.WEB_TILE_QUALITY);\n }\n writer.setOutput(out);\n writer.write(null, new IIOImage(buffer, null, null), param);\n out.flush();\n } catch (IOException e) {\n Logger.warn(\"Could not write tile image: \" + tmp);\n e.printStackTrace();\n } finally {\n if (writer != null) {\n writer.dispose();\n }\n }\n try {\n FileUtil.atomicMove(tmp, path);\n } catch (IOException e) {\n Logger.warn(\"Could not write tile image: \" + path);\n e.printStackTrace();\n }\n }\n }\n}\n\ncore/src/main/java/net/pl3x/map/core/configuration/Lang.java\n@SuppressWarnings(\"CanBeFinal\")\npublic final class Lang extends AbstractConfig {\n @Key(\"prefix.command\")\n public static String PREFIX_COMMAND = \"[Pl3xMap] \";\n @Key(\"command.base\")\n public static String COMMAND_BASE = \"View the map at ''>'\";\n\n @Key(\"command.event.click-for-help\")\n public static String CLICK_FOR_HELP = \"Click for help\";\n @Key(\"command.event.click-to-confirm\")\n public static String CLICK_TO_CONFIRM = \"Click to confirm\";\n\n @Key(\"httpd.started.success\")\n public static String HTTPD_STARTED = \"Internal webserver running on :\";\n @Key(\"httpd.started.error\")\n public static String HTTPD_START_ERROR = \"Internal webserver could not start\";\n @Key(\"httpd.stopped.success\")\n public static String HTTPD_STOPPED = \"Internal webserver stopped\";\n @Key(\"httpd.stopped.error\")\n public static String HTTPD_STOP_ERROR = \"An error occurred with the internal webserver\";\n @Key(\"httpd.disabled\")\n public static String HTTPD_DISABLED = \"Internal webserver is disabled\";\n\n @Key(\"progress.eta.unknown\")\n public static String PROGRESS_ETA_UNKNOWN = \"Unknown\";\n\n @Key(\"command.argument.optional-player\")\n public static String COMMAND_ARGUMENT_OPTIONAL_PLAYER_DESCRIPTION = \"Defaults to the executing player if unspecified (console must specify a player)\";\n @Key(\"command.argument.optional-center\")\n public static String COMMAND_ARGUMENT_OPTIONAL_CENTER_DESCRIPTION = \"Defaults to (0, 0) if unspecified\";\n @Key(\"command.argument.optional-zoom\")\n public static String COMMAND_ARGUMENT_OPTIONAL_ZOOM_DESCRIPTION = \"Map zoom level\";\n @Key(\"command.argument.required-renderer\")\n public static String COMMAND_ARGUMENT_REQUIRED_RENDERER_DESCRIPTION = \"Renderer is required\";\n @Key(\"command.argument.required-world\")\n public static String COMMAND_ARGUMENT_REQUIRED_WORLD_DESCRIPTION = \"World is required\";\n\n @Key(\"command.confirm.description\")\n public static String COMMAND_CONFIRM_DESCRIPTION = \"Confirm a pending command\";\n @Key(\"command.confirm.not-rendering\")\n public static String COMMAND_CONFIRM_CONFIRMATION_REQUIRED_MESSAGE = \"Confirmation required. Confirm using /map confirm\";\n @Key(\"command.confirm.success\")\n public static String COMMAND_CONFIRM_NO_PENDING_MESSAGE = \"You don't have any pending confirmations\";\n\n @Key(\"command.fullrender.description\")\n public static String COMMAND_FULLRENDER_DESCRIPTION = \"Fully render a world\";\n @Key(\"command.fullrender.starting\")\n public static String COMMAND_FULLRENDER_STARTING = \"Full render starting. Check /map status for more info\";\n\n @Key(\"command.help.description\")\n public static String COMMAND_HELP_DESCRIPTION = \"Get help for Pl3xmap commands\";\n @Key(\"command.help.argument.query\")\n public static String COMMAND_HELP_ARGUMENT_QUERY_DESCRIPTION = \"Help Query\";\n\n @Key(\"command.hide.description\")\n public static String COMMAND_HIDE_DESCRIPTION = \"Hide a player from the map\";\n @Key(\"command.hide.already-hidden\")\n public static String COMMAND_HIDE_ALREADY_HIDDEN = \" is already hidden from the map\";\n @Key(\"command.hide.success\")\n public static String COMMAND_HIDE_SUCCESS = \" is now hidden from the map\";\n\n @Key(\"command.pause.description\")\n public static String COMMAND_PAUSE_DESCRIPTION = \"Toggle the pause state of renderers\";\n @Key(\"command.pause.paused\")\n public static String COMMAND_PAUSE_PAUSED = \"Renderers are now paused\";\n @Key(\"command.pause.unpaused\")\n public static String COMMAND_PAUSE_UNPAUSED = \"Renderers are now unpaused\";\n\n @Key(\"command.radiusrender.description\")\n public static String COMMAND_RADIUSRENDER_DESCRIPTION = \"Render a section of a world\";\n @Key(\"command.radiusrender.starting\")\n public static String COMMAND_RADIUSRENDER_STARTING = \"Radius render starting. Check /map status for more info\";\n\n @Key(\"command.reload.description\")\n public static String COMMAND_RELOAD_DESCRIPTION = \"Reloads the plugin\";\n @Key(\"command.reload.success\")\n public static String COMMAND_RELOAD_SUCCESS = \"Pl3xMap v reloaded\";\n\n @Key(\"command.resetmap.description\")\n public static String COMMAND_RESETMAP_DESCRIPTION = \"Cancel active render of a world\";\n @Key(\"command.resetmap.begin\")\n public static String COMMAND_RESETMAP_BEGIN = \"Map reset for has begun\";\n @Key(\"command.resetmap.success\")\n public static String COMMAND_RESETMAP_SUCCESS = \"Successfully reset map for \";\n @Key(\"command.resetmap.failed\")\n public static String COMMAND_RESETMAP_FAILED = \"Could not reset map for \";\n\n @Key(\"command.show.description\")\n public static String COMMAND_SHOW_DESCRIPTION = \"Show a player on the map\";\n @Key(\"command.show.not-hidden\")\n public static String COMMAND_SHOW_NOT_HIDDEN = \" is not hidden from the map\";\n @Key(\"command.show.success\")\n public static String COMMAND_SHOW_SUCCESS = \" is no longer hidden from the map\";\n\n @Key(\"command.status.description\")\n public static String COMMAND_STATUS_DESCRIPTION = \"View the render status\";\n\n @Key(\"command.stitch.description\")\n public static String COMMAND_STITCH_DESCRIPTION = \"Stitches tiles into one image\";\n @Key(\"command.stitch.missing-directory\")\n public static String COMMAND_STITCH_MISSING_DIRECTORY = \"Unable to find tiles directory.\";\n @Key(\"command.stitch.error-reading-directory\")\n public static String COMMAND_STITCH_ERROR_READING_DIRECTORY = \"There was a problem reading the tiles directory.\";\n @Key(\"command.stitch.empty-directory\")\n public static String COMMAND_STITCH_EMPTY_DIRECTORY = \"There are no tiles to stitch.\";\n @Key(\"command.stitch.starting\")\n public static String COMMAND_STITCH_STARTING = \"Started stitching tiles..\\n(min: , max: , size: ,)\";\n @Key(\"command.stitch.finished\")\n public static String COMMAND_STITCH_FINISHED = \"Finished stitching tiles!\\nYou can find it at /tiles//stitched/\";\n\n @Key(\"command.version.description\")\n public static String COMMAND_VERSION_DESCRIPTION = \"Get version information\";\n @Key(\"command.version.please-wait\")\n public static String COMMAND_VERSION_PLEASE_WAIT = \"Checking version, please wait...\";\n @Key(\"command.version.still-checking\")\n public static String COMMAND_VERSION_STILL_CHECKING = \"Still checking...\";\n @Key(\"command.version.error.not-array\")\n public static String COMMAND_VERSION_ERROR_NOT_ARRAY = \"Error: response not an array\";\n @Key(\"command.version.error.corrupt-json\")\n public static String COMMAND_VERSION_ERROR_CORRUPT_JSON = \"Error: response is corrupt json\";\n @Key(\"command.version.error.unknown-version\")\n public static String COMMAND_VERSION_ERROR_UNKNOWN_VERSION = \"Error: response has unknown version\";\n @Key(\"command.version.error.unable-to-determine\")\n public static String COMMAND_VERSION_ERROR_UNABLE_TO_DETERMINE = \"Error: Unable to determine latest build\";\n @Key(\"command.version.success\")\n public static String COMMAND_VERSION_SUCCESS = \"Pl3xMap v3 () git-\";\n @Key(\"command.version.snapshot\")\n public static String COMMAND_VERSION_SNAPSHOT = \"You are running a snapshot\";\n @Key(\"command.version.latest-build-is\")\n public static String COMMAND_VERSION_LATEST_BUILD_IS = \"Latest build is \";\n @Key(\"command.version.running-latest-build\")\n public static String COMMAND_VERSION_RUNNING_LATEST_BUILD = \"You are running the latest build.\";\n @Key(\"command.version.builds-behind\")\n public static String COMMAND_VERSION_BUILDS_BEHIND = \"You are builds behind.\";\n @Key(\"command.version.download\")\n public static String COMMAND_VERSION_DOWNLOAD = \"Download new build at: \";\n @Key(\"command.version.time-traveler\")\n public static String COMMAND_VERSION_TIME_TRAVELER = \"Are you a time traveler?\";\n\n @Key(\"error.must-specify-player\")\n public static String ERROR_MUST_SPECIFY_PLAYER = \"You must specify the player\";\n @Key(\"error.no-such-player\")\n public static String ERROR_NO_SUCH_PLAYER = \"No such player \";\n @Key(\"error.must-specify-renderer\")\n public static String ERROR_MUST_SPECIFY_RENDERER = \"You must specify the renderer\";\n @Key(\"error.no-such-renderer\")\n public static String ERROR_NO_SUCH_RENDERER = \"No such renderer \";\n @Key(\"error.must-specify-world\")\n public static String ERROR_MUST_SPECIFY_WORLD = \"You must specify the world\";\n @Key(\"error.no-such-world\")\n public static String ERROR_NO_SUCH_WORLD = \"No such world \";\n @Key(\"error.world-disabled\")\n public static String ERROR_WORLD_DISABLED = \"Pl3xMap is disabled for world \";\n @Key(\"error.not-valid-zoom-level\")\n public static String ERROR_NOT_VALID_ZOOM_LEVEL = \"Not a valid zoom level\";\n @Key(\"error.point-invalid-format\")\n public static String ERROR_POINT_INVALID_FORMAT = \"'' is not a valid location. Required format is ' '\";\n\n @Key(\"ui.layer.players\")\n public static String UI_LAYER_PLAYERS = \"Players\";\n @Key(\"ui.layer.spawn\")\n public static String UI_LAYER_SPAWN = \"Spawn\";\n @Key(\"ui.layer.worldborder\")\n public static String UI_LAYER_WORLDBORDER = \"World Border\";\n\n @Key(\"ui.title\")\n public static String UI_TITLE = \"Pl3xMap\";\n @Key(\"ui.block-and-biome-lang-file\")\n public static String UI_BLOCK_AND_BIOME_LANG_FILE = \"en_us.json\";\n @Key(\"ui.blockinfo.label\")\n public static String UI_BLOCKINFO_LABEL = \"BlockInfo\";\n @Key(\"ui.blockinfo.value\")\n public static String UI_BLOCKINFO_VALUE = \"
\";\n @Key(\"ui.coords.label\")\n public static String UI_COORDS_LABEL = \"Coordinates\";\n @Key(\"ui.coords.value\")\n public static String UI_COORDS_VALUE = \", , \";\n @Key(\"ui.link.label\")\n public static String UI_LINK_LABEL = \"Sharable Link\";\n @Key(\"ui.link.value\")\n public static String UI_LINK_VALUE = \"\";\n @Key(\"ui.markers.label\")\n public static String UI_MARKERS_LABEL = \"Markers\";\n @Key(\"ui.markers.value\")\n public static String UI_MARKERS_VALUE = \"No markers have been configured\";\n @Key(\"ui.players.label\")\n public static String UI_PLAYERS_LABEL = \"Players (/)\";\n @Key(\"ui.players.value\")\n public static String UI_PLAYERS_VALUE = \"No players are currently online\";\n @Key(\"ui.worlds.label\")\n public static String UI_WORLDS_LABEL = \"Worlds\";\n @Key(\"ui.worlds.value\")\n public static String UI_WORLDS_VALUE = \"No worlds have been configured\";\n @Key(\"ui.layers.label\")\n public static String UI_LAYERS_LABEL = \"Layers\";\n @Key(\"ui.layers.value\")\n public static String UI_LAYERS_VALUE = \"No layers have been configured\";\n\n private static final Lang CONFIG = new Lang();\n\n public static void reload() {\n Path localeDir = Pl3xMap.api().getMainDir().resolve(\"locale\");\n\n // extract locale dir from jar\n FileUtil.extractDir(\"/locale/\", localeDir, false);\n\n CONFIG.reload(localeDir.resolve(Config.LANGUAGE_FILE), Lang.class);\n }\n\n public static @NotNull Component parse(@NotNull String msg, @NotNull TagResolver.@NotNull Single... placeholders) {\n return MiniMessage.miniMessage().deserialize(msg, placeholders);\n }\n\n public static @NotNull String strip(@NotNull String msg) {\n return MiniMessage.miniMessage().stripTags(msg);\n }\n}", "answers": [" Renderer.Builder renderer = context.get(\"renderer\");"], "length": 1889, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "313a061c-5931-4f21-a87d-4becca1380af", "reasoning": "In executeAsync, after extracting the sender and the required 'world' argument, the next logical step is to retrieve the other required arguments for the command. The command definition includes a required 'renderer' argument, so the code should get that from the context before proceeding. Therefore, the next line should obtain the renderer from the command context.", "reasoning_model_answer": "Renderer renderer = context.get(\"renderer\");", "assistant_with_reasoning": "\nIn executeAsync, after extracting the sender and the required 'world' argument, the next logical step is to retrieve the other required arguments for the command. The command definition includes a required 'renderer' argument, so the code should get that from the context before proceeding. Therefore, the next line should obtain the renderer from the command context.\n\nRenderer renderer = context.get(\"renderer\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.72, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22275, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "Renderer renderer = context.get(\"renderer\");", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.badlogic.gdx.math.Vector2;\nimport com.csse3200.game.ai.tasks.Task.Status;\nimport com.csse3200.game.areas.TestGameArea;\nimport com.csse3200.game.areas.terrain.GameMap;\nimport com.csse3200.game.areas.terrain.TerrainComponent;\nimport com.csse3200.game.areas.terrain.TerrainFactory;\nimport com.csse3200.game.components.CameraComponent;\nimport com.csse3200.game.entities.Entity;\nimport com.csse3200.game.events.listeners.EventListener1;\nimport com.csse3200.game.extensions.GameExtension;\nimport com.csse3200.game.physics.PhysicsService;\nimport com.csse3200.game.physics.components.PhysicsComponent;\nimport com.csse3200.game.physics.components.PhysicsMovementComponent;\nimport com.csse3200.game.rendering.DebugRenderer;\nimport com.csse3200.game.rendering.RenderService;\nimport com.csse3200.game.services.GameTime;\nimport com.csse3200.game.services.ResourceService;\nimport com.csse3200.game.services.ServiceLocator;\nimport com.csse3200.game.utils.DirectionUtils;\nimport com.csse3200.game.utils.math.Vector2Utils;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeAll;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport static org.junit.jupiter.api.Assertions.*;\nimport static org.mockito.ArgumentMatchers.anyLong;\nimport static org.mockito.Mockito.*;", "context": "source/core/src/test/com/csse3200/game/components/tasks/MovementTaskTest.java\npackage com.csse3200.game.components.tasks;\n\n\n\n@ExtendWith(GameExtension.class)\nclass MovementTaskTest {\n\t//TestGameArea to register so GameMap can be accessed through the ServiceLocator\n\tprivate static final TestGameArea gameArea = new TestGameArea();\n\n\t@BeforeAll\n\tstatic void setupGameAreaAndMap() {\n\t\t//necessary for allowing the Terrain factory to properly generate the map with correct tile dimensions\n\t\tResourceService resourceService = new ResourceService();\n\t\tresourceService.loadTextures(TerrainFactory.getMapTextures());\n\t\tresourceService.loadAll();\n\t\tServiceLocator.registerResourceService(resourceService);\n\n\t\t//Loads the test terrain into the GameMap\n\t\tTerrainComponent terrainComponent = mock(TerrainComponent.class);\n\t\tdoReturn(TerrainFactory.WORLD_TILE_SIZE).when(terrainComponent).getTileSize();\n\t\tGameMap gameMap = new GameMap(new TerrainFactory(new CameraComponent()));\n\t\tgameMap.setTerrainComponent(terrainComponent);\n\t\tgameMap.loadTestTerrain(\"configs/TestMaps/allDirt20x20_map.txt\");\n\n\t\t//Sets the GameMap in the TestGameArea\n\t\tgameArea.setGameMap(gameMap);\n\n\t\t//Only needed the assets for the map loading, can be unloaded\n\t\tresourceService.unloadAssets(TerrainFactory.getMapTextures());\n\t\tresourceService.dispose();\n\t}\n\n\t@BeforeEach\n\tvoid beforeEach() {\n\t\tRenderService renderService = new RenderService();\n\t\trenderService.setDebug(mock(DebugRenderer.class));\n\t\tServiceLocator.registerRenderService(renderService);\n\t\tGameTime gameTime = mock(GameTime.class);\n\t\twhen(gameTime.getDeltaTime()).thenReturn(20f / 1000);\n\t\tServiceLocator.registerTimeSource(gameTime);\n\t\tServiceLocator.registerPhysicsService(new PhysicsService());\n\t\twhen(gameTime.getTime()).thenReturn(0L);\n\t\tServiceLocator.registerGameArea(gameArea);\n\t}\n\n\t@Test\n\tvoid shouldMoveOnStart() {\n\t\tVector2 target = new Vector2(10f, 10f);\n\t\tMovementTask task = new MovementTask(target);\n\t\tEntity entity = new Entity().addComponent(new PhysicsComponent());\n\t\tPhysicsMovementComponent movementComponent = new PhysicsMovementComponent();\n\t\tentity.addComponent(movementComponent);\n\t\tentity.create();\n\n\t\ttask.create(() -> entity);\n\t\ttask.start();\n\t\tassertTrue(movementComponent.getMoving());\n\t\tassertEquals(target, movementComponent.getTarget());\n\t\tassertEquals(Status.ACTIVE, task.getStatus());\n\t}\n\n\t@Test\n\tvoid shouldStopWhenClose() {\n\t\tMovementTask task = new MovementTask(new Vector2(10f, 10f), 2f);\n\t\tEntity entity = new Entity().addComponent(new PhysicsComponent());\n\t\tPhysicsMovementComponent movementComponent = new PhysicsMovementComponent();\n\t\tentity.addComponent(movementComponent);\n\t\tentity.setPosition(5f, 5f);\n\t\tentity.create();\n\n\t\ttask.create(() -> entity);\n\t\ttask.start();\n\t\ttask.update();\n\t\tassertTrue(movementComponent.getMoving());\n\t\tassertEquals(Status.ACTIVE, task.getStatus());\n\n\t\tentity.setPosition(10f, 9f);\n\t\ttask.update();\n\t\tassertFalse(movementComponent.getMoving());\n\t\tassertEquals(Status.FINISHED, task.getStatus());\n\t}\n\n\t@Test\n\tvoid testSetSpeedChangesSpeed() {\n\t\tint framesElapsed1 = 0;\n\t\tint framesElapsed2 = 0;\n\n\t\tMovementTask task = new MovementTask(new Vector2(1f, 1f));\n\t\tEntity entity = new Entity().addComponent(new PhysicsComponent());\n\t\tPhysicsMovementComponent movementComponent = new PhysicsMovementComponent();\n\t\tentity.addComponent(movementComponent);\n\t\tentity.create();\n\t\tentity.setPosition(0f, 0f);\n\n\t\ttask.create(() -> entity);\n\t\ttask.start();\n\n\t\twhile (task.getStatus() == Status.ACTIVE) {\n\t\t\ttask.update();\n\t\t\tentity.earlyUpdate();\n\t\t\tentity.update();\n\t\t\tServiceLocator.getPhysicsService().getPhysics().update();\n\n\t\t\tframesElapsed1 += 1;\n\t\t}\n\t\tentity.setPosition(0f, 0f);\n\n\t\tMovementTask fasterTask = new MovementTask(new Vector2(1f, 1f), new Vector2(3f, 3f));\n\t\tfasterTask.create(() -> entity);\n\t\tfasterTask.start();\n\n\t\twhile (fasterTask.getStatus() == Status.ACTIVE) {\n\t\t\tfasterTask.update();\n\t\t\tentity.earlyUpdate();\n\t\t\tentity.update();\n\t\t\tServiceLocator.getPhysicsService().getPhysics().update();\n\n\t\t\tframesElapsed2 += 1;\n\t\t}\n\n\t\t// Verify that setMaxSpeed is called with the expected argument\n\t\tassertTrue(framesElapsed1 > framesElapsed2);\n\t}\n\n\t@Test\n\tvoid shouldTriggerChangeDirection() {\n\t\t// create movement task to right of entity\n\t\tMovementTask task = new MovementTask(new Vector2(10f, 10f));\n\t\tEntity entity = new Entity().addComponent(new PhysicsMovementComponent());\n\n\t\tentity.setPosition(5f, 5f);\n\t\tentity.create();\n\n\t\t// Register callbacks\n\t\tEventListener1 callback = (EventListener1) mock(EventListener1.class);\n\t\tentity.getEvents().addListener(\"directionChange\", callback);\n\n\nsource/core/src/main/com/csse3200/game/services/ServiceLocator.java\npublic class ServiceLocator {\n\tprivate static final Logger logger = LoggerFactory.getLogger(ServiceLocator.class);\n\tprivate static EntityService entityService;\n\tprivate static RenderService renderService;\n\tprivate static PhysicsService physicsService;\n\tprivate static InputService inputService;\n\tprivate static ResourceService resourceService;\n\tprivate static TimeService timeService;\n\tprivate static GameTime timeSource;\n\tprivate static GameArea gameArea;\n\tprivate static LightService lightService;\n\tprivate static GameAreaDisplay pauseMenuArea;\n\tprivate static GameAreaDisplay craftArea;\n\tprivate static GdxGame game;\n\tprivate static InventoryDisplayManager inventoryDisplayManager;\n\tprivate static CameraComponent cameraComponent;\n\tprivate static SaveLoadService saveLoadService;\n\tprivate static MissionManager missions;\n\tprivate static PlanetOxygenService planetOxygenService;\n\tprivate static SoundService soundService;\n\tprivate static UIService uiService;\n\n\tprivate static PlantCommandService plantCommandService;\n\tprivate static PlayerHungerService playerHungerService;\n\n\tprivate static PlayerMapService playerMapService;\n\n\tprivate static PlantInfoService plantInfoService;\n\tprivate static boolean cutSceneRunning; // true for running and false otherwise\n\n\tprivate static ParticleService particleService;\n\n\tpublic static PlantCommandService getPlantCommandService() {\n\t\treturn plantCommandService;\n\t}\n\n\tpublic static PlantInfoService getPlantInfoService() {\n\t\treturn plantInfoService;\n\t}\n\n\tpublic static boolean god = false;\n\n\tpublic static GameArea getGameArea() {\n\t\treturn gameArea;\n\t}\n\n\tpublic static CameraComponent getCameraComponent() {\n\t\treturn cameraComponent;\n\t}\n\n\tpublic static EntityService getEntityService() {\n\t\treturn entityService;\n\t}\n\n\tpublic static RenderService getRenderService() {\n\t\treturn renderService;\n\t}\n\n\tpublic static PhysicsService getPhysicsService() {\n\t\treturn physicsService;\n\t}\n\n\tpublic static InputService getInputService() {\n\t\treturn inputService;\n\t}\n\n\tpublic static ResourceService getResourceService() {\n\t\treturn resourceService;\n\t}\n\n\tpublic static GameTime getTimeSource() {\n\t\treturn timeSource;\n\t}\n\n\tpublic static TimeService getTimeService() {\n\t\treturn timeService;\n\t}\n\n\tpublic static LightService getLightService() {\n\t\treturn lightService;\n\t}\n\n\tpublic static MissionManager getMissionManager() {\n\t\treturn missions;\n\t}\n\n\tpublic static PlanetOxygenService getPlanetOxygenService() {\n\t\treturn planetOxygenService;\n\t}\n\n\tpublic static PlayerHungerService getPlayerHungerService() {\n\t\treturn playerHungerService;\n\t}\n\n\tpublic static PlayerMapService getPlayerMapService() {\n\t\treturn playerMapService;\n\t}\n\n\tpublic static SaveLoadService getSaveLoadService() {\n\t\treturn saveLoadService;\n\t}\n\n\tpublic static SoundService getSoundService() {\n\t\treturn soundService;\n\t}\n\n\tpublic static UIService getUIService() {\n\t\treturn uiService;\n\t}\n\n\tpublic static ParticleService getParticleService() {\n\t\treturn particleService;\n\t}\n\n\t/**\n\t * Sets the cutscene status to either running or not running.\n\t *\n\t * @param isRunning true if cutscene is running, false otherwise\n\t */\n\tpublic static void setCutSceneRunning(boolean isRunning) {\n\t\tcutSceneRunning = isRunning;\n\t}\n\n\t/**\n\t * Gets the cutscene status.\n\t *\n\t * @return true if cutscene is running, false otherwise\n\t */\n\tpublic static boolean getCutSceneStatus() {\n\t\treturn cutSceneRunning;\n\t}\n\n\tpublic static void registerGameArea(GameArea area) {\n\t\tlogger.debug(\"Registering game area {}\", area);\n\t\tgameArea = area;\n\t}\n\n\tpublic static void registerCameraComponent(CameraComponent camera) {\n\t\tlogger.debug(\"Registering game area {}\", camera);\n\t\tcameraComponent = camera;\n\t}\n\n\tpublic static void registerEntityService(EntityService service) {\n\t\tlogger.debug(\"Registering entity service {}\", service);\n\t\tentityService = service;\n\t}\n\n\tpublic static void registerRenderService(RenderService service) {\n\t\tlogger.debug(\"Registering render service {}\", service);\n\t\trenderService = service;\n\t}\n\n\tpublic static void registerPhysicsService(PhysicsService service) {\n\t\tlogger.debug(\"Registering physics service {}\", service);\n\t\tphysicsService = service;\n\t}\n\n\tpublic static void registerTimeService(TimeService service) {\n\t\tlogger.debug(\"Registering time service {}\", service);\n\t\ttimeService = service;\n\t}\n\n\tpublic static void registerInputService(InputService source) {\n\t\tlogger.debug(\"Registering input service {}\", source);\n\t\tinputService = source;\n\t}\n\n\tpublic static void registerResourceService(ResourceService source) {\n\t\tlogger.debug(\"Registering resource service {}\", source);\n\t\tresourceService = source;\n\t}\n\n\tpublic static void registerTimeSource(GameTime source) {\n\t\tlogger.debug(\"Registering time source {}\", source);\n\t\ttimeSource = source;\n\t}\n\n\tpublic static void registerMissionManager(MissionManager source) {\n\t\tlogger.debug(\"Registering mission manager {}\", source);\n\t\tmissions = source;\n\t}\n\n\tpublic static void registerUIService(UIService source) {\n\t\tlogger.debug(\"Registering UI service {}\", source);\n\t\tuiService = source;\n\t}\n\n\tpublic static void registerPlanetOxygenService(PlanetOxygenService source) {\n\t\tlogger.debug(\"Registering planet oxygen service {}\", source);\n\t\tplanetOxygenService = source;\n\t}\n\n\n\tpublic static void registerPlayerHungerService(PlayerHungerService source) {\n\t\tlogger.debug(\"Registering player hunger service {}\", source);\n\t\tplayerHungerService = source;\n\t}\n\n\tpublic static void registerPlayerMapService(PlayerMapService source) {\n\t\tlogger.debug(\"Registering player map service {}\", source);\n\t\tplayerMapService = source;\n\t}\n\n\tpublic static void registerPlantCommandService(PlantCommandService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantCommandService = source;\n\t}\n\n\tpublic static void registerPlantInfoService(PlantInfoService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantInfoService = source;\n\t}\n\n\tpublic static void registerLightService(LightService source) {\n\t\tlogger.debug(\"Registering light service {}\", source);\n\t\tlightService = source;\n\t}\n\n\tpublic static void registerInventoryDisplayManager(InventoryDisplayManager source) {\n\t\tlogger.debug(\"Registering inventory display manager {}\", source);\n\t\tinventoryDisplayManager = source;\n\t}\n\n\tpublic static void registerParticleService(ParticleService source) {\n\t\tparticleService = source;\n\t}\n\n\t/**\n\t * Registers the save/load service.\n\t *\n\t * @param source the service to register\n\t */\n\tpublic static void registerSaveLoadService(SaveLoadService source) {\n\t\tlogger.debug(\"Registering Save/Load service {}\", source);\n\t\tsaveLoadService = source;\n\t}\n\n\tpublic static void registerSoundService(SoundService source) {\n\t\tlogger.debug(\"Registering sound service {}\", source);\n\t\tsoundService = source;\n\t}\n\n\t/**\n\t * Clears all registered services.\n\t * Do not clear saveLoadService\n\t */\n\tpublic static void clear() {\n\t\tentityService = null;\n\t\trenderService = null;\n\t\tphysicsService = null;\n\t\ttimeSource = null;\n\t\tinputService = null;\n\t\tresourceService = null;\n\t\tgameArea = null;\n\t\tsoundService = null;\n\t\tlightService = null;\n\t\tparticleService = null;\n\t\ttimeService = null;\n\t\tuiService = null;\n\t}\n\n\tprivate ServiceLocator() {\n\t\tthrow new IllegalStateException(\"Instantiating static util class\");\n\t}\n\n\tpublic static void registerPauseArea(GameAreaDisplay area) {\n\t\tpauseMenuArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getPauseMenuArea() {\n\t\treturn pauseMenuArea;\n\t}\n\n\tpublic static InventoryDisplayManager getInventoryDisplayManager() {\n\t\treturn inventoryDisplayManager;\n\t}\n\n\tpublic static void registerCraftArea(GameAreaDisplay area) {\n\t\tcraftArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getCraftArea() {\n\t\treturn craftArea;\n\t}\n\n\tpublic static void registerGame(GdxGame gameVar) {\n\t\tgame = gameVar;\n\t}\n\n\tpublic static GdxGame getGame() {\n\t\treturn game;\n\t}\n\n\n}\n\nsource/core/src/test/com/csse3200/game/extensions/GameExtension.java\npublic class GameExtension implements AfterEachCallback, BeforeAllCallback {\n\tprivate Application game;\n\n\t@Override\n\tpublic void beforeAll(ExtensionContext context) {\n\t\t// 'Headless' back-end, so no rendering happens\n\t\tgame = new HeadlessApplication(new ApplicationAdapter() {\n\t\t});\n\n\t\t// Mock any calls to OpenGL\n\t\tGdx.gl20 = Mockito.mock(GL20.class);\n\t\tGdx.gl = Gdx.gl20;\n\t}\n\n\t@Override\n\tpublic void afterEach(ExtensionContext context) {\n\t\t// Clear the global state from the service locator\n\t\tServiceLocator.clear();\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/rendering/RenderService.java\npublic class RenderService implements Disposable {\n\tprivate static final int INITIAL_LAYER_CAPACITY = 4;\n\tprivate static final int INITIAL_CAPACITY = 4;\n\tprivate Stage stage;\n\tprivate DebugRenderer debugRenderer;\n\n\t/**\n\t * Map from layer to list of renderables, allows us to render each layer in the correct order\n\t */\n\tprivate final SortedIntMap> renderables =\n\t\t\tnew SortedIntMap<>(INITIAL_LAYER_CAPACITY);\n\n\t/**\n\t * Register a new renderable.\n\t *\n\t * @param renderable new renderable.\n\t */\n\tpublic void register(Renderable renderable) {\n\t\tint layerIndex = renderable.getLayer();\n\t\tif (!renderables.containsKey(layerIndex)) {\n\t\t\trenderables.put(layerIndex, new Array<>(INITIAL_CAPACITY));\n\t\t}\n\t\tArray layer = renderables.get(layerIndex);\n\t\tlayer.add(renderable);\n\t}\n\n\t/**\n\t * Unregister a renderable.\n\t *\n\t * @param renderable renderable to unregister.\n\t */\n\tpublic void unregister(Renderable renderable) {\n\t\tArray layer = renderables.get(renderable.getLayer());\n\t\tif (layer != null) {\n\t\t\tlayer.removeValue(renderable, true);\n\t\t}\n\t}\n\n\t/**\n\t * Trigger rendering on the given batch. This should be called only from the main renderer.\n\t *\n\t * @param batch batch to render to.\n\t */\n\tpublic void render(SpriteBatch batch) {\n\t\tfor (Array layer : renderables) {\n\t\t\t// Sort into rendering order\n\t\t\tlayer.sort();\n\n\t\t\tfor (Renderable renderable : layer) {\n\t\t\t\trenderable.render(batch);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setStage(Stage stage) {\n\t\tthis.stage = stage;\n\t}\n\n\tpublic Stage getStage() {\n\t\treturn stage;\n\t}\n\n\tpublic void setDebug(DebugRenderer debugRenderer) {\n\t\tthis.debugRenderer = debugRenderer;\n\t}\n\n\tpublic DebugRenderer getDebug() {\n\t\treturn debugRenderer;\n\t}\n\n\t@Override\n\tpublic void dispose() {\n\t\trenderables.clear();\n\t}\n}", "answers": ["\t\ttask.create(() -> entity);"], "length": 1472, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "8761473c-93ed-4842-9ecc-4f16b05bce53", "reasoning": "The test method shouldTriggerChangeDirection is setting up a MovementTask and an entity, then registers a listener for the \"directionChange\" event. Following the pattern used in earlier tests, the next steps are to create the task with the entity supplier and start it. The immediate next line after adding the listener is therefore the task creation call.", "reasoning_model_answer": "task.create(() -> entity);", "assistant_with_reasoning": "\nThe test method shouldTriggerChangeDirection is setting up a MovementTask and an entity, then registers a listener for the \"directionChange\" event. Following the pattern used in earlier tests, the next steps are to create the task with the entity supplier and start it. The immediate next line after adding the listener is therefore the task creation call.\n\ntask.create(() -> entity);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.386, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16354, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "task.create(() -> entity);", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.sql.SQLException;\nimport java.util.Optional;\nimport javax.annotation.PostConstruct;\nimport javax.sql.DataSource;\nimport org.flywaydb.core.Flyway;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\nimport org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;\nimport org.springframework.boot.context.properties.EnableConfigurationProperties;\nimport org.springframework.context.annotation.*;\nimport org.springframework.retry.RetryContext;\nimport org.springframework.retry.backoff.NoBackOffPolicy;\nimport org.springframework.retry.policy.SimpleRetryPolicy;\nimport org.springframework.retry.support.RetryTemplate;\nimport com.netflix.conductor.postgres.dao.PostgresExecutionDAO;\nimport com.netflix.conductor.postgres.dao.PostgresIndexDAO;\nimport com.netflix.conductor.postgres.dao.PostgresMetadataDAO;\nimport com.netflix.conductor.postgres.dao.PostgresQueueDAO;\nimport com.fasterxml.jackson.databind.ObjectMapper;", "context": "persistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/config/PostgresConfiguration.java\n/*\n *

\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *

\n * http://www.apache.org/licenses/LICENSE-2.0\n *

\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\npackage com.netflix.conductor.postgres.config;\n\n\n\n\n\n\n@Configuration(proxyBeanMethods = false)\n@EnableConfigurationProperties(PostgresProperties.class)\n@ConditionalOnProperty(name = \"conductor.db.type\", havingValue = \"postgres\")\n// Import the DataSourceAutoConfiguration when postgres database is selected.\n// By default, the datasource configuration is excluded in the main module.\n@Import(DataSourceAutoConfiguration.class)\npublic class PostgresConfiguration {\n\n DataSource dataSource;\n\n private final PostgresProperties properties;\n\n public PostgresConfiguration(DataSource dataSource, PostgresProperties properties) {\n this.dataSource = dataSource;\n this.properties = properties;\n }\n\n @Bean(initMethod = \"migrate\")\n @PostConstruct\n public Flyway flywayForPrimaryDb() {\n return Flyway.configure()\n .locations(\"classpath:db/migration_postgres\")\n .schemas(properties.getSchema())\n .dataSource(dataSource)\n .baselineOnMigrate(true)\n .load();\n }\n\n @Bean\n @DependsOn({\"flywayForPrimaryDb\"})\n public PostgresMetadataDAO postgresMetadataDAO(\n @Qualifier(\"postgresRetryTemplate\") RetryTemplate retryTemplate,\n ObjectMapper objectMapper,\n PostgresProperties properties) {\n return new PostgresMetadataDAO(retryTemplate, objectMapper, dataSource, properties);\n }\n\n @Bean\n @DependsOn({\"flywayForPrimaryDb\"})\n public PostgresExecutionDAO postgresExecutionDAO(\n @Qualifier(\"postgresRetryTemplate\") RetryTemplate retryTemplate,\n ObjectMapper objectMapper) {\n return new PostgresExecutionDAO(retryTemplate, objectMapper, dataSource);\n }\n\n @Bean\n @DependsOn({\"flywayForPrimaryDb\"})\n public PostgresQueueDAO postgresQueueDAO(\n @Qualifier(\"postgresRetryTemplate\") RetryTemplate retryTemplate,\n ObjectMapper objectMapper) {\n\npersistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/dao/PostgresQueueDAO.java\npublic class PostgresQueueDAO extends PostgresBaseDAO implements QueueDAO {\n\n private static final Long UNACK_SCHEDULE_MS = 60_000L;\n\n private final ScheduledExecutorService scheduledExecutorService;\n\n public PostgresQueueDAO(\n RetryTemplate retryTemplate, ObjectMapper objectMapper, DataSource dataSource) {\n super(retryTemplate, objectMapper, dataSource);\n\n this.scheduledExecutorService =\n Executors.newSingleThreadScheduledExecutor(\n ExecutorsUtil.newNamedThreadFactory(\"postgres-queue-\"));\n this.scheduledExecutorService.scheduleAtFixedRate(\n this::processAllUnacks,\n UNACK_SCHEDULE_MS,\n UNACK_SCHEDULE_MS,\n TimeUnit.MILLISECONDS);\n logger.debug(\"{} is ready to serve\", PostgresQueueDAO.class.getName());\n }\n\n @PreDestroy\n public void destroy() {\n try {\n this.scheduledExecutorService.shutdown();\n if (scheduledExecutorService.awaitTermination(30, TimeUnit.SECONDS)) {\n logger.debug(\"tasks completed, shutting down\");\n } else {\n logger.warn(\"Forcing shutdown after waiting for 30 seconds\");\n scheduledExecutorService.shutdownNow();\n }\n } catch (InterruptedException ie) {\n logger.warn(\n \"Shutdown interrupted, invoking shutdownNow on scheduledExecutorService for processAllUnacks\",\n ie);\n scheduledExecutorService.shutdownNow();\n Thread.currentThread().interrupt();\n }\n }\n\n @Override\n public void push(String queueName, String messageId, long offsetTimeInSecond) {\n push(queueName, messageId, 0, offsetTimeInSecond);\n }\n\n @Override\n public void push(String queueName, String messageId, int priority, long offsetTimeInSecond) {\n withTransaction(\n tx -> pushMessage(tx, queueName, messageId, null, priority, offsetTimeInSecond));\n }\n\n @Override\n public void push(String queueName, List messages) {\n withTransaction(\n tx ->\n messages.forEach(\n message ->\n pushMessage(\n tx,\n queueName,\n message.getId(),\n message.getPayload(),\n message.getPriority(),\n 0)));\n }\n\n @Override\n public boolean pushIfNotExists(String queueName, String messageId, long offsetTimeInSecond) {\n return pushIfNotExists(queueName, messageId, 0, offsetTimeInSecond);\n }\n\n @Override\n public boolean pushIfNotExists(\n String queueName, String messageId, int priority, long offsetTimeInSecond) {\n return getWithRetriedTransactions(\n tx -> {\n if (!existsMessage(tx, queueName, messageId)) {\n pushMessage(tx, queueName, messageId, null, priority, offsetTimeInSecond);\n return true;\n }\n return false;\n });\n }\n\n @Override\n public List pop(String queueName, int count, int timeout) {\n return pollMessages(queueName, count, timeout).stream()\n .map(Message::getId)\n .collect(Collectors.toList());\n }\n\n @Override\n public List pollMessages(String queueName, int count, int timeout) {\n if (timeout < 1) {\n List messages =\n getWithTransactionWithOutErrorPropagation(\n tx -> popMessages(tx, queueName, count, timeout));\n if (messages == null) {\n return new ArrayList<>();\n }\n return messages;\n }\n\n long start = System.currentTimeMillis();\n final List messages = new ArrayList<>();\n\n while (true) {\n List messagesSlice =\n getWithTransactionWithOutErrorPropagation(\n tx -> popMessages(tx, queueName, count - messages.size(), timeout));\n if (messagesSlice == null) {\n logger.warn(\n \"Unable to poll {} messages from {} due to tx conflict, only {} popped\",\n count,\n queueName,\n messages.size());\n // conflict could have happened, returned messages popped so far\n return messages;\n }\n\n messages.addAll(messagesSlice);\n if (messages.size() >= count || ((System.currentTimeMillis() - start) > timeout)) {\n return messages;\n }\n Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);\n }\n }\n\n @Override\n public void remove(String queueName, String messageId) {\n withTransaction(tx -> removeMessage(tx, queueName, messageId));\n }\n\n @Override\n public int getSize(String queueName) {\n final String GET_QUEUE_SIZE = \"SELECT COUNT(*) FROM queue_message WHERE queue_name = ?\";\n return queryWithTransaction(\n GET_QUEUE_SIZE, q -> ((Long) q.addParameter(queueName).executeCount()).intValue());\n }\n\n @Override\n public boolean ack(String queueName, String messageId) {\n return getWithRetriedTransactions(tx -> removeMessage(tx, queueName, messageId));\n }\n\n @Override\n public boolean setUnackTimeout(String queueName, String messageId, long unackTimeout) {\n long updatedOffsetTimeInSecond = unackTimeout / 1000;\n\n final String UPDATE_UNACK_TIMEOUT =\n \"UPDATE queue_message SET offset_time_seconds = ?, deliver_on = (current_timestamp + (? ||' seconds')::interval) WHERE queue_name = ? AND message_id = ?\";\n\n return queryWithTransaction(\n UPDATE_UNACK_TIMEOUT,\n q ->\n q.addParameter(updatedOffsetTimeInSecond)\n .addParameter(updatedOffsetTimeInSecond)\n .addParameter(queueName)\n .addParameter(messageId)\n .executeUpdate())\n == 1;\n }\n\n @Override\n public void flush(String queueName) {\n final String FLUSH_QUEUE = \"DELETE FROM queue_message WHERE queue_name = ?\";\n executeWithTransaction(FLUSH_QUEUE, q -> q.addParameter(queueName).executeDelete());\n }\n\n @Override\n public Map queuesDetail() {\n final String GET_QUEUES_DETAIL =\n \"SELECT queue_name, (SELECT count(*) FROM queue_message WHERE popped = false AND queue_name = q.queue_name) AS size FROM queue q FOR SHARE SKIP LOCKED\";\n return queryWithTransaction(\n GET_QUEUES_DETAIL,\n q ->\n q.executeAndFetch(\n rs -> {\n Map detail = Maps.newHashMap();\n while (rs.next()) {\n String queueName = rs.getString(\"queue_name\");\n Long size = rs.getLong(\"size\");\n detail.put(queueName, size);\n }\n return detail;\n }));\n }\n\n @Override\n public Map>> queuesDetailVerbose() {\n // @formatter:off\n final String GET_QUEUES_DETAIL_VERBOSE =\n \"SELECT queue_name, \\n\"\n + \" (SELECT count(*) FROM queue_message WHERE popped = false AND queue_name = q.queue_name) AS size,\\n\"\n + \" (SELECT count(*) FROM queue_message WHERE popped = true AND queue_name = q.queue_name) AS uacked \\n\"\n + \"FROM queue q FOR SHARE SKIP LOCKED\";\n // @formatter:on\n\n return queryWithTransaction(\n GET_QUEUES_DETAIL_VERBOSE,\n q ->\n q.executeAndFetch(\n rs -> {\n Map>> result =\n Maps.newHashMap();\n while (rs.next()) {\n String queueName = rs.getString(\"queue_name\");\n Long size = rs.getLong(\"size\");\n Long queueUnacked = rs.getLong(\"uacked\");\n result.put(\n queueName,\n ImmutableMap.of(\n \"a\",\n ImmutableMap\n .of( // sharding not implemented,\n // returning only\n // one shard with all the\n // info\n \"size\",\n size,\n \"uacked\",\n queueUnacked)));\n }\n return result;\n }));\n }\n\n /**\n * Un-pop all un-acknowledged messages for all queues.\n *\n * @since 1.11.6\n */\n public void processAllUnacks() {\n logger.trace(\"processAllUnacks started\");\n\n getWithRetriedTransactions(\n tx -> {\n String LOCK_TASKS =\n \"SELECT queue_name, message_id FROM queue_message WHERE popped = true AND (deliver_on + (60 ||' seconds')::interval) < current_timestamp limit 1000 FOR UPDATE SKIP LOCKED\";\n\n List messages =\n query(\n tx,\n LOCK_TASKS,\n p ->\n p.executeAndFetch(\n rs -> {\n List results =\n new ArrayList();\n while (rs.next()) {\n QueueMessage qm = new QueueMessage();\n qm.queueName =\n rs.getString(\"queue_name\");\n qm.messageId =\n rs.getString(\"message_id\");\n results.add(qm);\n }\n return results;\n }));\n\n if (messages.size() == 0) {\n return 0;\n }\n\n Map> queueMessageMap = new HashMap>();\n for (QueueMessage qm : messages) {\n if (!queueMessageMap.containsKey(qm.queueName)) {\n queueMessageMap.put(qm.queueName, new ArrayList());\n }\n queueMessageMap.get(qm.queueName).add(qm.messageId);\n }\n\n int totalUnacked = 0;\n for (String queueName : queueMessageMap.keySet()) {\n Integer unacked = 0;\n ;\n try {\n final List msgIds = queueMessageMap.get(queueName);\n final String UPDATE_POPPED =\n String.format(\n \"UPDATE queue_message SET popped = false WHERE queue_name = ? and message_id IN (%s)\",\n Query.generateInBindings(msgIds.size()));\n\n unacked =\n query(\n tx,\n UPDATE_POPPED,\n q ->\n q.addParameter(queueName)\n .addParameters(msgIds)\n .executeUpdate());\n } catch (Exception e) {\n e.printStackTrace();\n }\n totalUnacked += unacked;\n logger.debug(\"Unacked {} messages from all queues\", unacked);\n }\n\n if (totalUnacked > 0) {\n logger.debug(\"Unacked {} messages from all queues\", totalUnacked);\n }\n return totalUnacked;\n });\n }\n\n @Override\n public void processUnacks(String queueName) {\n final String PROCESS_UNACKS =\n \"UPDATE queue_message SET popped = false WHERE queue_name = ? AND popped = true AND (current_timestamp - (60 ||' seconds')::interval) > deliver_on\";\n executeWithTransaction(PROCESS_UNACKS, q -> q.addParameter(queueName).executeUpdate());\n }\n\n @Override\n public boolean resetOffsetTime(String queueName, String messageId) {\n long offsetTimeInSecond = 0; // Reset to 0\n final String SET_OFFSET_TIME =\n \"UPDATE queue_message SET offset_time_seconds = ?, deliver_on = (current_timestamp + (? ||' seconds')::interval) \\n\"\n + \"WHERE queue_name = ? AND message_id = ?\";\n\n return queryWithTransaction(\n SET_OFFSET_TIME,\n q ->\n q.addParameter(offsetTimeInSecond)\n .addParameter(offsetTimeInSecond)\n .addParameter(queueName)\n .addParameter(messageId)\n .executeUpdate()\n == 1);\n }\n\n private boolean existsMessage(Connection connection, String queueName, String messageId) {\n final String EXISTS_MESSAGE =\n \"SELECT EXISTS(SELECT 1 FROM queue_message WHERE queue_name = ? AND message_id = ?) FOR SHARE\";\n return query(\n connection,\n EXISTS_MESSAGE,\n q -> q.addParameter(queueName).addParameter(messageId).exists());\n }\n\n private void pushMessage(\n Connection connection,\n String queueName,\n String messageId,\n String payload,\n Integer priority,\n long offsetTimeInSecond) {\n\n createQueueIfNotExists(connection, queueName);\n\n String UPDATE_MESSAGE =\n \"UPDATE queue_message SET payload=?, deliver_on=(current_timestamp + (? ||' seconds')::interval) WHERE queue_name = ? AND message_id = ?\";\n int rowsUpdated =\n query(\n connection,\n UPDATE_MESSAGE,\n q ->\n q.addParameter(payload)\n .addParameter(offsetTimeInSecond)\n .addParameter(queueName)\n .addParameter(messageId)\n .executeUpdate());\n\n if (rowsUpdated == 0) {\n String PUSH_MESSAGE =\n \"INSERT INTO queue_message (deliver_on, queue_name, message_id, priority, offset_time_seconds, payload) VALUES ((current_timestamp + (? ||' seconds')::interval), ?,?,?,?,?) ON CONFLICT (queue_name,message_id) DO UPDATE SET payload=excluded.payload, deliver_on=excluded.deliver_on\";\n execute(\n connection,\n PUSH_MESSAGE,\n q ->\n q.addParameter(offsetTimeInSecond)\n .addParameter(queueName)\n .addParameter(messageId)\n .addParameter(priority)\n .addParameter(offsetTimeInSecond)\n .addParameter(payload)\n .executeUpdate());\n }\n }\n\n private boolean removeMessage(Connection connection, String queueName, String messageId) {\n final String REMOVE_MESSAGE =\n \"DELETE FROM queue_message WHERE queue_name = ? AND message_id = ?\";\n return query(\n connection,\n REMOVE_MESSAGE,\n q -> q.addParameter(queueName).addParameter(messageId).executeDelete());\n }\n\n private List peekMessages(Connection connection, String queueName, int count) {\n if (count < 1) {\n return Collections.emptyList();\n }\n\n final String PEEK_MESSAGES =\n \"SELECT message_id, priority, payload FROM queue_message WHERE queue_name = ? AND popped = false AND deliver_on <= (current_timestamp + (1000 ||' microseconds')::interval) ORDER BY priority DESC, deliver_on, created_on LIMIT ? FOR UPDATE SKIP LOCKED\";\n\n return query(\n connection,\n PEEK_MESSAGES,\n p ->\n p.addParameter(queueName)\n .addParameter(count)\n .executeAndFetch(\n rs -> {\n List results = new ArrayList<>();\n while (rs.next()) {\n Message m = new Message();\n m.setId(rs.getString(\"message_id\"));\n m.setPriority(rs.getInt(\"priority\"));\n m.setPayload(rs.getString(\"payload\"));\n results.add(m);\n }\n return results;\n }));\n }\n\n private List popMessages(\n Connection connection, String queueName, int count, int timeout) {\n List messages = peekMessages(connection, queueName, count);\n\n if (messages.isEmpty()) {\n return messages;\n }\n\n List poppedMessages = new ArrayList<>();\n for (Message message : messages) {\n final String POP_MESSAGE =\n \"UPDATE queue_message SET popped = true WHERE queue_name = ? AND message_id = ? AND popped = false\";\n int result =\n query(\n connection,\n POP_MESSAGE,\n q ->\n q.addParameter(queueName)\n .addParameter(message.getId())\n .executeUpdate());\n\n if (result == 1) {\n poppedMessages.add(message);\n }\n }\n return poppedMessages;\n }\n\n @Override\n public boolean containsMessage(String queueName, String messageId) {\n return getWithRetriedTransactions(tx -> existsMessage(tx, queueName, messageId));\n }\n\n private void createQueueIfNotExists(Connection connection, String queueName) {\n logger.trace(\"Creating new queue '{}'\", queueName);\n final String EXISTS_QUEUE =\n \"SELECT EXISTS(SELECT 1 FROM queue WHERE queue_name = ?) FOR SHARE\";\n boolean exists = query(connection, EXISTS_QUEUE, q -> q.addParameter(queueName).exists());\n if (!exists) {\n final String CREATE_QUEUE =\n \"INSERT INTO queue (queue_name) VALUES (?) ON CONFLICT (queue_name) DO NOTHING\";\n execute(connection, CREATE_QUEUE, q -> q.addParameter(queueName).executeUpdate());\n }\n }\n\n private class QueueMessage {\n public String queueName;\n public String messageId;\n }\n}", "answers": [" return new PostgresQueueDAO(retryTemplate, objectMapper, dataSource);"], "length": 1629, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "23ba27b2-581e-48a9-a73b-9cafb861b26f", "reasoning": "The method postgresQueueDAO is a Spring @Bean that should create and return a PostgresQueueDAO instance. Looking at the similar bean methods above, they each return a new DAO constructed with the provided retryTemplate, objectMapper, and the dataSource field of the configuration class. Therefore the next line should be the return statement constructing the PostgresQueueDAO with those arguments.", "reasoning_model_answer": "return new PostgresQueueDAO(retryTemplate, objectMapper, dataSource);", "assistant_with_reasoning": "\nThe method postgresQueueDAO is a Spring @Bean that should create and return a PostgresQueueDAO instance. Looking at the similar bean methods above, they each return a new DAO constructed with the provided retryTemplate, objectMapper, and the dataSource field of the configuration class. Therefore the next line should be the return statement constructing the PostgresQueueDAO with those arguments.\n\nreturn new PostgresQueueDAO(retryTemplate, objectMapper, dataSource);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.942, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 25210, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return new PostgresQueueDAO(retryTemplate, objectMapper, dataSource);", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.ispirer.sw.types.PictureType;\r\nimport com.ispirer.sw.types.StructureModel;\r\nimport org.apache.commons.lang3.StringUtils;\r\nimport java.math.BigDecimal;\r\nimport java.util.List;\r", "context": "IspirerFramework/com/ispirer/sw/strings/StringUtil.java\n/*\r\n\t© 2021, Ispirer Systems OÜ. All rights reserved.\r\n\tNOTICE OF LICENSE\r\n\tThis file\\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only.\r\n\tIF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! \r\n\tPLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. \r\n\tRedistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes.\r\n\tIf you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com \r\n*/\r\npackage com.ispirer.sw.strings;\r\n\r\n\r\n\r\npublic class StringUtil {\r\n\r\n\t/**\r\n\t * replases searchString to replacement in the str first time\r\n\t * \r\n\t * @param str\r\n\t * @param searchString\r\n\t * @param replacement\r\n\t * @return result of replacing\r\n\t */\r\n\tpublic static String replaceLeading(String str, String searchString, String replacement) {\r\n\t\tif (str.indexOf(searchString) == 0) {\r\n\t\t\tString newStr = \"\";\r\n\t\t\twhile (str.indexOf(searchString) == 0) {\r\n\t\t\t\tnewStr += str.substring(0, searchString.length());\r\n\t\t\t\tstr = str.substring(searchString.length(), str.length());\r\n\t\t\t}\r\n\t\t\tnewStr = newStr.replaceAll(searchString, replacement);\r\n\t\t\treturn newStr + str;\r\n\t\t}\r\n\t\treturn str;\r\n\t}\r\n\r\n\tpublic static Integer tallyingLeading(String str, String searchString) {\r\n\t\tInteger res = 0;\r\n\t\twhile (str.indexOf(searchString) == 0) {\r\n\t\t\tres++;\r\n\t\t\tstr = str.substring(searchString.length());\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\r\n\t/**\r\n\t * fills List variable by String value\r\n\t * \r\n\t * @param array to fill\r\n\t * @param str to fill by\r\n\t * @return filled list\r\n\t */\r\n\tpublic static List initializeArray(List array, String str) {\r\n\t\tObject firstel = array.get(0);\r\n\t\tint sizeOneVariable = 0;\r\n\t\tif (firstel instanceof StructureModel) {\r\n\t\t\tsizeOneVariable = ((StructureModel) firstel).getSize();\r\n\t\t} else if (firstel instanceof PictureType) {\r\n\t\t\tsizeOneVariable = ((PictureType) firstel).getSize();\r\n\t\t}\r\n\r\n\t\tif (str.length() < sizeOneVariable * array.size()) {\r\n\t\t\tstr = str + StringUtils.repeat(\" \", sizeOneVariable * array.size() - str.length());\r\n\t\t}\r\n\t\tfor (int i = 0; i < array.size(); i++) {\r\n\t\t\tif (firstel instanceof StructureModel) {\r\n\t\t\t\t((StructureModel) array.get(i))\r\n\t\t\t\t\t\t.setData(str.substring(i * sizeOneVariable, (i + 1) * sizeOneVariable).toCharArray());\r\n\t\t\t} else if (firstel instanceof PictureType) {\r\n\t\t\t\t((PictureType) array.get(i)).setValue(str.substring(i * sizeOneVariable, (i + 1) * sizeOneVariable));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn array;\r\n\t}\r\n\r\n\tpublic static List initializeArray(List array, String str, int size) {\r\n\t\tObject firstel = array.get(0);\r\n\t\tif (str.length() < size * array.size()) {\r\n\t\t\tstr = str + StringUtils.repeat(\" \", size * array.size() - str.length());\r\n\t\t}\r\n\t\tfor (int i = 0; i < array.size(); i++) {\r\n\t\t\tif (firstel instanceof String) {\r\n\t\t\t\tarray.set(i, str.substring(i * size, (i + 1) * size));\r\n\t\t\t} else if (firstel instanceof Integer) {\r\n\t\t\t\tarray.set(i, Integer.parseInt(str.substring(i * size, (i + 1) * size)));\r\n\t\t\t} else if (firstel instanceof BigDecimal) {\r\n\t\t\t\tarray.set(i, new BigDecimal(str.substring(i * size, (i + 1) * size)));\r\n\t\t\t} else if (firstel instanceof Long) {\r\n\t\t\t\tarray.set(i, Long.parseLong(str.substring(i * size, (i + 1) * size)));\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn array;\r\n\t}\r\n\r\n\t/**\r\n\t * fills array by DefaultValue\r\n\t * \r\n\t * @param array to fill\r\n\t * @param str DefaultValue object\r\n\t * @return\r\n\t */\r\n\tpublic static List initializeArray(List array, PictureType.DefaultValue str) {\r\n\t\tObject firstel = array.get(0);\r\n\t\tfor (int i = 0; i < array.size(); i++) {\r\n\t\t\tif (firstel instanceof StructureModel) {\r\n\nIspirerFramework/com/ispirer/sw/types/StructureModel.java\npublic abstract class StructureModel {\r\n\r\n\tprotected List redefobjs = new ArrayList<>();\r\n\tprotected List prevReds = new ArrayList<>();\r\n\tprotected Boolean isRed = false;\r\n\r\n\tprotected void initRedefineObjs(StructureModel... objs) {\r\n\t\tif (objs.length > 0) {\r\n\t\t\tredefobjs.addAll(Arrays.asList(objs));\r\n\t\t\tif (objs[0] != null) {\r\n\t\t\t\tobjs[0].setPrevRed(this);\r\n\t\t\t\tisRed = true;\r\n\t\t\t\tsetData(objs[0].toString().toCharArray());\r\n\t\t\t\tisRed = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void setPrevRed(StructureModel prevRed) {\r\n\t\tthis.prevReds.add(prevRed);\r\n\t}\r\n\r\n\tprotected String getArrayString(List models) {\r\n\t\tString result = \"\";\r\n\t\tfor (Object model : models) {\r\n\t\t\tresult = result.concat(model.toString());\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprotected String getArrayString(List models, Integer index) {\r\n\t\tString result = \"\";\r\n\t\tfor (int i = 0; i < index; i++) {\r\n\t\t\tresult = result.concat(models.get(i).toString());\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprotected String repeat(String par, int size) {\r\n\t\treturn StringUtils.repeat(par, size);\r\n\t}\r\n\r\n\t/**\r\n\t * creates array of strings from array of chars. it collect chars to strings\r\n\t * using length in size array\r\n\t *\r\n\t * @param data char array to collect into strings\r\n\t * @param sizes sizes of resulting strings\r\n\t * @return\r\n\t */\r\n\tpublic String[] getStringValues(char[] data, int[] sizes) {\r\n\t\tString[] result = new String[sizes.length];\r\n\t\tfor (int i = 0; i < sizes.length; i++) {\r\n\t\t\tStringBuilder tmp = new StringBuilder();\r\n\t\t\tfor (int j = 0; j < ((data.length < sizes[i]) ? data.length : sizes[i]) && data.length > 0; j++) {\r\n\t\t\t\ttmp.append(data[j]);\r\n\t\t\t}\r\n\t\t\tdata = new String(data, ((data.length < sizes[i]) ? data.length : sizes[i]),\r\n\t\t\t\t\tdata.length - ((data.length < sizes[i]) ? data.length : sizes[i])).toCharArray();\r\n\t\t\tresult[i] = sizes[i] > tmp.length() ? tmp.toString() + StringUtils.repeat(\" \", sizes[i] - tmp.length())\r\n\t\t\t\t\t: tmp.toString();\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * creates correct array of bytes Cuts useless or add usefull bytes\r\n\t *\r\n\t * @param data byte array to correct\r\n\t * @return corrected byte array\r\n\t */\r\n\tpublic byte[] getFullArray(byte[] data) {\r\n\t\tbyte[] result = new byte[getSize()];\r\n\t\tfor (int i = 0; i < result.length; i++) {\r\n\t\t\tresult[i] = data.length > i ? data[i] : 32;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * creates array from string. splits string by size\r\n\t *\r\n\t * @param data\r\n\t * @param size\r\n\t * @return array of splitted strings\r\n\t */\r\n\tpublic String[] getArrayValues(String data, int size) {\r\n\t\tString[] result = new String[size];\r\n\t\tint pieceLength = data.length() / size;\r\n\t\tint offset = 0;\r\n\t\tfor (int i = 0; i < size; i++) {\r\n\t\t\tresult[i] = data.substring(offset, pieceLength * (i + 1));\r\n\t\t\toffset += pieceLength;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprotected void redefine() {\r\n\t\t// if (prevReds != null && !prevReds.getRed()) {\r\n\t\tif (prevReds.size() > 0) {\r\n\t\t\tfor (StructureModel obj : prevReds) {\r\n\t\t\t\tif (!obj.getRed()) {\r\n\t\t\t\t\tredefine(obj);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (redefobjs.size() > 0) {\r\n\t\t\tif (redefobjs.get(0) != null) {\r\n\t\t\t\tif (!redefobjs.get(0).getRed()) {\r\n\t\t\t\t\tredefine(redefobjs.get(0));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (int i = 1; i < redefobjs.size(); i++) {\r\n\t\t\t\tif (redefobjs.get(i) != null) {\r\n\t\t\t\t\tif (!redefobjs.get(i).getRed()) {\r\n\t\t\t\t\t\tredefobjs.get(i).redefine();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void redefineDef(PictureType.DefaultValue defaultValue) {\r\n// if (prevReds != null && !prevReds.getRed()) {\r\n// redefineDef(prevReds, defaultValue);\r\n// return;\r\n// }\r\n\t\tif (prevReds.size() > 0) {\r\n\t\t\tfor (StructureModel obj : prevReds) {\r\n\t\t\t\tif (obj != null && !obj.getRed()) {\r\n\t\t\t\t\tredefineDef(obj, defaultValue);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (StructureModel obj : redefobjs) {\r\n\t\t\tredefineDef(obj, defaultValue);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid redefineDef(StructureModel obj, PictureType.DefaultValue defaultValue) {\r\n\t\tsetRed(true);\r\n\t\tobj.setDefaultValue(defaultValue);\r\n\t\tsetRed(false);\r\n\t}\r\n\r\n\tprotected void redefine(StructureModel obj) {\r\n\t\tif (obj.getRed()) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tString data = \"\";\r\n\t\tif ((obj.toString().length() >= this.toString().toCharArray().length) && !(this instanceof IntField)) {\r\n\t\t\tdata = this.toString() + obj.toString().substring(this.toString().toCharArray().length);\r\n\t\t} else {\r\n\t\t\tdata = this.toString();\r\n\t\t}\r\n\t\tif (obj instanceof StrField\r\n\t\t\t\t&& (this instanceof IntField || this instanceof LongField || this instanceof BigDecimalField)) {\r\n\t\t\tsetRed(true);\r\n\t\t\tif (this instanceof IntField) {\r\n\t\t\t\tobj.setData(((IntField) this).value);\r\n\t\t\t} else if (this instanceof LongField) {\r\n\t\t\t\tobj.setData(((LongField) this).value);\r\n\t\t\t} else {\r\n\t\t\t\tobj.setData(((BigDecimalField) this).value);\r\n\r\n\t\t\t}\r\n\t\t\tsetRed(false);\r\n\t\t} else {\r\n\t\t\tsetRed(true);\r\n\t\t\tobj.setData(data.toCharArray());\r\n\t\t\tsetRed(false);\r\n\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * set data from PT variable\r\n\t *\r\n\t * @param var PT variable\r\n\t */\r\n\tpublic void setData(PictureType var) {\r\n\t\tif (var.hasDefVal && (var.compareTo(Spaces) == 0 || var.compareTo(HighValues) == 0\r\n\t\t\t\t|| var.compareTo(LowValues) == 0 || var.compareTo(Zeroes) == 0)) {\r\n\t\t\tsetDefaultValue(var.getDefValue());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tsetData(var.toString().toCharArray());\r\n\t\tredefine();\r\n\t}\r\n\r\n\tpublic abstract String toString();\r\n\r\n\tpublic abstract void setData(char[] data);\r\n\r\n\tpublic abstract void setData(String[] data);\r\n\r\n\tpublic abstract int getSize();\r\n\r\n\tpublic abstract void initialize();\r\n\r\n\tpublic abstract byte[] toFile();\r\n\r\n\tpublic abstract void setDataFromFile(byte[] bytes);\r\n\r\n\tpublic abstract void setDefaultValue(PictureType.DefaultValue value);\r\n\r\n\t// next methods implements compareTo licics with different types\r\n\t/**\r\n\t * implements compareTo logic with DefaultValue\r\n\t *\r\n\t * @param value DefaultValue to compare\r\n\t * @return result of comparison\r\n\t */\r\n\tpublic int compareTo(PictureType.DefaultValue value) {\r\n\t\tswitch (value) {\r\n\t\tcase Spaces:\r\n\t\tcase HighValues:\r\n\t\t\treturn toString().replaceAll(\"[+-.,/ ]\", \"\").equals(\"\") ? 0 : 1;\r\n\t\tcase Zeroes:\r\n\t\t\ttry {\r\n\t\t\t\treturn new BigInteger(toString().replaceAll(\"[ +-.,]\", \"\").trim()).compareTo(new BigInteger(\"0\"));\r\n\t\t\t} catch (NumberFormatException e) {\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\r\n\t\tcase LowValues:\r\n\t\t\treturn toString().equals(\"\") ? 0 : 1;\r\n\t\tcase Quotes:\r\n\t\t\treturn toString().compareTo(StringUtils.repeat(\"\\\"\", getSize()));\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t/**\r\n\t * implements compareTo logic with PT\r\n\t *\r\n\t * @param value PT variable\r\n\t * @return result of comparison\r\n\t */\r\n\tpublic int compareTo(PictureType value) {\r\n\t\treturn value.compareTo(this) * -1;\r\n\t}\r\n\r\n\t/**\r\n\t * implements compareTo logic with other structure\r\n\t *\r\n\t * @param value structure variable\r\n\t * @return result of comparison\r\n\t */\r\n\tpublic int compareTo(StructureModel value) {\r\n\t\treturn compareTo(value.toString());\r\n\t}\r\n\r\n\t/**\r\n\t * implements compareTo logic with int variable\r\n\t *\r\n\t * @param value int variable\r\n\t * @return result of comparison\r\n\t */\r\n\tpublic int compareTo(int value) {\r\n\t\tint res = toString().trim().compareTo(String.valueOf(value));\r\n\t\tif (res > 0) {\r\n\t\t\treturn 1;\r\n\t\t} else if (res < 0) {\r\n\t\t\treturn -1;\r\n\t\t} else {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * implements compareTo logic with String variable\r\n\t *\r\n\t * @param value String variable\r\n\t * @return result of comparison\r\n\t */\r\n\tpublic int compareTo(String value) {\r\n\t\tint res = toString().trim().compareTo(value);\r\n\t\tif (res > 0) {\r\n\t\t\treturn 1;\r\n\t\t} else if (res < 0) {\r\n\t\t\treturn -1;\r\n\t\t} else {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\tprotected StructureModel[] extendArray(StructureModel[] array, StructureModel... addElements) {\r\n\t\tArrayList redList;\r\n\t\tredList = new ArrayList<>(Arrays.asList(array));\r\n\t\tif (!redList.isEmpty()) {\r\n\t\t\tredList.remove(0);\r\n\t\t}\r\n\t\tfor (StructureModel element : addElements) {\r\n\t\t\tredList.add(0, element);\r\n\t\t}\r\n\t\treturn redList.toArray(array);\r\n\t}\r\n\r\n\tprivate Boolean getRed() {\r\n\t\treturn isRed;\r\n\t}\r\n\r\n\tprivate void setRed(Boolean red) {\r\n\t\tisRed = red;\r\n\t}\r\n}\r", "answers": ["\t\t\t\t((StructureModel) array.get(i)).setDefaultValue(str);\r"], "length": 1580, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ed67de67-a386-47fd-8442-d7dfda5957dc", "reasoning": "The method initializeArray(List array, PictureType.DefaultValue str) is meant to fill a list with a default value. The code already retrieved the first element to determine the type and started a loop. The next step is handling the case where the elements are StructureModel instances, which have a setDefaultValue method that accepts a PictureType.DefaultValue. Therefore the next line should set the default value for each StructureModel element in the list.", "reasoning_model_answer": "((StructureModel) array.get(i)).setDefaultValue(str);", "assistant_with_reasoning": "\nThe method initializeArray(List array, PictureType.DefaultValue str) is meant to fill a list with a default value. The code already retrieved the first element to determine the type and started a loop. The next step is handling the case where the elements are StructureModel instances, which have a setDefaultValue method that accepts a PictureType.DefaultValue. Therefore the next line should set the default value for each StructureModel element in the list.\n\n((StructureModel) array.get(i)).setDefaultValue(str);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.173, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12770, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "((StructureModel) array.get(i)).setDefaultValue(str);", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import io.github.f4pl0.companydata.CompanyData;\nimport io.github.f4pl0.config.ConfigInjector;\nimport io.github.f4pl0.config.IEXCloudConfig;\nimport io.github.f4pl0.equitiesmarketdata.EquitiesMarketData;\nimport io.github.f4pl0.historicaldata.HistoricalData;\nimport io.github.f4pl0.reference.Reference;", "context": "src/main/java/io/github/f4pl0/IEXCloudClient.java\npackage io.github.f4pl0;\n\n\n/**\n * The IEXCloudClient is the main entry point for the IEX Cloud API.\n * You will need to set the publishable token before building the client.\n */\npublic class IEXCloudClient {\n public final EquitiesMarketData equitiesMarketData;\n private final Reference reference;\n private final CompanyData companyData;\n private final HistoricalData historicalData;\n\n /**\n * Create a new IEXCloudClient.\n * @param config\n */\n private IEXCloudClient(IEXCloudConfig config) {\n ConfigInjector.injectIEXConfiguration(IEXHttpClient.getInstance(), config);\n equitiesMarketData = new EquitiesMarketData();\n reference = new Reference();\n companyData = new CompanyData();\n historicalData = new HistoricalData();\n }\n\n public Reference fetchReferenceData() {\n return this.reference;\n }\n\n public CompanyData fetchCompanyData() {\n return this.companyData;\n }\n\n public HistoricalData fetchHistoricalData() {\n return this.historicalData;\n }\n\n /**\n * Builder for the IEXCloudClient.\n * You will need to set the publishable token before building the client.\n */\n public static class IEXCloudClientBuilder {\n private String publishableToken;\n private String secretToken;\n private String baseEndpoint = \"https://api.iex.cloud/v1\";\n\n /**\n * Set the publishable token for the IEXCloudClient.\n * @param publishableToken The IEX Cloud publishable token.\n * @return The IEXCloudClientBuilder object.\n */\n public IEXCloudClientBuilder setPublishableToken(String publishableToken) {\n this.publishableToken = publishableToken;\n return this;\n }\n\n /**\n * Set the secret token for the IEXCloudClient.\n * @param secretToken The IEX Cloud secret token.\n * @return The IEXCloudClientBuilder object.\n */\n public IEXCloudClientBuilder setSecretToken(String secretToken) {\n this.secretToken = secretToken;\n return this;\n }\n\n /**\n * Set the base endpoint for the IEXCloudClient.\n * @param baseEndpoint The IEX Cloud base endpoint.\n * @return The IEXCloudClientBuilder object.\n */\n public IEXCloudClientBuilder setBaseEndpoint(String baseEndpoint) {\n this.baseEndpoint = baseEndpoint;\n return this;\n }\n\n /**\n * Build the IEXCloudClient object.\n * @return The IEXCloudClient object.\n * @throws IllegalArgumentException If the publishable token is not set.\n */\n public IEXCloudClient build() {\n // Validate the builder\n if (publishableToken == null || publishableToken.isEmpty()) {\n throw new IllegalArgumentException(\"Publishable token must be set\");\n }\n\n IEXCloudConfig config = new IEXCloudConfig();\n config.setPublishableToken(publishableToken);\n config.setSecretToken(secretToken);\n config.setBaseEndpoint(baseEndpoint);\n\nsrc/main/java/io/github/f4pl0/historicaldata/HistoricalData.java\npublic class HistoricalData {\n private final IEXHttpClient httpClient = IEXHttpClient.getInstance();\n private final ObjectMapper mapper = new ObjectMapper();\n \n /**\n * Historical Equity Prices\n *\n *

\n * Returns daily, end of day split adjusted, dividend + split adjusted, and unadjusted equity prices since 2005\n * for the U.S. and over 100 international exchanges.\n *

\n *\n * @see IEX Cloud API\n * @param symbol The stock symbol.\n * @param range The date range.\n * @param limit The number of results to return. Defaults to 1. Ignored if range is {@link DateRange#YEAR_TO_DATE}.\n * @throws IOException If the request fails.\n * @return A list of {@link IEXHistoricalEquityPrice} objects.\n */\n public List historicalEquityPrices(\n @NonNull String symbol,\n @NonNull DateRange range,\n int limit\n ) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n String requestUri = \"/data/core/historical_prices/\" + encodedSymbol;\n\n if (range == DateRange.YEAR_TO_DATE) {\n requestUri += \"?range=\" + range.toString();\n } else if (limit < 1) {\n requestUri += \"?range=1\" + range.toString();\n } else {\n requestUri += \"?range=\" + limit + range.toString();\n }\n\n CloseableHttpResponse response = httpClient.execute(requestUri);\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXHistoricalEquityPrice.class));\n }\n\n // TODO: Add technical indicators endpoint\n}\n\nsrc/main/java/io/github/f4pl0/equitiesmarketdata/EquitiesMarketData.java\npublic class EquitiesMarketData {\n private final IEXHttpClient httpClient = IEXHttpClient.getInstance();\n private final ObjectMapper mapper = new ObjectMapper();\n\n /**\n * IEX Depth of Book (DEEP)\n *\n *

\n * DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations\n * received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not\n * indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed\n * portions of reserve orders are not represented in DEEP.\n *

\n *\n *

\n * DEEP also provides last trade price and size information. Trades resulting from either displayed or\n * non-displayed orders matching on IEX will be reported. Routed executions will not be reported.\n *

\n *\n * @see IEX Cloud API\n * @param symbol The stock symbol to get the DEEP data for.\n * @return The DEEP data for the given stock symbol.\n * @throws IOException If the request fails.\n */\n public IEXDEEP getDEEP(@NonNull String symbol) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n CloseableHttpResponse response = httpClient.execute(\"/data/core/iex_deep/\" + encodedSymbol);\n\n List data = mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXDEEP.class));\n\n return data.get(0);\n }\n\n /**\n * IEX Depth of Book (DEEP)\n *\n *

\n * DEEP is used to receive real-time depth of book quotations direct from IEX. The depth of book quotations\n * received via DEEP provide an aggregated size of resting displayed orders at a price and side, and do not\n * indicate the size or number of individual orders at any price level. Non-displayed orders and non-displayed\n * portions of reserve orders are not represented in DEEP.\n *

\n *\n *

\n * DEEP also provides last trade price and size information. Trades resulting from either displayed or\n * non-displayed orders matching on IEX will be reported. Routed executions will not be reported.\n *

\n *\n * @see IEX Cloud API\n * @param symbols The stock symbols to get the DEEP data for.\n * @return The DEEP data for the given stock symbols.\n * @throws IOException If the request fails.\n */\n public List getDEEP(@NonNull String[] symbols) throws IOException {\n List encodedSymbols = new ArrayList<>(symbols.length);\n for (String symbol : symbols) {\n encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8));\n }\n String joinedSymbols = String.join(\",\", encodedSymbols);\n CloseableHttpResponse response = httpClient.execute(\"/data/core/iex_deep/\" + joinedSymbols);\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXDEEP.class));\n }\n\n /**\n * Intraday Equity Prices\n *\n *

\n * Aggregated intraday prices in n-minute buckets for the current day, where n is 10 minutes or 30 minutes,\n * depending on the range you specify.\n *

\n *\n * @see IEX Cloud API\n * @param symbol The stock symbol to get the intraday prices for.\n * @return The intraday prices for the given stock symbol.\n * @throws IOException If the request fails.\n */\n public List getIntradayPrices(@NonNull String symbol) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n CloseableHttpResponse response = httpClient.execute(\"/data/core/intraday-prices/\" + encodedSymbol);\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXIntradayEquityPrice.class));\n }\n // TODO: Add intraday prices for multiple symbols. and support for the range parameter.\n // TODO: Finish the rest of the endpoints.\n\n\n}\n\nsrc/main/java/io/github/f4pl0/config/ConfigInjector.java\npublic class ConfigInjector {\n\n @SneakyThrows(IllegalAccessException.class)\n public static void injectIEXConfiguration(Object instance, IEXCloudConfig config) {\n Class clazz = instance.getClass();\n\n for (Field field : clazz.getDeclaredFields()) {\n if (field.isAnnotationPresent(IEXConfiguration.class)) {\n field.setAccessible(true);\n field.set(instance, config);\n }\n }\n }\n}\n\nsrc/main/java/io/github/f4pl0/config/IEXCloudConfig.java\n@Data\npublic class IEXCloudConfig {\n private String publishableToken;\n private String secretToken;\n private String baseEndpoint;\n}\n\nsrc/main/java/io/github/f4pl0/companydata/CompanyData.java\npublic class CompanyData {\n private final IEXHttpClient httpClient = IEXHttpClient.getInstance();\n private final ObjectMapper mapper = new ObjectMapper();\n\n /**\n * Company Information\n *\n *

Latest snapshot of public company information such as address, number of employees, CEO, and description.

\n *\n * @see IEX Cloud API\n * @param symbol Company symbol.\n * @throws IOException If the request fails.\n * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyData} object.\n */\n public IEXCompanyData companyData(@NonNull String symbol) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n CloseableHttpResponse response = httpClient.execute(\"/data/core/company/\" + encodedSymbol);\n\n List data = mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class));\n\n return data.get(0);\n }\n\n /**\n * Company Information\n *\n *

Latest snapshot of public company information such as address, number of employees, CEO, and description.

\n *\n * @see IEX Cloud API\n * @param symbols Company symbols.\n * @throws IOException If the request fails.\n * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects.\n */\n public List companyData(@NonNull String[] symbols) throws IOException {\n List encodedSymbols = new ArrayList<>(symbols.length);\n for (String symbol : symbols) {\n encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8));\n }\n String joinedSymbols = String.join(\",\", encodedSymbols);\n CloseableHttpResponse response = httpClient.execute(\"/data/core/company/\" + joinedSymbols);\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class));\n }\n\n /**\n * Historical Company Snapshots\n *\n *

Historical daily snapshot of public company information such as address, number of employees, CEO, and description.

\n *\n * @see IEX Cloud API\n * @param symbol Company symbol.\n * @throws IOException If the request fails.\n * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects.\n */\n public List companyDataSnapshots(@NonNull String symbol) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n CloseableHttpResponse response = httpClient.execute(\"/data/core/company_historical/\" + encodedSymbol);\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class));\n }\n\n /**\n * Historical Company Snapshots\n *\n *

Historical daily snapshot of public company information such as address, number of employees, CEO, and description.

\n *\n * @see IEX Cloud API\n * @param symbol Company symbol.\n * @param last Number of records to return.\n * @throws IOException If the request fails.\n * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects.\n */\n public List companyDataSnapshots(@NonNull String symbol, int last) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n CloseableHttpResponse response = httpClient.execute(\n \"/data/core/company_historical/\" + encodedSymbol + \"?last=\" + last\n );\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class));\n }\n\n /**\n * Historical Company Snapshots\n *\n *

Historical daily snapshot of public company information such as address, number of employees, CEO, and description.

\n *\n * @see IEX Cloud API\n * @param symbols Company symbols.\n * @throws IOException If the request fails.\n * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects.\n */\n public List companyDataSnapshots(@NonNull String[] symbols) throws IOException {\n List encodedSymbols = new ArrayList<>(symbols.length);\n for (String symbol : symbols) {\n encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8));\n }\n String joinedSymbols = String.join(\",\", encodedSymbols);\n CloseableHttpResponse response = httpClient.execute(\"/data/core/company_historical/\" + joinedSymbols);\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class));\n }\n\n /**\n * Historical Company Snapshots\n *\n *

Historical daily snapshot of public company information such as address, number of employees, CEO, and description.

\n *\n * @see IEX Cloud API\n * @param symbols Company symbols.\n * @param last Number of records to return.\n * @throws IOException If the request fails.\n * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects.\n */\n public List companyDataSnapshots(@NonNull String[] symbols, int last) throws IOException {\n List encodedSymbols = new ArrayList<>(symbols.length);\n for (String symbol : symbols) {\n encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8));\n }\n String joinedSymbols = String.join(\",\", encodedSymbols);\n CloseableHttpResponse response = httpClient.execute(\n \"/data/core/company_historical/\" + joinedSymbols + \"?last=\" + last\n );\n\n return mapper.readValue(\n EntityUtils.toString(response.getEntity()),\n mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class));\n }\n\n /**\n * CEO Compensation\n *\n *

Returns the latest compensation information for the CEO of the company matching the symbol.

\n *\n * @see IEX Cloud API\n * @param symbol Company symbol.\n * @throws IOException If the request fails.\n * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyCeoCompensation} object.\n */\n public IEXCompanyCeoCompensation companyCeoCompensation(@NonNull String symbol) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n CloseableHttpResponse response = httpClient.execute(\"/stock/\" + encodedSymbol + \"/ceo-compensation\");\n\n return mapper.readValue(EntityUtils.toString(response.getEntity()), IEXCompanyCeoCompensation.class);\n }\n\n /**\n * Company Logo\n *\n *

Returns a logo (if available) for the company.

\n *\n * @see IEX Cloud API\n * @param symbol Company symbol.\n * @throws IOException If the request fails.\n * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyLogo} object.\n */\n public IEXCompanyLogo companyLogo(@NonNull String symbol) throws IOException {\n String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8);\n CloseableHttpResponse response = httpClient.execute(\"/stock/\" + encodedSymbol + \"/logo\");\n\n return mapper.readValue(EntityUtils.toString(response.getEntity()), IEXCompanyLogo.class);\n }\n}", "answers": [" return new IEXCloudClient(config);"], "length": 1738, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "696f6120-2ee4-49a6-b3a2-84e4c50be995", "reasoning": "In IEXCloudClientBuilder.build(), after validating the token and populating an IEXCloudConfig object, the builder must create and return an IEXCloudClient instance using that config. The next logical line is the return statement that constructs the client with the config.", "reasoning_model_answer": "return new IEXCloudClient(config);", "assistant_with_reasoning": "\nIn IEXCloudClientBuilder.build(), after validating the token and populating an IEXCloudConfig object, the builder must create and return an IEXCloudClient instance using that config. The next logical line is the return statement that constructs the client with the config.\n\nreturn new IEXCloudClient(config);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.884, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19191, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return new IEXCloudClient(config);", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport java.util.List;\nimport javax.servlet.http.HttpServletResponse;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.validation.annotation.Validated;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PutMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\nimport com.metax.common.core.utils.StringUtils;\nimport com.metax.common.core.utils.poi.ExcelUtil;\nimport com.metax.common.core.web.controller.BaseController;\nimport com.metax.common.core.web.domain.AjaxResult;\nimport com.metax.common.core.web.page.TableDataInfo;\nimport com.metax.common.log.annotation.Log;\nimport com.metax.common.log.enums.BusinessType;\nimport com.metax.common.security.annotation.RequiresPermissions;\nimport com.metax.common.security.utils.SecurityUtils;\nimport com.metax.system.api.domain.SysDictData;\nimport com.metax.system.service.ISysDictDataService;\nimport com.metax.system.service.ISysDictTypeService;", "context": "metax-modules/metax-system/src/main/java/com/metax/system/controller/SysDictDataController.java\npackage com.metax.system.controller;\n\n\n/**\n * 数据字典信息\n * \n * @author ruoyi\n */\n@RestController\n@RequestMapping(\"/dict/data\")\npublic class SysDictDataController extends BaseController\n{\n @Autowired\n private ISysDictDataService dictDataService;\n \n @Autowired\n private ISysDictTypeService dictTypeService;\n\n @RequiresPermissions(\"system:dict:list\")\n @GetMapping(\"/list\")\n public TableDataInfo list(SysDictData dictData)\n {\n startPage();\n List list = dictDataService.selectDictDataList(dictData);\n return getDataTable(list);\n }\n\n @Log(title = \"字典数据\", businessType = BusinessType.EXPORT)\n @RequiresPermissions(\"system:dict:export\")\n @PostMapping(\"/export\")\n public void export(HttpServletResponse response, SysDictData dictData)\n {\n List list = dictDataService.selectDictDataList(dictData);\n ExcelUtil util = new ExcelUtil(SysDictData.class);\n util.exportExcel(response, list, \"字典数据\");\n }\n\n /**\n * 查询字典数据详细\n */\n @RequiresPermissions(\"system:dict:query\")\n @GetMapping(value = \"/{dictCode}\")\n public AjaxResult getInfo(@PathVariable Long dictCode)\n {\n return success(dictDataService.selectDictDataById(dictCode));\n }\n\n /**\n * 根据字典类型查询字典数据信息\n */\n @GetMapping(value = \"/type/{dictType}\")\n public AjaxResult dictType(@PathVariable String dictType)\n {\n List data = dictTypeService.selectDictDataByType(dictType);\n if (StringUtils.isNull(data))\n {\n data = new ArrayList();\n }\n return success(data);\n }\n\n /**\n * 新增字典类型\n */\n @RequiresPermissions(\"system:dict:add\")\n @Log(title = \"字典数据\", businessType = BusinessType.INSERT)\n @PostMapping\n public AjaxResult add(@Validated @RequestBody SysDictData dict)\n {\n dict.setCreateBy(SecurityUtils.getUsername());\n\nmetax-common/metax-common-security/src/main/java/com/metax/common/security/utils/SecurityUtils.java\npublic class SecurityUtils\n{\n /**\n * 获取用户ID\n */\n public static Long getUserId()\n {\n return SecurityContextHolder.getUserId();\n }\n\n /**\n * 获取用户名称\n */\n public static String getUsername()\n {\n return SecurityContextHolder.getUserName();\n }\n\n /**\n * 获取用户key\n */\n public static String getUserKey()\n {\n return SecurityContextHolder.getUserKey();\n }\n\n /**\n * 获取登录用户信息\n */\n public static LoginUser getLoginUser()\n {\n return SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUser.class);\n }\n\n /**\n * 获取请求token\n */\n public static String getToken()\n {\n return getToken(ServletUtils.getRequest());\n }\n\n /**\n * 根据request获取请求token\n */\n public static String getToken(HttpServletRequest request)\n {\n // 从header获取token标识\n String token = request.getHeader(TokenConstants.AUTHENTICATION);\n return replaceTokenPrefix(token);\n }\n\n /**\n * 裁剪token前缀\n */\n public static String replaceTokenPrefix(String token)\n {\n // 如果前端设置了令牌前缀,则裁剪掉前缀\n if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))\n {\n token = token.replaceFirst(TokenConstants.PREFIX, \"\");\n }\n return token;\n }\n\n /**\n * 是否为管理员\n * \n * @param userId 用户ID\n * @return 结果\n */\n public static boolean isAdmin(Long userId)\n {\n return userId != null && 1L == userId;\n }\n\n /**\n * 生成BCryptPasswordEncoder密码\n *\n * @param password 密码\n * @return 加密字符串\n */\n public static String encryptPassword(String password)\n {\n BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();\n return passwordEncoder.encode(password);\n }\n\n /**\n * 判断密码是否相同\n *\n * @param rawPassword 真实密码\n * @param encodedPassword 加密后字符\n * @return 结果\n */\n public static boolean matchesPassword(String rawPassword, String encodedPassword)\n {\n BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();\n return passwordEncoder.matches(rawPassword, encodedPassword);\n }\n}\n\nmetax-api/metax-api-system/src/main/java/com/metax/system/api/domain/SysDictData.java\npublic class SysDictData extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 字典编码 */\n @Excel(name = \"字典编码\", cellType = ColumnType.NUMERIC)\n private Long dictCode;\n\n /** 字典排序 */\n @Excel(name = \"字典排序\", cellType = ColumnType.NUMERIC)\n private Long dictSort;\n\n /** 字典标签 */\n @Excel(name = \"字典标签\")\n private String dictLabel;\n\n /** 字典键值 */\n @Excel(name = \"字典键值\")\n private String dictValue;\n\n /** 字典类型 */\n @Excel(name = \"字典类型\")\n private String dictType;\n\n /** 样式属性(其他样式扩展) */\n private String cssClass;\n\n /** 表格字典样式 */\n private String listClass;\n\n /** 是否默认(Y是 N否) */\n @Excel(name = \"是否默认\", readConverterExp = \"Y=是,N=否\")\n private String isDefault;\n\n /** 状态(0正常 1停用) */\n @Excel(name = \"状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n public Long getDictCode()\n {\n return dictCode;\n }\n\n public void setDictCode(Long dictCode)\n {\n this.dictCode = dictCode;\n }\n\n public Long getDictSort()\n {\n return dictSort;\n }\n\n public void setDictSort(Long dictSort)\n {\n this.dictSort = dictSort;\n }\n\n @NotBlank(message = \"字典标签不能为空\")\n @Size(min = 0, max = 100, message = \"字典标签长度不能超过100个字符\")\n public String getDictLabel()\n {\n return dictLabel;\n }\n\n public void setDictLabel(String dictLabel)\n {\n this.dictLabel = dictLabel;\n }\n\n @NotBlank(message = \"字典键值不能为空\")\n @Size(min = 0, max = 100, message = \"字典键值长度不能超过100个字符\")\n public String getDictValue()\n {\n return dictValue;\n }\n\n public void setDictValue(String dictValue)\n {\n this.dictValue = dictValue;\n }\n\n @NotBlank(message = \"字典类型不能为空\")\n @Size(min = 0, max = 100, message = \"字典类型长度不能超过100个字符\")\n public String getDictType()\n {\n return dictType;\n }\n\n public void setDictType(String dictType)\n {\n this.dictType = dictType;\n }\n\n @Size(min = 0, max = 100, message = \"样式属性长度不能超过100个字符\")\n public String getCssClass()\n {\n return cssClass;\n }\n\n public void setCssClass(String cssClass)\n {\n this.cssClass = cssClass;\n }\n\n public String getListClass()\n {\n return listClass;\n }\n\n public void setListClass(String listClass)\n {\n this.listClass = listClass;\n }\n\n public boolean getDefault()\n {\n return UserConstants.YES.equals(this.isDefault);\n }\n\n public String getIsDefault()\n {\n return isDefault;\n }\n\n public void setIsDefault(String isDefault)\n {\n this.isDefault = isDefault;\n }\n\n public String getStatus()\n {\n return status;\n }\n\n public void setStatus(String status)\n {\n this.status = status;\n }\n \n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"dictCode\", getDictCode())\n .append(\"dictSort\", getDictSort())\n .append(\"dictLabel\", getDictLabel())\n .append(\"dictValue\", getDictValue())\n .append(\"dictType\", getDictType())\n .append(\"cssClass\", getCssClass())\n .append(\"listClass\", getListClass())\n .append(\"isDefault\", getIsDefault())\n .append(\"status\", getStatus())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .toString();\n }\n}\n\nmetax-common/metax-common-log/src/main/java/com/metax/common/log/enums/BusinessType.java\npublic enum BusinessType\n{\n /**\n * 其它\n */\n OTHER,\n\n /**\n * 新增\n */\n INSERT,\n\n /**\n * 修改\n */\n UPDATE,\n\n /**\n * 删除\n */\n DELETE,\n\n /**\n * 授权\n */\n GRANT,\n\n /**\n * 导出\n */\n EXPORT,\n\n /**\n * 导入\n */\n IMPORT,\n\n /**\n * 强退\n */\n FORCE,\n\n /**\n * 生成代码\n */\n GENCODE,\n\n /**\n * 清空数据\n */\n CLEAN,\n\n /**\n * 发送\n */\n SEND,\n\n /**\n * 启动\n */\n START,\n\n /**\n * 停止\n */\n STOP,\n}\n\nmetax-common/metax-common-core/src/main/java/com/metax/common/core/web/page/TableDataInfo.java\npublic class TableDataInfo implements Serializable\n{\n private static final long serialVersionUID = 1L;\n\n /** 总记录数 */\n private long total;\n\n /** 列表数据 */\n private List rows;\n\n /** 消息状态码 */\n private int code;\n\n /** 消息内容 */\n private String msg;\n\n /**\n * 表格数据对象\n */\n public TableDataInfo()\n {\n }\n\n /**\n * 分页\n * \n * @param list 列表数据\n * @param total 总记录数\n */\n public TableDataInfo(List list, int total)\n {\n this.rows = list;\n this.total = total;\n }\n\n public long getTotal()\n {\n return total;\n }\n\n public void setTotal(long total)\n {\n this.total = total;\n }\n\n public List getRows()\n {\n return rows;\n }\n\n public void setRows(List rows)\n {\n this.rows = rows;\n }\n\n public int getCode()\n {\n return code;\n }\n\n public void setCode(int code)\n {\n this.code = code;\n }\n\n public String getMsg()\n {\n return msg;\n }\n\n public void setMsg(String msg)\n {\n this.msg = msg;\n }\n}\n\nmetax-common/metax-common-core/src/main/java/com/metax/common/core/web/controller/BaseController.java\npublic class BaseController\n{\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @InitBinder\n public void initBinder(WebDataBinder binder)\n {\n // Date 类型转换\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport()\n {\n @Override\n public void setAsText(String text)\n {\n setValue(DateUtils.parseDate(text));\n }\n });\n }\n\n /**\n * 设置请求分页数据\n */\n protected void startPage()\n {\n PageUtils.startPage();\n }\n\n /**\n * 清理分页的线程变量\n */\n protected void clearPage()\n {\n PageUtils.clearPage();\n }\n\n /**\n * 响应请求分页数据\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n protected TableDataInfo getDataTable(List list)\n {\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(HttpStatus.SUCCESS);\n rspData.setRows(list);\n rspData.setMsg(\"查询成功\");\n rspData.setTotal(new PageInfo(list).getTotal());\n return rspData;\n }\n\n /**\n * 返回成功\n */\n public AjaxResult success()\n {\n return AjaxResult.success();\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(String message)\n {\n return AjaxResult.success(message);\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(Object data)\n {\n return AjaxResult.success(data);\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error()\n {\n return AjaxResult.error();\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error(String message)\n {\n return AjaxResult.error(message);\n }\n\n /**\n * 返回警告消息\n */\n public AjaxResult warn(String message)\n {\n return AjaxResult.warn(message);\n }\n\n /**\n * 响应返回结果\n * \n * @param rows 影响行数\n * @return 操作结果\n */\n protected AjaxResult toAjax(int rows)\n {\n return rows > 0 ? AjaxResult.success() : AjaxResult.error();\n }\n\n /**\n * 响应返回结果\n * \n * @param result 结果\n * @return 操作结果\n */\n protected AjaxResult toAjax(boolean result)\n {\n return result ? success() : error();\n }\n}\n\nmetax-common/metax-common-core/src/main/java/com/metax/common/core/web/domain/AjaxResult.java\npublic class AjaxResult extends HashMap\n{\n private static final long serialVersionUID = 1L;\n\n /** 状态码 */\n public static final String CODE_TAG = \"code\";\n\n /** 返回内容 */\n public static final String MSG_TAG = \"msg\";\n\n /** 数据对象 */\n public static final String DATA_TAG = \"data\";\n\n /**\n * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。\n */\n public AjaxResult()\n {\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n * \n * @param code 状态码\n * @param msg 返回内容\n */\n public AjaxResult(int code, String msg)\n {\n super.put(CODE_TAG, code);\n super.put(MSG_TAG, msg);\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n * \n * @param code 状态码\n * @param msg 返回内容\n * @param data 数据对象\n */\n public AjaxResult(int code, String msg, Object data)\n {\n super.put(CODE_TAG, code);\n super.put(MSG_TAG, msg);\n if (StringUtils.isNotNull(data))\n {\n super.put(DATA_TAG, data);\n }\n }\n\n /**\n * 返回成功消息\n * \n * @return 成功消息\n */\n public static AjaxResult success()\n {\n return AjaxResult.success(\"操作成功\");\n }\n\n /**\n * 返回成功数据\n * \n * @return 成功消息\n */\n public static AjaxResult success(Object data)\n {\n return AjaxResult.success(\"操作成功\", data);\n }\n\n /**\n * 返回成功消息\n * \n * @param msg 返回内容\n * @return 成功消息\n */\n public static AjaxResult success(String msg)\n {\n return AjaxResult.success(msg, null);\n }\n\n /**\n * 返回成功消息\n * \n * @param msg 返回内容\n * @param data 数据对象\n * @return 成功消息\n */\n public static AjaxResult success(String msg, Object data)\n {\n return new AjaxResult(HttpStatus.SUCCESS, msg, data);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static AjaxResult warn(String msg)\n {\n return AjaxResult.warn(msg, null);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static AjaxResult warn(String msg, Object data)\n {\n return new AjaxResult(HttpStatus.WARN, msg, data);\n }\n\n /**\n * 返回错误消息\n * \n * @return 错误消息\n */\n public static AjaxResult error()\n {\n return AjaxResult.error(\"操作失败\");\n }\n\n /**\n * 返回错误消息\n * \n * @param msg 返回内容\n * @return 错误消息\n */\n public static AjaxResult error(String msg)\n {\n return AjaxResult.error(msg, null);\n }\n\n /**\n * 返回错误消息\n * \n * @param msg 返回内容\n * @param data 数据对象\n * @return 错误消息\n */\n public static AjaxResult error(String msg, Object data)\n {\n return new AjaxResult(HttpStatus.ERROR, msg, data);\n }\n\n /**\n * 返回错误消息\n * \n * @param code 状态码\n * @param msg 返回内容\n * @return 错误消息\n */\n public static AjaxResult error(int code, String msg)\n {\n return new AjaxResult(code, msg, null);\n }\n\n /**\n * 是否为成功消息\n *\n * @return 结果\n */\n public boolean isSuccess()\n {\n return Objects.equals(HttpStatus.SUCCESS, this.get(CODE_TAG));\n }\n\n /**\n * 是否为警告消息\n *\n * @return 结果\n */\n public boolean isWarn()\n {\n return Objects.equals(HttpStatus.WARN, this.get(CODE_TAG));\n }\n\n /**\n * 是否为错误消息\n *\n * @return 结果\n */\n public boolean isError()\n {\n return Objects.equals(HttpStatus.ERROR, this.get(CODE_TAG));\n }\n\n /**\n * 方便链式调用\n *\n * @param key\n * @param value\n * @return\n */\n @Override\n public AjaxResult put(String key, Object value)\n {\n super.put(key, value);\n return this;\n }\n}", "answers": [" return toAjax(dictDataService.insertDictData(dict));"], "length": 1567, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "f26f3bce-8244-4bce-a589-6eb20b987f3f", "reasoning": "The add method sets the creator and then should call the service to insert the dictionary data and return the result wrapped via toAjax. In the RuoYi style, the next line is the return statement invoking dictDataService.insertDictData(dict).", "reasoning_model_answer": "return toAjax(dictDataService.insertDictData(dict));", "assistant_with_reasoning": "\nThe add method sets the creator and then should call the service to insert the dictionary data and return the result wrapped via toAjax. In the RuoYi style, the next line is the return statement invoking dictDataService.insertDictData(dict).\n\nreturn toAjax(dictDataService.insertDictData(dict));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.186, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17341, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return toAjax(dictDataService.insertDictData(dict));", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.File;\nimport java.util.Iterator;\nimport org.apache.logging.log4j.Level;\nimport enviromine.core.EM_ConfigHandler;\nimport enviromine.core.EM_ConfigHandler.EnumLogVerbosity;\nimport enviromine.core.EM_Settings;\nimport enviromine.core.EnviroMine;\nimport enviromine.handlers.ObjectHandler;\nimport enviromine.trackers.properties.helpers.PropertyBase;\nimport enviromine.trackers.properties.helpers.SerialisableProperty;\nimport enviromine.utils.EnviroUtils;\nimport net.minecraft.init.Items;\nimport net.minecraft.item.Item;\nimport net.minecraft.item.ItemFood;\nimport net.minecraft.nbt.NBTTagCompound;\nimport net.minecraftforge.common.config.Configuration;", "context": "src/main/java/enviromine/trackers/properties/RotProperties.java\npackage enviromine.trackers.properties;\n\n\n\n\npublic class RotProperties implements SerialisableProperty, PropertyBase\n{\n\tpublic static final RotProperties base = new RotProperties();\n\tstatic String[] RPName;\n\t\n\tpublic String name;\n\tpublic int meta;\n\tpublic String rotID;\n\tpublic int rotMeta;\n\tpublic int days;\n\tpublic String loadedFrom;\n\t\n\tpublic RotProperties(NBTTagCompound tags)\n\t{\n\t\tthis.ReadFromNBT(tags);\n\t}\n\t\n\tpublic RotProperties()\n\t{\n\t\t// THIS CONSTRUCTOR IS FOR STATIC PURPOSES ONLY!\n\t\t\n\t\tif(base != null && base != this)\n\t\t{\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\t\n\tpublic RotProperties(String name, int meta, String rotID, int rotMeta, int days, String fileName)\n\t{\n\t\tthis.name = name;\n\t\tthis.meta = meta;\n\t\tthis.rotID = rotID;\n\t\tthis.rotMeta = rotMeta;\n\t\tthis.days = days;\n\t\tthis.loadedFrom = fileName;\n\t}\n\n\t@Override\n\tpublic NBTTagCompound WriteToNBT()\n\t{\n\t\tNBTTagCompound tags = new NBTTagCompound();\n\t\ttags.setString(\"name\", this.name);\n\t\ttags.setInteger(\"meta\", this.meta);\n\t\ttags.setString(\"rotID\", this.rotID);\n\t\ttags.setInteger(\"rotMeta\", this.rotMeta);\n\t\ttags.setInteger(\"days\", this.days);\n\t\treturn tags;\n\t}\n\n\t@Override\n\tpublic void ReadFromNBT(NBTTagCompound tags)\n\t{\n\t\tthis.name = tags.getString(\"name\");\n\t\tthis.meta = tags.getInteger(\"meta\");\n\t\tthis.rotID = tags.getString(\"rotID\");\n\t\tthis.rotMeta = tags.getInteger(\"rotMeta\");\n\t\tthis.days = tags.getInteger(\"days\");\n\t}\n\n\t@Override\n\tpublic String categoryName()\n\t{\n\t\treturn \"spoiling\";\n\t}\n\n\t@Override\n\tpublic String categoryDescription()\n\t{\n\t\treturn \"Set the properties of spoliable items\";\n\t}\n\n\t@Override\n\tpublic void LoadProperty(Configuration config, String category)\n\t{\n\t\tconfig.addCustomCategoryComment(this.categoryName(), this.categoryDescription());\n\t\tString name = config.get(category, RPName[0], \"\").getString();\n\t\tint meta = config.get(category, RPName[1], -1).getInt(-1);\n\t\tString rotID = config.get(category, RPName[2], \"\", \"Set blank to rot into nothing\").getString();\n\t\tint rotMeta = config.get(category, RPName[3], 0).getInt(0);\n\t\tint DTR = config.get(category, RPName[4], 0, \"Set this to -1 to disable rotting on this item\").getInt(0);\n\t\tString filename = config.getConfigFile().getName();\n\t\t\n\t\tRotProperties entry = new RotProperties(name, meta, rotID, rotMeta, DTR, filename);\n\t\t\n\t\tif(meta < 0)\n\t\t{\n\t\t\t// If item already exist and current file hasn't completely been loaded do this\n\t\t\tif(EM_Settings.rotProperties.containsKey(\"\" + name) && !EM_ConfigHandler.loadedConfigs.contains(filename))\n\t\t\t{\n\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, \"CONFIG DUPLICATE: Spoiling/Rot -\"+ name.toUpperCase() +\" was already added from \"+ EM_Settings.rotProperties.get(name).loadedFrom.toUpperCase() +\" and will be overriden by \"+ filename.toUpperCase());\n\t\t\t}\n\t\t\t\n\t\t\tEM_Settings.rotProperties.put(\"\" + name, entry);\n\t\t} else\n\t\t{\n\t\t\t// If item already exist and current file hasn't completely been loaded do this\n\nsrc/main/java/enviromine/core/EnviroMine.java\n@Mod(modid = EM_Settings.MOD_ID, name = EM_Settings.MOD_NAME, version = EM_Settings.VERSION, guiFactory = EM_Settings.GUI_FACTORY)\npublic class EnviroMine\n{\n\tpublic static Logger logger;\n\tpublic static BiomeGenCaves caves;\n\tpublic static EnviroTab enviroTab;\n\n\t@Instance(EM_Settings.MOD_ID)\n\tpublic static EnviroMine instance;\n\n\t@SidedProxy(clientSide = EM_Settings.Proxy + \".EM_ClientProxy\", serverSide = EM_Settings.Proxy + \".EM_CommonProxy\")\n\tpublic static EM_CommonProxy proxy;\n\n\tpublic SimpleNetworkWrapper network;\n\n\t//public static EM_WorldData theWorldEM;\n\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent event)\n\t{\n\t\t// The following overrides the mcmod.info file!\n\t\t// Adapted from Jabelar's Magic Beans:\n\t\t// https://github.com/jabelar/MagicBeans-1.7.10/blob/e48456397f9c6c27efce18e6b9ad34407e6bc7c7/src/main/java/com/blogspot/jabelarminecraft/magicbeans/MagicBeans.java\n event.getModMetadata().autogenerated = false ; // stops it from complaining about missing mcmod.info\n\n event.getModMetadata().name = \t\t\t// name\n \t\tEnumChatFormatting.AQUA +\n \t\tEM_Settings.MOD_NAME;\n\n event.getModMetadata().version = \t\t// version\n \t\tEnumChatFormatting.DARK_AQUA +\n \t\tEM_Settings.VERSION;\n\n event.getModMetadata().credits = \t\t// credits\n \t\tEnumChatFormatting.AQUA +\n \t\t\"Big thanks to the IronArmy and EpicNation for all the hard work debugging this mod.\";\n\n event.getModMetadata().authorList.clear();\n event.getModMetadata().authorList.add( // authorList - added as a list\n \t\tEnumChatFormatting.BLUE +\n \t\t\"Funwayguy, TimbuckTato, GenDeathrow, thislooksfun, AstroTibs\"\n \t\t);\n\n event.getModMetadata().url = EnumChatFormatting.GRAY +\n \t\tEM_Settings.URL;\n\n event.getModMetadata().description = \t// description\n\t \t\tEnumChatFormatting.GREEN +\n\t \t\t\"Adds more realism to Minecraft with environmental effects, physics, gases and a cave dimension.\";\n\n event.getModMetadata().logoFile = \"title.png\";\n\n\n\t\tlogger = event.getModLog();\n\n\t\tenviroTab = new EnviroTab(\"enviromine.enviroTab\");\n\n\t\tLegacyHandler.preInit();\n\t\tLegacyHandler.init();\n\n\t\tproxy.preInit(event);\n\n\t\tObjectHandler.initItems();\n\t\tObjectHandler.registerItems();\n\t\tObjectHandler.initBlocks();\n\t\tObjectHandler.registerBlocks();\n\n\t\t// Load Configuration files And Custom files\n\t\tEM_ConfigHandler.initConfig();\n\n\n // Version check monitors\n\t\t// Have to be initialized after the configs so that the value is read\n/* \tif ((EM_Settings.VERSION).contains(\"DEV\"))\n \t{\n \t\tFMLCommonHandler.instance().bus().register(DevVersionWarning.instance);\n \t}\n \telse if (EM_Settings.versionChecker)\n \t{\n \t\tFMLCommonHandler.instance().bus().register(VersionChecker.instance);\n \t}\n*/\n\n\t\tObjectHandler.registerGases();\n\t\tObjectHandler.registerEntities();\n\n\t\tif(EM_Settings.shaftGen == true)\n\t\t{\n\t\t\tVillagerRegistry.instance().registerVillageCreationHandler(new EnviroShaftCreationHandler());\n\t\t\tMapGenStructureIO.func_143031_a(EM_VillageMineshaft.class, \"ViMS\");\n\t\t}\n\n\t\tthis.network = NetworkRegistry.INSTANCE.newSimpleChannel(EM_Settings.Channel);\n\t\tthis.network.registerMessage(PacketEnviroMine.HandlerServer.class, PacketEnviroMine.class, 0, Side.SERVER);\n\t\tthis.network.registerMessage(PacketEnviroMine.HandlerClient.class, PacketEnviroMine.class, 1, Side.CLIENT);\n\t\tthis.network.registerMessage(PacketAutoOverride.Handler.class, PacketAutoOverride.class, 2, Side.CLIENT);\n\t\tthis.network.registerMessage(PacketServerOverride.Handler.class, PacketServerOverride.class, 3, Side.CLIENT);\n\n\n\t\tGameRegistry.registerWorldGenerator(new WorldFeatureGenerator(), 20);\n\t}\n\n\t@EventHandler\n\tpublic void init(FMLInitializationEvent event)\n\t{\n\t\tproxy.init(event);\n\n\t\tObjectHandler.registerRecipes();\n\n\t\tEnviroUtils.extendPotionList();\n\n\t\tEnviroPotion.RegisterPotions();\n\n\t\tEnviroAchievements.InitAchievements();\n\n\t\tcaves = (BiomeGenCaves)(new BiomeGenCaves(EM_Settings.caveBiomeID).setColor(0).setBiomeName(\"Caves\").setDisableRain().setTemperatureRainfall(1.0F, 0.0F));\n\t\t//GameRegistry.addBiome(caves);\n\t\tBiomeDictionary.registerBiomeType(caves, Type.WASTELAND);\n\n\n\t\tDimensionManager.registerProviderType(EM_Settings.caveDimID, WorldProviderCaves.class, false);\n\t\tDimensionManager.registerDimension(EM_Settings.caveDimID, EM_Settings.caveDimID);\n\n\n\t\tproxy.registerTickHandlers();\n\t\tproxy.registerEventHandlers();\n\t}\n\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent event)\n\t{\n\t\tproxy.postInit(event);\n\n\t\t//TODO Moved inside of Config Handler.general config to add in custom list\n\t\t//ObjectHandler.LoadIgnitionSources();\n\n\t\tEM_ConfigHandler.initConfig(); // Second pass for object initialized after pre-init\n\t}\n\n\t@EventHandler\n\tpublic void serverStart(FMLServerStartingEvent event)\n\t{\n\t\tMinecraftServer server = MinecraftServer.getServer();\n\t\tICommandManager command = server.getCommandManager();\n\t\tServerCommandManager manager = (ServerCommandManager) command;\n\n\t\tmanager.registerCommand(new CommandPhysics());\n\t\tmanager.registerCommand(new EnviroCommand());\n\t\tmanager.registerCommand(new QuakeCommand());\n\t}\n}\n\nsrc/main/java/enviromine/utils/EnviroUtils.java\npublic class EnviroUtils\n{\n public static final String[] reservedNames = new String[] {\"CON\", \"COM\", \"PRN\", \"AUX\", \"CLOCK$\", \"NUL\", \"COM1\", \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\", \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", \"LPT9\"};\n public static final char[] specialCharacters = new char[] {'/', '\\n', '\\r', '\\t', '\\u0000', '\\f', '`', '?', '*', '\\\\', '<', '>', '|', '\\\"', ':'};\n\tprivate static final String IEEP_PLAYER_WITCHERY = \"WitcheryExtendedPlayer\";\n\tprivate static final String IEEP_PLAYER_WITCHERY_CREATURE_TYPE = \"CreatureType\";\n\tprivate static final String IEEP_PLAYER_WITCHERY_VAMPIRE_LEVEL = \"VampireLevel\";\n\tprivate static final String IEEP_PLAYER_WITCHERY_WEREWOLF_LEVEL = \"WerewolfLevel\";\n\tprivate static final String IEEP_PLAYER_WITCHERY_DEMON_LEVEL = \"DemonLevel\";\n\tprivate static final String IEEP_PLAYER_MO_ANDROID = \"AndroidPlayer\";\n\tprivate static final String IEEP_PLAYER_MO_ISANDROID = \"isAndroid\";\n\n\tpublic static void extendPotionList()\n\t{\n\t\tint maxID = 32;\n\n\t\tif(EM_Settings.heatstrokePotionID >= maxID)\n\t\t{\n\t\t\tmaxID = EM_Settings.heatstrokePotionID + 1;\n\t\t}\n\n\t\tif(EM_Settings.hypothermiaPotionID >= maxID)\n\t\t{\n\t\t\tmaxID = EM_Settings.hypothermiaPotionID + 1;\n\t\t}\n\n\t\tif(EM_Settings.frostBitePotionID >= maxID)\n\t\t{\n\t\t\tmaxID = EM_Settings.frostBitePotionID + 1;\n\t\t}\n\n\t\tif(EM_Settings.dehydratePotionID >= maxID)\n\t\t{\n\t\t\tmaxID = EM_Settings.dehydratePotionID + 1;\n\t\t}\n\n\t\tif(EM_Settings.insanityPotionID >= maxID)\n\t\t{\n\t\t\tmaxID = EM_Settings.insanityPotionID + 1;\n\t\t}\n\n\t\tif(Potion.potionTypes.length >= maxID)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tPotion[] potionTypes = null;\n\n\t\tfor(Field f : Potion.class.getDeclaredFields())\n\t\t{\n\t\t\tf.setAccessible(true);\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif(f.getName().equals(\"potionTypes\") || f.getName().equals(\"field_76425_a\"))\n\t\t\t\t{\n\t\t\t\t\tField modfield = Field.class.getDeclaredField(\"modifiers\");\n\t\t\t\t\tmodfield.setAccessible(true);\n\t\t\t\t\tmodfield.setInt(f, f.getModifiers() & ~Modifier.FINAL);\n\n\t\t\t\t\tpotionTypes = (Potion[])f.get(null);\n\t\t\t\t\tfinal Potion[] newPotionTypes = new Potion[maxID];\n\t\t\t\t\tSystem.arraycopy(potionTypes, 0, newPotionTypes, 0, potionTypes.length);\n\t\t\t\t\tf.set(null, newPotionTypes);\n\t\t\t\t}\n\t\t\t} catch(Exception e)\n\t\t\t{\n\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.LOW.getLevel()) EnviroMine.logger.log(Level.ERROR, \"Failed to extend potion list for EnviroMine!\", e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static int[] getAdjacentBlockCoordsFromSide(int x, int y, int z, int side)\n\t{\n\t\tint[] coords = new int[3];\n\t\tcoords[0] = x;\n\t\tcoords[1] = y;\n\t\tcoords[2] = z;\n\n\t\tForgeDirection dir = ForgeDirection.getOrientation(side);\n\t\tswitch(dir)\n\t\t{\n\t\t\tcase NORTH:\n\t\t\t{\n\t\t\t\tcoords[2] -= 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase SOUTH:\n\t\t\t{\n\t\t\t\tcoords[2] += 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase WEST:\n\t\t\t{\n\t\t\t\tcoords[0] -= 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase EAST:\n\t\t\t{\n\t\t\t\tcoords[0] += 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase UP:\n\t\t\t{\n\t\t\t\tcoords[1] += 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase DOWN:\n\t\t\t{\n\t\t\t\tcoords[1] -= 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase UNKNOWN:\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn coords;\n\t}\n\n\n\tpublic static String replaceULN(String unlocalizedName)\n\t{\n\t\tunlocalizedName = unlocalizedName.replaceAll(\"[\\\\(\\\\)]\", \"\");\n\t\tunlocalizedName = unlocalizedName.replaceAll(\"\\\\.+\", \"\\\\_\");\n\n\t\treturn unlocalizedName;\n\t}\n\n\tpublic static float convertToFarenheit(float num)\n\t{\n\t\treturn convertToFarenheit(num, 2);\n\t}\n\tpublic static float convertToFarenheit(float num, int decimalPlace)\n\t{\n\t\tfloat newNum = (float) ((num * 1.8) + 32F);\n\t\tBigDecimal convert = new BigDecimal(Float.toString(newNum));\n\t\tconvert.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);\n\n\t\treturn convert.floatValue();\n\t}\n\n\tpublic static float convertToCelcius(float num)\n\t{\n\t\treturn((num - 32F) * (5 / 9));\n\t}\n\n\n\tpublic static double getBiomeTemp(BiomeGenBase biome)\n\t{\n\t\treturn getBiomeTemp(biome.temperature);\n\t}\n\tpublic static double getBiomeTemp(int x, int y, int z, BiomeGenBase biome)\n\t{\n\t\treturn getBiomeTemp(biome.getFloatTemperature(x, y, z));\n\t}\n\tprivate static double getBiomeTemp(float biomeTemp)\n\t{\n\t\t// You can calibrate temperatures using these\n\t\t// This does not take into account the time of day (These are the midday maximums)\n\t\tfloat maxTemp = 45F; // Desert\n\t\tfloat minTemp = -15F;\n\n\t\t// CALCULATE!\n\t\treturn biomeTemp >= 0? Math.sin(Math.toRadians(biomeTemp*45F))*maxTemp : Math.sin(Math.toRadians(biomeTemp*45F))*minTemp;\n\t}\n\n\t/*\n\t * This isn't accurate enough to\n\t */\n\tpublic static String getBiomeWater(BiomeGenBase biome)\n\t{\n\t\tint waterColour = biome.getWaterColorMultiplier();\n\t\tboolean looksBad = false;\n\n\t\tif(waterColour != 16777215)\n\t\t{\n\t\t\tColor bColor = new Color(waterColour);\n\n\t\t\tif(bColor.getRed() < 200 || bColor.getGreen() < 200 || bColor.getBlue() < 200)\n\t\t\t{\n\t\t\t\tlooksBad = true;\n\t\t\t}\n\t\t}\n\n\t\tArrayList typeList = new ArrayList();\n\t\tType[] typeArray = BiomeDictionary.getTypesForBiome(biome);\n\t\tfor(int i = 0; i < typeArray.length; i++)\n\t\t{\n\t\t\ttypeList.add(typeArray[i]);\n\t\t}\n\n\n\t\tif(typeList.contains(Type.SWAMP) || typeList.contains(Type.JUNGLE) || typeList.contains(Type.DEAD) || typeList.contains(Type.WASTELAND) || looksBad)\n\t\t{\n\t\t\treturn \"dirty\";\n\t\t} else if(typeList.contains(Type.OCEAN) || typeList.contains(Type.BEACH))\n\t\t{\n\t\t\treturn \"salty\";\n\t\t} else if(typeList.contains(Type.SNOWY) || typeList.contains(Type.CONIFEROUS) || biome.temperature < 0F)\n\t\t{\n\t\t\treturn \"cold\";\n\t\t} else\n\t\t{\n\t\t\treturn \"clean\";\n\t\t}\n\t}\n\n\tpublic static StabilityType getDefaultStabilityType(Block block)\n\t{\n\t\tStabilityType type = null;\n\n\t\tMaterial material = block.getMaterial();\n\n\t\tif(block instanceof BlockMobSpawner || block instanceof BlockLadder || block instanceof BlockWeb || block instanceof BlockSign || block instanceof BlockBed || block instanceof BlockDoor || block instanceof BlockAnvil || block instanceof BlockGravel || block instanceof BlockPortal || block instanceof BlockEndPortal || block instanceof BlockEndPortalFrame || block == Blocks.grass || block == ObjectHandler.elevator || block == Blocks.end_stone || block.getMaterial() == Material.vine || !block.getMaterial().blocksMovement())\n\t\t{\n\t\t\ttype = EM_Settings.stabilityTypes.get(\"none\");\n\t\t} else if(block instanceof BlockGlowstone)\n\t\t{\n\t\t\ttype = EM_Settings.stabilityTypes.get(\"glowstone\");\n\t\t} else if(isTCLoaded() && block instanceof BlockMagicalLeaves ){\n\n type = EM_Settings.stabilityTypes.get(\"average\");\n } else if(block instanceof BlockFalling)\n\t\t{\n\t\t\ttype = EM_Settings.stabilityTypes.get(\"sand-like\");\n\t\t} else if(material == Material.iron || material == Material.wood || block instanceof BlockObsidian || block == Blocks.stonebrick || block == Blocks.brick_block || block == Blocks.quartz_block)\n\t\t{\n\t\t\ttype = EM_Settings.stabilityTypes.get(\"strong\");\n\t\t} else if(material == Material.rock || material == Material.glass || material == Material.ice || block instanceof BlockLeavesBase)\n\t\t{\n\t\t\ttype = EM_Settings.stabilityTypes.get(\"average\");\n\t\t}\n\n else\n\t\t{\n\t\t\ttype = EM_Settings.stabilityTypes.get(EM_Settings.defaultStability);\n\t\t}\n\n\t\tif(type == null)\n\t\t{\n\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.LOW.getLevel()) EnviroMine.logger.log(Level.ERROR, \"Block \" + block.getUnlocalizedName() + \" has a null StabilityType. Crash imminent!\");\n\t\t}\n\n\t\treturn type;\n\t}\n\n\tpublic static String SafeFilename(String filename)\n\t{\n\t\tString safeName = filename;\n\t\tfor(String reserved : reservedNames)\n\t\t{\n\t\t\tif(safeName.equalsIgnoreCase(reserved))\n\t\t\t{\n\t\t\t\tsafeName = \"_\" + safeName + \"_\";\n\t\t\t}\n\t\t}\n\n\t\tfor(char badChar : specialCharacters)\n\t\t{\n\t\t\tsafeName = safeName.replace(badChar, '_');\n\t\t}\n\n\t\treturn safeName;\n\t}\n\n\t/**\n\t * Will compare Versions numbers and give difference\n\t * @param oldVer\n\t * @param newVer\n\t * @return\n\t */\n\tpublic static int compareVersions(String oldVer, String newVer)\n\t{\n\t\tif(oldVer == null || newVer == null || oldVer.isEmpty() || newVer.isEmpty())\n\t\t{\n\t\t\treturn -2;\n\t\t}\n\n\t\tint result = 0;\n\t\tint[] oldNum;\n\t\tint[] newNum;\n\t\tString[] oldNumStr;\n\t\tString[] newNumStr;\n\n\t\ttry\n\t\t{\n\t\t\toldNumStr = oldVer.split(\"\\\\.\");\n\t\t\tnewNumStr = newVer.split(\"\\\\.\");\n\n\t\t\toldNum = new int[]{Integer.valueOf(oldNumStr[0]),Integer.valueOf(oldNumStr[1]),Integer.valueOf(oldNumStr[2])};\n\t\t\tnewNum = new int[]{Integer.valueOf(newNumStr[0]),Integer.valueOf(newNumStr[1]),Integer.valueOf(newNumStr[2])};\n\t\t} catch(IndexOutOfBoundsException e)\n\t\t{\n\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel()) EnviroMine.logger.log(Level.WARN, \"An IndexOutOfBoundsException occured while checking version!\", e);\n\t\t\treturn -2;\n\t\t} catch(NumberFormatException e)\n\t\t{\n\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel()) EnviroMine.logger.log(Level.WARN, \"A NumberFormatException occured while checking version!\\n\", e);\n\t\t\treturn -2;\n\t\t}\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tif(oldNum[i] < newNum[i])\n\t\t\t{\n\t\t\t\treturn -1;\n\t\t\t} else if(oldNum[i] > newNum[i])\n\t\t\t{\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\n\t/**\n\t * Checks a player's \"Attributes\" NBT data for an attribute with a specified name,\n\t * and if so whether that attribute has a \"Modifiers\" tag with a specified name\n\t */\n\tpublic static boolean doesPlayerHaveAttributeModifier(EntityPlayer player, String attribute, String modifier)\n\t{\n\t\t// Obtain player's NBT\n\t\tNBTTagCompound nbttc = new NBTTagCompound();\n\t\tplayer.writeEntityToNBT(nbttc);\n\n\t\t// Extract the Attributes tag list\n\t\tif (!nbttc.hasKey(\"Attributes\"))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tNBTTagList attributes_tag = nbttc.getTagList(\"Attributes\", 10);\n\n\t\t// Scan these tags for the specified attribute\n\t\tfor (int i=0; i0;}\n\n\t/**\n\t * Returns the VampireLevel value from Witchery's IExtendedEntityProperties\n\t */\n\tpublic static int getWitcheryVampireLevel(Entity entity)\n\t{\n\t\tNBTTagCompound ieep_witchery = getIEEPTag(entity, IEEP_PLAYER_WITCHERY);\n\t\treturn ieep_witchery!=null && ieep_witchery.hasKey(IEEP_PLAYER_WITCHERY_VAMPIRE_LEVEL) ? ieep_witchery.getInteger(IEEP_PLAYER_WITCHERY_VAMPIRE_LEVEL) : 0;\n\t}\n\tpublic static boolean isPlayerAVampire(EntityPlayer player) {return getWitcheryVampireLevel(player)>0;}\n\n\t/**\n\t * Returns the WerewolfLevel value from Witchery's IExtendedEntityProperties\n\t */\n\tpublic static int getWitcheryWerewolfLevel(Entity entity)\n\t{\n\t\tNBTTagCompound ieep_witchery = getIEEPTag(entity, IEEP_PLAYER_WITCHERY);\n\t\treturn ieep_witchery!=null && ieep_witchery.hasKey(IEEP_PLAYER_WITCHERY_WEREWOLF_LEVEL) ? ieep_witchery.getInteger(IEEP_PLAYER_WITCHERY_WEREWOLF_LEVEL) : 0;\n\t}\n\tpublic static boolean isPlayerAWerewolf(EntityPlayer player) {return getWitcheryWerewolfLevel(player)>0;}\n\n\t/**\n\t * Returns whether a player is a Matter Overdrive Android\n\t */\n\tpublic static boolean isPlayerCurrentlyMOAndroid(EntityPlayer player)\n\t{\n\t\tNBTTagCompound ieep_witchery = getIEEPTag(player, IEEP_PLAYER_MO_ANDROID);\n\t\treturn ieep_witchery!=null && ieep_witchery.hasKey(IEEP_PLAYER_MO_ISANDROID) ? ieep_witchery.getBoolean(IEEP_PLAYER_MO_ISANDROID) : false;\n\t}\n}", "answers": ["\t\t\tif(EM_Settings.rotProperties.containsKey(\"\" + name + \",\" + meta) && !EM_ConfigHandler.loadedConfigs.contains(filename))"], "length": 1998, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "9893204a-b84e-486e-afc6-1cf09df674bd", "reasoning": "The LoadProperty method is handling configuration entries. After the comment inside the else block (when meta >= 0), the code should check for duplicate entries using a key that includes both the item name and its meta value, mirroring the duplicate‑check logic used for meta < 0. The next logical line is an if‑statement that looks up the combined key in EM_Settings.rotProperties and ensures the config file hasn't already been fully loaded.", "reasoning_model_answer": "if(EM_Settings.rotProperties.containsKey(name + \":\" + meta) && !EM_ConfigHandler.loadedConfigs.contains(filename))", "assistant_with_reasoning": "\nThe LoadProperty method is handling configuration entries. After the comment inside the else block (when meta >= 0), the code should check for duplicate entries using a key that includes both the item name and its meta value, mirroring the duplicate‑check logic used for meta < 0. The next logical line is an if‑statement that looks up the combined key in EM_Settings.rotProperties and ensures the config file hasn't already been fully loaded.\n\nif(EM_Settings.rotProperties.containsKey(name + \":\" + meta) && !EM_ConfigHandler.loadedConfigs.contains(filename))", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.792, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 22204, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "if(EM_Settings.rotProperties.containsKey(name + \":\" + meta) && !EM_ConfigHandler.loadedConfigs.contains(filename))", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.tokensTool.pandoraNext.pojo.systemSetting;\nimport com.tokensTool.pandoraNext.service.impl.apiServiceImpl;\nimport com.tokensTool.pandoraNext.service.impl.poolServiceImpl;\nimport com.tokensTool.pandoraNext.service.impl.systemServiceImpl;\nimport com.tokensTool.pandoraNext.util.JwtUtils;\nimport com.tokensTool.pandoraNext.util.MyTaskUtils;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.scheduling.annotation.EnableScheduling;\nimport javax.annotation.PostConstruct;\nimport java.time.Instant;\nimport java.util.UUID;", "context": "rearServer/src/main/java/com/tokensTool/pandoraNext/tokensToolApplication.java\npackage com.tokensTool.pandoraNext;\n\n\n\n/**\n * @author YANGYANG\n */\n\n/**\n * 定时注解\n */\n@Slf4j\n@EnableScheduling\n@SpringBootApplication\npublic class tokensToolApplication {\n\n @Autowired\n private apiServiceImpl serviceImpl;\n\n @Autowired\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n private Integer timeout;\n /**\n * 部署服务流量走代理\n */\n private String proxy_url;\n /**\n * GPT中创建的对话分享\n */\n private Boolean public_share;\n /**\n * 访问网站密码\n */\n private String site_password;\n /**\n * 重载服务密码\n */\n private String setup_password;\n /**\n * 白名单(null则不限制,为空数组[]则限制所有账号)\n */\n private String whitelist;\n\n /**\n * pandoraNext验证license_id\n */\n private String license_id;\n\n /**\n * tokensTool登录Username\n */\n private String loginUsername;\n\n /**\n * tokensTool密码Password\n */\n private String loginPassword;\n\n /**\n * tokensTool 验证信息\n */\n private validation validation;\n\n /**\n * tokensTool 更新token网址\n * 为\"default\"则调用本机的,不为“default\"则自定义\n */\n private String autoToken_url;\n\n /**\n * 是否开启拿tokensTool的后台token\n */\n private Boolean isGetToken;\n /**\n * tokensTool 拿到getTokenPassword\n * 为\"getTokenPassword\" 默认:123456\n * 默认拿getTokenPassword\n */\n private String getTokenPassword;\n\n /**\n * tokensTool 更新containerName(容器名)\n * 通过容器名实现开启,关闭,重新启动容器\n */\n private String containerName;\n\n\n /**\n * PandoraNext tls证书\n */\n private tls tls;\n\n /**\n * PandoraNext config.json位置\n */\n private String configPosition;\n\n /**\n * PandoraNext 接口地址添加前缀\n */\n private String isolated_conv_title;\n\n /**\n * PandoraNext 会话标题\n */\n private String proxy_api_prefix;\n\n /**\n * 禁用注册账号功能,true或false\n */\n private Boolean disable_signup;\n\n /**\n * 在proxy模式使用gpt-4模型调用/backend-api/conversation接口是否自动打码,使用消耗为4+10。\n */\n private Boolean auto_conv_arkose;\n\n /**\n * 在proxy模式是否使用PandoraNext的文件代理服务,避免官方文件服务的墙。\n */\n private Boolean proxy_file_service;\n\n /**\n * 配置自定义的DoH主机名,建议使用IP形式。默认在+8区使用223.6.6.6,其余地区使用1.1.1.1。\n */\n private String custom_doh_host;\n\n /**\n * 自动刷新session的开关\n */\n private Boolean auto_updateSession;\n\n /**\n * 自动刷新session的时间 (天为单位)\n */\n private Integer auto_updateTime;\n\n /**\n * 自动刷新session的个数 (个)\n */\n private Integer auto_updateNumber;\n\n /**\n * PadoraNext的公网访问地址\n */\n private String pandoraNext_outUrl;\n\n /**\n * oneAPi的公网访问地址\n */\n private String oneAPi_outUrl;\n\n /**\n * oneApi访问令牌\n */\n private String oneAPi_intoToken;\n}\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/util/JwtUtils.java\n@Slf4j\n@Data\n@NoArgsConstructor\npublic class JwtUtils {\n //硬编码的伤\n private static String signKey = \"123456\";\n // JWT里的内容\n private static String JwtPassword = \"tokensTool\";\n // 有效期\n private static Long expire = 604800000L;\n\n public static String getSignKey() {\n return signKey;\n }\n\n /**\n * 更换signkey的值\n */\n public static void setSignKey(String key) {\n signKey = key;\n }\n\n public static String getJwtPassword() {\n return JwtPassword;\n }\n\n public static void setJwtPassword(String password) {\n JwtPassword = password;\n }\n\n /**\n * 生成JWT令牌\n *\n * @param claims JWT第二部分负载 payload 中存储的内容\n * @return\n */\n public static String generateJwt(Map claims) {\n String jwt = Jwts.builder()\n .addClaims(claims)\n .signWith(SignatureAlgorithm.HS256, getSignKey())\n .setExpiration(new Date(System.currentTimeMillis() + expire))\n .compact();\n return jwt;\n }\n\n /**\n * 解析JWT令牌\n *\n * @param jwt JWT令牌\n * @return JWT第二部分负载 payload 中存储的内容\n */\n public static Claims parseJWT(String jwt) {\n Claims claims = Jwts.parser()\n .setSigningKey(getSignKey())\n .parseClaimsJws(jwt)\n .getBody();\n return claims;\n }\n}\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/systemServiceImpl.java\n@Slf4j\n@Service\npublic class systemServiceImpl implements systemService {\n @Value(\"${deployPosition}\")\n private String deployPosition;\n private String deploy = \"default\";\n\n\n public String selectFile() {\n String projectRoot;\n if (deploy.equals(deployPosition)) {\n projectRoot = System.getProperty(\"user.dir\");\n } else {\n projectRoot = deployPosition;\n }\n String parent = projectRoot + File.separator + \"config.json\";\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n // 如果 JSON 文件不存在,创建一个新的 JSON 对象\n if (!jsonFile.exists()) {\n try {\n // 创建文件config.json\n Files.createFile(jsonFilePath);\n // 往 config.json 文件中添加一个空数组,防止重启报错\n Files.writeString(jsonFilePath, \"{}\");\n log.info(\"空数组添加完成\");\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n log.info(\"config.json创建完成: \" + jsonFilePath);\n }\n return parent;\n }\n\n /**\n * 初始化config.json文件\n */\n public void initializeConfigJson() {\n String parent = selectFile();\n try {\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 定义一个 Map,其中键是 JSON 属性的名称,值是默认值\n Map keysAndDefaults = new HashMap<>();\n keysAndDefaults.put(\"loginUsername\", \"root\");\n keysAndDefaults.put(\"loginPassword\", \"123456\");\n keysAndDefaults.put(\"license_id\", \"\");\n keysAndDefaults.put(\"autoToken_url\", \"default\");\n keysAndDefaults.put(\"isGetToken\", \"false\");\n keysAndDefaults.put(\"getTokenPassword\", \"\");\n keysAndDefaults.put(\"containerName\", \"PandoraNext\");\n keysAndDefaults.put(\"isolated_conv_title\", \"*\");\n keysAndDefaults.put(\"proxy_api_prefix\", \"\");\n keysAndDefaults.put(\"disable_signup\", false);\n keysAndDefaults.put(\"auto_conv_arkose\", false);\n keysAndDefaults.put(\"proxy_file_service\", false);\n keysAndDefaults.put(\"custom_doh_host\", \"\");\n\n // 0.4.9.3\n keysAndDefaults.put(\"auto_updateSession\", false);\n keysAndDefaults.put(\"auto_updateTime\", 5);\n keysAndDefaults.put(\"auto_updateNumber\", 1);\n keysAndDefaults.put(\"pandoraNext_outUrl\", \"\");\n\n // 0.5.0\n\n keysAndDefaults.put(\"oneAPi_outUrl\", \"\");\n keysAndDefaults.put(\"oneAPi_intoToken\", \"\");\n\n boolean exist = checkAndSetDefaults(jsonObject, keysAndDefaults);\n\n JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject(\"captcha\")).orElse(new JSONObject());\n validation captchaSetting = new validation(\n captchaJson.optString(\"provider\", \"\"),\n captchaJson.optString(\"site_key\", \"\"),\n captchaJson.optString(\"site_secret\", \"\"),\n captchaJson.optBoolean(\"site_login\", false),\n captchaJson.optBoolean(\"setup_login\", false),\n captchaJson.optBoolean(\"oai_username\", false),\n captchaJson.optBoolean(\"oai_password\", false)\n );\n\n JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject(\"tls\")).orElse(new JSONObject());\n tls tlsSetting = new tls(\n tlsJson.optBoolean(\"enabled\", false),\n tlsJson.optString(\"cert_file\", \"\"),\n tlsJson.optString(\"key_file\", \"\")\n );\n\n if (tlsJson.length() == 0) {\n jsonObject.put(\"tls\", tlsSetting.toJSONObject());\n exist = false;\n }\n if (captchaJson.length() == 0) {\n jsonObject.put(\"captcha\", captchaSetting.toJSONObject());\n exist = false;\n }\n if (!exist) {\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n }\n log.info(\"初始化config.json成功!\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n // 通用方法,检查和设置默认值\n private boolean checkAndSetDefaults(JSONObject jsonObject, Map keysAndDefaults) throws JSONException {\n boolean exist = true;\n for (Map.Entry entry : keysAndDefaults.entrySet()) {\n try {\n jsonObject.get(entry.getKey());\n } catch (JSONException e) {\n jsonObject.put(entry.getKey(), entry.getValue());\n log.info(\"config.json没有新增\" + entry.getKey() + \"参数,现已增加!\");\n exist = false;\n }\n }\n return exist;\n }\n\n /**\n * 修改config.json里的系统值\n *\n * @return \"修改成功!\"or\"修改失败\"\n */\n @Override\n public String requiredSetting(systemSetting tem) {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n JSONObject jsonObject = new JSONObject(jsonContent);\n updateJsonValue(jsonObject, \"bind\", tem.getBing());\n updateJsonValue(jsonObject, \"timeout\", tem.getTimeout());\n updateJsonValue(jsonObject, \"proxy_url\", tem.getProxy_url());\n updateJsonValue(jsonObject, \"public_share\", tem.getPublic_share());\n updateJsonValue(jsonObject, \"site_password\", tem.getSite_password());\n updateJsonValue(jsonObject, \"setup_password\", tem.getSetup_password());\n JSONArray jsonArray = null;\n if (tem.getWhitelist() != null && tem.getWhitelist().length() > 0 && tem.getWhitelist() != \"null\") {\n String numbersString = tem.getWhitelist().replaceAll(\"[\\\\[\\\\]]\", \"\");\n String[] numbersArray = numbersString.split(\",\");\n // 将数组转换为 List\n List numbersList = new ArrayList<>(Arrays.asList(numbersArray));\n jsonArray = new JSONArray(numbersList);\n jsonObject.put(\"whitelist\", jsonArray);\n } else {\n jsonObject.put(\"whitelist\", JSONObject.NULL);\n }\n\n //4.7.2\n if (!tem.getLoginPassword().equals(jsonObject.optString(\"loginPassword\"))\n || !tem.getLoginUsername().equals(jsonObject.optString(\"loginUsername\"))) {\n Instant instant = Instant.now();\n //时间戳\n String key = String.valueOf(instant.toEpochMilli());\n JwtUtils.setSignKey(key);\n }\n\n updateJsonValue(jsonObject, \"loginUsername\", tem.getLoginUsername());\n updateJsonValue(jsonObject, \"loginPassword\", tem.getLoginPassword());\n\n updateJsonValue(jsonObject, \"license_id\", tem.getLicense_id());\n updateJsonValue(jsonObject, \"autoToken_url\", tem.getAutoToken_url());\n updateJsonValue(jsonObject, \"isGetToken\", tem.getIsGetToken());\n updateJsonValue(jsonObject, \"getTokenPassword\", tem.getGetTokenPassword());\n updateJsonValue(jsonObject, \"containerName\", tem.getContainerName());\n\n updateJsonValue(jsonObject, \"isolated_conv_title\", tem.getIsolated_conv_title());\n updateJsonValue(jsonObject, \"proxy_api_prefix\", tem.getProxy_api_prefix());\n\n // 4,9\n updateJsonValue(jsonObject, \"disable_signup\", tem.getDisable_signup());\n updateJsonValue(jsonObject, \"auto_conv_arkose\", tem.getAuto_conv_arkose());\n updateJsonValue(jsonObject, \"proxy_file_service\", tem.getProxy_file_service());\n updateJsonValue(jsonObject, \"custom_doh_host\", tem.getCustom_doh_host());\n\n // validation\n validation validation = tem.getValidation();\n JSONObject captchaJson = jsonObject.getJSONObject(\"captcha\");\n updateJsonValue(captchaJson, \"provider\", validation.getProvider());\n updateJsonValue(captchaJson, \"site_key\", validation.getSite_key());\n updateJsonValue(captchaJson, \"site_secret\", validation.getSite_secret());\n updateJsonValue(captchaJson, \"site_login\", validation.isSite_login());\n updateJsonValue(captchaJson, \"setup_login\", validation.isSetup_login());\n updateJsonValue(captchaJson, \"oai_username\", validation.isOai_username());\n updateJsonValue(captchaJson, \"oai_password\", validation.isOai_password());\n\n // tls\n tls tls = tem.getTls();\n JSONObject tlsJson = jsonObject.getJSONObject(\"tls\");\n updateJsonValue(tlsJson, \"enabled\", tls.isEnabled());\n updateJsonValue(tlsJson, \"cert_file\", tls.getCert_file());\n updateJsonValue(tlsJson, \"key_file\", tls.getKey_file());\n\n // 将修改后的 JSONObject 转换为格式化的 JSON 字符串\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n return \"修改config.json成功,快去重启PandoraNext吧!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"修改config.json失败\";\n }\n\n private void updateJsonValue(JSONObject jsonObject, String key, Object value) {\n if (value == null) {\n return;\n }\n try {\n if (value != null && value.toString().length() > 0) {\n jsonObject.put(key, value);\n } else if (value.toString().length() == 0) {\n jsonObject.put(key, \"\");\n }\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 查询config.json里的系统值\n *\n * @return systemSettings类\n */\n public systemSetting selectSetting() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setSite_password(jsonObject.optString(\"site_password\"));\n config.setSetup_password(jsonObject.optString(\"setup_password\"));\n config.setBing(jsonObject.optString(\"bind\"));\n config.setPublic_share(jsonObject.optBoolean(\"public_share\"));\n config.setProxy_url(jsonObject.optString(\"proxy_url\"));\n config.setWhitelist(jsonObject.isNull(\"whitelist\") ? null : jsonObject.optString(\"whitelist\"));\n config.setTimeout(jsonObject.optInt(\"timeout\"));\n\n config.setLoginUsername(jsonObject.optString(\"loginUsername\"));\n config.setLoginPassword(jsonObject.optString(\"loginPassword\"));\n\n config.setLicense_id(jsonObject.optString(\"license_id\"));\n config.setAutoToken_url(jsonObject.optString(\"autoToken_url\"));\n config.setIsGetToken(jsonObject.optBoolean(\"isGetToken\"));\n config.setGetTokenPassword(jsonObject.optString(\"getTokenPassword\"));\n config.setContainerName(jsonObject.optString(\"containerName\"));\n\n // 4.0\n config.setIsolated_conv_title(jsonObject.optString(\"isolated_conv_title\"));\n config.setProxy_api_prefix(jsonObject.optString(\"proxy_api_prefix\"));\n\n // 4.9\n config.setDisable_signup(jsonObject.optBoolean(\"disable_signup\"));\n config.setAuto_conv_arkose(jsonObject.optBoolean(\"auto_conv_arkose\"));\n config.setProxy_file_service(jsonObject.optBoolean(\"proxy_file_service\"));\n config.setCustom_doh_host(jsonObject.optString(\"custom_doh_host\"));\n\n // 0.4.9.3\n config.setAuto_updateSession(jsonObject.optBoolean(\"auto_updateSession\"));\n config.setAuto_updateTime(jsonObject.optInt(\"auto_updateTime\"));\n config.setAuto_updateNumber(jsonObject.optInt(\"auto_updateNumber\"));\n config.setPandoraNext_outUrl(jsonObject.optString(\"pandoraNext_outUrl\"));\n\n // 0.5.0\n config.setOneAPi_outUrl(jsonObject.optString(\"oneAPi_outUrl\"));\n config.setOneAPi_intoToken(jsonObject.optString(\"oneAPi_intoToken\"));\n\n // 获取 captcha 相关属性\n JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject(\"captcha\")).orElse(new JSONObject());\n validation captchaSetting = new validation(\n captchaJson.optString(\"provider\", \"\"),\n captchaJson.optString(\"site_key\", \"\"),\n captchaJson.optString(\"site_secret\", \"\"),\n captchaJson.optBoolean(\"site_login\", false),\n captchaJson.optBoolean(\"setup_login\", false),\n captchaJson.optBoolean(\"oai_username\", false),\n captchaJson.optBoolean(\"oai_password\", false)\n );\n config.setValidation(captchaSetting);\n\n // 获取 tls 相关属性\n JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject(\"tls\")).orElse(new JSONObject());\n tls tlsSetting = new tls(\n tlsJson.optBoolean(\"enabled\", false),\n tlsJson.optString(\"cert_file\", \"\"),\n tlsJson.optString(\"key_file\", \"\")\n );\n config.setTls(tlsSetting);\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public systemSetting selectSettingUrl() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setBing(jsonObject.optString(\"bind\"));\n config.setAutoToken_url(jsonObject.optString(\"autoToken_url\"));\n config.setProxy_api_prefix(jsonObject.optString(\"proxy_api_prefix\"));\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public systemSetting selectSettingLicense() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setLicense_id(jsonObject.optString(\"license_id\"));\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public String requireTimeTask(systemSetting tem) {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n\n JSONObject jsonObject = new JSONObject(jsonContent);\n // 0.4.9.3\n updateJsonValue(jsonObject, \"auto_updateSession\", tem.getAuto_updateSession());\n updateJsonValue(jsonObject, \"auto_updateTime\", tem.getAuto_updateTime());\n updateJsonValue(jsonObject, \"auto_updateNumber\", tem.getAuto_updateNumber());\n updateJsonValue(jsonObject, \"pandoraNext_outUrl\", tem.getPandoraNext_outUrl());\n // 0.5.0\n updateJsonValue(jsonObject, \"oneAPi_outUrl\", tem.getOneAPi_outUrl());\n updateJsonValue(jsonObject, \"oneAPi_intoToken\", tem.getOneAPi_intoToken());\n\n // 将修改后的 JSONObject 转换为格式化的 JSON 字符串\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n return \"修改定时任务和url成功!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"修改定时任务和url失败!\";\n }\n\n public String[] selectOneAPi() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n String[] oneApi = new String[2];\n oneApi[0] = jsonObject.optString(\"oneAPi_outUrl\");\n oneApi[1] = jsonObject.optString(\"oneAPi_intoToken\");\n return oneApi;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n}\n\nrearServer/src/main/java/com/tokensTool/pandoraNext/util/MyTaskUtils.java\n@Slf4j\n@Service\npublic class MyTaskUtils {\n private final TaskScheduler taskScheduler;\n @Autowired\n private apiServiceImpl apiService;\n private ScheduledFuture future;\n\n public MyTaskUtils(TaskScheduler taskScheduler) {\n this.taskScheduler = taskScheduler;\n }\n\n\n public void stopTask() {\n if (future != null) {\n future.cancel(true);\n log.info(\"取消定时任务成功!\");\n }\n }\n\n public void changeTask(systemSetting setting) {\n try {\n if (future != null) {\n future.cancel(true);\n }\n String cron = \"0 0 1 */\" + setting.getAuto_updateTime() + \" * ?\";\n future = taskScheduler.schedule(() -> {\n // 这里是任务内容\n System.out.println(\"自定义定时更新session_token开始进行...................\");\n for (int i = 0; i < setting.getAuto_updateNumber(); i++) {\n apiService.updateSession();\n log.info(\"更新session_token开始完成\");\n }\n }, new CronTrigger(cron));\n log.info(\"定时任务开启成功!\");\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n}", "answers": [" private systemServiceImpl systemService;"], "length": 1490, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "a269597e-6efe-4598-bd19-ad28f8836cb0", "reasoning": "In the main Spring Boot application class, after autowiring the apiServiceImpl field, another @Autowired annotation is present awaiting a field declaration. The imports include systemServiceImpl, poolServiceImpl, and MyTaskUtils, indicating that the next field to be injected is likely the systemServiceImpl service. Therefore the next line should declare the systemServiceImpl field with the @Autowired annotation already placed.", "reasoning_model_answer": "private systemServiceImpl systemService;", "assistant_with_reasoning": "\nIn the main Spring Boot application class, after autowiring the apiServiceImpl field, another @Autowired annotation is present awaiting a field declaration. The imports include systemServiceImpl, poolServiceImpl, and MyTaskUtils, indicating that the next field to be injected is likely the systemServiceImpl service. Therefore the next line should declare the systemServiceImpl field with the @Autowired annotation already placed.\n\nprivate systemServiceImpl systemService;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.227, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 23340, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private systemServiceImpl systemService;", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.github.pagehelper.Page;\nimport com.github.pagehelper.page.PageMethod;\nimport supie.common.core.object.ResponseResult;\nimport supie.common.core.object.MyPageData;\nimport supie.common.core.object.MyPageParam;\nimport supie.common.core.util.MyModelUtil;\nimport supie.common.core.util.MyPageUtil;\nimport supie.common.dict.dto.GlobalDictDto;\nimport supie.common.dict.model.GlobalDict;\nimport supie.common.dict.service.GlobalDictService;\nimport supie.common.dict.vo.GlobalDictVo;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\nimport java.util.List;", "context": "common/common-dict/src/main/java/supie/common/dict/util/GlobalDictOperationHelper.java\npackage supie.common.dict.util;\n\n\n\n/**\n * 全局编码字典操作的通用帮助对象。\n *\n * @author rm -rf .bug\n * @date 2020-11-12\n */\n@Slf4j\n@Component\npublic class GlobalDictOperationHelper {\n\n @Autowired\n private GlobalDictService globalDictService;\n\n /**\n * 获取全部编码字典列表。\n *\n * @param globalDictDtoFilter 过滤对象。\n * @param pageParam 分页参数。\n * @return 字典的数据列表。\n */\n public ResponseResult> listAllGlobalDict(\n GlobalDictDto globalDictDtoFilter, MyPageParam pageParam) {\n if (pageParam != null) {\n PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());\n }\n GlobalDict filter = MyModelUtil.copyTo(globalDictDtoFilter, GlobalDict.class);\n List dictList = globalDictService.getGlobalDictList(filter, null);\n List dictVoList = MyModelUtil.copyCollectionTo(dictList, GlobalDictVo.class);\n long totalCount = 0L;\n if (dictList instanceof Page) {\n totalCount = ((Page) dictList).getTotal();\n }\n\ncommon/common-dict/src/main/java/supie/common/dict/vo/GlobalDictVo.java\n@ApiModel(\"全局系统字典Vo\")\n@Data\npublic class GlobalDictVo {\n\n /**\n * 主键Id。\n */\n @ApiModelProperty(value = \"主键Id\")\n private Long dictId;\n\n /**\n * 字典编码。\n */\n @ApiModelProperty(value = \"字典编码\")\n private String dictCode;\n\n /**\n * 字典中文名称。\n */\n @ApiModelProperty(value = \"字典中文名称\")\n private String dictName;\n\n /**\n * 创建用户Id。\n */\n @ApiModelProperty(value = \"创建用户Id\")\n private Long createUserId;\n\n /**\n * 创建时间。\n */\n @ApiModelProperty(value = \"创建时间\")\n private Date createTime;\n\n /**\n * 创建用户名。\n */\n @ApiModelProperty(value = \"创建用户名\")\n private Long updateUserId;\n\n /**\n * 更新时间。\n */\n @ApiModelProperty(value = \"更新时间\")\n private Date updateTime;\n}\n\ncommon/common-core/src/main/java/supie/common/core/object/MyPageData.java\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MyPageData {\n /**\n * 数据列表。\n */\n private List dataList;\n /**\n * 数据总数量。\n */\n private Long totalCount;\n\n /**\n * 为了保持前端的数据格式兼容性,在没有数据的时候,需要返回空分页对象。\n * @return 空分页对象。\n */\n public static MyPageData emptyPageData() {\n return new MyPageData<>(new LinkedList<>(), 0L);\n }\n}\n\ncommon/common-core/src/main/java/supie/common/core/object/MyPageParam.java\n@Getter\npublic class MyPageParam {\n\n public static final int DEFAULT_PAGE_NUM = 1;\n public static final int DEFAULT_PAGE_SIZE = 10;\n public static final int DEFAULT_MAX_SIZE = 2000;\n\n /**\n * 分页号码,从1开始计数。\n */\n private Integer pageNum = DEFAULT_PAGE_NUM;\n\n /**\n * 每页大小。\n */\n private Integer pageSize = DEFAULT_PAGE_SIZE;\n\n /**\n * 设置当前分页页号。\n *\n * @param pageNum 页号,如果传入非法值,则使用缺省值。\n */\n public void setPageNum(Integer pageNum) {\n if (pageNum == null) {\n return;\n }\n if (pageNum <= 0) {\n pageNum = DEFAULT_PAGE_NUM;\n }\n this.pageNum = pageNum;\n }\n\n /**\n * 设置分页的大小。\n *\n * @param pageSize 分页大小,如果传入非法值,则使用缺省值。\n */\n public void setPageSize(Integer pageSize) {\n if (pageSize == null) {\n return;\n }\n if (pageSize <= 0) {\n pageSize = DEFAULT_PAGE_SIZE;\n }\n if (pageSize > DEFAULT_MAX_SIZE) {\n pageSize = DEFAULT_MAX_SIZE;\n }\n this.pageSize = pageSize;\n }\n}\n\ncommon/common-dict/src/main/java/supie/common/dict/service/GlobalDictService.java\npublic interface GlobalDictService extends IBaseService {\n\n /**\n * 保存全局字典对象。\n *\n * @param globalDict 全局字典对象。\n * @return 保存后的字典对象。\n */\n GlobalDict saveNew(GlobalDict globalDict);\n\n /**\n * 更新全局字典对象。\n *\n * @param globalDict 更新的全局字典对象。\n * @param originalGlobalDict 原有的全局字典对象。\n * @return 更新成功返回true,否则false。\n */\n boolean update(GlobalDict globalDict, GlobalDict originalGlobalDict);\n\n /**\n * 删除全局字典对象,以及其关联的字典项目数据。\n *\n * @param dictId 全局字典Id。\n * @return 是否删除成功。\n */\n boolean remove(Long dictId);\n\n /**\n * 获取全局字典列表。\n *\n * @param filter 过滤对象。\n * @param orderBy 排序条件。\n * @return 查询结果集列表。\n */\n List getGlobalDictList(GlobalDict filter, String orderBy);\n\n /**\n * 判断字典编码是否存在。\n *\n * @param dictCode 字典编码。\n * @return true表示存在,否则false。\n */\n boolean existDictCode(String dictCode);\n\n /**\n * 判断指定字典编码的字典项目是否存在。\n * 该方法通常会在业务主表中调用,为了提升整体运行时效率,该方法会从缓存中获取,如果缓存为空,\n * 会从数据库读取指定编码的字典数据,并同步到缓存。\n *\n * @param dictCode 字典编码。\n * @param itemId 字典项目Id。\n * @return true表示存在,否则false。\n */\n boolean existDictItemFromCache(String dictCode, Serializable itemId);\n\n /**\n * 从缓存中获取指定编码的字典项目列表。\n * 该方法通常会在业务主表中调用,为了提升整体运行时效率,该方法会从缓存中获取,如果缓存为空,\n * 会从数据库读取指定编码的字典数据,并同步到缓存。\n *\n * @param dictCode 字典编码。\n * @param itemIds 字典项目Id集合。\n * @return 查询结果列表。\n */\n List getGlobalDictItemListFromCache(String dictCode, Set itemIds);\n\n /**\n * 从缓存中获取指定编码的字典项目列表。返回的结果Map中,键是itemId,值是itemName。\n * 该方法通常会在业务主表中调用,为了提升整体运行时效率,该方法会从缓存中获取,如果缓存为空,\n * 会从数据库读取指定编码的字典数据,并同步到缓存。\n *\n * @param dictCode 字典编码。\n * @param itemIds 字典项目Id集合。\n * @return 查询结果列表。\n */\n Map getGlobalDictItemDictMapFromCache(String dictCode, Set itemIds);\n\n /**\n * 强制同步指定字典编码的全部字典项目到缓存。\n *\n * @param dictCode 字典编码。\n */\n void reloadCachedData(String dictCode);\n\n /**\n * 从缓存中移除指定字典编码的数据。\n *\n * @param dictCode 字典编码。\n */\n void removeCache(String dictCode);\n}\n\ncommon/common-core/src/main/java/supie/common/core/object/ResponseResult.java\n@Slf4j\n@Data\npublic class ResponseResult {\n\n /**\n * 为了优化性能,所有没有携带数据的正确结果,均可用该对象表示。\n */\n private static final ResponseResult OK = new ResponseResult<>();\n /**\n * 是否成功标记。\n */\n private boolean success = true;\n /**\n * 错误码。\n */\n private String errorCode = \"NO-ERROR\";\n /**\n * 错误信息描述。\n */\n private String errorMessage = \"NO-MESSAGE\";\n /**\n * 实际数据。\n */\n private T data = null;\n\n /**\n * 根据参数errorCodeEnum的枚举值,判断创建成功对象还是错误对象。\n * 如果返回错误对象,errorCode 和 errorMessage 分别取自于参数 errorCodeEnum 的 name() 和 getErrorMessage()。\n *\n * @param errorCodeEnum 错误码枚举\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult create(ErrorCodeEnum errorCodeEnum) {\n return create(errorCodeEnum, errorCodeEnum.getErrorMessage());\n }\n\n /**\n * 根据参数errorCodeEnum的枚举值,判断创建成功对象还是错误对象。\n * 如果返回错误对象,errorCode 和 errorMessage 分别取自于参数 errorCodeEnum 的 name() 和参数 errorMessage。\n *\n * @param errorCodeEnum 错误码枚举。\n * @param errorMessage 如果该参数为null,错误信息取自errorCodeEnum参数内置的errorMessage,否则使用当前参数。\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult create(ErrorCodeEnum errorCodeEnum, String errorMessage) {\n errorMessage = errorMessage != null ? errorMessage : errorCodeEnum.getErrorMessage();\n return errorCodeEnum == ErrorCodeEnum.NO_ERROR ? success() : error(errorCodeEnum.name(), errorMessage);\n }\n\n /**\n * 根据参数errorCode是否为空,判断创建成功对象还是错误对象。\n * 如果返回错误对象,errorCode 和 errorMessage 分别取自于参数 errorCode 和参数 errorMessage。\n *\n * @param errorCode 自定义的错误码\n * @param errorMessage 自定义的错误信息\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult create(String errorCode, String errorMessage) {\n return errorCode == null ? success() : error(errorCode, errorMessage);\n }\n\n /**\n * 根据参数errorCodeEnum的枚举值,判断创建成功对象还是错误对象。\n * 如果返回错误对象,errorCode 和 errorMessage 分别取自于参数 errorCodeEnum 的 name() 和参数 errorMessage。\n *\n * @param errorCodeEnum 错误码枚举。\n * @param errorMessage 如果该参数为null,错误信息取自errorCodeEnum参数内置的errorMessage,否则使用当前参数。\n * @param data 如果错误枚举值为NO_ERROR,则返回该数据。\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult create(ErrorCodeEnum errorCodeEnum, String errorMessage, T data) {\n errorMessage = errorMessage != null ? errorMessage : errorCodeEnum.getErrorMessage();\n return errorCodeEnum == ErrorCodeEnum.NO_ERROR ? success(data) : error(errorCodeEnum.name(), errorMessage);\n }\n\n /**\n * 创建成功对象。\n * 如果需要绑定返回数据,可以在实例化后调用setDataObject方法。\n *\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult success() {\n return OK;\n }\n\n /**\n * 创建带有返回数据的成功对象。\n *\n * @param data 返回的数据对象\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult success(T data) {\n ResponseResult resp = new ResponseResult<>();\n resp.data = data;\n return resp;\n }\n\n /**\n * 创建错误对象。\n * 如果返回错误对象,errorCode 和 errorMessage 分别取自于参数 errorCodeEnum 的 name() 和 getErrorMessage()。\n *\n * @param errorCodeEnum 错误码枚举\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult error(ErrorCodeEnum errorCodeEnum) {\n return error(errorCodeEnum.name(), errorCodeEnum.getErrorMessage());\n }\n\n /**\n * 创建错误对象。\n * 如果返回错误对象,errorCode 和 errorMessage 分别取自于参数 errorCodeEnum 的 name() 和参数 errorMessage。\n *\n * @param errorCodeEnum 错误码枚举\n * @param errorMessage 自定义的错误信息\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult error(ErrorCodeEnum errorCodeEnum, String errorMessage) {\n return error(errorCodeEnum.name(), errorMessage);\n }\n\n /**\n * 创建错误对象。\n * 如果返回错误对象,errorCode 和 errorMessage 分别取自于参数 errorCode 和参数 errorMessage。\n *\n * @param errorCode 自定义的错误码\n * @param errorMessage 自定义的错误信息\n * @return 返回创建的ResponseResult实例对象\n */\n public static ResponseResult error(String errorCode, String errorMessage) {\n return new ResponseResult<>(errorCode, errorMessage);\n }\n\n /**\n * 根据参数中出错的ResponseResult,创建新的错误应答对象。\n *\n * @param errorCause 导致错误原因的应答对象。\n * @return 返回创建的ResponseResult实例对象。\n */\n public static ResponseResult errorFrom(ResponseResult errorCause) {\n return error(errorCause.errorCode, errorCause.getErrorMessage());\n }\n\n /**\n * 根据参数中出错的CallResult,创建新的错误应答对象。\n *\n * @param errorCause 导致错误原因的应答对象。\n * @return 返回创建的ResponseResult实例对象。\n */\n public static ResponseResult errorFrom(CallResult errorCause) {\n return error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorCause.getErrorMessage());\n }\n\n /**\n * 根据参数中CallResult,创建新的应答对象。\n *f\n * @param result CallResult对象。\n * @return 返回创建的ResponseResult实例对象。\n */\n public static ResponseResult from(CallResult result) {\n if (result.isSuccess()) {\n return success();\n }\n return error(ErrorCodeEnum.DATA_VALIDATED_FAILED, result.getErrorMessage());\n }\n\n /**\n * 是否成功。\n *\n * @return true成功,否则false。\n */\n public boolean isSuccess() {\n return success;\n }\n \n /**\n * 通过HttpServletResponse直接输出应该信息的工具方法。\n *\n * @param httpStatus http状态码。\n * @param responseResult 应答内容。\n * @param 数据对象类型。\n * @throws IOException 异常错误。\n */\n public static void output(int httpStatus, ResponseResult responseResult) throws IOException {\n if (httpStatus != HttpServletResponse.SC_OK) {\n log.error(JSON.toJSONString(responseResult));\n } else {\n log.info(JSON.toJSONString(responseResult));\n }\n HttpServletResponse response = ContextUtil.getHttpResponse();\n PrintWriter out = response.getWriter();\n response.setContentType(\"application/json; charset=utf-8\");\n response.setStatus(httpStatus);\n if (responseResult != null) {\n out.print(JSON.toJSONString(responseResult));\n }\n out.flush();\n }\n\n /**\n * 通过HttpServletResponse直接输出应该信息的工具方法。\n *\n * @param httpStatus http状态码。\n * @throws IOException 异常错误。\n */\n public static void output(int httpStatus) throws IOException {\n output(httpStatus, null);\n }\n\n /**\n * 通过HttpServletResponse直接输出应该信息的工具方法。Http状态码为200。\n *\n * @param responseResult 应答内容。\n * @param 数据对象类型。\n * @throws IOException 异常错误。\n */\n public static void output(ResponseResult responseResult) throws IOException {\n output(HttpServletResponse.SC_OK, responseResult);\n }\n\n private ResponseResult() {\n\n }\n\n private ResponseResult(String errorCode, String errorMessage) {\n this.success = false;\n this.errorCode = errorCode;\n this.errorMessage = errorMessage;\n }\n}\n\ncommon/common-dict/src/main/java/supie/common/dict/dto/GlobalDictDto.java\n@ApiModel(\"全局系统字典Dto\")\n@Data\npublic class GlobalDictDto {\n\n /**\n * 主键Id。\n */\n @ApiModelProperty(value = \"主键Id\")\n @NotNull(message = \"数据验证失败,主键Id不能为空!\", groups = {UpdateGroup.class})\n private Long dictId;\n\n /**\n * 字典编码。\n */\n @ApiModelProperty(value = \"字典编码\")\n @NotBlank(message = \"数据验证失败,字典编码不能为空!\")\n private String dictCode;\n\n /**\n * 字典中文名称。\n */\n @ApiModelProperty(value = \"字典中文名称\")\n @NotBlank(message = \"数据验证失败,字典中文名称不能为空!\")\n private String dictName;\n}\n\ncommon/common-core/src/main/java/supie/common/core/util/MyPageUtil.java\npublic class MyPageUtil {\n\n private static final String DATA_LIST_LITERAL = \"dataList\";\n private static final String TOTAL_COUNT_LITERAL = \"totalCount\";\n\n /**\n * 用户构建带有分页信息的数据列表。\n *\n * @param dataList 数据列表,该参数必须是调用PageMethod.startPage之后,立即执行mybatis查询操作的结果集。\n * @param includeFields 结果集中需要返回到前端的字段,多个字段之间逗号分隔。\n * @return 返回只是包含includeFields字段的数据列表,以及结果集TotalCount。\n */\n public static JSONObject makeResponseData(List dataList, String includeFields) {\n JSONObject pageData = new JSONObject();\n pageData.put(DATA_LIST_LITERAL, BeanQuery.select(includeFields).from(dataList).execute());\n if (dataList instanceof Page) {\n pageData.put(TOTAL_COUNT_LITERAL, ((Page)dataList).getTotal());\n }\n return pageData;\n }\n\n /**\n * 用户构建带有分页信息的数据列表。\n *\n * @param dataList 数据列表,该参数必须是调用PageMethod.startPage之后,立即执行mybatis查询操作的结果集。\n * @return 返回分页数据对象。\n */\n public static MyPageData makeResponseData(List dataList) {\n MyPageData pageData = new MyPageData<>();\n pageData.setDataList(dataList);\n if (dataList instanceof Page) {\n pageData.setTotalCount(((Page)dataList).getTotal());\n }\n return pageData;\n }\n\n /**\n * 用户构建带有分页信息的数据列表。\n *\n * @param dataList 数据列表,该参数必须是调用PageMethod.startPage之后,立即执行mybatis查询操作的结果集。\n * @param totalCount 总数量。\n * @return 返回分页数据对象。\n */\n public static MyPageData makeResponseData(List dataList, Long totalCount) {\n MyPageData pageData = new MyPageData<>();\n pageData.setDataList(dataList);\n if (totalCount != null) {\n pageData.setTotalCount(totalCount);\n }\n return pageData;\n }\n\n /**\n * 用户构建带有分页信息的数据列表。\n *\n * @param dataList 实体对象数据列表。\n * @param modelMapper 实体对象到DomainVO对象的数据映射器。\n * @param DomainVO对象类型。\n * @param 实体对象类型。\n * @return 返回分页数据对象。\n */\n public static MyPageData makeResponseData(List dataList, BaseModelMapper modelMapper) {\n long totalCount = 0L;\n if (CollectionUtils.isEmpty(dataList)) {\n // 这里需要构建分页数据对象,统一前端数据格式\n return MyPageData.emptyPageData();\n }\n if (dataList instanceof Page) {\n totalCount = ((Page) dataList).getTotal();\n }\n return MyPageUtil.makeResponseData(modelMapper.fromModelList(dataList), totalCount);\n }\n\n /**\n * 构建带有分页信息的数据列表。\n *\n * @param dataList 实体对象数据列表。\n * @param 结果类型。\n * @param 实体对象类型。\n * @return 返回分页数据对象。\n */\n public static MyPageData makeResponseData(List dataList, Function converter) {\n long totalCount = 0L;\n if (CollUtil.isEmpty(dataList)) {\n // 这里需要构建分页数据对象,统一前端数据格式\n return MyPageData.emptyPageData();\n }\n if (dataList instanceof Page) {\n totalCount = ((Page) dataList).getTotal();\n }\n List resultList = dataList.stream().map(converter).collect(Collectors.toList());\n return MyPageUtil.makeResponseData(resultList, totalCount);\n }\n\n /**\n * 用户构建带有分页信息的数据列表。\n *\n * @param responseData 第一个数据时数据列表,第二个是列表数量。\n * @param 源数据类型。\n * @return 返回分页数据对象。\n */\n public static MyPageData makeResponseData(Tuple2, Long> responseData) {\n return makeResponseData(responseData.getFirst(), responseData.getSecond());\n }\n\n /**\n * 私有构造函数,明确标识该常量类的作用。\n */\n private MyPageUtil() {\n }\n}", "answers": [" return ResponseResult.success(MyPageUtil.makeResponseData(dictVoList, totalCount));"], "length": 1534, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "2309d6ca-3553-42f6-88da-e09648a4d470", "reasoning": "The method listAllGlobalDict builds a list of GlobalDictVo (dictVoList) and calculates totalCount. The next logical step is to wrap the paginated data into a MyPageData object using MyPageUtil.makeResponseData and then return it as a successful ResponseResult. The appropriate line is:\nreturn ResponseResult.success(MyPageUtil.makeResponseData(dictVoList, totalCount));", "reasoning_model_answer": "return ResponseResult.success(MyPageUtil.makeResponseData(dictVoList, totalCount));", "assistant_with_reasoning": "\nThe method listAllGlobalDict builds a list of GlobalDictVo (dictVoList) and calculates totalCount. The next logical step is to wrap the paginated data into a MyPageData object using MyPageUtil.makeResponseData and then return it as a successful ResponseResult. The appropriate line is:\nreturn ResponseResult.success(MyPageUtil.makeResponseData(dictVoList, totalCount));\n\nreturn ResponseResult.success(MyPageUtil.makeResponseData(dictVoList, totalCount));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.356, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17942, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return ResponseResult.success(MyPageUtil.makeResponseData(dictVoList, totalCount));", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.ghostchu.plugins.dodosrv.command.bukkit.CommandManager;\nimport com.ghostchu.plugins.dodosrv.command.bukkit.SimpleCommandManager;\nimport com.ghostchu.plugins.dodosrv.database.DatabaseManager;\nimport com.ghostchu.plugins.dodosrv.dodo.DodoManager;\nimport com.ghostchu.plugins.dodosrv.dodo.UserBindManager;\nimport com.ghostchu.plugins.dodosrv.listener.bukkit.BukkitListener;\nimport com.ghostchu.plugins.dodosrv.listener.dodo.DoDoListener;\nimport com.ghostchu.plugins.dodosrv.text.TextManager;\nimport com.ghostchu.plugins.dodosrv.util.JsonUtil;\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.gson.JsonObject;\nimport net.deechael.dodo.API;\nimport net.deechael.dodo.api.Channel;\nimport net.deechael.dodo.api.TextChannel;\nimport net.deechael.dodo.content.Message;\nimport net.deechael.dodo.content.TextMessage;\nimport net.deechael.dodo.gate.Gateway;\nimport net.deechael.dodo.impl.ChannelImpl;\nimport net.deechael.dodo.impl.DodoBot;\nimport net.deechael.dodo.network.Route;\nimport net.deechael.dodo.types.MessageType;\nimport org.bukkit.Bukkit;\nimport org.bukkit.plugin.java.JavaPlugin;\nimport java.io.File;\nimport java.lang.reflect.Field;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.TimeUnit;", "context": "src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java\npackage com.ghostchu.plugins.dodosrv;\n\n\n\npublic final class DoDoSRV extends JavaPlugin {\n\n private DodoBot bot;\n private DatabaseManager databaseManager;\n private UserBindManager userBindManager;\n private TextManager textManager;\n private SimpleCommandManager commandManager;\n private DoDoListener doDoListener;\n private DodoManager dodoManager;\n private static Cache MESSAGE_ID_TO_ECHO = CacheBuilder.newBuilder()\n .expireAfterWrite(24, TimeUnit.HOURS)\n .maximumSize(15000)\n .build();\n\n\n @Override\n public void onEnable() {\n // Plugin startup logic\n saveDefaultConfig();\n saveDefTranslations();\n this.textManager = new TextManager(this, new File(getDataFolder(), \"messages.yml\"));\n this.databaseManager = initDatabase();\n this.userBindManager = new UserBindManager(this, databaseManager);\n try {\n initDoDoBot();\n } catch (Exception e) {\n Bukkit.getPluginManager().disablePlugin(this);\n throw new RuntimeException(e);\n }\n this.dodoManager = new DodoManager(this);\n\nsrc/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/SimpleCommandManager.java\n@Data\n@SuppressWarnings(\"unchecked\")\npublic class SimpleCommandManager implements CommandManager, TabCompleter, CommandExecutor {\n private static final String[] EMPTY_ARGS = new String[0];\n private final Set cmds = Sets.newCopyOnWriteArraySet(); //Because we open to allow register, so this should be thread-safe\n private final DoDoSRV plugin;\n private final CommandContainer rootContainer;\n\n public SimpleCommandManager(DoDoSRV plugin) {\n this.plugin = plugin;\n this.rootContainer = CommandContainer.builder()\n .prefix(\"\")\n .permission(null)\n .executor(new SubCommand_Help(plugin))\n .build();\n registerCmd(\n CommandContainer.builder()\n .prefix(\"help\")\n .permission(null)\n .executor(new SubCommand_Help(plugin))\n .build());\n SubCommand_Link link = new SubCommand_Link(plugin);\n registerCmd(\n CommandContainer.builder()\n .prefix(\"link\")\n .permission(\"dodosrv.link\")\n .executor(link)\n .build());\n SubCommand_Unlink unlink = new SubCommand_Unlink(plugin);\n registerCmd(\n CommandContainer.builder()\n .prefix(\"unlink\")\n .permission(\"dodosrv.unlink\")\n .executor(unlink)\n .build());\n registerCmd(\n CommandContainer.builder()\n .prefix(\"editintegral\")\n .permission(\"dodosrv.editintegral\")\n .executor(new SubCommand_EditIntegral(plugin))\n .build());\n }\n\n /**\n * This is a interface to allow addons to register the subcommand into quickshop command manager.\n *\n * @param container The command container to register\n * @throws IllegalStateException Will throw the error if register conflict.\n */\n @Override\n public void registerCmd(@NotNull CommandContainer container) {\n if (cmds.contains(container)) {\n return;\n }\n container.bakeExecutorType();\n cmds.removeIf(commandContainer -> commandContainer.getPrefix().equalsIgnoreCase(container.getPrefix()));\n cmds.add(container);\n }\n\n /**\n * This is a interface to allow addons to unregister the registered/butil-in subcommand from command manager.\n *\n * @param container The command container to unregister\n */\n @Override\n public void unregisterCmd(@NotNull CommandContainer container) {\n cmds.remove(container);\n }\n\n /**\n * Gets a list contains all registered commands\n *\n * @return All registered commands.\n */\n @Override\n @NotNull\n public List getRegisteredCommands() {\n return new ArrayList<>(this.getCmds());\n }\n\n @Override\n public boolean onCommand(\n @NotNull CommandSender sender,\n @NotNull Command command,\n @NotNull String commandLabel,\n @NotNull String[] cmdArg) {\n if (cmdArg.length == 0) {\n //Handle main command\n rootContainer.getExecutor().onCommand(capture(sender), commandLabel, EMPTY_ARGS);\n } else {\n //Handle subcommand\n String[] passThroughArgs = new String[cmdArg.length - 1];\n System.arraycopy(cmdArg, 1, passThroughArgs, 0, passThroughArgs.length);\n for (CommandContainer container : cmds) {\n if (!container.getPrefix().equalsIgnoreCase(cmdArg[0])) {\n continue;\n }\n if (container.isDisabled() || (container.getDisabledSupplier() != null && container.getDisabledSupplier().get())) {\n sender.sendMessage(container.getDisableText(sender));\n return true;\n }\n if (!isAdapt(container, sender)) {\n plugin.text().of(sender, \"command-type-mismatch\", container.getExecutorType().getSimpleName()).send();\n return true;\n }\n List requirePermissions = container.getPermissions();\n List selectivePermissions = container.getSelectivePermissions();\n if (!checkPermissions(sender, commandLabel, passThroughArgs, requirePermissions, PermissionType.REQUIRE, Action.EXECUTE)) {\n plugin.text().of(sender, \"no-permission\").send();\n return true;\n }\n if (!checkPermissions(sender, commandLabel, passThroughArgs, selectivePermissions, PermissionType.SELECTIVE, Action.EXECUTE)) {\n plugin.text().of(sender, \"no-permission\").send();\n return true;\n }\n container.getExecutor().onCommand(capture(sender), commandLabel, passThroughArgs);\n return true;\n }\n rootContainer.getExecutor().onCommand(capture(sender), commandLabel, passThroughArgs);\n }\n return true;\n }\n\n /**\n * Method for capturing generic type\n */\n private T2 capture(T1 type) {\n return (T2) type;\n }\n\n private boolean checkPermissions(CommandSender sender, String commandLabel, String[] cmdArg, List permissionList, PermissionType permissionType, Action action) {\n if (permissionList == null || permissionList.isEmpty()) {\n return true;\n }\n if (permissionType == PermissionType.REQUIRE) {\n for (String requirePermission : permissionList) {\n if (requirePermission != null\n && !requirePermission.isEmpty()\n && !sender.hasPermission(requirePermission)) {\n return false;\n }\n }\n return true;\n } else {\n for (String selectivePermission : permissionList) {\n if (selectivePermission != null && !selectivePermission.isEmpty()) {\n if (sender.hasPermission(selectivePermission)) {\n return true;\n }\n }\n }\n return false;\n }\n }\n\n\n private boolean isAdapt(CommandContainer container, CommandSender sender) {\n return container.getExecutorType().isInstance(sender);\n }\n\n @Override\n public @Nullable List onTabComplete(\n @NotNull CommandSender sender,\n @NotNull Command command,\n @NotNull String commandLabel,\n @NotNull String[] cmdArg) {\n if (cmdArg.length <= 1) {\n //If no args or one args passed, return the sub command list matching\n final List candidate = new ArrayList<>();\n String firstArg = cmdArg.length > 0 ? cmdArg[0] : \"\";\n for (CommandContainer container : cmds) {\n if (!container.getPrefix().startsWith(firstArg)) {\n continue;\n }\n\n final List requirePermissions = container.getPermissions();\n final List selectivePermissions = container.getSelectivePermissions();\n if (!checkPermissions(sender, commandLabel, EMPTY_ARGS, requirePermissions, PermissionType.REQUIRE, Action.TAB_COMPLETE)) {\n continue;\n }\n if (!checkPermissions(sender, commandLabel, EMPTY_ARGS, selectivePermissions, PermissionType.SELECTIVE, Action.TAB_COMPLETE)) {\n continue;\n }\n if (!container.isHidden() && !(container.isDisabled() || (container.getDisabledSupplier() != null && container.getDisabledSupplier().get()))) {\n candidate.add(container.getPrefix());\n }\n }\n return candidate;\n } else {\n // If two args passed, tab-completing the subcommand args\n String[] passThroughArgs = new String[cmdArg.length - 1];\n System.arraycopy(cmdArg, 1, passThroughArgs, 0, passThroughArgs.length);\n for (CommandContainer container : cmds) {\n if (!container.getPrefix().toLowerCase().startsWith(cmdArg[0])) {\n continue;\n }\n if (!isAdapt(container, sender)) {\n return Collections.emptyList();\n }\n List requirePermissions = container.getPermissions();\n List selectivePermissions = container.getSelectivePermissions();\n if (!checkPermissions(sender, commandLabel, passThroughArgs, requirePermissions, PermissionType.REQUIRE, Action.TAB_COMPLETE)) {\n return Collections.emptyList();\n }\n if (!checkPermissions(sender, commandLabel, passThroughArgs, selectivePermissions, PermissionType.SELECTIVE, Action.TAB_COMPLETE)) {\n return Collections.emptyList();\n }\n return container.getExecutor().onTabComplete(capture(sender), commandLabel, passThroughArgs);\n\n }\n return Collections.emptyList();\n }\n }\n\n private enum Action {\n EXECUTE(\"execute\"),\n TAB_COMPLETE(\"tab-complete\");\n final String name;\n\n Action(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n }\n\n enum PermissionType {\n REQUIRE,\n SELECTIVE\n }\n}\n\nsrc/main/java/com/ghostchu/plugins/dodosrv/util/JsonUtil.java\npublic final class JsonUtil {\n private static final Gson STANDARD_GSON = new GsonBuilder()\n .enableComplexMapKeySerialization()\n .setExclusionStrategies(new HiddenAnnotationExclusionStrategy())\n .serializeNulls()\n .disableHtmlEscaping()\n .create();\n\n private static final Gson PRETTY_PRINT_GSON = new GsonBuilder()\n .enableComplexMapKeySerialization()\n .setExclusionStrategies(new HiddenAnnotationExclusionStrategy())\n .serializeNulls()\n .disableHtmlEscaping()\n .setPrettyPrinting()\n .create();\n\n @NotNull\n @Deprecated\n public static Gson get() {\n return standard();\n }\n\n @NotNull\n public static Gson standard() {\n return STANDARD_GSON;\n }\n\n public static Gson getGson() {\n return STANDARD_GSON;\n }\n\n @NotNull\n @Deprecated\n public static Gson getPrettyPrinting() {\n return prettyPrinting();\n }\n\n @NotNull\n public static Gson prettyPrinting() {\n return PRETTY_PRINT_GSON;\n }\n\n @NotNull\n public static JsonObject readObject(@NotNull Reader reader) {\n return JsonParser.parseReader(reader).getAsJsonObject();\n }\n\n @NotNull\n public static JsonObject readObject(@NotNull String s) {\n return JsonParser.parseString(s).getAsJsonObject();\n }\n\n @NotNull\n public static JsonArray readArray(@NotNull String s) {\n return JsonParser.parseString(s).getAsJsonArray();\n }\n @NotNull\n public static JsonArray readArray(@NotNull Reader reader) {\n return JsonParser.parseReader(reader).getAsJsonArray();\n }\n public static Gson regular() {\n return STANDARD_GSON;\n }\n public static boolean isJson(String str) {\n if (str == null || str.isBlank()) {\n return false;\n }\n try {\n JsonElement element = JsonParser.parseString(str);\n return element.isJsonObject() || element.isJsonArray();\n } catch (JsonParseException exception) {\n return false;\n }\n }\n @NotNull\n public static String toString(@NotNull JsonElement element) {\n return Objects.requireNonNull(standard().toJson(element));\n }\n\n @NotNull\n public static String toStringPretty(@NotNull JsonElement element) {\n return Objects.requireNonNull(prettyPrinting().toJson(element));\n }\n\n public static void writeElement(@NotNull Appendable writer, @NotNull JsonElement element) {\n standard().toJson(element, writer);\n }\n\n public static void writeElementPretty(@NotNull Appendable writer, @NotNull JsonElement element) {\n prettyPrinting().toJson(element, writer);\n }\n\n public static void writeObject(@NotNull Appendable writer, @NotNull JsonObject object) {\n standard().toJson(object, writer);\n }\n\n public static void writeObjectPretty(@NotNull Appendable writer, @NotNull JsonObject object) {\n prettyPrinting().toJson(object, writer);\n }\n\n public @interface Hidden {\n\n }\n\n public static class HiddenAnnotationExclusionStrategy implements ExclusionStrategy {\n @Override\n public boolean shouldSkipField(FieldAttributes f) {\n return f.getAnnotation(Hidden.class) != null;\n }\n\n @Override\n public boolean shouldSkipClass(Class clazz) {\n return clazz.getDeclaredAnnotation(Hidden.class) != null;\n }\n }\n\n}\n\nsrc/main/java/com/ghostchu/plugins/dodosrv/listener/bukkit/BukkitListener.java\npublic class BukkitListener implements Listener {\n private final DoDoSRV plugin;\n private String requriedPrefix;\n\n public BukkitListener(DoDoSRV plugin) {\n this.plugin = plugin;\n init();\n }\n\n private void init() {\n requriedPrefix = plugin.getConfig().getString(\"feature.minecraft-to-dodo.enable.require-prefix\");\n if (StringUtils.isBlank(requriedPrefix)) requriedPrefix = null;\n plugin.getLogger().info(\"Bukkit Listener Registered\");\n }\n\n private String getAvatarLink(UUID uuid) {\n return Util.fillArgs(plugin.getConfig().getString(\"avatar-url\"), uuid.toString(), \"512\");\n }\n\n private boolean allowForward(@NotNull String key) {\n return plugin.getConfig().getBoolean(\"feature.minecraft-to-dodo.forward.\" + key, false);\n\n }\n\n @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)\n public void onJoin(PlayerJoinEvent event) {\n if (!allowForward(\"join\")) {\n return;\n }\n String message = plugin.text().of(\"player-join-message\",\n event.getPlayer().getDisplayName(), getAvatarLink(event.getPlayer().getUniqueId())).plain();\n plugin.sendMessageToDefChannel(message);\n }\n\n @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)\n public void onQuit(PlayerQuitEvent event) {\n if (!allowForward(\"quit\")) {\n return;\n }\n String message = plugin.text().of(\"player-quit-message\", event.getPlayer().getDisplayName(),\n getAvatarLink(event.getPlayer().getUniqueId())).plain();\n plugin.sendMessageToDefChannel(message);\n }\n\n @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)\n public void onDeath(PlayerDeathEvent event) {\n if (!allowForward(\"death\")) {\n return;\n }\n Location loc = event.getEntity().getLocation();\n String msg = plugin.text().of(\"player-death-message\",\n event.getEntity().getDisplayName(),\n event.getDeathMessage(),\n loc.getWorld().getName() + \" \" + loc.getBlockX() + \", \" + loc.getBlockY() + \", \" + loc.getBlockZ(),\n event.getDrops().size(),\n event.getDroppedExp(),\n getAvatarLink(event.getEntity().getUniqueId())\n ).plain();\n plugin.sendMessageToDefChannel(msg);\n }\n\n @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)\n public void onAdvancementEvent(PlayerAdvancementDoneEvent event) {\n if (!allowForward(\"advancement\")) {\n return;\n }\n AdvancementDisplay display = event.getAdvancement().getDisplay();\n if (display == null) return;\n if (!display.shouldShowToast()) return;\n if (!display.shouldAnnounceChat()) return;\n\n// String title = switch (display.getType()) {\n// case TASK, GOAL -> \"(font)\" + display.getTitle() + \"(font)\" + \"[success]\";\n// case CHALLENGE -> \"(font)\" + display.getTitle() + \"(font)\" + \"[purple]\";\n// };\n String title = display.getTitle();\n String description = display.getDescription();\n\n String type = plugin.text().of(\"advancement-message.\" + display.getType().name()).plain();\n\n String msg = plugin.text().of(\"player-unlock-advancement-message\",\n event.getPlayer().getDisplayName(),\n type,\n title,\n description,\n getAvatarLink(event.getPlayer().getUniqueId())).plain();\n plugin.sendMessageToDefChannel(msg);\n }\n\n @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)\n public void onChat(AsyncPlayerChatEvent event) {\n if (!allowForward(\"chat\")) {\n return;\n }\n if (requriedPrefix != null) {\n if (!event.getMessage().startsWith(requriedPrefix)) {\n return;\n }\n }\n plugin.sendMessageToDefChannel(plain(plugin.text().of(\"minecraft-to-dodo-format\", event.getPlayer().getDisplayName(), event.getMessage()).component()));\n }\n\n private String plain(Component component) {\n return PlainTextComponentSerializer.plainText().serialize(component);\n }\n}\n\nsrc/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/CommandManager.java\npublic interface CommandManager{\n /**\n * This is a interface to allow addons to register the subcommand into quickshop command manager.\n *\n * @param container The command container to register\n * @throws IllegalStateException Will throw the error if register conflict.\n */\n void registerCmd(@NotNull CommandContainer container);\n\n /**\n * This is a interface to allow addons to unregister the registered/butil-in subcommand from command manager.\n *\n * @param container The command container to unregister\n */\n void unregisterCmd(@NotNull CommandContainer container);\n\n /**\n * Gets a list contains all registered commands\n *\n * @return All registered commands.\n */\n @NotNull List getRegisteredCommands();\n\n boolean onCommand(\n @NotNull CommandSender sender,\n @NotNull Command command,\n @NotNull String commandLabel,\n @NotNull String[] cmdArg);\n\n @Nullable List onTabComplete(\n @NotNull CommandSender sender,\n @NotNull Command command,\n @NotNull String commandLabel,\n @NotNull String[] cmdArg);\n}", "answers": [" this.commandManager = new SimpleCommandManager(this);"], "length": 1503, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "fbcda739-0832-414c-a63d-9380ce89ccd9", "reasoning": "In DoDoSRV.onEnable(), after initializing dodoManager the next logical step is to set up the command manager field. The class has a private SimpleCommandManager commandManager; and SimpleCommandManager is imported. So the next line should assign a new SimpleCommandManager instance with this plugin.", "reasoning_model_answer": "this.commandManager = new SimpleCommandManager(this);", "assistant_with_reasoning": "\nIn DoDoSRV.onEnable(), after initializing dodoManager the next logical step is to set up the command manager field. The class has a private SimpleCommandManager commandManager; and SimpleCommandManager is imported. So the next line should assign a new SimpleCommandManager instance with this plugin.\n\nthis.commandManager = new SimpleCommandManager(this);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.32, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 21424, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "this.commandManager = new SimpleCommandManager(this);", "score": 0.93, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Random;\nimport routing.util.EnergyModel;\nimport routing.util.MessageTransferAcceptPolicy;\nimport routing.util.RoutingInfo;\nimport util.Tuple;\nimport core.Connection;\nimport core.DTNHost;\nimport core.Message;\nimport core.MessageListener;\nimport core.NetworkInterface;\nimport core.Settings;\nimport core.SimClock;", "context": "src/routing/ActiveRouter.java\n/*\n * Copyright 2010 Aalto University, ComNet\n * Released under GPLv3. See LICENSE.txt for details.\n */\npackage routing;\n\n\n\n\n/**\n * Superclass of active routers. Contains convenience methods (e.g.\n * {@link #getNextMessageToRemove(boolean)}) and watching of sending connections (see\n * {@link #update()}).\n */\npublic abstract class ActiveRouter extends MessageRouter {\n\t/** Delete delivered messages -setting id ({@value}). Boolean valued.\n\t * If set to true and final recipient of a message rejects it because it\n\t * already has it, the message is deleted from buffer. Default=false. */\n\tpublic static final String DELETE_DELIVERED_S = \"deleteDelivered\";\n\t/** should messages that final recipient marks as delivered be deleted\n\t * from message buffer */\n\tprotected boolean deleteDelivered;\n\n\t/** prefix of all response message IDs */\n\tpublic static final String RESPONSE_PREFIX = \"R_\";\n\t/** how often TTL check (discarding old messages) is performed */\n\tpublic static int TTL_CHECK_INTERVAL = 60;\n\t/** connection(s) that are currently used for sending */\n\tprotected ArrayList sendingConnections;\n\t/** sim time when the last TTL check was done */\n\tprivate double lastTtlCheck;\n\n\tprivate MessageTransferAcceptPolicy policy;\n\tprivate EnergyModel energy;\n\n\t/**\n\t * Constructor. Creates a new message router based on the settings in\n\t * the given Settings object.\n\t * @param s The settings object\n\t */\n\tpublic ActiveRouter(Settings s) {\n\t\tsuper(s);\n\n\t\tthis.policy = new MessageTransferAcceptPolicy(s);\n\n\t\tthis.deleteDelivered = s.getBoolean(DELETE_DELIVERED_S, false);\n\n\t\tif (s.contains(EnergyModel.INIT_ENERGY_S)) {\n\t\t\tthis.energy = new EnergyModel(s);\n\t\t} else {\n\t\t\tthis.energy = null; /* no energy model */\n\t\t}\n\t}\n\n\t/**\n\t * Copy constructor.\n\t * @param r The router prototype where setting values are copied from\n\t */\n\tprotected ActiveRouter(ActiveRouter r) {\n\t\tsuper(r);\n\t\tthis.deleteDelivered = r.deleteDelivered;\n\t\tthis.policy = r.policy;\n\t\tthis.energy = (r.energy != null ? r.energy.replicate() : null);\n\t}\n\n\t@Override\n\tpublic void init(DTNHost host, List mListeners) {\n\t\tsuper.init(host, mListeners);\n\t\tthis.sendingConnections = new ArrayList(1);\n\t\tthis.lastTtlCheck = 0;\n\t}\n\n\t/**\n\t * Called when a connection's state changes. If energy modeling is enabled,\n\t * and a new connection is created to this node, reduces the energy for the\n\t * device discovery (scan response) amount\n\t * @param con The connection whose state changed\n\t */\n\t@Override\n\tpublic void changedConnection(Connection con) {\n\t\tif (this.energy != null && con.isUp() && !con.isInitiator(getHost())) {\n\t\t\tthis.energy.reduceDiscoveryEnergy();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean requestDeliverableMessages(Connection con) {\n\t\tif (isTransferring()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tDTNHost other = con.getOtherNode(getHost());\n\t\t/* do a copy to avoid concurrent modification exceptions\n\t\t * (startTransfer may remove messages) */\n\t\tArrayList temp =\n\t\t\tnew ArrayList(this.getMessageCollection());\n\t\tfor (Message m : temp) {\n\t\t\tif (other == m.getTo()) {\n\t\t\t\tif (startTransfer(m, con) == RCV_OK) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean createNewMessage(Message m) {\n\t\tmakeRoomForNewMessage(m.getSize());\n\t\treturn super.createNewMessage(m);\n\t}\n\n\t@Override\n\tpublic int receiveMessage(Message m, DTNHost from) {\n\t\tint recvCheck = checkReceiving(m, from);\n\t\tif (recvCheck != RCV_OK) {\n\t\t\treturn recvCheck;\n\t\t}\n\n\t\t// seems OK, start receiving the message\n\t\treturn super.receiveMessage(m, from);\n\t}\n\n\t@Override\n\tpublic Message messageTransferred(String id, DTNHost from) {\n\t\tMessage m = super.messageTransferred(id, from);\n\n\t\t/**\n\t\t * N.B. With application support the following if-block\n\t\t * becomes obsolete, and the response size should be configured\n\t\t * to zero.\n\t\t */\n\t\t// check if msg was for this host and a response was requested\n\nsrc/routing/util/MessageTransferAcceptPolicy.java\npublic class MessageTransferAcceptPolicy {\n\n\t/** Namespace for all \"Message Transfer Accept policy\" settings ({@value})*/\n\tpublic static final String MTA_POLICY_NS = \"mtaPolicy\";\n\n\t/** Number of Module Communication Bus Conditions -setting id ({@value}).\n\t * Two comma separated values. Defines the number of receiving and number of\n\t * sending conditions to read from the settings. */\n\tpublic static final String NROF_MCBCS_S = \"nrofMCBACs\";\n\n\t/** Module Communication Bus Arithmetic Condition for Receiving -setting id\n\t * ({@value}). {@link ArithmeticCondition}. Defines one arithmetic condition\n\t * to use for receiving messages. */\n\tpublic static final String MCBACR_S = \"MCBRcondition\";\n\t/** Module Communication Bus Arithmetic Condition for Sending -setting id\n\t * ({@value}). {@link ArithmeticCondition}. */\n\tpublic static final String MCBACS_S = \"MCBScondition\";\n\n\t/** Module Communication Bus Condition Value for Receiving -setting id\n\t * ({@value}). String. Defines the ID to use with the receiving\n\t * condition. */\n\tpublic static final String MCBCVR_S = \"MCBRvalue\";\n\t/** Module Communication Bus Condition Value for Sending -setting id\n\t * ({@value}). String. Defines the ID to use with the sending\n\t * condition. */\n\tpublic static final String MCBCVS_S = \"MCBSvalue\";\n\n\t/** The valued used in to-policy to refer to this host ({@value}) */\n\tpublic static final int TO_ME_VALUE = -1;\n\n\t/** Simple-policy accept-to -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the destination of a\n\t * message when receiving messages. Special value {@link #TO_ME_VALUE}\n\t * refers to this host. */\n\tpublic static final String TO_RPOLICY_S = \"toReceivePolicy\";\n\n\t/** Simple-policy accept-from -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the source of a\n\t * message when receiving messages. Special value {@link #TO_ME_VALUE}\n\t * refers to this host. */\n\tpublic static final String FROM_RPOLICY_S = \"fromReceivePolicy\";\n\n\t/** Simple-policy accept-to -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the destination of a\n\t * message when sending messages. Special value {@link #TO_ME_VALUE} refers\n\t * to this host (but doesn't usually make much sense here). */\n\tpublic static final String TO_SPOLICY_S = \"toSendPolicy\";\n\n\t/**

Simple-policy accept-from -setting id ({@value}). Integer list.\n\t * Defines the addresses of the hosts accepted as the source of a\n\t * message when sending messages. Special value {@link #TO_ME_VALUE} refers\n\t * to this host.

\n\t *

Note: if this setting is defined and the {@link #TO_ME_VALUE}\n\t * is NOT listed, the hosts own messages are not sent anywhere.

*/\n\tpublic static final String FROM_SPOLICY_S = \"fromSendPolicy\";\n\n\t/** Hop count forwarding receive policy -setting id ({@value}).\n\t * {@link ArithmeticCondition}. Defines condition for the message hop\n\t * count; if the condition does not match, the message is rejected,\n\t * unless it is destined to this node. */\n\tpublic static final String HOPCOUNT_RPOLICY_S = \"hopCountReceivePolicy\";\n\t/** Hop count forwarding send policy -setting id ({@value}).\n\t * {@link ArithmeticCondition}. Defines condition for the message hop\n\t * count; if the condition does not match, the message is not offered\n\t * to other nodes, unless it would be delivered to the final destination. */\n\tpublic static final String HOPCOUNT_SPOLICY_S = \"hopCountSendPolicy\";\n\n\tprivate ArrayList> recvConditions = null;\n\tprivate ArrayList> sendConditions = null;\n\n\tprivate Range[] toSendPolicy = null;\n\tprivate Range[] fromSendPolicy = null;\n\tprivate Range[] toReceivePolicy = null;\n\tprivate Range[] fromReceivePolicy = null;\n\tprivate ArithmeticCondition hopCountSendPolicy = null;\n\tprivate ArithmeticCondition hopCountReceivePolicy = null;\n\n\tpublic MessageTransferAcceptPolicy(Settings nsSettings) {\n\t\tSettings s;\n\n\t\tif (! nsSettings.contains(MTA_POLICY_NS)) {\n\t\t\treturn; /* no (or \"default\") policy */\n\t\t}\n\n\t\ts = new Settings(nsSettings.getSetting(MTA_POLICY_NS));\n\t\taddMCBCs(s);\n\n\t\tif (s.contains(TO_SPOLICY_S)) {\n\t\t\tthis.toSendPolicy = s.getCsvRanges(TO_SPOLICY_S);\n\t\t}\n\t\tif (s.contains(FROM_SPOLICY_S)) {\n\t\t\tthis.fromSendPolicy = s.getCsvRanges(FROM_SPOLICY_S);\n\t\t}\n\t\tif (s.contains(TO_RPOLICY_S)) {\n\t\t\tthis.toReceivePolicy = s.getCsvRanges(TO_RPOLICY_S);\n\t\t}\n\t\tif (s.contains(FROM_RPOLICY_S)) {\n\t\t\tthis.fromReceivePolicy = s.getCsvRanges(FROM_RPOLICY_S);\n\t\t}\n\t\tif (s.contains(HOPCOUNT_SPOLICY_S)) {\n\t\t\thopCountSendPolicy = s.getCondition(HOPCOUNT_SPOLICY_S);\n\t\t}\n\t\tif (s.contains(HOPCOUNT_RPOLICY_S)) {\n\t\t\thopCountReceivePolicy = s.getCondition(HOPCOUNT_RPOLICY_S);\n\t\t}\n\t}\n\n\t/**\n\t * Adds MessageCommunicationBus Conditions\n\t * @param s Settings where the conditions are read from\n\t */\n\tprivate void addMCBCs(Settings s) {\n\t\tif (!s.contains(NROF_MCBCS_S)) {\n\t\t\treturn; /* no transfer policy defined */\n\t\t}\n\n\t\tint[] nrof = s.getCsvInts(NROF_MCBCS_S);\n\t\tif (nrof[0] > 0) { /* create lists only if needed */\n\t\t\tthis.recvConditions =\n\t\t\t\tnew ArrayList>();\n\t\t}\n\t\tif (nrof[1] > 0) {\n\t\t\tthis.sendConditions =\n\t\t\t\tnew ArrayList>();\n\t\t}\n\n\t\taddConditions(s, MCBACR_S, MCBCVR_S, this.recvConditions, nrof[0]);\n\t\taddConditions(s, MCBACS_S, MCBCVS_S, this.sendConditions, nrof[1]);\n\t}\n\n\t/**\n\t * Read conditions from the settings and add them to the given list\n\t * @param s The settings object\n\t * @param cPrefix Condition setting prefix\n\t * @param vPrefix Value setting prefix\n\t * @param list The list to add conditions\n\t * @param nrof The number of settings to read\n\t */\n\tprivate void addConditions(Settings s, String cPrefix, String vPrefix,\n\t\t\tArrayList> list,\n\t\t\tint nrof) {\n\t\tfor (int i=1; i<=nrof; i++) {\n\t\t\tArithmeticCondition ac = s.getCondition(cPrefix + i);\n\t\t\tString mcbValue = s.getSetting(vPrefix + i);\n\t\t\tlist.add(new Tuple(mcbValue, ac));\n\t\t}\n\t}\n\n\t/**\n\t * Checks all the Module Communication Bus conditions and returns false\n\t * if at least one of them failed.\n\t * @param mcb The module communication bus to use\n\t * @param receiving Should check using the receiving conditions list;\n\t * if false, the sending conditions list is used\n\t * @return true if all conditions evaluated to true\n\t */\n\tprivate boolean checkMcbConditions(ModuleCommunicationBus mcb,\n\t\t\tboolean receiving) {\n\t\tArrayList> list =\n\t\t\t(receiving ? this.recvConditions : this.sendConditions);\n\n\t\tif (list == null) {\n\t\t\treturn true;\n\t\t}\n\n\t\tfor (Tuple t : list) {\n\t\t\tif (!mcb.containsProperty(t.getKey())) {\n\t\t\t\tcontinue; /* no value in the bus; can't fail condition */\n\t\t\t}\n\t\t\tif (t.getValue().isTrueFor(mcb.getDouble(t.getKey(), 0))){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if the host's address is contained in the policy list\n\t * (or {@value #TO_ME_VALUE} is contained and the address matches to\n\t * thisHost parameter)\n\t * @param host The hosts whose address to check\n\t * @param policy The list of accepted addresses\n\t * @param thisHost The address of this host\n\t * @return True if the address was in the policy list, or the policy list\n\t * was null\n\t */\n\tprivate boolean checkSimplePolicy(DTNHost host, Range [] policy,\n\t\t\tint thisHost) {\n\t\tint address;\n\n\t\tif (policy == null) {\n\t\t\treturn true;\n\t\t}\n\n\t\taddress = host.getID();\n\n\t\tfor (Range r : policy) {\n\t\t\tif (r.isInRange(TO_ME_VALUE) && address == thisHost) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t else if (r.isInRange(address)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks the given messages hop count against the given policy arithmetic\n\t * condition\n\t * @param m The message whose hop count is checked\n\t * @param ac The policy arithmetic condition\n\t * @return True if the condition is null or the hop count matches to the\n\t * condition, false otherwise\n\t */\n\tprivate boolean checkHopCountPolicy(Message m, ArithmeticCondition ac) {\n\t\tif (ac == null) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn ac.isTrueFor(m.getHopCount());\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if the given message, using the given connection, is OK\n\t * to send from \"from\" to \"to\" host.\n\t * @param from The sending host\n\t * @param to The receiving host\n\t * @param con The connection used by the hosts\n\t * @param m The message to transfer\n\t * @return True if the message is OK to transfer, false is not\n\t */\n\tpublic boolean acceptSending(DTNHost from, DTNHost to, Connection con,\n\t\t\tMessage m) {\n\t\tif (!checkMcbConditions(from.getComBus(), false)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tint myAddr = from.getID();\n\t\tif (! (checkSimplePolicy(m.getTo(), this.toSendPolicy, myAddr) &&\n\t\t\tcheckSimplePolicy(m.getFrom(), this.fromSendPolicy,\tmyAddr)) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m.getTo() != to &&\n\t\t\t\t!checkHopCountPolicy(m, this.hopCountSendPolicy)){\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns true if the given message is OK to receive from \"from\" to\n\t * \"to\" host.\n\t * @param from The sending host\n\t * @param to The receiving host\n\t * @param m The message to transfer\n\t * @return True if the message is OK to transfer, false is not\n\t */\n\tpublic boolean acceptReceiving(DTNHost from, DTNHost to, Message m) {\n\t\tif (! checkMcbConditions(to.getComBus(), true)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tint myAddr = to.getID();\n\t\tif (! (checkSimplePolicy(m.getTo(), this.toReceivePolicy,myAddr) &&\n\t\t\tcheckSimplePolicy(m.getFrom(), this.fromReceivePolicy, myAddr)) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m.getTo() != to &&\n\t\t\t\t!checkHopCountPolicy(m, this.hopCountReceivePolicy)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n}", "answers": ["\t\tif (m.getTo() == getHost() && m.getResponseSize() > 0) {"], "length": 1824, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "5b5c4ed4-5517-4774-ab9d-0a9a2eb45f24", "reasoning": "In ActiveRouter.messageTransferred, after the comment about checking if the message was for this host and a response was requested, the next logical step is to test those conditions. The code should verify that the message's destination is the current host and that a response size is specified (>0). This is done with an if statement comparing m.getTo() to getHost() and checking m.getResponseSize(). Hence the next line is the if condition.", "reasoning_model_answer": "if (m.getTo() == getHost() && m.getResponseSize() > 0) {", "assistant_with_reasoning": "\nIn ActiveRouter.messageTransferred, after the comment about checking if the message was for this host and a response was requested, the next logical step is to test those conditions. The code should verify that the message's destination is the current host and that a response size is specified (>0). This is done with an if statement comparing m.getTo() to getHost() and checking m.getResponseSize(). Hence the next line is the if condition.\n\nif (m.getTo() == getHost() && m.getResponseSize() > 0) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 7.633, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14187, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "if (m.getTo() == getHost() && m.getResponseSize() > 0) {", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.io.IOException;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PutMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.multipart.MultipartFile;\nimport com.nhXJH.common.annotation.Log;\nimport com.nhXJH.common.config.LibraryMSConfig;\nimport com.nhXJH.common.constant.UserConstants;\nimport com.nhXJH.common.core.controller.BaseController;\nimport com.nhXJH.common.core.domain.AjaxResult;\nimport com.nhXJH.common.core.domain.entity.SysUser;\nimport com.nhXJH.common.core.domain.model.LoginUser;\nimport com.nhXJH.common.enums.BusinessType;\nimport com.nhXJH.common.utils.SecurityUtils;\nimport com.nhXJH.common.utils.StringUtils;\nimport com.nhXJH.common.utils.file.FileUploadUtils;\nimport com.nhXJH.framework.web.service.TokenService;\nimport com.nhXJH.system.service.ISysUserService;", "context": "nhXJH-admin/src/main/java/com/nhXJH/web/controller/system/SysProfileController.java\npackage com.nhXJH.web.controller.system;\n\n\n/**\n * 个人信息 业务处理\n * \n * @author nhXJH\n */\n@RestController\n@RequestMapping(\"/system/user/profile\")\npublic class SysProfileController extends BaseController {\n @Autowired\n private ISysUserService userService;\n\n @Autowired\n private TokenService tokenService;\n\n /**\n * 个人信息\n */\n @GetMapping\n public AjaxResult profile() {\n LoginUser loginUser = getLoginUser();\n SysUser user = loginUser.getUser();\n AjaxResult ajax = AjaxResult.success(user);\n ajax.put(\"roleGroup\", userService.selectUserRoleGroup(loginUser.getUsername()));\n ajax.put(\"postGroup\", userService.selectUserPostGroup(loginUser.getUsername()));\n return ajax;\n }\n\n /**\n * 修改用户\n */\n @Log(title = \"个人信息\", businessType = BusinessType.UPDATE)\n @PutMapping\n public AjaxResult updateProfile(@RequestBody SysUser user) {\n LoginUser loginUser = getLoginUser();\n SysUser sysUser = loginUser.getUser();\n user.setUserName(sysUser.getUserName());\n if (StringUtils.isNotEmpty(user.getPhonenumber())\n\nnhXJH-common/src/main/java/com/nhXJH/common/core/controller/BaseController.java\npublic class BaseController {\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @InitBinder\n public void initBinder(WebDataBinder binder) {\n // Date 类型转换\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {\n @Override\n public void setAsText(String text) {\n setValue(DateUtils.parseDate(text));\n }\n });\n }\n\n /**\n * 设置请求分页数据\n */\n protected void startPage() {\n PageUtils.startPage();\n }\n\n /**\n * 设置请求排序数据\n */\n protected void startOrderBy() {\n PageDomain pageDomain = TableSupport.buildPageRequest();\n if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {\n String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());\n PageHelper.orderBy(orderBy);\n }\n }\n\n /**\n * 响应请求分页数据\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n protected TableDataInfo getDataTable(List list) {\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(HttpStatus.SUCCESS);\n rspData.setMsg(\"查询成功\");\n rspData.setRows(list);\n rspData.setTotal((int) new PageInfo(list).getTotal());\n return rspData;\n }\n\n /**\n * 返回成功\n */\n public AjaxResult success() {\n return AjaxResult.success();\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error() {\n return AjaxResult.error();\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(String message) {\n return AjaxResult.success(message);\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error(String message) {\n return AjaxResult.error(message);\n }\n\n /**\n * 响应返回结果\n * \n * @param rows 影响行数\n * @return 操作结果\n */\n protected AjaxResult toAjax(int rows) {\n return rows > 0 ? AjaxResult.success() : AjaxResult.error();\n }\n\n /**\n * 响应返回结果\n * \n * @param result 结果\n * @return 操作结果\n */\n protected AjaxResult toAjax(boolean result) {\n return result ? success() : error();\n }\n\n /**\n * 页面跳转\n */\n public String redirect(String url) {\n return StringUtils.format(\"redirect:{}\", url);\n }\n\n /**\n * 获取用户缓存信息\n */\n public LoginUser getLoginUser() {\n return SecurityUtils.getLoginUser();\n }\n\n /**\n * 获取登录用户id\n */\n public Long getUserId() {\n return getLoginUser().getUserId();\n }\n\n /**\n * 获取登录部门id\n */\n public Long getDeptId() {\n return getLoginUser().getDeptId();\n }\n\n /**\n * 获取登录用户名\n */\n public String getUsername() {\n return getLoginUser().getUsername();\n }\n}\n\nnhXJH-common/src/main/java/com/nhXJH/common/utils/StringUtils.java\npublic class StringUtils extends org.apache.commons.lang3.StringUtils {\n /** 空字符串 */\n private static final String NULLSTR = \"\";\n\n /** 下划线 */\n private static final char SEPARATOR = '_';\n\n /**\n * 获取参数不为空值\n * \n * @param value defaultValue 要判断的value\n * @return value 返回值\n */\n public static T nvl(T value, T defaultValue) {\n return value != null ? value : defaultValue;\n }\n\n /**\n * * 判断一个Collection是否为空, 包含List,Set,Queue\n * \n * @param coll 要判断的Collection\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Collection coll) {\n return isNull(coll) || coll.isEmpty();\n }\n\n /**\n * * 判断一个Collection是否非空,包含List,Set,Queue\n * \n * @param coll 要判断的Collection\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Collection coll) {\n return !isEmpty(coll);\n }\n\n /**\n * * 判断一个对象数组是否为空\n * \n * @param objects 要判断的对象数组\n ** @return true:为空 false:非空\n */\n public static boolean isEmpty(Object[] objects) {\n return isNull(objects) || (objects.length == 0);\n }\n\n /**\n * * 判断一个对象数组是否非空\n * \n * @param objects 要判断的对象数组\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Object[] objects) {\n return !isEmpty(objects);\n }\n\n /**\n * * 判断一个Map是否为空\n * \n * @param map 要判断的Map\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Map map) {\n return isNull(map) || map.isEmpty();\n }\n\n /**\n * * 判断一个Map是否为空\n * \n * @param map 要判断的Map\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Map map) {\n return !isEmpty(map);\n }\n\n /**\n * * 判断一个字符串是否为空串\n * \n * @param str String\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(String str) {\n return isNull(str) || NULLSTR.equals(str.trim());\n }\n\n /**\n * * 判断一个字符串是否为非空串\n * \n * @param str String\n * @return true:非空串 false:空串\n */\n public static boolean isNotEmpty(String str) {\n return !isEmpty(str);\n }\n\n /**\n * * 判断一个对象是否为空\n * \n * @param object Object\n * @return true:为空 false:非空\n */\n public static boolean isNull(Object object) {\n return object == null;\n }\n\n /**\n * * 判断一个对象是否非空\n * \n * @param object Object\n * @return true:非空 false:空\n */\n public static boolean isNotNull(Object object) {\n return !isNull(object);\n }\n\n /**\n * * 判断一个对象是否是数组类型(Java基本型别的数组)\n * \n * @param object 对象\n * @return true:是数组 false:不是数组\n */\n public static boolean isArray(Object object) {\n return isNotNull(object) && object.getClass().isArray();\n }\n\n /**\n * 去空格\n */\n public static String trim(String str) {\n return (str == null ? \"\" : str.trim());\n }\n\n /**\n * 截取字符串\n * \n * @param str 字符串\n * @param start 开始\n * @return 结果\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return NULLSTR;\n }\n\n if (start < 0) {\n start = str.length() + start;\n }\n\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return NULLSTR;\n }\n\n return str.substring(start);\n }\n\n /**\n * 截取字符串\n * \n * @param str 字符串\n * @param start 开始\n * @param end 结束\n * @return 结果\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return NULLSTR;\n }\n\n if (end < 0) {\n end = str.length() + end;\n }\n if (start < 0) {\n start = str.length() + start;\n }\n\n if (end > str.length()) {\n end = str.length();\n }\n\n if (start > end) {\n return NULLSTR;\n }\n\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n\n return str.substring(start, end);\n }\n\n /**\n * 格式化文本, {} 表示占位符
\n * 此方法只是简单将占位符 {} 按照顺序替换为参数
\n * 如果想输出 {} 使用 \\\\转义 { 即可,如果想输出 {} 之前的 \\ 使用双转义符 \\\\\\\\ 即可
\n * 例:
\n * 通常使用:format(\"this is {} for {}\", \"a\", \"b\") -> this is a for b
\n * 转义{}: format(\"this is \\\\{} for {}\", \"a\", \"b\") -> this is \\{} for a
\n * 转义\\: format(\"this is \\\\\\\\{} for {}\", \"a\", \"b\") -> this is \\a for b
\n * \n * @param template 文本模板,被替换的部分用 {} 表示\n * @param params 参数值\n * @return 格式化后的文本\n */\n public static String format(String template, Object... params) {\n if (isEmpty(params) || isEmpty(template)) {\n return template;\n }\n return StrFormatter.format(template, params);\n }\n\n /**\n * 是否为http(s)://开头\n * \n * @param link 链接\n * @return 结果\n */\n public static boolean ishttp(String link) {\n return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);\n }\n\n /**\n * 字符串转set\n * \n * @param str 字符串\n * @param sep 分隔符\n * @return set集合\n */\n public static final Set str2Set(String str, String sep) {\n return new HashSet(str2List(str, sep, true, false));\n }\n\n /**\n * 字符串转list\n * \n * @param str 字符串\n * @param sep 分隔符\n * @param filterBlank 过滤纯空白\n * @param trim 去掉首尾空白\n * @return list集合\n */\n public static final List str2List(String str, String sep, boolean filterBlank, boolean trim) {\n List list = new ArrayList();\n if (StringUtils.isEmpty(str)) {\n return list;\n }\n\n // 过滤空白字符串\n if (filterBlank && StringUtils.isBlank(str)) {\n return list;\n }\n String[] split = str.split(sep);\n for (String string : split) {\n if (filterBlank && StringUtils.isBlank(string)) {\n continue;\n }\n if (trim) {\n string = string.trim();\n }\n list.add(string);\n }\n\n return list;\n }\n\n /**\n * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写\n *\n * @param cs 指定字符串\n * @param searchCharSequences 需要检查的字符串数组\n * @return 是否包含任意一个字符串\n */\n public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {\n if (isEmpty(cs) || isEmpty(searchCharSequences)) {\n return false;\n }\n for (CharSequence testStr : searchCharSequences) {\n if (containsIgnoreCase(cs, testStr)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 驼峰转下划线命名\n */\n public static String toUnderScoreCase(String str) {\n if (str == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n // 前置字符是否大写\n boolean preCharIsUpperCase = true;\n // 当前字符是否大写\n boolean curreCharIsUpperCase = true;\n // 下一字符是否大写\n boolean nexteCharIsUpperCase = true;\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (i > 0) {\n preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));\n }\n else {\n preCharIsUpperCase = false;\n }\n\n curreCharIsUpperCase = Character.isUpperCase(c);\n\n if (i < (str.length() - 1)) {\n nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));\n }\n\n if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {\n sb.append(SEPARATOR);\n }\n else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {\n sb.append(SEPARATOR);\n }\n sb.append(Character.toLowerCase(c));\n }\n\n return sb.toString();\n }\n\n /**\n * 是否包含字符串\n * \n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs) {\n if (str != null && strs != null) {\n for (String s : strs) {\n if (str.equalsIgnoreCase(trim(s))) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld\n * \n * @param name 转换前的下划线大写方式命名的字符串\n * @return 转换后的驼峰式命名的字符串\n */\n public static String convertToCamelCase(String name) {\n StringBuilder result = new StringBuilder();\n // 快速检查\n if (name == null || name.isEmpty()) {\n // 没必要转换\n return \"\";\n }\n else if (!name.contains(\"_\")) {\n // 不含下划线,仅将首字母大写\n return name.substring(0, 1).toUpperCase() + name.substring(1);\n }\n // 用下划线将原始字符串分割\n String[] camels = name.split(\"_\");\n for (String camel : camels) {\n // 跳过原始字符串中开头、结尾的下换线或双重下划线\n if (camel.isEmpty()) {\n continue;\n }\n // 首字母大写\n result.append(camel.substring(0, 1).toUpperCase());\n result.append(camel.substring(1).toLowerCase());\n }\n return result.toString();\n }\n\n /**\n * 驼峰式命名法 例如:user_name->userName\n */\n public static String toCamelCase(String s) {\n if (s == null) {\n return null;\n }\n s = s.toLowerCase();\n StringBuilder sb = new StringBuilder(s.length());\n boolean upperCase = false;\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n\n if (c == SEPARATOR) {\n upperCase = true;\n }\n else if (upperCase) {\n sb.append(Character.toUpperCase(c));\n upperCase = false;\n }\n else {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n /**\n * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串\n * \n * @param str 指定字符串\n * @param strs 需要检查的字符串数组\n * @return 是否匹配\n */\n public static boolean matches(String str, List strs) {\n if (isEmpty(str) || isEmpty(strs)) {\n return false;\n }\n for (String pattern : strs) {\n if (isMatch(pattern, str)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断url是否与规则配置: \n * ? 表示单个字符; \n * * 表示一层路径内的任意字符串,不可跨层级; \n * ** 表示任意层路径;\n * \n * @param pattern 匹配规则\n * @param url 需要匹配的url\n * @return\n */\n public static boolean isMatch(String pattern, String url) {\n AntPathMatcher matcher = new AntPathMatcher();\n return matcher.match(pattern, url);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static T cast(Object obj) {\n return (T) obj;\n }\n\n /**\n * 过滤特殊字符\n * */\n public static String stringFilter(String str){\n String regEx=\"[\\\\u00A0\\\\s\\\"`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]\";\n Pattern p = Pattern.compile(regEx);\n Matcher m = p.matcher(str);\n return m.replaceAll(\"\").trim();\n }\n /**\n * 是否包含特殊字符特殊字符\n * */\n public static boolean hasSpecialChar(String str){\n String regEx=\"[\\\\u00A0\\\\s\\\"`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]\";\n Pattern p = Pattern.compile(regEx);\n Matcher m = p.matcher(str);\n return m.find();\n }\n\n public static String replaceBlank(String str) {\n String dest = \"\";\n if (str!=null) {\n Pattern p = Pattern.compile(\"\\\\s{2,}|\\t|\\r|\\n\");\n Matcher m = p.matcher(str);\n dest = m.replaceAll(\"\");\n }\n return dest;\n }\n}", "answers": [" && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {"], "length": 1681, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "c7eca660-40ba-494c-b770-6e15beec2393", "reasoning": "The method updateProfile is checking the new phone number. The current line ends with an open if condition checking that the phone number is not empty. The next line should complete the condition by checking uniqueness via the user service and opening the block. In the typical implementation, it adds the && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { line.", "reasoning_model_answer": "&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {", "assistant_with_reasoning": "\nThe method updateProfile is checking the new phone number. The current line ends with an open if condition checking that the phone number is not empty. The next line should complete the condition by checking uniqueness via the user service and opening the block. In the typical implementation, it adds the && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { line.\n\n&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.192, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17192, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "import itertools\nimport logging\nimport numpy as np\nimport operator\nimport pickle\nimport torch\nimport torch.utils.data as torchdata\nfrom collections import OrderedDict, defaultdict\nfrom typing import Any, Callable, Dict, List, Optional, Union\nfrom tabulate import tabulate\nfrom termcolor import colored\nfrom ..config import configurable\nfrom ..structures import BoxMode\nfrom ..utils.comm import get_world_size\nfrom ..utils.env import seed_all_rng\nfrom ..utils.file_io import PathManager\nfrom ..utils.logger import _log_api_usage, log_first_n\nfrom .catalog import DatasetCatalog, MetadataCatalog\nfrom .common import AspectRatioGroupedDataset, DatasetFromList, MapDataset, ToIterableDataset\nfrom .dataset_mapper import DatasetMapper\nfrom .detection_utils import check_metadata_consistency\nfrom .samplers import (\n InferenceSampler,\n RandomSubsetTrainingSampler,\n RepeatFactorTrainingSampler,\n TrainingSampler,\n)", "context": "nativedancer/third_part/detectron2/data/build.py\n sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces\n indices to be applied on ``dataset``.\n If ``dataset`` is map-style, the default sampler is a :class:`TrainingSampler`,\n which coordinates an infinite random shuffle sequence across all workers.\n Sampler must be None if ``dataset`` is iterable.\n total_batch_size (int): total batch size across all workers.\n aspect_ratio_grouping (bool): whether to group images with similar\n aspect ratio for efficiency. When enabled, it requires each\n element in dataset be a dict with keys \"width\" and \"height\".\n num_workers (int): number of parallel data loading workers\n collate_fn: a function that determines how to do batching, same as the argument of\n `torch.utils.data.DataLoader`. Defaults to do no collation and return a list of\n data. No collation is OK for small batch size and simple data structures.\n If your batch size is large and each sample contains too many small tensors,\n it's more efficient to collate them in data loader.\n\n Returns:\n torch.utils.data.DataLoader:\n a dataloader. Each output from it is a ``list[mapped_element]`` of length\n ``total_batch_size / num_workers``, where ``mapped_element`` is produced\n by the ``mapper``.\n \"\"\"\n if isinstance(dataset, list):\n dataset = DatasetFromList(dataset, copy=False)\n if mapper is not None:\n dataset = MapDataset(dataset, mapper)\n\n if isinstance(dataset, torchdata.IterableDataset):\n assert sampler is None, \"sampler must be None if dataset is IterableDataset\"\n else:\n if sampler is None:\n sampler = TrainingSampler(len(dataset))\n assert isinstance(sampler, torchdata.Sampler), f\"Expect a Sampler but got {type(sampler)}\"\n return build_batch_data_loader(\n dataset,\n sampler,\n total_batch_size,\n aspect_ratio_grouping=aspect_ratio_grouping,\n num_workers=num_workers,\n collate_fn=collate_fn,\n **kwargs\n )\n\n\ndef _test_loader_from_config(cfg, dataset_name, mapper=None):\n \"\"\"\n Uses the given `dataset_name` argument (instead of the names in cfg), because the\n standard practice is to evaluate each test set individually (not combining them).\n \"\"\"\n if isinstance(dataset_name, str):\n dataset_name = [dataset_name]\n\n dataset = get_detection_dataset_dicts(\n dataset_name,\n filter_empty=False,\n proposal_files=[\n cfg.DATASETS.PROPOSAL_FILES_TEST[list(cfg.DATASETS.TEST).index(x)] for x in dataset_name\n ]\n if cfg.MODEL.LOAD_PROPOSALS\n else None,\n )\n if mapper is None:\n mapper = DatasetMapper(cfg, False)\n return {\n \"dataset\": dataset,\n \"mapper\": mapper,\n \"num_workers\": cfg.DATALOADER.NUM_WORKERS,\n \"sampler\": InferenceSampler(len(dataset))\n if not isinstance(dataset, torchdata.IterableDataset)\n else None,\n }\n\n\n@configurable(from_config=_test_loader_from_config)\ndef build_detection_test_loader(\n dataset: Union[List[Any], torchdata.Dataset],\n *,\n mapper: Callable[[Dict[str, Any]], Any],\n sampler: Optional[torchdata.Sampler] = None,\n batch_size: int = 1,\n num_workers: int = 0,\n collate_fn: Optional[Callable[[List[Any]], Any]] = None,\n) -> torchdata.DataLoader:\n \"\"\"\n Similar to `build_detection_train_loader`, with default batch size = 1,\n and sampler = :class:`InferenceSampler`. This sampler coordinates all workers\n to produce the exact set of all samples.\n\n Args:\n dataset: a list of dataset dicts,\n or a pytorch dataset (either map-style or iterable). They can be obtained\n by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`.\n mapper: a callable which takes a sample (dict) from dataset\n and returns the format to be consumed by the model.\n When using cfg, the default choice is ``DatasetMapper(cfg, is_train=False)``.\n sampler: a sampler that produces\n indices to be applied on ``dataset``. Default to :class:`InferenceSampler`,\n which splits the dataset across all workers. Sampler must be None\n if `dataset` is iterable.\n batch_size: the batch size of the data loader to be created.\n Default to 1 image per worker since this is the standard when reporting\n inference time in papers.\n num_workers: number of parallel data loading workers\n collate_fn: same as the argument of `torch.utils.data.DataLoader`.\n Defaults to do no collation and return a list of data.\n\n Returns:\n DataLoader: a torch DataLoader, that loads the given detection\n dataset, with test-time transformation and batching.\n\n Examples:\n ::\n data_loader = build_detection_test_loader(\n DatasetRegistry.get(\"my_test\"),\n mapper=DatasetMapper(...))\n\n # or, instantiate with a CfgNode:\n data_loader = build_detection_test_loader(cfg, \"my_test\")\n \"\"\"\n if isinstance(dataset, list):\n\n\nnativedancer/third_part/detectron2/structures/boxes.py\nclass BoxMode(IntEnum):\n \"\"\"\n Enum of different ways to represent a box.\n \"\"\"\n\n XYXY_ABS = 0\n \"\"\"\n (x0, y0, x1, y1) in absolute floating points coordinates.\n The coordinates in range [0, width or height].\n \"\"\"\n XYWH_ABS = 1\n \"\"\"\n (x0, y0, w, h) in absolute floating points coordinates.\n \"\"\"\n XYXY_REL = 2\n \"\"\"\n Not yet supported!\n (x0, y0, x1, y1) in range [0, 1]. They are relative to the size of the image.\n \"\"\"\n XYWH_REL = 3\n \"\"\"\n Not yet supported!\n (x0, y0, w, h) in range [0, 1]. They are relative to the size of the image.\n \"\"\"\n XYWHA_ABS = 4\n \"\"\"\n (xc, yc, w, h, a) in absolute floating points coordinates.\n (xc, yc) is the center of the rotated box, and the angle a is in degrees ccw.\n \"\"\"\n\n @staticmethod\n def convert(box: _RawBoxType, from_mode: \"BoxMode\", to_mode: \"BoxMode\") -> _RawBoxType:\n \"\"\"\n Args:\n box: can be a k-tuple, k-list or an Nxk array/tensor, where k = 4 or 5\n from_mode, to_mode (BoxMode)\n\n Returns:\n The converted box of the same type.\n \"\"\"\n if from_mode == to_mode:\n return box\n\n original_type = type(box)\n is_numpy = isinstance(box, np.ndarray)\n single_box = isinstance(box, (list, tuple))\n if single_box:\n assert len(box) == 4 or len(box) == 5, (\n \"BoxMode.convert takes either a k-tuple/list or an Nxk array/tensor,\"\n \" where k == 4 or 5\"\n )\n arr = torch.tensor(box)[None, :]\n else:\n # avoid modifying the input box\n if is_numpy:\n arr = torch.from_numpy(np.asarray(box)).clone()\n else:\n arr = box.clone()\n\n assert to_mode not in [BoxMode.XYXY_REL, BoxMode.XYWH_REL] and from_mode not in [\n BoxMode.XYXY_REL,\n BoxMode.XYWH_REL,\n ], \"Relative mode not yet supported!\"\n\n if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:\n assert (\n arr.shape[-1] == 5\n ), \"The last dimension of input shape must be 5 for XYWHA format\"\n original_dtype = arr.dtype\n arr = arr.double()\n\n w = arr[:, 2]\n h = arr[:, 3]\n a = arr[:, 4]\n c = torch.abs(torch.cos(a * math.pi / 180.0))\n s = torch.abs(torch.sin(a * math.pi / 180.0))\n # This basically computes the horizontal bounding rectangle of the rotated box\n new_w = c * w + s * h\n new_h = c * h + s * w\n\n # convert center to top-left corner\n arr[:, 0] -= new_w / 2.0\n arr[:, 1] -= new_h / 2.0\n # bottom-right corner\n arr[:, 2] = arr[:, 0] + new_w\n arr[:, 3] = arr[:, 1] + new_h\n\n arr = arr[:, :4].to(dtype=original_dtype)\n elif from_mode == BoxMode.XYWH_ABS and to_mode == BoxMode.XYWHA_ABS:\n original_dtype = arr.dtype\n arr = arr.double()\n arr[:, 0] += arr[:, 2] / 2.0\n arr[:, 1] += arr[:, 3] / 2.0\n angles = torch.zeros((arr.shape[0], 1), dtype=arr.dtype)\n arr = torch.cat((arr, angles), axis=1).to(dtype=original_dtype)\n else:\n if to_mode == BoxMode.XYXY_ABS and from_mode == BoxMode.XYWH_ABS:\n arr[:, 2] += arr[:, 0]\n arr[:, 3] += arr[:, 1]\n elif from_mode == BoxMode.XYXY_ABS and to_mode == BoxMode.XYWH_ABS:\n arr[:, 2] -= arr[:, 0]\n arr[:, 3] -= arr[:, 1]\n else:\n raise NotImplementedError(\n \"Conversion from BoxMode {} to {} is not supported yet\".format(\n from_mode, to_mode\n )\n )\n\n if single_box:\n return original_type(arr.flatten().tolist())\n if is_numpy:\n return arr.numpy()\n else:\n return arr\n\nnativedancer/third_part/detectron2/data/common.py\nclass ToIterableDataset(data.IterableDataset):\n \"\"\"\n Convert an old indices-based (also called map-style) dataset\n to an iterable-style dataset.\n \"\"\"\n\n def __init__(\n self,\n dataset: data.Dataset,\n sampler: Sampler,\n shard_sampler: bool = True,\n shard_chunk_size: int = 1,\n ):\n \"\"\"\n Args:\n dataset: an old-style dataset with ``__getitem__``\n sampler: a cheap iterable that produces indices to be applied on ``dataset``.\n shard_sampler: whether to shard the sampler based on the current pytorch data loader\n worker id. When an IterableDataset is forked by pytorch's DataLoader into multiple\n workers, it is responsible for sharding its data based on worker id so that workers\n don't produce identical data.\n\n Most samplers (like our TrainingSampler) do not shard based on dataloader worker id\n and this argument should be set to True. But certain samplers may be already\n sharded, in that case this argument should be set to False.\n shard_chunk_size: when sharding the sampler, each worker will\n \"\"\"\n assert not isinstance(dataset, data.IterableDataset), dataset\n assert isinstance(sampler, Sampler), sampler\n self.dataset = dataset\n self.sampler = sampler\n self.shard_sampler = shard_sampler\n self.shard_chunk_size = shard_chunk_size\n\n def __iter__(self):\n if not self.shard_sampler:\n sampler = self.sampler\n else:\n # With map-style dataset, `DataLoader(dataset, sampler)` runs the\n # sampler in main process only. But `DataLoader(ToIterableDataset(dataset, sampler))`\n # will run sampler in every of the N worker. So we should only keep 1/N of the ids on\n # each worker. The assumption is that sampler is cheap to iterate so it's fine to\n # discard ids in workers.\n sampler = _shard_iterator_dataloader_worker(self.sampler, self.shard_chunk_size)\n for idx in sampler:\n yield self.dataset[idx]\n\n def __len__(self):\n return len(self.sampler)\n\nnativedancer/third_part/detectron2/utils/file_io.py\nclass Detectron2Handler(PathHandler):\n PREFIX = \"detectron2://\"\n S3_DETECTRON2_PREFIX = \"https://dl.fbaipublicfiles.com/detectron2/\"\n def _get_supported_prefixes(self):\n def _get_local_path(self, path, **kwargs):\n def _open(self, path, mode=\"r\", **kwargs):\n\nnativedancer/third_part/detectron2/data/common.py\nclass AspectRatioGroupedDataset(data.IterableDataset):\n \"\"\"\n Batch data that have similar aspect ratio together.\n In this implementation, images whose aspect ratio < (or >) 1 will\n be batched together.\n This improves training speed because the images then need less padding\n to form a batch.\n\n It assumes the underlying dataset produces dicts with \"width\" and \"height\" keys.\n It will then produce a list of original dicts with length = batch_size,\n all with similar aspect ratios.\n \"\"\"\n\n def __init__(self, dataset, batch_size):\n \"\"\"\n Args:\n dataset: an iterable. Each element must be a dict with keys\n \"width\" and \"height\", which will be used to batch data.\n batch_size (int):\n \"\"\"\n self.dataset = dataset\n self.batch_size = batch_size\n self._buckets = [[] for _ in range(2)]\n # Hard-coded two aspect ratio groups: w > h and w < h.\n # Can add support for more aspect ratio groups, but doesn't seem useful\n\n def __iter__(self):\n for d in self.dataset:\n w, h = d[\"width\"], d[\"height\"]\n bucket_id = 0 if w > h else 1\n bucket = self._buckets[bucket_id]\n bucket.append(d)\n if len(bucket) == self.batch_size:\n data = bucket[:]\n # Clear bucket first, because code after yield is not\n # guaranteed to execute\n del bucket[:]\n yield data", "answers": [" dataset = DatasetFromList(dataset, copy=False)"], "length": 1580, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "c5616a0c-53d9-41b1-8382-b4e6de43008b", "reasoning": "In build_detection_test_loader, after checking if the provided dataset is a list, the code should convert that list into a Detectron2 Dataset object. The standard conversion uses DatasetFromList with copy=False, matching the pattern used earlier in the train loader.", "reasoning_model_answer": "dataset = DatasetFromList(dataset, copy=False)", "assistant_with_reasoning": "\nIn build_detection_test_loader, after checking if the provided dataset is a list, the code should convert that list into a Detectron2 Dataset object. The standard conversion uses DatasetFromList with copy=False, matching the pattern used earlier in the train loader.\n\ndataset = DatasetFromList(dataset, copy=False)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.007, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 14455, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "dataset = DatasetFromList(dataset, copy=False)", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.qingmeng.config.adapt.FriendAdapt;\nimport com.qingmeng.constant.RedisConstant;\nimport com.qingmeng.constant.SystemConstant;\nimport com.qingmeng.dao.SysUserDao;\nimport com.qingmeng.dao.SysUserFriendDao;\nimport com.qingmeng.entity.SysUser;\nimport com.qingmeng.entity.SysUserFriend;\nimport com.qingmeng.entity.SysUserFriendSetting;\nimport com.qingmeng.utils.CommonUtils;\nimport com.qingmeng.utils.RedisUtils;\nimport com.qingmeng.vo.user.FriendTypeVO;\nimport org.springframework.cache.annotation.CacheEvict;\nimport org.springframework.cache.annotation.Cacheable;\nimport org.springframework.stereotype.Component;\nimport javax.annotation.Resource;\nimport java.util.*;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;", "context": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/cache/UserCache.java\npackage com.qingmeng.config.cache;\n\n\n\n/**\n * @author 清梦\n * @version 1.0.0\n * @Description 用户缓存类\n * @createTime 2023年11月22日 08:27:00\n */\n@Component\npublic class UserCache extends AbstractRedisStringCache {\n @Resource\n private SysUserDao sysUserDao;\n @Resource\n private SysUserFriendDao sysUserFriendDao;\n @Resource\n private UserFriendSettingCache userFriendSettingCache;\n\n /**\n * 根据输入对象获取缓存的键。\n *\n * @param userId 输入对象\n * @return {@link String }\n * @author qingmeng\n * @createTime: 2023/11/22 09:28:29\n */\n @Override\n protected String getKey(Long userId) {\n return RedisConstant.USER_INFO_KEY + userId;\n }\n\n /**\n * 获取缓存的过期时间(秒)。\n *\n * @return {@link Long }\n * @author qingmeng\n * @createTime: 2023/11/22 09:28:26\n */\n @Override\n protected Long getExpireSeconds() {\n return RedisConstant.USER_INFO_EXPIRE * SystemConstant.MINUTE;\n }\n\n /**\n * 批量加载缓存数据。\n *\n * @param userIds id集合\n * @return {@link Map }<{@link Long }, {@link SysUser }>\n * @author qingmeng\n * @createTime: 2023/11/22 09:28:11\n */\n @Override\n protected Map load(List userIds) {\n List list = sysUserDao.listByIds(userIds);\n return list.stream().collect(Collectors.toMap(SysUser::getId, Function.identity()));\n }\n\n /**\n * 离线\n *\n * @param userId 用户 ID\n * @param lastOperateTime 上次操作时间\n * @author qingmeng\n * @createTime: 2023/11/23 15:59:15\n */\n public void offline(Long userId, Date lastOperateTime) {\n //移除上线线表\n RedisUtils.zRemove(RedisConstant.ONLINE_USERID_KEY, userId);\n //更新上线表\n RedisUtils.zAdd(RedisConstant.OFFLINE_USERID_KEY, userId.toString(), lastOperateTime.getTime());\n }\n\n /**\n * 在线\n *\n * @param userId 用户 ID\n * @param lastOperateTime 上次操作时间\n * @author qingmeng\n * @createTime: 2023/11/23 15:59:12\n */\n public void online(Long userId, Date lastOperateTime) {\n //移除离线表\n RedisUtils.zRemove(RedisConstant.OFFLINE_USERID_KEY, userId);\n //更新上线表\n\ntalktime-framework/talktime-dao/src/main/java/com/qingmeng/vo/user/FriendTypeVO.java\n@Data\npublic class FriendTypeVO {\n\n /**\n * 类型\n */\n private String type;\n\n /**\n * 用户列表\n */\n private List userList;\n\n}\n\ntalktime-framework/talktime-dao/src/main/java/com/qingmeng/dao/SysUserFriendDao.java\n@Service\npublic class SysUserFriendDao extends ServiceImpl {\n\n /**\n * 按好友id删除\n *\n * @param friendId 好友 ID\n * @author qingmeng\n * @createTime: 2023/12/01 09:20:40\n */\n public void removeByFriend(Long userId,Long friendId) {\n lambdaUpdate()\n .eq(SysUserFriend::getUserId, userId)\n .eq(SysUserFriend::getFriendId, friendId)\n .set(SysUserFriend::getIsDeleted, LogicDeleteEnum.IS_DELETE.getCode())\n .update(new SysUserFriend());\n }\n\n /**\n * 通过两个ID获取好友\n *\n * @param userId 用户 ID\n * @param targetId 目标 ID\n * @return {@link SysUserFriend }\n * @author qingmeng\n * @createTime: 2023/12/01 09:28:04\n */\n public SysUserFriend getFriendByBothId(Long userId, Long targetId) {\n return lambdaQuery()\n .eq(SysUserFriend::getUserId,targetId)\n .eq(SysUserFriend::getFriendId,userId)\n .one();\n }\n\n /**\n * 自定义保存或更新\n *\n * @param saveUserFriend 保存用户好友\n * @author qingmeng\n * @createTime: 2023/12/01 16:18:31\n */\n @Transactional(rollbackFor = Exception.class)\n public void saveOrUpdateByCustom(SysUserFriend saveUserFriend) {\n LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();\n wrapper.eq(SysUserFriend::getUserId, saveUserFriend.getUserId());\n wrapper.eq(SysUserFriend::getFriendId, saveUserFriend.getFriendId());\n wrapper.eq(SysUserFriend::getIsDeleted, LogicDeleteEnum.IS_DELETE.getCode());\n saveOrUpdate(saveUserFriend);\n }\n\n /**\n * 按ID获取好友列表\n *\n * @param userId 用户 ID\n * @return {@link List }<{@link Long }>\n * @author qingmeng\n * @createTime: 2023/12/03 11:03:58\n */\n public List getFriendListById(Long userId) {\n return lambdaQuery().eq(SysUserFriend::getUserId,userId).list();\n }\n\n /**\n * 通过ID获取好友\n *\n * @param userId 用户 ID\n * @return {@link SysUserFriend }\n * @author qingmeng\n * @createTime: 2023/12/03 13:08:35\n */\n public SysUserFriend getFriendById(Long userId) {\n return lambdaQuery().eq(SysUserFriend::getUserId,userId).one();\n }\n}\n\ntalktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/FriendAdapt.java\npublic class FriendAdapt {\n\n /**\n * 构建保存好友信息\n *\n * @param applyFriendDTO 申请好友 dto\n * @return {@link SysUserApply }\n * @author qingmeng\n * @createTime: 2023/11/27 14:31:48\n */\n public static SysUserApply buildSaveSysUserApply(ApplyFriendDTO applyFriendDTO) {\n SysUserApply sysUserApply = new SysUserApply();\n sysUserApply.setUserId(applyFriendDTO.getUserId());\n sysUserApply.setApplyStatus(ApplyStatusEnum.APPLYING.getCode());\n sysUserApply.setTargetId(applyFriendDTO.getTargetId());\n sysUserApply.setApplyDescribe(applyFriendDTO.getApplyDescribe());\n sysUserApply.setApplyChannel(applyFriendDTO.getApplyChannel());\n sysUserApply.setReadStatus(ReadStatusEnum.UNREAD.getCode());\n return sysUserApply;\n }\n\n /**\n * 构建 好友 记录\n *\n * @param sysUserApply 申请好友记录参数\n * @return {@link SysUserFriendSetting }\n * @author qingmeng\n * @createTime: 2023/11/28 17:38:48\n */\n public static SysUserFriend buildFriendRecord(SysUserApply sysUserApply) {\n SysUserFriend userFriend = new SysUserFriend();\n userFriend.setUserId(sysUserApply.getUserId());\n userFriend.setFriendId(sysUserApply.getTargetId());\n return userFriend;\n }\n\n /**\n * 构建逆向 好友 记录\n *\n * @param sysUserApply 申请好友记录参数\n * @return {@link SysUserFriend }\n * @author qingmeng\n * @createTime: 2023/12/01 16:27:54\n */\n public static SysUserFriend buildFriendRecordReverse(SysUserApply sysUserApply) {\n SysUserFriend userFriend = new SysUserFriend();\n userFriend.setUserId(sysUserApply.getTargetId());\n userFriend.setFriendId(sysUserApply.getUserId());\n return userFriend;\n }\n\n /**\n * 建立 好友申请记录分页列表 VO\n *\n * @param pageList 页面列表\n * @param userList 用户列表\n * @return {@link CommonPageVO }<{@link FriendApplyRecordVO }>\n * @author qingmeng\n * @createTime: 2023/11/29 08:19:32\n */\n public static CommonPageVO buildFriendApplyRecordPageListVO(IPage pageList, List userList) {\n List voList = buildFriendApplyRecordListVO(pageList.getRecords(), userList);\n return CommonPageVO.init(pageList.getCurrent(), pageList.getSize(), pageList.getTotal(), voList);\n }\n\n\n /**\n * 建立 好友申请记录 列表 VO\n *\n * @param applyList 申请列表\n * @param userList 用户列表\n * @return {@link List }<{@link FriendApplyRecordVO }>\n * @author qingmeng\n * @createTime: 2023/11/29 11:03:59\n */\n public static List buildFriendApplyRecordListVO(List applyList, List userList) {\n return applyList.stream().map(apply -> {\n FriendApplyRecordVO applyRecordVO = new FriendApplyRecordVO();\n applyRecordVO.setApplyId(apply.getId());\n applyRecordVO.setApplyUserId(apply.getUserId());\n applyRecordVO.setApplyChannel(apply.getApplyChannel());\n applyRecordVO.setApplyStatus(apply.getApplyStatus());\n applyRecordVO.setCreateTime(apply.getCreateTime());\n userList.stream()\n .filter(user -> user.getId().equals(apply.getUserId()))\n .findFirst()\n .ifPresent(user -> {\n applyRecordVO.setUserName(user.getUserName());\n applyRecordVO.setUserAvatar(user.getUserAvatar());\n });\n return applyRecordVO;\n }).collect(Collectors.toList());\n }\n\n /**\n * 建立好友列表\n *\n * @param listMap 列表映射\n * @param friendSettingList 好友设置列表\n * @return {@link List }<{@link FriendTypeVO }>\n * @author qingmeng\n * @createTime: 2023/12/03 12:28:59\n */\n public static List buildFriendList(Map> listMap, List friendSettingList, Long userId) {\n List categorizedUserList = new ArrayList<>();\n listMap.forEach((key, value) -> {\n FriendTypeVO vo = new FriendTypeVO();\n vo.setType(key);\n List userInfoList = value.stream().map(friendUser -> {\n // 获取 当前用户 对 对方 的设置数据,判断是否进行备注\n SysUserFriendSetting friendSetting = friendSettingList.stream()\n .filter(setting -> {\n // 通过tagKey和userId定位数据 tagKey:1-2 userId:1 表示用户1对用户2的设置\n boolean flagA = setting.getTagKey().equals(CommonUtils.getKeyBySort(Arrays.asList(userId, friendUser.getId())));\n boolean flagB = setting.getUserId().equals(userId);\n return flagA && flagB;\n })\n .findAny()\n .orElse(new SysUserFriendSetting());\n SimpleUserInfo userInfo = new SimpleUserInfo();\n userInfo.setUserAvatar(friendUser.getUserAvatar());\n // 如果有备注则采用备注,否则则使用对方原本的用户名\n userInfo.setUserName(StrUtil.isNotBlank(friendSetting.getNickName()) ? friendSetting.getNickName() : friendUser.getUserName());\n return userInfo;\n }).collect(Collectors.toList());\n vo.setUserList(userInfoList);\n categorizedUserList.add(vo);\n });\n return categorizedUserList;\n }\n\n /**\n * 构造 检查好友列表\n *\n * @param friendIds 好友ID\n * @param checkFriendDTO 检查好友 DTO\n * @return {@link List }<{@link CheckFriendVO }>\n * @author qingmeng\n * @createTime: 2023/12/03 12:53:44\n */\n public static List buildCheckFriendList(List friendIds, CheckFriendListDTO checkFriendDTO) {\n return checkFriendDTO.getFriendIdList().stream().map(id -> {\n CheckFriendVO vo = new CheckFriendVO();\n vo.setFriendId(id);\n vo.setCheckStatus(friendIds.contains(id));\n return vo;\n }).collect(Collectors.toList());\n }\n\n /**\n * 构建检查好友\n *\n * @param sysUserFriend sys 用户好友\n * @param checkFriendDTO 检查好友 DTO\n * @return {@link CheckFriendVO }\n * @author qingmeng\n * @createTime: 2023/12/03 13:10:41\n */\n public static CheckFriendVO buildCheckFriend(SysUserFriend sysUserFriend, CheckFriendDTO checkFriendDTO) {\n CheckFriendVO vo = new CheckFriendVO();\n vo.setFriendId(checkFriendDTO.getFriendId());\n vo.setCheckStatus(sysUserFriend.getFriendId().equals(checkFriendDTO.getFriendId()));\n return vo;\n }\n}\n\ntalktime-framework/talktime-dao/src/main/java/com/qingmeng/entity/SysUserFriendSetting.java\n@Getter\n@Setter\n@TableName(\"sys_user_friend_setting\")\npublic class SysUserFriendSetting implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 以双方user_id排序生成的唯一标识\n */\n private String tagKey;\n\n /**\n * 用户 ID\n */\n private Long userId;\n\n /**\n * 昵称\n */\n private String nickName;\n\n /**\n * 好友状态 0正常 1拉黑\n * @see com.qingmeng.enums.user.FriendStausEnum\n */\n private Integer friendStatus;\n\n /**\n * 置顶状态 0不置顶 1置顶\n * @see com.qingmeng.enums.chat.MessageTopStatusEnum\n */\n private Integer topStatus;\n\n /**\n * 提醒状态 0关闭 1开启\n * @see com.qingmeng.enums.chat.RemindStatusEnum\n */\n private Integer remindStatus;\n\n\n /**\n * 添加渠道\n */\n private String addChannel;\n\n\n /**\n * 创建时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date createTime;\n\n /**\n * 更新时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date updateTime;\n\n /**\n * 逻辑删除\n * @see LogicDeleteEnum\n */\n @TableLogic\n @TableField(fill = FieldFill.INSERT)\n private Integer isDeleted;\n\n}\n\ntalktime-common/src/main/java/com/qingmeng/constant/SystemConstant.java\npublic class SystemConstant {\n /**\n * 本地ip\n */\n public static final String LOCAL_IP = \"127.0.0.1\";\n\n /**\n * 万能验证码\n */\n public static final String UNIVERSAL_VERIFICATION_CODE = \"qingmeng\";\n\n /**\n * 密码加盐\n */\n public static final String MD5_SALT = \"talktime\";\n\n /**\n * 默认密码\n */\n public static final String DEFAULT_PASSWORD = \"talktime123456\";\n\n /**\n * WebSocket 服务器监听的端口号\n */\n public static final int WEB_SOCKET_PORT = 9111;\n\n /**\n * 重试间隔分钟\n */\n public static final double RETRY_INTERVAL_MINUTES = 2D;\n\n /**\n * 最大重试次数\n */\n public static final int MAX_RETRY_COUNT = 3;\n\n /**\n * 秒\n */\n public static final int SECOND = 60;\n\n /**\n * 分钟\n */\n public static final int MINUTE = 60 * 60;\n\n /**\n * 日\n */\n public static final int DAY = 24 * 60 * 60;\n\n /**\n * 字母列表\n */\n public static final List ALPHABET_LIST = Arrays.asList(\n \"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\n \"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\n \"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\n \"V\",\"W\",\"X\",\"Y\",\"Z\",\"#\"\n );\n\n /**\n * 昵称最大长度\n */\n public static final int NICK_NAME_MAX_LENGTH = 10;\n\n /**\n * QR码宽度\n */\n public static final int QRCODE_WIDTH = 300;\n\n /**\n * QR码高度\n */\n public static final int QRCODE_HEIGHT = 300;\n\n /**\n * 成员最大数量\n */\n public static Long MEMBER_MAX_COUNT = 500L;\n\n /**\n * 邀请提醒计数\n */\n public static int INVITE_REMIND_COUNT = 200;\n\n /**\n * 创建组最小计数\n */\n public static int CREATE_GROUP_MIN_COUNT = 3;\n\n /**\n * 邀请成员最小计数\n */\n public static int INVITE_MEMBER_MIN_COUNT = 1;\n\n /**\n * 添加管理最小计数\n */\n public static int ADD_MANAGEMENT_MIN_COUNT = 1;\n\n /**\n * 管理最大计数\n */\n public static Long MANAGEMENT_MAX_COUNT = 3L;\n\n}\n\ntalktime-framework/talktime-dao/src/main/java/com/qingmeng/entity/SysUserFriend.java\n@Data\n@TableName(\"sys_user_friend\")\npublic class SysUserFriend implements Serializable {\n\n private static final long serialVersionUID = -9040425393852722191L;\n private Long id;\n\n /**\n * 用户id\n */\n private Long userId;\n\n /**\n * 好友id\n */\n private Long friendId;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private Date createTime;\n\n /**\n * 更新时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date updateTime;\n\n /**\n * 逻辑删除\n * @see LogicDeleteEnum\n */\n @TableLogic\n @TableField(fill = FieldFill.INSERT)\n private Integer isDeleted;\n\n}\n\ntalktime-framework/talktime-dao/src/main/java/com/qingmeng/dao/SysUserDao.java\n@Service\npublic class SysUserDao extends ServiceImpl {\n\n /**\n * 通过账号密码查询对应用户所有信息\n *\n * @param paramDTO 参数类\n * @return {@link SysUser }\n * @author qingmeng\n * @createTime: 2023/11/22 07:54:17\n */\n public SysUser getUserInfoByAccount(LoginParamDTO paramDTO) {\n return lambdaQuery()\n .eq(StrUtil.isNotBlank(paramDTO.getAccount()), SysUser::getUserAccount, paramDTO.getAccount())\n .eq(StrUtil.isNotBlank(paramDTO.getPassword()), SysUser::getUserPassword, paramDTO.getPassword())\n .one();\n }\n\n /**\n * 通过账号查询对应用户所有信息\n *\n * @param account 账户\n * @return {@link SysUser }\n * @author qingmeng\n * @createTime: 2023/11/22 07:54:54\n */\n public SysUser getUserInfoByAccount(String account) {\n return lambdaQuery().eq(SysUser::getUserAccount, account).one();\n }\n\n /**\n * 通过手机号查询对应用户所有信息\n *\n * @param phone 电话\n * @return {@link SysUser }\n * @author qingmeng\n * @createTime: 2023/11/22 07:57:06\n */\n public SysUser getUserInfoByPhone(String phone) {\n return lambdaQuery().eq(SysUser::getUserPhone, phone).one();\n }\n\n /**\n * 更改账户\n *\n * @param userId 用户 ID\n * @param alterAccountCount 改名卡次数\n * @param userAccount 用户账户\n * @author qingmeng\n * @createTime: 2023/12/02 10:19:54\n */\n public void alterAccount(Long userId,Integer alterAccountCount,String userAccount) {\n lambdaUpdate()\n .eq(SysUser::getId,userId)\n .set(SysUser::getAlterAccountCount,alterAccountCount)\n .set(SysUser::getUserAccount,userAccount)\n .update(new SysUser());\n }\n\n /**\n * 更改个人信息\n *\n * @param userId 用户 ID\n * @param alterAccountPersonalInfoDTO 更改账户个人信息 DTO\n * @author qingmeng\n * @createTime: 2023/12/02 10:45:14\n */\n public void alterPersonalInfo(Long userId, AlterPersonalInfoDTO alterAccountPersonalInfoDTO) {\n lambdaUpdate()\n .eq(SysUser::getId,userId)\n .set(StrUtil.isNotBlank(alterAccountPersonalInfoDTO.getUserName()),SysUser::getUserName, alterAccountPersonalInfoDTO.getUserName())\n .set(StrUtil.isNotBlank(alterAccountPersonalInfoDTO.getUserPhone()),SysUser::getUserPhone, alterAccountPersonalInfoDTO.getUserPhone())\n .set(StrUtil.isNotBlank(alterAccountPersonalInfoDTO.getUserAvatar()),SysUser::getUserAvatar, alterAccountPersonalInfoDTO.getUserAvatar())\n .set(Objects.nonNull(alterAccountPersonalInfoDTO.getUserSex()),SysUser::getUserSex, alterAccountPersonalInfoDTO.getUserSex())\n .update(new SysUser());\n }\n\n /**\n * 更新二维码\n *\n * @param userId 用户id\n * @param qrcodeUrl 二维码地址\n * @author qingmeng\n * @createTime: 2023/12/05 22:29:49\n */\n public void updateQrcode(Long userId,String qrcodeUrl) {\n lambdaUpdate()\n .eq(SysUser::getId,userId)\n .set(SysUser::getQrcodeUrl,qrcodeUrl)\n .update(new SysUser());\n }\n}", "answers": [" RedisUtils.zAdd(RedisConstant.ONLINE_USERID_KEY, userId.toString(), lastOperateTime.getTime());"], "length": 1551, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "a7a22021-80eb-436f-a2b3-1396cfdd729f", "reasoning": "The online method mirrors the offline method: it first removes the user ID from the offline sorted set, then adds it to the online sorted set with the timestamp. The next line should therefore add the user to the online set using RedisUtils.zAdd with the appropriate key, member, and score.", "reasoning_model_answer": "RedisUtils.zAdd(RedisConstant.ONLINE_USERID_KEY, userId.toString(), lastOperateTime.getTime());", "assistant_with_reasoning": "\nThe online method mirrors the offline method: it first removes the user ID from the offline sorted set, then adds it to the online sorted set with the timestamp. The next line should therefore add the user to the online set using RedisUtils.zAdd with the appropriate key, member, and score.\n\nRedisUtils.zAdd(RedisConstant.ONLINE_USERID_KEY, userId.toString(), lastOperateTime.getTime());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.532, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19562, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "RedisUtils.zAdd(RedisConstant.ONLINE_USERID_KEY, userId.toString(), lastOperateTime.getTime());", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import net.kyori.adventure.key.Key;\nimport net.kyori.adventure.sound.Sound;\nimport net.kyori.adventure.text.Component;\nimport net.minestom.server.event.inventory.InventoryCloseEvent;\nimport net.minestom.server.event.inventory.InventoryPreClickEvent;\nimport net.minestom.server.inventory.Inventory;\nimport net.minestom.server.inventory.InventoryType;\nimport net.minestom.server.item.ItemStack;\nimport net.minestom.server.item.Material;\nimport net.swofty.types.generic.data.DataHandler;\nimport net.swofty.types.generic.data.datapoints.DatapointDouble;\nimport net.swofty.types.generic.gui.inventory.ItemStackCreator;\nimport net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI;\nimport net.swofty.types.generic.gui.inventory.SkyBlockShopGUI;\nimport net.swofty.types.generic.gui.inventory.item.GUIClickableItem;\nimport net.swofty.types.generic.item.SkyBlockItem;\nimport net.swofty.types.generic.item.updater.NonPlayerItemUpdater;\nimport net.swofty.types.generic.user.SkyBlockPlayer;\nimport net.swofty.types.generic.utility.StringUtility;\nimport java.util.ArrayList;\nimport java.util.List;", "context": "generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/shop/GUIGenericTradingOptions.java\npackage net.swofty.types.generic.gui.inventory.inventories.shop;\n\n\n\npublic final class GUIGenericTradingOptions extends SkyBlockInventoryGUI {\n private final SkyBlockShopGUI.ShopItem item;\n private final SkyBlockShopGUI retPointer;\n private final double stackPrice;\n\n public GUIGenericTradingOptions(SkyBlockShopGUI.ShopItem item, SkyBlockShopGUI retPoint, double stackPrice) {\n super(\"Shop Trading Options\", InventoryType.CHEST_6_ROW);\n this.item = item;\n this.retPointer = retPoint;\n this.stackPrice = stackPrice;\n }\n\n @Override\n public void onOpen(InventoryGUIOpenEvent e) {\n fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE, \" \"));\n set(createTradeItem(item, 20, 1, getPlayer(), stackPrice));\n set(createTradeItem(item, 21, 5, getPlayer(), stackPrice));\n set(createTradeItem(item, 22, 10, getPlayer(), stackPrice));\n set(createTradeItem(item, 23, 32, getPlayer(), stackPrice));\n set(createTradeItem(item, 24, 64, getPlayer(), stackPrice));\n\n set(GUIClickableItem.getGoBackItem(49, retPointer));\n\n updateItemStacks(e.inventory(), getPlayer());\n }\n\n\ngeneric/src/main/java/net/swofty/types/generic/utility/StringUtility.java\npublic class StringUtility {\n public static char[] ALPHABET = {\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z'\n };\n\n public static String commaify(int i) {\n return NumberFormat.getInstance().format(i);\n }\n\n public static Material getMaterialFromBlock(Block block) {\n return Material.fromNamespaceId(block.namespace());\n }\n\n public static String profileAge(long tbf) {\n if (tbf > 86400000) return commaify(tbf / 86400000) + \"d \";\n if (tbf > 3600000) return commaify(tbf / 3600000) + \"h \";\n if (tbf > 60000) return commaify(tbf / 60000) + \"m \";\n if (tbf > 1000) return commaify(tbf / 1000) + \"s\";\n if (tbf < 1000) return commaify(tbf) + \"ms\";\n return \"\";\n }\n\n public static String getAsRomanNumeral(int num) {\n StringBuilder sb = new StringBuilder();\n int times;\n String[] romans = new String[]{\"I\", \"IV\", \"V\", \"IX\", \"X\", \"XL\", \"L\",\n \"XC\", \"C\", \"CD\", \"D\", \"CM\", \"M\"};\n int[] ints = new int[]{1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500,\n 900, 1000};\n for (int i = ints.length - 1; i >= 0; i--) {\n times = num / ints[i];\n num %= ints[i];\n while (times > 0) {\n sb.append(romans[i]);\n times--;\n }\n }\n return sb.toString();\n }\n\n public static String getTextFromComponent(Component component) {\n if (!(component instanceof TextComponent))\n throw new IllegalArgumentException(\"Component must be a TextComponent\");\n return PlainTextComponentSerializer.plainText().serialize(component);\n }\n\n public static String toNormalCase(String string) {\n if (Acronym.isAcronym(string)) return string.toUpperCase();\n string = string.replaceAll(\"_\", \" \");\n String[] spl = string.split(\" \");\n StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i < spl.length; i++) {\n String s = spl[i];\n if (s.length() == 0) {\n continue;\n }\n if (s.length() == 1) {\n s = s.toUpperCase();\n } else {\n s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();\n }\n // Append the processed string to the StringBuilder\n // Only add a space if it's not the first word\n if (sb.length() > 0) {\n sb.append(\" \");\n }\n sb.append(s);\n }\n return sb.toString();\n }\n\n public static String commaify(double d) {\n if (d < 1) {\n return \"0\";\n }\n return new DecimalFormat(\"#,###.0\").format(d);\n }\n\n public static List splitByWordAndLength(String string, int splitLength, String separator) {\n List result = new ArrayList<>();\n Pattern pattern = Pattern.compile(\"\\\\G\" + separator + \"*(.{1,\" + splitLength + \"})(?=\\\\s|$)\", Pattern.DOTALL);\n Matcher matcher = pattern.matcher(string);\n while (matcher.find())\n result.add(matcher.group(1));\n return result;\n }\n\n public static double random(double min, double max) {\n return Math.random() * (max - min) + min;\n }\n\n public static String zeroed(long l) {\n return l > 9 ? \"\" + l : \"0\" + l;\n }\n\n public static String commaify(long l) {\n return NumberFormat.getInstance().format(l);\n }\n\n public static String limitStringLength(String s, int charLimit) {\n if (s.length() <= charLimit) return s;\n return s.substring(0, charLimit - 1);\n }\n\n public static String ntify(int i) {\n if (i == 11 || i == 12 || i == 13)\n return i + \"th\";\n String s = String.valueOf(i);\n char last = s.charAt(s.length() - 1);\n switch (last) {\n case '1':\n return i + \"st\";\n case '2':\n return i + \"nd\";\n case '3':\n return i + \"rd\";\n default:\n return i + \"th\";\n }\n }\n}\n\ngeneric/src/main/java/net/swofty/types/generic/gui/inventory/item/GUIClickableItem.java\npublic abstract class GUIClickableItem extends GUIItem {\n public GUIClickableItem(int slot) {\n super(slot);\n }\n\n public abstract void run(InventoryPreClickEvent e, SkyBlockPlayer player);\n\n public static GUIClickableItem getCloseItem(int slot) {\n return new GUIClickableItem(slot) {\n @Override\n public void run(InventoryPreClickEvent e, SkyBlockPlayer player) {\n player.closeInventory();\n }\n\n @Override\n public ItemStack.Builder getItem(SkyBlockPlayer player) {\n return ItemStackCreator.createNamedItemStack(Material.BARRIER, \"§cClose\");\n }\n };\n }\n\n public static GUIClickableItem getGoBackItem(int slot, SkyBlockInventoryGUI gui) {\n return new GUIClickableItem(slot) {\n @Override\n public void run(InventoryPreClickEvent e, SkyBlockPlayer player) {\n gui.open(player);\n }\n\n @Override\n public ItemStack.Builder getItem(SkyBlockPlayer player) {\n return ItemStackCreator.getStack(\"§aGo Back\",\n Material.ARROW,\n (short) 0, 1, \"§7To \" + gui.getTitle());\n }\n };\n }\n\n static GUIClickableItem createGUIOpenerItem(SkyBlockInventoryGUI gui,\n String name, int slot,\n Material type, short data, String... lore) {\n return new GUIClickableItem(slot) {\n @Override\n public ItemStack.Builder getItem(SkyBlockPlayer player) {\n return ItemStackCreator.getStack(name, type, data, 1, lore);\n }\n\n @Override\n public void run(InventoryPreClickEvent e, SkyBlockPlayer player) {\n if (gui == null) return;\n gui.open(player);\n }\n };\n }\n}\n\ngeneric/src/main/java/net/swofty/types/generic/gui/inventory/ItemStackCreator.java\npublic class ItemStackCreator {\n\n public static ItemStack.Builder createNamedItemStack(Material material, String name) {\n return ItemStack.builder(material).displayName(Component.text(name)).meta(meta -> {\n meta.displayName(Component.text(name).decoration(TextDecoration.ITALIC, false));\n meta.hideFlag(ItemHideFlag.HIDE_ATTRIBUTES);\n meta.hideFlag(ItemHideFlag.HIDE_ENCHANTS);\n meta.hideFlag(ItemHideFlag.HIDE_POTION_EFFECTS);\n meta.hideFlag(ItemHideFlag.HIDE_UNBREAKABLE);\n });\n }\n\n public static ItemStack.Builder createNamedItemStack(Material material) {\n return createNamedItemStack(material, \"\");\n }\n\n public static ItemStack.Builder getSingleLoreStack(String name, String color, Material material, short data, int amount, String lore) {\n List l = new ArrayList<>();\n for (String line : StringUtility.splitByWordAndLength(lore, 30, \"\\\\s\"))\n l.add(color + line);\n return getStack(name, material, data, amount, l.toArray(new String[]{}));\n }\n\n public static ItemStack.Builder getStack(String name, Material material, short data, int amount, String... lore) {\n return getStack(name, material, data, amount, Arrays.asList(lore));\n }\n\n public static ItemStack.Builder updateLore(ItemStack.Builder builder, List lore) {\n List copiedLore = new ArrayList<>();\n for (String s : lore) {\n copiedLore.add(color(s));\n }\n\n return builder.meta(meta -> {\n meta.lore(copiedLore.stream()\n .map(line -> Component.text(line).decoration(TextDecoration.ITALIC, false))\n .collect(Collectors.toList()));\n\n meta.hideFlag(ItemHideFlag.HIDE_ATTRIBUTES);\n meta.hideFlag(ItemHideFlag.HIDE_ENCHANTS);\n meta.hideFlag(ItemHideFlag.HIDE_POTION_EFFECTS);\n meta.hideFlag(ItemHideFlag.HIDE_UNBREAKABLE);\n });\n }\n\n public static ItemStack.Builder getStack(String name, Material material, int amount, String... lore) {\n return getStack(name, material, (short) 0, amount, Arrays.asList(lore));\n }\n\n public static ItemStack.Builder enchant(ItemStack.Builder builder) {\n ItemMeta metaToSet = builder.meta(meta -> {\n meta.hideFlag(ItemHideFlag.HIDE_ENCHANTS);\n meta.enchantment(Enchantment.EFFICIENCY, (short) 1);\n }).build().getMeta();\n\n return builder.meta(metaToSet);\n }\n\n public static ItemStack.Builder getStack(String name, Material material, int amount, List lore) {\n return getStack(name, material, (short) 0, amount, lore);\n }\n\n public static ItemStack.Builder getStack(String name, Material material, int data, int amount, List lore) {\n List copiedLore = new ArrayList<>();\n for (String s : lore) {\n copiedLore.add(color(s));\n }\n\n return ItemStack.builder(material).meta(meta -> {\n meta.damage(data);\n meta.displayName(Component.text(name).decoration(TextDecoration.ITALIC, false));\n meta.hideFlag(ItemHideFlag.HIDE_ATTRIBUTES);\n meta.hideFlag(ItemHideFlag.HIDE_ENCHANTS);\n meta.hideFlag(ItemHideFlag.HIDE_POTION_EFFECTS);\n meta.hideFlag(ItemHideFlag.HIDE_UNBREAKABLE);\n }).amount(amount).lore(copiedLore.stream()\n .map(line -> Component.text(line).decoration(TextDecoration.ITALIC, false))\n .collect(Collectors.toList()));\n }\n\n public static ItemStack.Builder getStackHead(String name, String texture, int amount, String... lore) {\n return getStackHead(name, texture, amount, Arrays.asList(lore));\n }\n\n public static ItemStack.Builder getStackHead(String name, String texture) {\n return getStackHead(name, texture, 1, new ArrayList<>());\n }\n\n public static ItemStack.Builder getStackHead(String texture) {\n return getStackHead(\"\", texture, 1, new ArrayList<>());\n }\n\n public static ItemStack.Builder getStackHead(String name, PlayerSkin skin, int amount, String... lore) {\n return getStackHead(name, skin, amount, Arrays.asList(lore));\n }\n\n public static ItemStack.Builder getStackHead(String name, String texture, int amount, List lore) {\n List copiedLore = new ArrayList<>();\n for (String s : lore) {\n copiedLore.add(color(s));\n }\n\n JSONObject json = new JSONObject();\n json.put(\"isPublic\", true);\n json.put(\"signatureRequired\", false);\n json.put(\"textures\", new JSONObject().put(\"SKIN\",\n new JSONObject().put(\"url\", \"http://textures.minecraft.net/texture/\" + texture).put(\"metadata\", new JSONObject().put(\"model\", \"slim\"))));\n\n String texturesEncoded = Base64.getEncoder().encodeToString(json.toString().getBytes());\n\n return ItemStack.builder(Material.PLAYER_HEAD).meta(meta -> {\n meta.displayName(Component.text(name).decoration(TextDecoration.ITALIC, false));\n meta.damage(3);\n meta.hideFlag(ItemHideFlag.HIDE_ATTRIBUTES);\n meta.hideFlag(ItemHideFlag.HIDE_ENCHANTS);\n meta.hideFlag(ItemHideFlag.HIDE_POTION_EFFECTS);\n meta.hideFlag(ItemHideFlag.HIDE_UNBREAKABLE);\n meta.set(ExtraItemTags.SKULL_OWNER, new ExtraItemTags.SkullOwner(null,\n \"25\", new PlayerSkin(texturesEncoded, null)));\n }).amount(amount).lore(copiedLore.stream()\n .map(line -> Component.text(line).decoration(TextDecoration.ITALIC, false))\n .collect(Collectors.toList()));\n }\n\n\n public static ItemStack.Builder getStackHead(String name, PlayerSkin skin, int amount, List lore) {\n List copiedLore = new ArrayList<>();\n for (String s : lore) {\n copiedLore.add(color(s));\n }\n\n return ItemStack.builder(Material.PLAYER_HEAD).meta(meta -> {\n meta.displayName(Component.text(name).decoration(TextDecoration.ITALIC, false));\n meta.damage(3);\n meta.hideFlag(ItemHideFlag.HIDE_ATTRIBUTES);\n meta.hideFlag(ItemHideFlag.HIDE_ENCHANTS);\n meta.hideFlag(ItemHideFlag.HIDE_POTION_EFFECTS);\n meta.hideFlag(ItemHideFlag.HIDE_UNBREAKABLE);\n meta.set(ExtraItemTags.SKULL_OWNER, new ExtraItemTags.SkullOwner(null,\n \"25\", skin));\n }).amount(amount).lore(copiedLore.stream()\n .map(line -> Component.text(line).decoration(TextDecoration.ITALIC, false))\n .collect(Collectors.toList()));\n }\n\n public static String color(String string) {\n return string.replace(\"&\", \"§\");\n }\n}\n\ngeneric/src/main/java/net/swofty/types/generic/gui/inventory/SkyBlockShopGUI.java\npublic abstract class SkyBlockShopGUI extends SkyBlockInventoryGUI {\n private static final int[] INTERIOR = new int[]{\n 10, 11, 12, 13, 14, 15, 16,\n 19, 20, 21, 22, 23, 24, 25,\n 28, 29, 30, 31, 32, 33, 34,\n 37, 38, 39, 40, 41, 42, 43\n };\n\n private final List shopItemList;\n private int page;\n\n public SkyBlockShopGUI(String title, int page) {\n super(title, InventoryType.CHEST_6_ROW);\n this.shopItemList = new ArrayList<>();\n this.page = page;\n initializeShopItems();\n }\n\n @Override\n public void onClose(InventoryCloseEvent e, CloseReason reason) {\n SkyBlockPlayer player = (SkyBlockPlayer) e.getPlayer();\n\n DataHandler.Data.INVENTORY.onLoad.accept(\n player, DataHandler.Data.INVENTORY.onQuit.apply(player)\n );\n }\n\n @Override\n public void onOpen(InventoryGUIOpenEvent e) {\n border(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE, \" \"));\n PaginationList paginatedItems = new PaginationList<>(INTERIOR.length);\n paginatedItems.addAll(shopItemList);\n\n updateItemStacks(e.inventory(), getPlayer());\n\n for (int slot = 0; slot < 36; slot++) {\n ItemStack stack = getPlayer().getInventory().getItemStack(slot);\n\n if (stack.material().equals(Material.AIR)) continue;\n\n SkyBlockItem item = new SkyBlockItem(stack);\n if (item.getGenericInstance() instanceof Sellable sellable) {\n ItemStack.Builder toReplace = PlayerItemUpdater.playerUpdate(\n getPlayer(), stack\n );\n\n double sellPrice = sellable.getSellValue() * stack.amount();\n List lore = new ArrayList<>(toReplace.build().getLore()\n .stream()\n .map(StringUtility::getTextFromComponent)\n .toList());\n\n lore.add(\"\");\n lore.add(\"§7Sell Price\");\n lore.add(\"§6\" + StringUtility.commaify(sellPrice) + \" Coin\" + (sellPrice != 1 ? \"s\" : \"\"));\n lore.add(\"\");\n lore.add(\"§eClick to sell!\");\n\n toReplace.lore(lore.stream().map(\n line -> Component.text(line).decoration(TextDecoration.ITALIC, false)\n ).toList());\n toReplace.displayName(Component.text(\n \"§a\" + StringUtility.getTextFromComponent(toReplace.build().getDisplayName()) +\n \" §8x\" + stack.amount()\n ).decoration(TextDecoration.ITALIC, false));\n\n getPlayer().getInventory().setItemStack(slot, toReplace.build());\n }\n }\n getPlayer().getInventory().update();\n\n if (paginatedItems.isEmpty()) page = 0;\n if (page > 1)\n set(new GUIClickableItem(45) {\n @Override\n public void run(InventoryPreClickEvent e, SkyBlockPlayer player) {\n SkyBlockShopGUI.this.page -= 1;\n SkyBlockShopGUI.this.open(player);\n }\n\n @Override\n public ItemStack.Builder getItem(SkyBlockPlayer player) {\n return ItemStackCreator.createNamedItemStack(Material.ARROW, \"§a<-\");\n }\n });\n\n if (page != paginatedItems.getPageCount())\n set(new GUIClickableItem(53) {\n @Override\n public void run(InventoryPreClickEvent e, SkyBlockPlayer player) {\n SkyBlockShopGUI.this.page += 1;\n SkyBlockShopGUI.this.open(player);\n }\n\n @Override\n public ItemStack.Builder getItem(SkyBlockPlayer player) {\n return ItemStackCreator.createNamedItemStack(Material.ARROW, \"§a->\");\n }\n });\n\n /*\n Buyback item\n */\n set(new GUIClickableItem(49) {\n @Override\n public void run(InventoryPreClickEvent e, SkyBlockPlayer player) {\n if (!player.getShoppingData().hasAnythingToBuyback())\n return;\n\n SkyBlockItem last = player.getShoppingData().lastBuyback().getKey();\n int amountOfLast = player.getShoppingData().lastBuyback().getValue();\n ItemStack.Builder itemStack = PlayerItemUpdater.playerUpdate(\n player, last.getItemStackBuilder().build()\n );\n itemStack.amount(amountOfLast);\n\n double value = (last.getGenericInstance() instanceof Sellable ? ((Sellable) last.getGenericInstance()).getSellValue() : 1)\n * amountOfLast;\n\n double playerCoins = player.getDataHandler().get(DataHandler.Data.COINS, DatapointDouble.class).getValue();\n if (playerCoins < value) {\n player.sendMessage(\"§cYou don't have enough coins!\");\n return;\n }\n player.addAndUpdateItem(new SkyBlockItem(itemStack.build()));\n player.playSuccessSound();\n player.getShoppingData().popBuyback();\n player.getDataHandler().get(DataHandler.Data.COINS, DatapointDouble.class).setValue(playerCoins - value);\n updateThis(player);\n }\n\n @Override\n public ItemStack.Builder getItem(SkyBlockPlayer player) {\n if (!player.getShoppingData().hasAnythingToBuyback()) {\n return ItemStackCreator.getStack(\"§aSell Item\", Material.HOPPER, (short) 0, 1,\n \"§7Click items in your inventory to\",\n \"§7sell them to this Shop!\");\n }\n\n SkyBlockItem last = player.getShoppingData().lastBuyback().getKey();\n int amountOfLast = player.getShoppingData().lastBuyback().getValue();\n ItemStack.Builder itemStack = PlayerItemUpdater.playerUpdate(\n player, last.getItemStackBuilder().build()\n );\n\n double buyBackPrice = ((Sellable) last.getGenericInstance()).getSellValue() * amountOfLast;\n\n List lore = new ArrayList<>(itemStack.build().getLore()\n .stream()\n .map(StringUtility::getTextFromComponent)\n .toList());\n lore.add(\"\");\n lore.add(\"§7Cost\");\n lore.add(\"§6\" + StringUtility.commaify(buyBackPrice) + \" Coin\" + (buyBackPrice != 1 ? \"s\" : \"\"));\n lore.add(\"\");\n lore.add(\"§eClick to buyback!\");\n\n itemStack.amount(amountOfLast);\n return itemStack.lore(lore.stream().map(\n line -> Component.text(line).decoration(TextDecoration.ITALIC, false)\n ).toList());\n }\n });\n\n updateItemStacks(e.inventory(), getPlayer());\n\n List p = paginatedItems.getPage(page);\n if (p == null) return;\n for (int i = 0; i < p.size(); i++) {\n int slot = INTERIOR[i];\n ShopItem item = p.get(i);\n SkyBlockItem sbItem = item.item;\n double price = item.price * item.amount;\n double stackPrice = item.price / item.modifier;\n if (stackPrice < 1) {\n stackPrice = 1;\n }\n double finalStackPrice = stackPrice;\n\n set(new GUIClickableItem(slot) {\n @Override\n public void run(InventoryPreClickEvent e, SkyBlockPlayer player) {\n if (!player.getShoppingData().canPurchase(item.item, item.amount)) {\n player.sendMessage(\"§cYou have reached the maximum amount of items you can buy!\");\n return;\n }\n\n if (item.stackable() && e.getClickType().equals(ClickType.RIGHT_CLICK)) {\n new GUIGenericTradingOptions(item, SkyBlockShopGUI.this, finalStackPrice).open(player);\n return;\n }\n\n double purse = player.getDataHandler().get(DataHandler.Data.COINS, DatapointDouble.class).getValue();\n if (price > purse) {\n player.sendMessage(\"§cYou don't have enough coins!\");\n return;\n }\n sbItem.setAmount(item.amount);\n player.addAndUpdateItem(sbItem);\n player.playSound(Sound.sound(Key.key(\"block.note_block.pling\"), Sound.Source.PLAYER, 1.0f, 2.0f));\n player.getDataHandler().get(DataHandler.Data.COINS, DatapointDouble.class).setValue(purse - price);\n player.getShoppingData().documentPurchase(item.item(), item.amount);\n updateThis(player);\n }\n\n @Override\n public ItemStack.Builder getItem(SkyBlockPlayer player) {\n ItemStack.Builder itemStack = PlayerItemUpdater.playerUpdate(\n player, sbItem.getItemStackBuilder().build()\n );\n\n List lore = new ArrayList<>(itemStack.build().getLore()\n .stream()\n .map(StringUtility::getTextFromComponent)\n .toList());\n\n lore.add(\"\");\n lore.add(\"§7Cost\");\n lore.add(\"§6\" + StringUtility.commaify(price) + \" Coin\" + (price != 1 ? \"s\" : \"\"));\n lore.add(\"\");\n lore.add(\"§7Stock\");\n lore.add(\"§6\" + getPlayer().getShoppingData().getStock(item.item()) + \" §7remaining\");\n lore.add(\"\");\n lore.add(\"§eClick to trade!\");\n\n if (item.stackable)\n lore.add(\"§eRight-click for more trading options!\");\n\n return itemStack.lore(lore.stream().map(\n line -> Component.text(line).decoration(TextDecoration.ITALIC, false)\n ).toList());\n }\n });\n }\n updateItemStacks(e.inventory(), getPlayer());\n }\n\n @Override\n public void onBottomClick(InventoryPreClickEvent e) {\n ItemStack stack = e.getClickedItem();\n e.setCancelled(true);\n if (stack.material().equals(Material.AIR)) return;\n SkyBlockItem item = new SkyBlockItem(stack);\n\n Sellable sellable;\n if (item.getGenericInstance() instanceof Sellable sellableInstance) {\n sellable = sellableInstance;\n } else {\n e.getPlayer().sendMessage(\"§cYou can't sell this item!\");\n return;\n }\n\n double sellPrice = sellable.getSellValue() * stack.amount();\n\n getPlayer().getShoppingData().pushBuyback(item, stack.getAmount());\n getPlayer().getDataHandler().get(DataHandler.Data.COINS, DatapointDouble.class).setValue(\n getPlayer().getDataHandler().get(DataHandler.Data.COINS, DatapointDouble.class).getValue() + sellPrice\n );\n getPlayer().sendMessage(\n \"§aYou sold §f\" + StringUtility.getTextFromComponent(stack.getDisplayName()) + \"§a for §6\"\n + StringUtility.commaify(sellPrice) + \" Coin\" + (sellPrice != 1 ? \"s\" : \"\") + \"§a!\"\n );\n\n getPlayer().getInventory().setItemStack(e.getSlot(), ItemStack.AIR);\n updateThis(getPlayer());\n }\n\n public abstract void initializeShopItems();\n\n public void attachItem(ShopItem i) {\n shopItemList.add(i);\n }\n\n private void updateThis(SkyBlockPlayer player) {\n SkyBlockShopGUI.this.open(player);\n }\n\n public record ShopItem(SkyBlockItem item, int amount, double price, double modifier, boolean stackable) {\n public static ShopItem Stackable(SkyBlockItem item, int amount, double price, double modifier) {\n return new ShopItem(item, amount, price, modifier, true);\n }\n\n public static ShopItem Single(SkyBlockItem item, int amount, double price, double modifier) {\n return new ShopItem(item, amount, price, modifier, false);\n }\n }\n}", "answers": [" private GUIClickableItem createTradeItem(SkyBlockShopGUI.ShopItem item, int slot, int amount, SkyBlockPlayer player, double stackprice) {"], "length": 1980, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "2685dd02-5dd2-40be-9db1-3b1243c94992", "reasoning": "The class GUIGenericTradingOptions ends the onOpen method with a closing brace. The next logical piece is the helper method used inside onOpen: createTradeItem. The code earlier calls createTradeItem, so the next line should be the method declaration for createTradeItem, returning a GUIClickableItem and taking the parameters (ShopItem, slot, amount, player, price). This matches the surrounding context and imports.", "reasoning_model_answer": "private GUIClickableItem createTradeItem(SkyBlockShopGUI.ShopItem item, int slot, int amount, SkyBlockPlayer player, double price) {", "assistant_with_reasoning": "\nThe class GUIGenericTradingOptions ends the onOpen method with a closing brace. The next logical piece is the helper method used inside onOpen: createTradeItem. The code earlier calls createTradeItem, so the next line should be the method declaration for createTradeItem, returning a GUIClickableItem and taking the parameters (ShopItem, slot, amount, player, price). This matches the surrounding context and imports.\n\nprivate GUIClickableItem createTradeItem(SkyBlockShopGUI.ShopItem item, int slot, int amount, SkyBlockPlayer player, double price) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.425, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 28024, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private GUIClickableItem createTradeItem(SkyBlockShopGUI.ShopItem item, int slot, int amount, SkyBlockPlayer player, double price) {", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import Chess.Main;\r\nimport Chess.chessComponent.EatenComponent;\r\nimport Chess.chessComponent.SquareComponent;\r\nimport Chess.controller.GameController;\r\nimport Chess.model.ChessColor;\r\nimport Chess.model.ChessboardPoint;\r\nimport Chess.utils.FileUtils;\r\nimport Chess.utils.GeneralUtils;\r\nimport Chess.utils.ImageUtils;\r\nimport com.google.gson.Gson;\r\nimport com.google.gson.reflect.TypeToken;\r\nimport javax.swing.*;\r\nimport java.awt.*;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.util.Arrays;\r\nimport static Chess.Main.*;\r\nimport static Chess.utils.GeneralUtils.log;\r\nimport static Chess.utils.ImageUtils.changeImageSize;\r", "context": "CS109_2022_Fall/Chess/view/ChessGameFrame.java\n\r\n private void addScoreLabel() {\r\n JLabel jLabel = new JLabel(\"红 - 黑\");\r\n jLabel.setLocation((int) (WIDTH * 11.14 / 15 + 5), (int) (HEIGHT / 13 * 9.3));\r\n jLabel.setSize(200, 60);\r\n jLabel.setFont(sansFont.deriveFont(Font.BOLD, 23));\r\n jLabel.setForeground(ChessColor.BLACK.getColor());\r\n add(jLabel);\r\n\r\n scoreLabel = new JLabel(\"00 - 00\");\r\n scoreLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 9.85));\r\n scoreLabel.setSize(200, 60);\r\n scoreLabel.setFont(sansFont.deriveFont(Font.BOLD, 23));\r\n scoreLabel.setForeground(ChessColor.BLACK.getColor());\r\n add(scoreLabel);\r\n }\r\n\r\n public static JLabel getStatusLabel() {\r\n return statusLabel;\r\n }\r\n\r\n public static JLabel getScoreLabel() {\r\n return scoreLabel;\r\n }\r\n\r\n public static JLabel getBlackEatenLabel() {\r\n return blackEatenLabel;\r\n }\r\n\r\n public static JLabel getRedEatenLabel() {\r\n return redEatenLabel;\r\n }\r\n\r\n /**\r\n * 在游戏窗体中增加一个按钮,如果按下的话就会显示Hello, world!\r\n */\r\n\r\n private void addBackButton() {\r\n JButton button = new JButton(\"返回\");\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n button.addActionListener((e) -> {\r\n Main.backStart();\r\n Main.playNotifyMusic(\"click\");\r\n });\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13);\r\n button.setSize(80, 40);\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n }\r\n\r\n private void addLoadButton() {\r\n JButton button = new JButton(\"存档\");\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 45);\r\n button.setSize(80, 40);\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n\r\n button.addActionListener(e -> {\r\n System.out.println(\"Click load\");\r\n Main.playNotifyMusic(\"click\");\r\n int option = JOptionPane.showOptionDialog(this, \"选择是要保存存档还是导入存档?\", \"请选择\", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{\"保存存档\", \"导入存档\"}, \"导入存档\");\r\n if (option == 1) {\r\n String path = JOptionPane.showInputDialog(this, \"在这里输入存档的文件绝对路径\");\r\n gameController.loadGSon(path);\r\n } else {\r\n gameController.toGSon();\r\n }\r\n });\r\n }\r\n\r\n private void addRefreshButton() {\r\n JButton button = new JButton(\"重置\");\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 90);\r\n button.setSize(80, 40);\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n\r\n button.addActionListener(e -> {\r\n Main.playNotifyMusic(\"click\");\r\n Main.refreshGame();\r\n });\r\n }\r\n\r\n private void addThemeButton() {\r\n JButton button = new JButton(\"主题\");\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 135);\r\n button.setSize(80, 40);\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n\r\n button.addActionListener(e -> {\r\n System.out.println(\"Click theme\");\r\n Main.playNotifyMusic(\"click\");\r\n String path = JOptionPane.showInputDialog(this, \"在下方输入主题的名字以选择主题(可选主题有像素、典雅、激情):\");\r\n\r\n if (path == null) {\r\n JOptionPane.showMessageDialog(this, \"不能输入空内容!\");\r\n } else if (path.equals(Main.themeList[0]) ||\r\n path.equals(Main.themeList[1]) ||\r\n path.equals(Main.themeList[2])) {\r\n log(\"SELECT \" + path);\r\n Main.theme = path;\r\n data.put(\"theme\", gson.toJsonTree(theme, new TypeToken() {\r\n }.getType()));\r\n FileUtils.saveDataToFile(\"data\", gson.toJson(data), \"json\");\r\n Main.startGame(Main.mode);\r\n } else {\r\n JOptionPane.showMessageDialog(this, \"没有这个主题,请重新选择!\");\r\n }\r\n });\r\n }\r\n\r\n\r\n private void addBg() {\r\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"bg\"));\r\n JLabel lbBg = null;\r\n try {\r\n\nCS109_2022_Fall/Chess/chessComponent/SquareComponent.java\npublic abstract class SquareComponent extends JComponent {\r\n private static final Color squareColor = new Color(250, 220, 190, 0);\r\n protected static int spacingLength;\r\n protected static final Font CHESS_FONT = serifFont.deriveFont(Font.BOLD, 30);\r\n private int blood;\r\n private int category;\r\n /**\r\n * chessboardPoint: 表示8*4棋盘中,当前棋子在棋格对应的位置,如(0, 0), (1, 0)等等\r\n * chessColor: 表示这个棋子的颜色,有红色,黑色,无色三种\r\n * isReversal: 表示是否翻转\r\n * selected: 表示这个棋子是否被选中\r\n */\r\n private ChessboardPoint chessboardPoint;\r\n protected final ChessColor chessColor;\r\n protected boolean isReversal;\r\n protected boolean isCheating;\r\n private boolean selected;\r\n\r\n /**\r\n * handle click event\r\n */\r\n private final ClickController clickController;\r\n\r\n public SquareComponent(ChessboardPoint chessboardPoint, Point location, ChessColor chessColor, ClickController clickController, int size, int blood, int category) {\r\n enableEvents(AWTEvent.MOUSE_EVENT_MASK);\r\n setLocation(location);\r\n setSize(size, size);\r\n this.chessboardPoint = chessboardPoint;\r\n this.chessColor = chessColor;\r\n this.selected = false;\r\n this.clickController = clickController;\r\n this.isReversal = false;\r\n this.isCheating = false;\r\n this.blood = blood;\r\n this.category = category;\r\n }\r\n\r\n public boolean isCheating() {\r\n return isCheating;\r\n }\r\n\r\n public void setCheating(boolean cheating) {\r\n isCheating = cheating;\r\n }\r\n\r\n public boolean isReversal() {\r\n return isReversal;\r\n }\r\n\r\n public void setReversal(boolean reversal) {\r\n isReversal = reversal;\r\n }\r\n\r\n public static void setSpacingLength(int spacingLength) {\r\n SquareComponent.spacingLength = spacingLength;\r\n }\r\n\r\n public ChessboardPoint getChessboardPoint() {\r\n return chessboardPoint;\r\n }\r\n\r\n public void setChessboardPoint(ChessboardPoint chessboardPoint) {\r\n this.chessboardPoint = chessboardPoint;\r\n }\r\n\r\n public ChessColor getChessColor() {\r\n return chessColor;\r\n }\r\n\r\n public boolean isSelected() {\r\n return selected;\r\n }\r\n\r\n public void setSelected(boolean selected) {\r\n this.selected = selected;\r\n }\r\n\r\n /**\r\n * @param another 主要用于和另外一个棋子交换位置\r\n *
\r\n * 调用时机是在移动棋子的时候,将操控的棋子和对应的空位置棋子(EmptySlotComponent)做交换\r\n */\r\n public void swapLocation(SquareComponent another) {\r\n ChessboardPoint chessboardPoint1 = getChessboardPoint(), chessboardPoint2 = another.getChessboardPoint();\r\n Point point1 = getLocation(), point2 = another.getLocation();\r\n setChessboardPoint(chessboardPoint2);\r\n setLocation(point2);\r\n another.setChessboardPoint(chessboardPoint1);\r\n another.setLocation(point1);\r\n }\r\n\r\n /**\r\n * @param e 响应鼠标监听事件\r\n *
\r\n * 当接收到鼠标动作的时候,这个方法就会自动被调用,调用监听者的onClick方法,处理棋子的选中,移动等等行为。\r\n */\r\n @Override\r\n protected void processMouseEvent(MouseEvent e) {\r\n super.processMouseEvent(e);\r\n if (e.getID() == MouseEvent.MOUSE_PRESSED) {\r\n System.out.printf(\"Click [%d,%d]\\n\", chessboardPoint.getX(), chessboardPoint.getY());\r\n clickController.onClick(this);\r\n }\r\n }\r\n\r\n /**\r\n * @param chessboard 棋盘\r\n * @param destination 目标位置,如(0, 0), (0, 1)等等\r\n * @param playerColor\r\n * @return this棋子对象的移动规则和当前位置(chessboardPoint)能否到达目标位置\r\n *
\r\n * 这个方法主要是检查移动的合法性,如果合法就返回true,反之是false。\r\n */\r\n public abstract boolean canMoveTo(SquareComponent[][] chessboard, ChessboardPoint destination, ChessboardPoint ONE, ChessColor playerColor);\r\n\r\n public abstract boolean isComMoveX(SquareComponent[][] chessBoard, int x1, int y1, int x, int y, ChessColor playerColor);\r\n\r\n public abstract boolean isComMoveY(SquareComponent[][] chessBoard, int x1, int y1, int x, int y, ChessColor playerColor);\r\n\r\n @Override\r\n protected void paintComponent(Graphics g) {\r\n super.paintComponents(g);\r\n //System.out.printf(\"repaint chess [%d,%d]\\n\", chessboardPoint.getX(), chessboardPoint.getY());\r\n g.setColor(squareColor);\r\n g.fillRect(1, 1, this.getWidth() - 2, this.getHeight() - 2);\r\n }\r\n\r\n public int getBlood() {\r\n return blood;\r\n }\r\n\r\n public void setBlood(int blood) {\r\n this.blood = blood;\r\n }\r\n\r\n public int getCategory() {\r\n return category;\r\n }\r\n\r\n public void setCategory(int category) {\r\n this.category = category;\r\n }\r\n}\r\n\nCS109_2022_Fall/Chess/chessComponent/EatenComponent.java\npublic class EatenComponent extends JComponent {\n String type, color;\n int number, x, y;\n static final int width = 24, height = 24;\n\n public EatenComponent(String type, int number, int x, int y, String color) {\n this.type = type;\n this.number = number;\n this.color = color;\n this.x = x;\n this.y = y;\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponents(g);\n if (Main.theme.equals(\"像素\")) {\n if (number > 0) {\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"chess-pixel\"));\n try {\n g.drawImage(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()),\n width, height).getImage(), 8, 3, this);\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n } else {\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"chess-pixel-opq\"));\n try {\n g.drawImage(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()),\n width, height).getImage(), 8, 3, this);\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n }\n } else {\n if (number > 0) {\n g.setColor(Color.decode(Main.getThemeResource(\"chessfill\")));\n g.fillOval(8, 3, width - 1, height - 1);\n } else {\n Color color = Color.decode(Main.getThemeResource(\"chessfillopaque\"));\n g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), 150));\n g.fillOval(8, 3, width - 1, height - 1);\n }\n\n ((Graphics2D) g).setStroke(new BasicStroke(1)); // border width\n g.setColor(Color.decode(Main.getThemeResource(\"chessborder\")));\n g.drawOval(8, 3, width - 1, height - 1);\n }\n\n if (number > 0) {\n g.setColor(color.equals(\"b\") ? ChessColor.BLACK.getColor() : ChessColor.RED.getColor());\n g.setFont(CHESS_FONT.deriveFont(13.5f));\n g.drawString(this.type, 13, 20);\n\n if (number > 1) {\n g.setFont(CHESS_FONT.deriveFont(8f));\n g.drawString(String.valueOf(number), 26, 26);\n }\n }\n\n ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n }\n}\n\nCS109_2022_Fall/Chess/model/ChessColor.java\npublic enum ChessColor {\r\n BLACK(\"BLACK\", Color.decode(\"#251f1e\")), RED(\"RED\", Color.decode(\"#e83505\")), NONE(\"No Player\", Color.WHITE);\r\n\r\n private final String name;\r\n private final Color color;\r\n\r\n ChessColor(String name, Color color) {\r\n this.name = name;\r\n this.color = color;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public Color getColor() {\r\n return color;\r\n }\r\n}\r\n\nCS109_2022_Fall/Chess/Main.java\npublic class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素\", currentUser = \"\";\r\n public static final String[] themeList = {\"典雅\", \"激情\", \"像素\"};\r\n\r\n private static RankFrame rankFrame = null;\r\n public static boolean hasLogon = false;\r\n public static int currentUserId = 0, mode = 0;\r\n public static Map data;\r\n public static ArrayList userList = new ArrayList<>();\r\n public static ArrayList scoresList = new ArrayList<>();\r\n\r\n public static void main(String[] args) {\r\n Gson gson = new Gson();\r\n\r\n FlatLightLaf.setup();\r\n\r\n String raw = FileUtils.getDataFromFile(\"data\");\r\n if (raw == null) raw = \"{}\";\r\n try {\r\n data = JsonParser.parseString(raw).getAsJsonObject().asMap();\r\n } catch (Exception e) {\r\n System.out.println(e.getMessage());\r\n data = new HashMap<>();\r\n }\r\n if (gson.fromJson(data.get(\"userList\"), new TypeToken>() {\r\n }.getType()) == null)\r\n userList.add(\"test\");\r\n else\r\n userList = gson.fromJson(data.get(\"userList\"), new TypeToken>() {\r\n }.getType());\r\n if (gson.fromJson(data.get(\"userScores\"), new TypeToken>() {\r\n }.getType()) == null)\r\n scoresList.add(0);\r\n else\r\n scoresList = gson.fromJson(data.get(\"userScores\"), new TypeToken>() {\r\n }.getType());\r\n theme = gson.fromJson(data.get(\"theme\"), new TypeToken() {\r\n }.getType()) == null ? \"像素\" : gson.fromJson(data.get(\"theme\"), new TypeToken() {\r\n }.getType());\r\n\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/FZShiGKSJW.TTF\");\r\n titleFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n titleFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SweiSpringCJKtc-Medium.ttf\");\r\n serifFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n serifFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SourceHanSansCN-Regular.otf\");\r\n sansFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n sansFont = Font.getFont(Font.SANS_SERIF);\r\n }\r\n\r\n SwingUtilities.invokeLater(Main::backStart);\r\n\r\n playBGMusic();\r\n }\r\n\r\n public static void startGame(int mode) {\r\n Main.mode = mode;\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n if (startFrame != null) startFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n playNotifyMusic(\"gamestart\");\r\n }\r\n\r\n public static void goRank() {\r\n rankFrame = new RankFrame(480, 720);\r\n rankFrame.setVisible(true);\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (startFrame != null) startFrame.dispose();\r\n }\r\n\r\n public static void refreshGame() {\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n }\r\n\r\n public static void backStart() {\r\n startFrame = new StartFrame(480, 720);\r\n startFrame.setVisible(true);\r\n if (rankFrame != null) rankFrame.dispose();\r\n if (gameFrame != null) gameFrame.dispose();\r\n }\r\n\r\n\r\n public static String getThemeResource(String type) {\r\n switch (type) {\r\n case \"bg\":\r\n if (theme.equals(themeList[0])) return \"Resources/background1.jpg\";\r\n if (theme.equals(themeList[1])) return \"Resources/background2.jpg\";\r\n else return \"Resources/background3.jpg\";\r\n case \"startbtn\":\r\n if (theme.equals(themeList[0])) return \"Resources/button2.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/button1.png\";\r\n else return \"Resources/button3.png\";\r\n case \"btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"md-btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn-md.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"board\":\r\n if (theme.equals(themeList[0])) return \"Resources/board1.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/board2.png\";\r\n else return \"Resources/board3.png\";\r\n case \"chess-pixel\":\r\n return \"Resources/pixel-chess.png\";\r\n case \"chess-pixel-sel\":\r\n return \"Resources/pixel-chess-sel.png\";\r\n case \"chess-pixel-opq\":\r\n return \"Resources/pixel-chess-opq.png\";\r\n case \"chessfill\":\r\n if (theme.equals(themeList[0])) return \"#f6b731\";\r\n else return \"#E28B24\";\r\n case \"chessfillopaque\":\r\n if (theme.equals(themeList[0])) return \"#f2deb2\";\r\n else return \"#dca35f\";\r\n case \"chessborder\":\r\n if (theme.equals(themeList[0])) return \"#e3914a\";\r\n else return \"#B3391F\";\r\n }\r\n return \"\";\r\n }\r\n\r\n public static Color getThemeColor(String type) {\r\n switch (type) {\r\n case \"indicatorBlack\":\r\n if (theme.equals(themeList[0]) || theme.equals(themeList[2]))\r\n return ChessColor.BLACK.getColor();\r\n else return Color.WHITE;\r\n case \"indicatorRed\":\r\n return ChessColor.RED.getColor();\r\n case \"title\":\r\n if (theme.equals(themeList[0])) return Color.WHITE;\r\n else return Color.BLACK;\r\n case \"black\":\r\n return Color.BLACK;\r\n }\r\n return Color.BLACK;\r\n }\r\n\r\n public static void playBGMusic() {\r\n playMusic(\"Resources/bgm1.wav\", 0f, true);\r\n }\r\n\r\n public static void playNotifyMusic(String id) {\r\n playMusic(\"Resources/\" + id + \".wav\", (id.equals(\"click\") ? 5f : 0f), false);\r\n }\r\n\r\n private static void playMusic(String filePath, float volume, boolean shouldLoop) {\r\n try {\r\n if (Main.class.getResourceAsStream(filePath) != null) {\r\n BufferedInputStream musicPath =\r\n new BufferedInputStream(Objects.requireNonNull(Main.class.getResourceAsStream(filePath)));\r\n Clip clip1;\r\n AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);\r\n clip1 = AudioSystem.getClip();\r\n clip1.open(audioInput);\r\n FloatControl gainControl = (FloatControl) clip1.getControl(FloatControl.Type.MASTER_GAIN);\r\n gainControl.setValue(volume); //设置音量,范围为 -60.0f 到 6.0f\r\n clip1.start();\r\n clip1.loop(shouldLoop ? Clip.LOOP_CONTINUOUSLY : 0);\r\n } else {\r\n log(\"Cannot find music\");\r\n }\r\n } catch (Exception ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n}\r", "answers": [" lbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), 0.3f));\r"], "length": 1559, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "cd160a6e-a567-4677-985f-db71cf3a4dfd", "reasoning": "The addBg method starts by obtaining an InputStream for the background image and declares a JLabel lbBg = null; then opens a try block. Inside the try block the code should create the JLabel with the background image, using the ImageUtils helper to resize the image to the frame dimensions. The appropriate next line therefore constructs the JLabel with a resized ImageIcon from the stream bytes.", "reasoning_model_answer": "lbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), WIDTH, HEIGHT));", "assistant_with_reasoning": "\nThe addBg method starts by obtaining an InputStream for the background image and declares a JLabel lbBg = null; then opens a try block. Inside the try block the code should create the JLabel with the background image, using the ImageUtils helper to resize the image to the frame dimensions. The appropriate next line therefore constructs the JLabel with a resized ImageIcon from the stream bytes.\n\nlbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), WIDTH, HEIGHT));", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.497, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 20521, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "lbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), WIDTH, HEIGHT));", "score": 0.85, "is_full_score": false, "is_nonzero_score": true}} {"input": "import io.swagger.v3.oas.annotations.Operation;\nimport static com.netflix.conductor.rest.config.RequestMappingConstants.METADATA;\nimport java.util.List;\nimport java.util.Map;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PutMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport com.netflix.conductor.common.metadata.tasks.TaskDef;\nimport com.netflix.conductor.common.metadata.workflow.WorkflowDef;\nimport com.netflix.conductor.common.metadata.workflow.WorkflowDefSummary;\nimport com.netflix.conductor.common.model.BulkResponse;\nimport com.netflix.conductor.service.MetadataService;", "context": "rest/src/main/java/com/netflix/conductor/rest/controllers/MetadataResource.java\n/*\n * Copyright 2020 Conductor Authors.\n *

\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *

\n * http://www.apache.org/licenses/LICENSE-2.0\n *

\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n */\npackage com.netflix.conductor.rest.controllers;\n\n\n\n\n\n\n@RestController\n@RequestMapping(value = METADATA)\n\ncore/src/main/java/com/netflix/conductor/service/MetadataService.java\n@Validated\npublic interface MetadataService {\n\n /**\n * @param taskDefinitions Task Definitions to register\n */\n void registerTaskDef(\n @NotNull(message = \"TaskDefList cannot be empty or null\")\n @Size(min = 1, message = \"TaskDefList is empty\")\n List<@Valid TaskDef> taskDefinitions);\n\n /**\n * @param taskDefinition Task Definition to be updated\n */\n void updateTaskDef(@NotNull(message = \"TaskDef cannot be null\") @Valid TaskDef taskDefinition);\n\n /**\n * @param taskType Remove task definition\n */\n void unregisterTaskDef(@NotEmpty(message = \"TaskName cannot be null or empty\") String taskType);\n\n /**\n * @return List of all the registered tasks\n */\n List getTaskDefs();\n\n /**\n * @param taskType Task to retrieve\n * @return Task Definition\n */\n TaskDef getTaskDef(@NotEmpty(message = \"TaskType cannot be null or empty\") String taskType);\n\n /**\n * @param def Workflow definition to be updated\n */\n void updateWorkflowDef(@NotNull(message = \"WorkflowDef cannot be null\") @Valid WorkflowDef def);\n\n /**\n * @param workflowDefList Workflow definitions to be updated.\n */\n BulkResponse updateWorkflowDef(\n @NotNull(message = \"WorkflowDef list name cannot be null or empty\")\n @Size(min = 1, message = \"WorkflowDefList is empty\")\n List<@NotNull(message = \"WorkflowDef cannot be null\") @Valid WorkflowDef>\n workflowDefList);\n\n /**\n * @param name Name of the workflow to retrieve\n * @param version Optional. Version. If null, then retrieves the latest\n * @return Workflow definition\n */\n WorkflowDef getWorkflowDef(\n @NotEmpty(message = \"Workflow name cannot be null or empty\") String name,\n Integer version);\n\n /**\n * @param name Name of the workflow to retrieve\n * @return Latest version of the workflow definition\n */\n Optional getLatestWorkflow(\n @NotEmpty(message = \"Workflow name cannot be null or empty\") String name);\n\n /**\n * @return Returns all workflow defs (all versions)\n */\n List getWorkflowDefs();\n\n /**\n * @return Returns workflow names and versions only (no definition bodies)\n */\n Map> getWorkflowNamesAndVersions();\n\n void registerWorkflowDef(\n @NotNull(message = \"WorkflowDef cannot be null\") @Valid WorkflowDef workflowDef);\n\n /**\n * Validates a {@link WorkflowDef}.\n *\n * @param workflowDef The {@link WorkflowDef} object.\n */\n default void validateWorkflowDef(\n @NotNull(message = \"WorkflowDef cannot be null\") @Valid WorkflowDef workflowDef) {\n // do nothing, WorkflowDef is annotated with @Valid and calling this method will validate it\n }\n\n /**\n * @param name Name of the workflow definition to be removed\n * @param version Version of the workflow definition to be removed\n */\n void unregisterWorkflowDef(\n @NotEmpty(message = \"Workflow name cannot be null or empty\") String name,\n @NotNull(message = \"Version cannot be null\") Integer version);\n\n /**\n * @param eventHandler Event handler to be added. Will throw an exception if an event handler\n * already exists with the name\n */\n void addEventHandler(\n @NotNull(message = \"EventHandler cannot be null\") @Valid EventHandler eventHandler);\n\n /**\n * @param eventHandler Event handler to be updated.\n */\n void updateEventHandler(\n @NotNull(message = \"EventHandler cannot be null\") @Valid EventHandler eventHandler);\n\n /**\n * @param name Removes the event handler from the system\n */\n void removeEventHandlerStatus(\n @NotEmpty(message = \"EventName cannot be null or empty\") String name);\n\n /**\n * @return All the event handlers registered in the system\n */\n List getAllEventHandlers();\n\n /**\n * @param event name of the event\n * @param activeOnly if true, returns only the active handlers\n * @return Returns the list of all the event handlers for a given event\n */\n List getEventHandlersForEvent(\n @NotEmpty(message = \"EventName cannot be null or empty\") String event,\n boolean activeOnly);\n\n List getWorkflowDefsLatestVersions();\n}\n\ncommon/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowDefSummary.java\n@ProtoMessage\npublic class WorkflowDefSummary implements Comparable {\n\n @NotEmpty(message = \"WorkflowDef name cannot be null or empty\")\n @ProtoField(id = 1)\n @NoSemiColonConstraint(\n message = \"Workflow name cannot contain the following set of characters: ':'\")\n private String name;\n\n @ProtoField(id = 2)\n private int version = 1;\n\n @ProtoField(id = 3)\n private Long createTime;\n\n /**\n * @return the version\n */\n public int getVersion() {\n return version;\n }\n\n /**\n * @return the workflow name\n */\n public String getName() {\n return name;\n }\n\n /**\n * @return the createTime\n */\n public Long getCreateTime() {\n return createTime;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n WorkflowDefSummary that = (WorkflowDefSummary) o;\n return getVersion() == that.getVersion() && Objects.equals(getName(), that.getName());\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public void setCreateTime(Long createTime) {\n this.createTime = createTime;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getName(), getVersion());\n }\n\n @Override\n public String toString() {\n return \"WorkflowDef{name='\" + name + \", version=\" + version + \"}\";\n }\n\n @Override\n public int compareTo(WorkflowDefSummary o) {\n int res = this.name.compareTo(o.name);\n if (res != 0) {\n return res;\n }\n res = Integer.compare(this.version, o.version);\n return res;\n }\n}", "answers": ["public class MetadataResource {"], "length": 869, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "99311381-dcd6-46eb-866a-a87ac7e28704", "reasoning": "In MetadataResource.java, after the @RestController and @RequestMapping annotations, the next logical line is the class declaration that uses those annotations. The typical pattern is `public class MetadataResource {` to define the controller class.", "reasoning_model_answer": "public class MetadataResource {", "assistant_with_reasoning": "\nIn MetadataResource.java, after the @RestController and @RequestMapping annotations, the next logical line is the class declaration that uses those annotations. The typical pattern is `public class MetadataResource {` to define the controller class.\n\npublic class MetadataResource {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 1.666, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8416, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public class MetadataResource {", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.net.URLDecoder;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport javax.annotation.PostConstruct;\nimport javax.servlet.ServletOutputStream;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport javax.validation.Valid;\nimport org.apache.commons.io.IOUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.PageRequest;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.util.ResourceUtils;\nimport org.springframework.validation.BindingResult;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.SessionAttribute;\nimport org.springframework.web.multipart.MultipartFile;\nimport com.github.pagehelper.util.StringUtil;\nimport cn.gson.oasys.model.dao.attendcedao.AttendceDao;\nimport cn.gson.oasys.model.dao.notedao.AttachmentDao;\nimport cn.gson.oasys.model.dao.plandao.TrafficDao;\nimport cn.gson.oasys.model.dao.processdao.BursementDao;\nimport cn.gson.oasys.model.dao.processdao.DetailsBurseDao;\nimport cn.gson.oasys.model.dao.processdao.EvectionDao;\nimport cn.gson.oasys.model.dao.processdao.EvectionMoneyDao;\nimport cn.gson.oasys.model.dao.processdao.HolidayDao;\nimport cn.gson.oasys.model.dao.processdao.OvertimeDao;\nimport cn.gson.oasys.model.dao.processdao.ProcessListDao;\nimport cn.gson.oasys.model.dao.processdao.RegularDao;\nimport cn.gson.oasys.model.dao.processdao.ResignDao;\nimport cn.gson.oasys.model.dao.processdao.ReviewedDao;\nimport cn.gson.oasys.model.dao.processdao.StayDao;\nimport cn.gson.oasys.model.dao.processdao.SubjectDao;\nimport cn.gson.oasys.model.dao.system.StatusDao;\nimport cn.gson.oasys.model.dao.system.TypeDao;\nimport cn.gson.oasys.model.dao.user.UserDao;\nimport cn.gson.oasys.model.entity.attendce.Attends;\nimport cn.gson.oasys.model.entity.note.Attachment;\nimport cn.gson.oasys.model.entity.process.AubUser;\nimport cn.gson.oasys.model.entity.process.Bursement;\nimport cn.gson.oasys.model.entity.process.DetailsBurse;\nimport cn.gson.oasys.model.entity.process.Evection;\nimport cn.gson.oasys.model.entity.process.EvectionMoney;\nimport cn.gson.oasys.model.entity.process.Holiday;\nimport cn.gson.oasys.model.entity.process.Overtime;\nimport cn.gson.oasys.model.entity.process.ProcessList;\nimport cn.gson.oasys.model.entity.process.Regular;\nimport cn.gson.oasys.model.entity.process.Resign;\nimport cn.gson.oasys.model.entity.process.Reviewed;\nimport cn.gson.oasys.model.entity.process.Stay;\nimport cn.gson.oasys.model.entity.process.Subject;\nimport cn.gson.oasys.model.entity.process.Traffic;\nimport cn.gson.oasys.model.entity.system.SystemStatusList;\nimport cn.gson.oasys.model.entity.system.SystemTypeList;\nimport cn.gson.oasys.model.entity.user.User;\nimport cn.gson.oasys.services.process.ProcessService;", "context": "src/main/java/cn/gson/oasys/controller/process/ProcedureController.java\npackage cn.gson.oasys.controller.process;\n\n\n\n\n\n\n@Controller\n@RequestMapping(\"/\")\npublic class ProcedureController {\n\t\n\t@Autowired\n\tprivate UserDao udao;\n\t@Autowired\n\tprivate SubjectDao sudao;\n\t@Autowired\n\tprivate StatusDao sdao;\n\t@Autowired\n\tprivate TypeDao tydao;\n\t@Autowired\n\tprivate ReviewedDao redao;\n\t@Autowired\n\tprivate EvectionMoneyDao emdao;\n\t@Autowired\n\tprivate BursementDao budao;\n\t@Autowired\n\tprivate ProcessListDao prodao;\n\t@Autowired\n\tprivate DetailsBurseDao dedao;\n\t@Autowired\n\tprivate ProcessService proservice;\n\t@Autowired\n\tprivate TrafficDao tdao;\n\t@Autowired\n\tprivate AttachmentDao AttDao;\n\t@Autowired\n\tprivate StayDao sadao;\n\t@Autowired\n\tprivate EvectionDao edao;\n\t@Autowired\n\tprivate OvertimeDao odao;\n\t@Autowired\n\nsrc/main/java/cn/gson/oasys/model/entity/process/Traffic.java\n@Entity\n@Table(name=\"aoa_traffic\")\n//交通费用明细表\npublic class Traffic {\n\n\t@Id\n\t@Column(name=\"traffic_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long trafficId;\n\t\n\t@OneToOne\n\t@JoinColumn(name=\"user_name\")\n\tprivate User user;//出差人员\n\t\n\t@Column(name=\"depart_time\")\n\tprivate Date departTime;//出发时间\n\t\n\t@Column(name=\"depart_name\")\n\tprivate String departName;//出发城市\n\t\n\t@Column(name=\"reach_name\")\n\tprivate String reachName;//到达城市\n\t\n\t@Column(name=\"traffic_name\")\n\tprivate String trafficName;//交通工具\n\t\n\t@Column(name=\"seat_type\")\n\tprivate String seatType;//座位类型\n\t\n\t@Column(name=\"traffic_money\")\n\tprivate Double trafficMoney;//交通标准\n\t\n\t@ManyToOne()\n\t@JoinColumn(name=\"evection_id\")\n\tprivate EvectionMoney evection;\n\t\n\t@Transient\n\tprivate String username;\n\t\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic Long getTrafficId() {\n\t\treturn trafficId;\n\t}\n\n\tpublic void setTrafficId(Long trafficId) {\n\t\tthis.trafficId = trafficId;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Date getDepartTime() {\n\t\treturn departTime;\n\t}\n\n\tpublic void setDepartTime(Date departTime) {\n\t\tthis.departTime = departTime;\n\t}\n\n\tpublic String getDepartName() {\n\t\treturn departName;\n\t}\n\n\tpublic void setDepartName(String departName) {\n\t\tthis.departName = departName;\n\t}\n\n\tpublic String getReachName() {\n\t\treturn reachName;\n\t}\n\n\tpublic void setReachName(String reachName) {\n\t\tthis.reachName = reachName;\n\t}\n\n\tpublic String getTrafficName() {\n\t\treturn trafficName;\n\t}\n\n\tpublic void setTrafficName(String trafficName) {\n\t\tthis.trafficName = trafficName;\n\t}\n\n\tpublic String getSeatType() {\n\t\treturn seatType;\n\t}\n\n\tpublic void setSeatType(String seatType) {\n\t\tthis.seatType = seatType;\n\t}\n\n\tpublic Double getTrafficMoney() {\n\t\treturn trafficMoney;\n\t}\n\n\tpublic void setTrafficMoney(Double trafficMoney) {\n\t\tthis.trafficMoney = trafficMoney;\n\t}\n\n\tpublic EvectionMoney getEvection() {\n\t\treturn evection;\n\t}\n\n\tpublic void setEvection(EvectionMoney evection) {\n\t\tthis.evection = evection;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Traffic [trafficId=\" + trafficId + \", departTime=\" + departTime + \", departName=\" + departName\n\t\t\t\t+ \", reachName=\" + reachName + \", trafficName=\" + trafficName + \", seatType=\" + seatType\n\t\t\t\t+ \", evection=\" + evection + \", username=\" + username + \"]\";\n\t}\n\n\t\n\t\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/notedao/AttachmentDao.java\n@Repository\npublic interface AttachmentDao extends JpaRepository{\n\n\tAttachment findByAttachmentPath(String AttachmentPath);\n\t\n\tAttachment findByAttachmentId(long AttachmentId);\n\t\n\t@Query(\"update Attachment a set a.attachmentName=?1,a.attachmentPath=?2,a.attachmentShuffix=?3,a.attachmentSize=?4,a.attachmentType=?5,a.uploadTime=?6 where a.attachmentId=?7\")\n @Modifying\n Integer updateatt(String attname,String attpath,String shu,Long size,String type,Date uptime,Long attid);\n}\n\nsrc/main/java/cn/gson/oasys/model/entity/process/Stay.java\n@Entity\n@Table(name=\"aoa_stay\")\n//住宿申请表\npublic class Stay {\n\n\t@Id\n\t@Column(name=\"stay_id\")\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Long stayId;\n\t\n\t@OneToOne\n\t@JoinColumn(name=\"user_name\")\n\tprivate User user;//出差人员\n\t\n\t@Column(name=\"stay_time\")\n\tprivate Date stayTime;//入住日期\n\t\n\t@Column(name=\"leave_time\")\n\tprivate Date leaveTime;//离店日期\n\t\n\t@Column(name=\"stay_city\")\n\tprivate String stayCity;//入住城市\n\t\n\t@Column(name=\"hotel_name\")\n\tprivate String hotelName;//入住酒店\n\t\n\t@Column(name=\"day\")\n\tprivate Integer day;//入住天数\n\t\n\t@Column(name=\"stay_money\")\n\tprivate Double stayMoney;//酒店标准\n\t\n\t@ManyToOne()\n\t@JoinColumn(name=\"evemoney_id\")\n\tprivate EvectionMoney evemoney;\n\t\n\t@Transient\n\tprivate String nameuser;\n\t\n\t\n\n\tpublic String getNameuser() {\n\t\treturn nameuser;\n\t}\n\n\tpublic void setNameuser(String nameuser) {\n\t\tthis.nameuser = nameuser;\n\t}\n\n\tpublic Long getStayId() {\n\t\treturn stayId;\n\t}\n\n\tpublic void setStayId(Long stayId) {\n\t\tthis.stayId = stayId;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Date getStayTime() {\n\t\treturn stayTime;\n\t}\n\n\tpublic void setStayTime(Date stayTime) {\n\t\tthis.stayTime = stayTime;\n\t}\n\n\tpublic Date getLeaveTime() {\n\t\treturn leaveTime;\n\t}\n\n\tpublic void setLeaveTime(Date leaveTime) {\n\t\tthis.leaveTime = leaveTime;\n\t}\n\n\tpublic String getStayCity() {\n\t\treturn stayCity;\n\t}\n\n\tpublic void setStayCity(String stayCity) {\n\t\tthis.stayCity = stayCity;\n\t}\n\n\tpublic String getHotelName() {\n\t\treturn hotelName;\n\t}\n\n\tpublic void setHotelName(String hotelName) {\n\t\tthis.hotelName = hotelName;\n\t}\n\n\tpublic Integer getDay() {\n\t\treturn day;\n\t}\n\n\tpublic void setDay(Integer day) {\n\t\tthis.day = day;\n\t}\n\n\tpublic Double getStayMoney() {\n\t\treturn stayMoney;\n\t}\n\n\tpublic void setStayMoney(Double stayMoney) {\n\t\tthis.stayMoney = stayMoney;\n\t}\n\n\tpublic EvectionMoney getEvemoney() {\n\t\treturn evemoney;\n\t}\n\n\tpublic void setEvemoney(EvectionMoney evemoney) {\n\t\tthis.evemoney = evemoney;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Stay [stayId=\" + stayId + \", stayTime=\" + stayTime + \", leaveTime=\" + leaveTime + \", stayCity=\"\n\t\t\t\t+ stayCity + \", hotelName=\" + hotelName + \", day=\" + day + \", stayMoney=\" + stayMoney + \", nameuser=\"\n\t\t\t\t+ nameuser + \"]\";\n\t}\n\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/SubjectDao.java\npublic interface SubjectDao extends PagingAndSortingRepository{\n\n\tList findByParentId(Long id);\n\t\n\tList findByParentIdNot(Long id);\n\t\n\t\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/EvectionMoneyDao.java\npublic interface EvectionMoneyDao extends PagingAndSortingRepository{\n\n\tEvectionMoney findByProId(ProcessList pro);\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/StayDao.java\npublic interface StayDao extends PagingAndSortingRepository{\n \n\tList findByEvemoney(EvectionMoney money);\n}\n\nsrc/main/java/cn/gson/oasys/model/dao/processdao/HolidayDao.java\npublic interface HolidayDao extends PagingAndSortingRepository{\n\n\tHoliday findByProId(ProcessList pro);\n\n}", "answers": ["\tprivate HolidayDao hdao;"], "length": 811, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "eaf7dcd0-5426-4701-aad0-9846ceb88c4b", "reasoning": "The ProcedureController class lists a series of @Autowired fields for various DAOs. The last shown line is an @Autowired annotation with no following field. Looking at the imported DAOs, the only ones not yet declared are AttendceDao, HolidayDao, RegularDao, and ResignDao. Following the existing order (UserDao, SubjectDao, StatusDao, TypeDao, ReviewedDao, EvectionMoneyDao, BursementDao, ProcessListDao, DetailsBurseDao, ProcessService, TrafficDao, AttachmentDao, StayDao, EvectionDao, OvertimeDao), the next logical DAO to inject is HolidayDao. Therefore the next line should declare the HolidayDao field.", "reasoning_model_answer": "private HolidayDao hdao;", "assistant_with_reasoning": "\nThe ProcedureController class lists a series of @Autowired fields for various DAOs. The last shown line is an @Autowired annotation with no following field. Looking at the imported DAOs, the only ones not yet declared are AttendceDao, HolidayDao, RegularDao, and ResignDao. Following the existing order (UserDao, SubjectDao, StatusDao, TypeDao, ReviewedDao, EvectionMoneyDao, BursementDao, ProcessListDao, DetailsBurseDao, ProcessService, TrafficDao, AttachmentDao, StayDao, EvectionDao, OvertimeDao), the next logical DAO to inject is HolidayDao. Therefore the next line should declare the HolidayDao field.\n\nprivate HolidayDao hdao;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.574, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10378, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private HolidayDao hdao;", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import static bms.player.beatoraja.ClearType.NoPlay;\nimport java.util.Arrays;\nimport com.badlogic.gdx.math.MathUtils;\nimport bms.player.beatoraja.MainController;\nimport bms.player.beatoraja.MainState;\nimport bms.player.beatoraja.ScoreData;\nimport bms.player.beatoraja.input.BMSPlayerInputProcessor;\nimport bms.player.beatoraja.ir.RankingData;", "context": "core/src/bms/player/beatoraja/result/AbstractResult.java\npackage bms.player.beatoraja.result;\n\n\n\n\n\npublic abstract class AbstractResult extends MainState {\n\n\t/**\n\t * 状態\n\t */\n\tprotected int state;\n\n\tpublic static final int STATE_OFFLINE = 0;\n\t/**\n\t * 状態:IR送信中\n\t */\n\tpublic static final int STATE_IR_PROCESSING = 1;\n\t/**\n\t * 状態:IR処理完了\n\t */\n\tpublic static final int STATE_IR_FINISHED = 2;\n\n\t/**\n\t * ランキングデータ\n\t */\n\tprotected RankingData ranking;\n\t/**\n\t * ランキング表示位置\n\t */\n\tprotected int rankingOffset = 0;\n\t/**\n\t * 全ノーツの平均ズレ(us)\n\t */\n\tprotected long avgduration;\n\t/**\n\t * タイミング分布\n\t */\n\tprotected TimingDistribution timingDistribution;\n\n\t/**\n\t * タイミング分布レンジ\n\t */\n\tfinal int distRange = 150;\n\t/**\n\t * 各リプレイデータ状態\n\t */\n\tprotected ReplayStatus[] saveReplay = new ReplayStatus[REPLAY_SIZE];\n\tprotected static final int REPLAY_SIZE = 4;\n\t\n\tpublic static final int SOUND_CLEAR = 0;\n\tpublic static final int SOUND_FAIL = 1;\n\tpublic static final int SOUND_CLOSE = 2;\n\t\n\tprotected int gaugeType;\n\n\t/**\n\t * 旧スコアデータ\n\t */\n\tprotected ScoreData oldscore = new ScoreData();\n\n\ncore/src/bms/player/beatoraja/ir/RankingData.java\npublic class RankingData {\n\t/**\n\t * 選択されている楽曲の現在のIR順位\n\t */\n\tprivate int irrank;\n\t/**\n\t * 選択されている楽曲の以前のIR順位\n\t */\n\tprivate int prevrank;\n\t/**\n\t * 選択されている楽曲のローカルスコアでの想定IR順位\n\t */\t\n\tprivate int localrank;\n\n\t/**\n\t * IR総プレイ数\n\t */\n\tprivate int irtotal;\n\t/**\n\t * 各クリアランプ総数\n\t */\n\tprivate int[] lamps = new int[11];\n\t/**\n\t * 全スコアデータ\n\t */\n\tprivate IRScoreData[] scores;\n\t/**\n\t * 各スコアデータの順位\n\t */\n\tprivate int[] scorerankings;\n\t/**\n\t * IRアクセス状態\n\t */\n\tprivate int state = NONE;\n\tpublic static final int NONE = 0;\n\tpublic static final int ACCESS = 1;\n\tpublic static final int FINISH = 2;\n\tpublic static final int FAIL = 3;\n\t\n\t/**\n\t * 最終更新時間\n\t */\n\tprivate long lastUpdateTime;\n\t\n\tpublic void load(MainState mainstate, Object song) {\n\t\tif(!(song instanceof SongData || song instanceof CourseData)) {\n\t\t\treturn;\n\t\t}\t\t\n\t\tstate = ACCESS;\n\t\tThread irprocess = new Thread(() -> {\n\t\t\tfinal IRStatus[] ir = mainstate.main.getIRStatus();\n\t IRResponse response = null;\n\t if(song instanceof SongData) {\n\t \t response = ir[0].connection.getPlayData(null, new IRChartData((SongData) song));\n\t } else if(song instanceof CourseData) {\n\t\t response = ir[0].connection.getCoursePlayData(null, new IRCourseData((CourseData) song, mainstate.main.getPlayerConfig().getLnmode()));\n\t }\n\t if(response.isSucceeded()) {\n\t \tupdateScore(response.getData(), mainstate.getScoreDataProperty().getScoreData());\n\t Logger.getGlobal().fine(\"IRからのスコア取得成功 : \" + response.getMessage());\n\t\t\t\tstate = FINISH;\n\t } else {\n\t Logger.getGlobal().warning(\"IRからのスコア取得失敗 : \" + response.getMessage());\n\t\t\t\tstate = FAIL;\n\t }\n\t lastUpdateTime = System.currentTimeMillis();\n\t\t});\n\t\tirprocess.start();\n\n\t}\n\t\n\tpublic void updateScore(IRScoreData[] scores, ScoreData localscore) {\n\t\tif(scores == null) {\n\t\t\treturn;\n\t\t}\n\t\tboolean firstUpdate = this.scores == null;\n\t\t\n\t\tArrays.sort(scores, (s1, s2) -> (s2.getExscore() - s1.getExscore()));\n\t\tint[] scorerankings = new int[scores.length];\n\t\tfor(int i = 0;i < scorerankings.length;i++) {\n\t\t\tscorerankings[i] = (i > 0 && scores[i].getExscore() == scores[i - 1].getExscore()) ? scorerankings[i - 1] : i + 1;\n\t\t}\n\t\t\n\t\tif(!firstUpdate) {\n\t\t\tprevrank = irrank;\t\n\t\t}\n\t\tthis.scores = scores;\n\t\tthis.scorerankings = scorerankings;\n irtotal = scores.length;\n Arrays.fill(lamps, 0);\n irrank = 0;\n localrank = 0;\n for(int i = 0;i < scores.length;i++) {\n if(irrank == 0 && scores[i].player.length() == 0) {\n \tirrank = scorerankings[i];\n }\n if(localscore != null && localrank == 0 && scores[i].getExscore() <= localscore.getExscore()) {\n \tlocalrank = scorerankings[i];\n }\n lamps[scores[i].clear.id]++;\n }\n \n if(firstUpdate && localrank != 0) {\n \tprevrank = Math.max(irrank, localrank);\n }\n \n\t\tstate = FINISH;\n lastUpdateTime = System.currentTimeMillis();\n\t}\n\t\n\t/**\n\t * 選択されている楽曲の現在のIR順位を返す\n\t * \n\t * @return 現在のIR順位\n\t */\n\tpublic int getRank() {\n\t\treturn irrank;\n\t}\n\n\t/**\n\t * 選択されている楽曲の以前のIR順位を返す\n\t * \n\t * @return 以前のIR順位\n\t */\n\tpublic int getPreviousRank() {\n\t\treturn prevrank;\n\t}\n\t\n\t/**\n\t * 選択されている楽曲のローカルスコアでの想定IR順位を返す\n\t * \n\t * @return ローカルスコアでの想定IR順位\n\t */\n\tpublic int getLocalRank() {\n\t\treturn localrank;\n\t}\n\t\n\t/**\n\t * IR上の総プレイ人数を返す\n\t * \n\t * @return 総プレイ人数\n\t */\n\tpublic int getTotalPlayer() {\n\t\treturn irtotal;\n\t}\n\n\t/**\n\t * IR上のindexに対応したプレイヤーのスコアデータを返す\n\n\t * @param index インデックス\n\t * @return 対応するスコアデータ。indexに対応したスコアデータが存在しない場合はnull\n\t */\n\tpublic IRScoreData getScore(int index) {\n\t\tif(scores != null && index >= 0 && index < scores.length) {\n\t\t\treturn scores[index];\t\t\t\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * IR上のindexに対応したプレイヤーの順位を返す\n\n\t * @param index インデックス\n\t * @return 対応するスコアデータの順位。indexに対応したスコアデータが存在しない場合はInteger.MIN_VALUEl\n\t */\n\tpublic int getScoreRanking(int index) {\n\t\tif(scorerankings != null && index >= 0 && index < scorerankings.length) {\n\t\t\treturn scorerankings[index];\t\t\t\n\t\t}\n\t\treturn Integer.MIN_VALUE;\n\t}\n\t\n\tpublic int getClearCount(int clearType) {\n\t\treturn lamps[clearType];\n\t}\n\t\n\tpublic int getState() {\n\t\treturn state;\n\t}\n\t\n\t/**\n\t * RankingDataの最終更新時間を返す\n\t * \n\t * @return RankingDataの最終更新時間(ms)\n\t */\n\tpublic long getLastUpdateTime() {\n\t\treturn lastUpdateTime;\n\t}\n}\n\ncore/src/bms/player/beatoraja/MainState.java\npublic abstract class MainState {\n\n\tpublic final MainController main;\n\n\t/**\n\t * スキン\n\t */\n\tprivate Skin skin;\n\n\tprivate Stage stage;\n\t\n\tpublic final TimerManager timer;\n\t\n\tpublic final PlayerResource resource;\n\n\tprivate final IntMap soundmap = new IntMap();\n\tprivate final IntMap soundloop = new IntMap();\n\n\tprivate final ScoreDataProperty score = new ScoreDataProperty();\n\n\tpublic MainState(MainController main) {\n\t\tthis.main = main;\n\t\ttimer = main.getTimer();\n\t\tresource = main.getPlayerResource();\n\t}\n\n\tpublic abstract void create();\n\n\tpublic void prepare() {\n\n\t}\n\n\tpublic void shutdown() {\n\n\t}\n\n\tpublic abstract void render();\n\n\tpublic void input() {\n\n\t}\n\n\tpublic void pause() {\n\n\t}\n\n\tpublic void resume() {\n\n\t}\n\n\tpublic void resize(int width, int height) {\n\n\t}\n\n\tpublic void dispose() {\n\t\tif (skin != null) {\n\t\t\tskin.dispose();\n\t\t\tskin = null;\n\t\t}\n\t\tif (stage != null) {\n\t\t\tstage.dispose();\n\t\t\tstage = null;\n\t\t}\n\t}\n\n\tpublic void executeEvent(int id) {\n\t\texecuteEvent(id, 0, 0);\n\t}\n\n\tpublic void executeEvent(int id, int arg) {\n\t\texecuteEvent(id, arg, 0);\n\t}\n\n\tpublic void executeEvent(int id, int arg1, int arg2) {\n\t\tif (SkinPropertyMapper.isCustomEventId(id)) {\n\t\t\tskin.executeCustomEvent(this, id, arg1, arg2);\n\t\t}\n\t}\n\n\tpublic void executeEvent(EventType e) {\n\t\texecuteEvent(e, 0, 0);\n\t}\n\n\tpublic void executeEvent(EventType e, int arg) {\n\t\texecuteEvent(e, arg, 0);\n\t}\n\n\tpublic void executeEvent(EventType e, int arg1, int arg2) {\n\t\te.event.exec(this, arg1, arg2);\n\t}\n\t\n\tpublic ScoreDataProperty getScoreDataProperty() {\n\t\treturn score;\n\t}\n\n\tpublic Skin getSkin() {\n\t\treturn skin;\n\t}\n\n\tpublic void setSkin(Skin skin) {\n\t\tif (this.skin != null) {\n\t\t\tthis.skin.dispose();\n\t\t}\n\t\tthis.skin = skin;\n\t\tif (skin != null) {\n\t\t\tfor (IntMap.Entry e : skin.getOffset().entries()) {\n\t\t\t\tSkinOffset offset = main.getOffset(e.key);\n\t\t\t\tif(offset == null || e.value == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\toffset.x = e.value.x;\n\t\t\t\toffset.y = e.value.y;\n\t\t\t\toffset.w = e.value.w;\n\t\t\t\toffset.h = e.value.h;\n\t\t\t\toffset.r = e.value.r;\n\t\t\t\toffset.a = e.value.a;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void loadSkin(SkinType skinType) {\n\t\tsetSkin(SkinLoader.load(this, skinType));\n\t}\n\n\tpublic int getJudgeCount(int judge, boolean fast) {\n\t\tScoreData sd = score.getScoreData();\n\t\treturn sd != null ? sd.getJudgeCount(judge, fast) : 0;\n\t}\n\n\tpublic SkinOffset getOffsetValue(int id) {\n\t\treturn main.getOffset(id);\n\t}\n\n\tpublic TextureRegion getImage(int imageid) {\n\t\tswitch (imageid) {\n\t\tcase IMAGE_BACKBMP:\n\t\t\treturn resource.getBMSResource().getBackbmp();\n\t\tcase IMAGE_STAGEFILE:\n\t\t\treturn resource.getBMSResource().getStagefile();\n\t\tcase IMAGE_BANNER:\n\t\t\treturn resource.getBMSResource().getBanner();\n\t\tcase IMAGE_BLACK:\n\t\t\treturn main.black;\n\t\tcase IMAGE_WHITE:\n\t\t\treturn main.white;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Stage getStage() {\n\t\treturn stage;\n\t}\n\n\tpublic void setStage(Stage stage) {\n\t\tthis.stage = stage;\n\t}\n\n\tpublic enum SoundType {\n\t\tBGM, SOUND\n\t}\n\n\tpublic void setSound(int id, String path, SoundType type, boolean loop) {\n\t\tfor(Path p :getSoundPaths(path, type)) {\n\t\t\tString newpath = p.toString();\n\t\t\tString oldpath = soundmap.get(id);\n\t\t\tif (newpath.equals(oldpath)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (oldpath != null) {\n\t\t\t\tmain.getAudioProcessor().dispose(oldpath);\n\t\t\t}\n\t\t\tsoundmap.put(id, newpath);\n\t\t\tsoundloop.put(id, loop);\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tpublic Path[] getSoundPaths(String filename, SoundType type) {\n\t\tPath p = null;\n\t\tswitch (type) {\n\t\tcase BGM:\n\t\t\tp = main.getSoundManager().getBGMPath();\n\t\t\tbreak;\n\t\tcase SOUND:\n\t\t\tp = main.getSoundManager().getSoundPath();\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tArray paths = new Array();\n\t\tif(p != null) {\n\t\t\tpaths.addAll(AudioDriver.getPaths(p.resolve(filename).toString()));\t\t\t\n\t\t}\n\t\tpaths.addAll(AudioDriver.getPaths(\"defaultsound/\" + filename.substring(filename.contains(\"/\") || filename.contains(\"\\\\\") ? Math.max(filename.lastIndexOf('/'),filename.lastIndexOf('\\\\')) + 1 : 0)));\n\t\treturn paths.toArray(Path.class);\n\t}\n\n\tpublic String getSound(int id) {\n\t\treturn soundmap.get(id);\n\t}\n\n\tpublic void play(int id) {\n\t\tfinal String path = soundmap.get(id);\n\t\tif (path != null) {\n\t\t\tmain.getAudioProcessor().play(path, resource.getConfig().getAudioConfig().getSystemvolume(),\n\t\t\t\t\tsoundloop.get(id));\n\t\t}\n\t}\n\n\tpublic void stop(int id) {\n\t\tfinal String path = soundmap.get(id);\n\t\tif (path != null) {\n\t\t\tmain.getAudioProcessor().stop(path);\n\t\t}\n\t}\n\t\n\tpublic enum MainStateType {\n\t\tMUSICSELECT,DECIDE,PLAY,RESULT,COURSERESULT,CONFIG,SKINCONFIG;\n\t}\n}", "answers": ["\tpublic AbstractResult(MainController main) {"], "length": 1158, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "05b2c08d-2341-40f0-9bfc-4a9eaa799738", "reasoning": "In AbstractResult.java, after the field declarations (ending with `protected ScoreData oldscore = new ScoreData();`), the class needs a constructor that forwards the MainController to the superclass MainState. The very next line is the constructor signature.", "reasoning_model_answer": "public AbstractResult(MainController main) {", "assistant_with_reasoning": "\nIn AbstractResult.java, after the field declarations (ending with `protected ScoreData oldscore = new ScoreData();`), the class needs a constructor that forwards the MainController to the superclass MainState. The very next line is the constructor signature.\n\npublic AbstractResult(MainController main) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.588, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10398, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public AbstractResult(MainController main) {", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "import yaa.pojos.MtdPack;\r\nimport yaa.pojos.YaaClz;\r\nimport yaa.pojos.YaaFun;\r\nimport java.util.LinkedList;\r", "context": "src/main/java/yaa/pojos/predefined/PropertyMold.java\npackage yaa.pojos.predefined;\r\n\r\n\r\n\r\npublic class PropertyMold {\r\n public static MtdPack property() {\r\n var mtd$list = new LinkedList();\r\n\r\n var right$string = new YaaFun(\"getProperty\", \"java/lang/System\");\r\n right$string.parameters.add(new YaaClz(\"java.lang.String\"));\r\n right$string.type = new YaaClz(\"java.lang.String\");\r\n mtd$list.add(right$string);\r\n\r\n var print_pack = new MtdPack(mtd$list, \"getProperty\");\r\n // print_pack.isPredefined = true;\r\n\nsrc/main/java/yaa/pojos/YaaFun.java\npublic class YaaFun extends YaaInfo {\r\n public MtdIsWhat mtdIsWhat;\r\n public boolean isAnonymous;\r\n public List parameters;\r\n public List raw_parameters; //these are the declared parameters b4 generic change took place\r\n public YaaInfo type = new YaaClz(void$name);\r\n public YaaInfo rawType;\r\n public List inputted = new ArrayList<>(1);\r\n public Map closures = new HashMap<>();\r\n public YaaClz theRemovedVarArgClz;\r\n\r\n public String owner;\r\n public boolean itIsTraitMtd = false;\r\n public boolean hasClzTypeParam;\r\n public boolean itIsStatic;\r\n public String iClzDescriptor;\r\n public String iMtdName;\r\n public String iMtdDescriptor;\r\n public String path;\r\n public List parameterNames;\r\n public boolean isFinal;\r\n public boolean isAutoGeneratedFInterfaceMtd;\r\n\r\n public YaaFun(String name, String owner) {\r\n this.name = name;\r\n this.owner = owner;\r\n this.parameters = new ArrayList<>();\r\n }\r\n\r\n public String signature() {\r\n return null;\r\n }\r\n\r\n @Override\r\n public String descriptor() {\r\n String return$type = type.descriptor();\r\n var sb = new StringBuilder();\r\n sb.append(\"(\");\r\n for (var field : closures.values()) {\r\n sb.append(field.descriptor());\r\n }\r\n for (var parameter : parameters) {\r\n sb.append(parameter.descriptor());\r\n }\r\n return sb.append(\")\").append(return$type).toString();\r\n }\r\n\r\n public String lambdaDescriptor() {\r\n String return$type = type.descriptor();\r\n var sb = new StringBuilder();\r\n sb.append(\"(\");\r\n for (var parameter : parameters) {\r\n sb.append(parameter.descriptor());\r\n }\r\n return sb.append(\")\").append(return$type).toString();\r\n }\r\n\r\n public YaaFun(String name) {\r\n this.name = name;\r\n parameters = new ArrayList<>(1);\r\n }\r\n\r\n public YaaFun(String name, List parameters) {\r\n this.name = name;\r\n this.parameters = parameters;\r\n }\r\n\r\n public YaaFun() {\r\n this.parameters = new ArrayList<>(1);\r\n }\r\n\r\n public FunCallInfo callInfo;\r\n\r\n @Override\r\n public YaaFun acceptsMtd(List arguments) {\r\n if (parameters.size() == arguments.size()) {\r\n var declared_parameters = new ArrayList();\r\n for (int i = 0; i < arguments.size(); i++) {\r\n var argument = arguments.get(i);\r\n var parameter = parameters.get(i);\r\n if (parameter.isIBounded() && !argument.isIBounded()) {\r\n return null;\r\n }\r\n if (!parameter.accepts(argument)) {\r\n if (parameter instanceof YaaClz clz) {\r\n if (argument instanceof YaaClz arg$clz) {\r\n if (!clz.isParentOf(arg$clz)) {\r\n if (arg$clz.hasTrait(clz) == null) {\r\n return null;\r\n }\r\n }\r\n } else {\r\n return null;\r\n }\r\n }\r\n }\r\n if (argument.typeParam != null && !argument.isPrimitive()) {\r\n declared_parameters.add(argument.typeParam.parent);\r\n } else if (parameter.typeParam != null) {\r\n declared_parameters.add(parameter.typeParam.parent);\r\n } else {\r\n declared_parameters.add(parameter);\r\n }\r\n }\r\n if (raw_parameters != null) {\r\n declared_parameters = new ArrayList<>(parameters.size());\r\n declared_parameters.addAll(raw_parameters);\r\n }\r\n var callInfo = new FunCallInfo(closures.values(), declared_parameters);\r\n if (rawType != null) {\r\n callInfo.declared_type = rawType;\r\n } else {\r\n callInfo.declared_type = type;\r\n }\r\n var method = (YaaFun) this.cloneInfo();\r\n method.callInfo = callInfo;\r\n return method;\r\n }\r\n return null;\r\n }\r\n\r\n public YaaFun setCallInfo(List arguments) {\r\n var declared_parameters = new ArrayList();\r\n var callInfo = new FunCallInfo(closures.values(), declared_parameters);\r\n for (int i = 0; i < parameters.size(); i++) {\r\n var argument = arguments.get(i);\r\n var parameter = parameters.get(i);\r\n if (argument.typeParam != null && !argument.isPrimitive()) {\r\n declared_parameters.add(argument.typeParam.parent);\r\n } else if (parameter.typeParam != null) {\r\n declared_parameters.add(parameter.typeParam.parent);\r\n } else {\r\n declared_parameters.add(parameter);\r\n }\r\n }\r\n if (raw_parameters != null) {\r\n declared_parameters = new ArrayList<>(parameters.size());\r\n declared_parameters.addAll(raw_parameters);\r\n }\r\n if (rawType != null) {\r\n callInfo.declared_type = rawType;\r\n } else {\r\n callInfo.declared_type = type;\r\n }\r\n var method = (YaaFun) this.cloneInfo();\r\n method.callInfo = callInfo;\r\n return method;\r\n }\r\n\r\n public boolean acceptsOpMtd(YaaInfo right_op) {\r\n if (parameters.size() == 1) {\r\n var parameter = parameters.get(0);\r\n if (!parameter.accepts(right_op)) {\r\n if (parameter instanceof YaaClz clz) {\r\n if (right_op instanceof YaaClz arg$clz) {\r\n return clz.isParentOf(arg$clz);\r\n }\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return (isAnonymous ? \"\" : name) + paramString() + type;\r\n }\r\n\r\n private String paramString() {\r\n if (parameters.size() == 0) {\r\n return \"()\";\r\n }\r\n if (parameters.size() == 1) {\r\n return \"(\" + parameters.get(0) + \")\";\r\n }\r\n var sb = new StringBuilder();\r\n sb.append(parameters.get(0));\r\n for (int i = 1; i < parameters.size(); i++) {\r\n sb.append(\", \").append(parameters.get(i));\r\n }\r\n return \"(\" + sb + \")\";\r\n }\r\n\r\n public void startCode() {\r\n F6.f6TopMtd.push(this);\r\n fs6.push$variables();\r\n variableMeta.push(new ArrayList<>());\r\n F6.mtdWriters.push(fs6.cw.peek().visitMethod(\r\n mtdCodeModifier(),\r\n name, descriptor(),\r\n null, new String[]{}\r\n ));\r\n }\r\n\r\n public void startCode(FunDecInfo funDecInfo) {\r\n F6.f6TopMtd.push(this);\r\n fs6.push$variables();\r\n variableMeta.push(new ArrayList<>());\r\n F6.mtdWriters.push(fs6.cw.peek().visitMethod(\r\n mtdCodeModifier(),\r\n name, funDecInfo.descriptor(),\r\n null, new String[]{}\r\n ));\r\n mw().visitCode();\r\n }\r\n\r\n public void initParam(List ast$params) {\r\n for (var closed$field : closures.values()) {\r\n var variables = fs6.variables.peek();\r\n var name = closed$field.field$name;\r\n var data = closed$field.data;\r\n switch (data.name) {\r\n case long$name, double$name -> {\r\n variables.putWideVar(name);\r\n }\r\n default -> variables.putVar(name);\r\n }\r\n }\r\n var variables = fs6.variables.peek();\r\n for (var param : ast$params) {\r\n var param$name = param.name.content;\r\n var param$field = (YaaField) fs.getSymbol(param$name);\r\n var data = param$field.data;\r\n switch (data.name) {\r\n case long$name, double$name -> {\r\n variables.putWideVar(param$name);\r\n }\r\n default -> variables.putVar(param$name);\r\n }\r\n var label = new Label();\r\n mw().visitLabel(label);\r\n mw().visitLineNumber(param.start.line, label);\r\n var index = variables.index;\r\n variableMeta.peek().add(new VariableData(\r\n param$name, label, data.descriptor(),\r\n data.clzUseSignature(), index, new ArrayList<>(0), new ArrayList<>(0)\r\n ));\r\n }\r\n }\r\n\r\n public int mtdCodeModifier() {\r\n var mtd$modifier = ACC_PUBLIC;\r\n if (privacy == 1) {\r\n mtd$modifier = ACC_PROTECTED;\r\n }\r\n if (privacy == 2) {\r\n mtd$modifier = ACC_PRIVATE;\r\n }\r\n if (mtdIsWhat == MtdIsWhat.abstractMtd) {\r\n mtd$modifier = mtd$modifier + ACC_ABSTRACT;\r\n }\r\n if (mtdIsWhat == MtdIsWhat.staticMtd) {\r\n mtd$modifier = mtd$modifier + ACC_STATIC;\r\n }\r\n if (mtdIsWhat == mainMtd) {\r\n mtd$modifier = mtd$modifier + ACC_STATIC;\r\n }\r\n if (mtdIsWhat == topMtd) {\r\n mtd$modifier = mtd$modifier + ACC_STATIC;\r\n }\r\n return mtd$modifier;\r\n }\r\n\r\n public void closeCode() {\r\n if (type.name.equals(void$name)) {\r\n mw().visitInsn(RETURN);\r\n }\r\n var end_label = new Label();\r\n mw().visitLabel(end_label);\r\n var variableMetaData = variableMeta.peek();\r\n for (var meta_data : variableMetaData) {\r\n var descriptor = meta_data.descriptor;\r\n mw().visitLocalVariable(\r\n meta_data.name,\r\n descriptor,\r\n meta_data.typeSignature,\r\n meta_data.label,\r\n end_label, meta_data.index\r\n );\r\n //for the annotations attached to this field\r\n if (meta_data.metaCalls != null) {\r\n var starts = new Label[meta_data.metaCalls.size()];\r\n var ends = new Label[meta_data.metaCalls.size()];\r\n var indices = new int[meta_data.metaCalls.size()];\r\n for (int index = 0; index < meta_data.metaCalls.size(); index++) {\r\n starts[index] = meta_data.label;\r\n ends[index] = end_label;\r\n indices[index] = meta_data.index;\r\n }\r\n for (var metaCall : meta_data.metaCalls) {\r\n var meta = (YaaMeta) fs6.getSymbol(metaCall.name.content);\r\n F6MetaCall.visitArguments(\r\n metaCall, meta,\r\n mw().visitLocalVariableAnnotation(\r\n 1073741824,\r\n null,\r\n starts,\r\n ends,\r\n indices,\r\n meta.descriptor(),\r\n meta.retention == RetentionPolicy.RUNTIME\r\n )\r\n );\r\n }\r\n }\r\n if (meta_data.type_args.size() > 0) {\r\n InternalMetaGen.nestedTypeArgs(meta_data.type_args, (fromString, meta, typeArg, metaCall) -> {\r\n var started = new Label[typeArg.metaCalls.size()];\r\n var ended = new Label[typeArg.metaCalls.size()];\r\n var indexical = new int[typeArg.metaCalls.size()];\r\n for (int i = 0; i < typeArg.metaCalls.size(); i++) {\r\n started[i] = meta_data.label;\r\n ended[i] = end_label;\r\n indexical[i] = meta_data.index;\r\n }\r\n F6MetaCall.visitArguments(\r\n metaCall, meta,\r\n mw().visitLocalVariableAnnotation(\r\n MetaReference.LOCAL_INTERNAL_META_REF,\r\n TypePath.fromString(fromString),\r\n started,\r\n ended,\r\n indexical,\r\n meta.descriptor(),\r\n meta.retention == RetentionPolicy.RUNTIME\r\n )\r\n );\r\n });\r\n }\r\n }\r\n mw().visitMaxs(0, 0);\r\n mw().visitEnd();\r\n F6.mtdWriters.pop();\r\n fs6.pop$variables();\r\n variableMeta.pop();\r\n F6.f6TopMtd.pop();\r\n }\r\n}", "answers": [" return print_pack;\r"], "length": 1002, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "28d23c9b-d4f9-4433-923b-7acd82a7a134", "reasoning": "In PropertyMold.property() we create a LinkedList of YaaFun, add a function, wrap it in an MtdPack called print_pack. The method should return this pack. The commented line suggests a possible flag, but the next logical line is to return the constructed pack.", "reasoning_model_answer": "return print_pack;", "assistant_with_reasoning": "\nIn PropertyMold.property() we create a LinkedList of YaaFun, add a function, wrap it in an MtdPack called print_pack. The method should return this pack. The commented line suggests a possible flag, but the next logical line is to return the constructed pack.\n\nreturn print_pack;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.388, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11554, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "return print_pack;", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.example.mediaarchival.controllers.MediaController;\nimport com.example.mediaarchival.enums.ArchivedStatus;\nimport com.example.mediaarchival.models.MediaModel;\nimport com.example.mediaarchival.repositories.MediaRepository;\nimport com.example.mediaarchival.utils.TarUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.time.Instant;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport software.amazon.awssdk.transfer.s3.model.FileDownload;\nimport software.amazon.awssdk.transfer.s3.model.FileUpload;\nimport software.amazon.awssdk.transfer.s3.progress.TransferListener;", "context": "backend/src/main/java/com/example/mediaarchival/consumers/MediaObjectTransferListener.java\npackage com.example.mediaarchival.consumers;\n\n\n\npublic class MediaObjectTransferListener implements TransferListener {\n\n private final MediaRepository mediaRepository;\n private final MediaController mediaController;\n private final MediaModel mediaObject;\n private final int updateIntervalPercentage;\n\n private final String tempPath;\n\n private final boolean isUpload;\n\n private long lastTransferredBytes = 0;\n private FileUpload fileUpload;\n private FileDownload fileDownload;\n private boolean jobPaused = false;\n\n private static final Logger errorLogger = LoggerFactory.getLogger(\"ERROR_LOGGER\");\n\n /**\n * A listener for media object transfer events, handling the progress tracking and completion\n * status updates for both uploads and downloads of media objects.\n */\n\n public MediaObjectTransferListener(\n MediaRepository mediaRepository,\n\nbackend/src/main/java/com/example/mediaarchival/controllers/MediaController.java\n@RestController\n@RequestMapping(\"/api/media-objects\")\npublic class MediaController {\n private final MediaRepository mediaRepository;\n\n private final JmsTemplate jmsTemplate;\n\n private static final Logger errorLogger = LoggerFactory.getLogger(\"ERROR_LOGGER\");\n\n public MediaController(MediaRepository mediaRepository, JmsTemplate jmsTemplate) {\n this.mediaRepository = mediaRepository;\n this.jmsTemplate = jmsTemplate;\n }\n\n /**\n * Retrieves a paginated, sorted, and filtered list of media objects based on the provided criteria.\n *\n * @param archivedStatus The status to filter archived media.\n * @param search The search term for media names.\n * @param libraryId The ID of the library to filter media.\n * @param isRecovering Filter for media currently in the process of recovery.\n * @param isArchiving Filter for media currently in the process of archiving.\n * @param page The page number for pagination.\n * @param size The size of each page.\n * @param sortBy The attribute to sort by.\n * @param sortDirection The direction of sorting.\n * @return A ResponseEntity containing a page of filtered, sorted media objects.\n */\n @GetMapping\n public ResponseEntity> getAllMedias(\n @RequestParam(required = false) ArchivedStatus archivedStatus,\n @RequestParam(required = false) String search,\n @RequestParam(required = false) Long libraryId,\n @RequestParam(required = false) Boolean isRecovering,\n @RequestParam(required = false) Boolean isArchiving,\n @RequestParam(defaultValue = \"0\") int page,\n @RequestParam(defaultValue = \"10\") int size,\n @RequestParam(required = false, defaultValue = \"name\") String sortBy,\n @RequestParam(required = false, defaultValue = \"asc\") String sortDirection) {\n\n Sort sort;\n if (\"asc\".equalsIgnoreCase(sortDirection)) {\n sort = Sort.by(Sort.Direction.ASC, sortBy);\n } else {\n sort = Sort.by(Sort.Direction.DESC, sortBy);\n }\n\n if (\"uploadJobs\".equals(sortBy)) {\n sort = MediaSpecifications.getUploadJobsSort();\n } else if (\"downloadJobs\".equals(sortBy)) {\n sort = MediaSpecifications.getDownloadJobsSort();\n }\n\n // Create a Pageable object with sorting\n Pageable pageable = PageRequest.of(page, size, sort);\n\n // Build the specification based on filters\n Specification specification =\n MediaSpecifications.filterByArchivedStatus(archivedStatus)\n .and(MediaSpecifications.searchMediaInSubset(search))\n .and(MediaSpecifications.filterByLibraryId(libraryId)) // Apply libraryId filter\n .and(\n MediaSpecifications.filterByIsRecovering(isRecovering)) // Apply isRetrieving filter\n .and(MediaSpecifications.filterByIsArchiving(isArchiving)); // Apply isArchiving filter\n\n // Fetch paginated, sorted, and filtered media objects\n Page media = mediaRepository.findAll(specification, pageable);\n\n return ResponseEntity.ok(media);\n }\n\n /**\n * Retrieves a specific media object by its ID.\n *\n * @param id The ID of the media object to retrieve.\n * @return A ResponseEntity containing the requested media object.\n * @throws ResourceNotFoundException If no media object is found with the given ID.\n */\n @GetMapping(\"/{id}\")\n public ResponseEntity getMediaById(@PathVariable Long id) {\n MediaModel media =\n mediaRepository\n .findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Media not found with id: \" + id));\n return ResponseEntity.ok(media);\n }\n\n /**\n * Deletes a specific media object by its ID.\n *\n * @param id The ID of the media object to delete.\n * @return A ResponseEntity with no content.\n * @throws ResourceNotFoundException If no media object is found with the given ID.\n */\n @DeleteMapping(\"/{id}\")\n public ResponseEntity deleteMedia(@PathVariable Long id) {\n MediaModel mediaObject =\n mediaRepository\n .findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Media not found with id: \" + id));\n\n mediaRepository.delete(mediaObject);\n return ResponseEntity.noContent().build();\n }\n\n /**\n * Bulk delete media objects\n *\n * @param ids The paths of the media objects to delete.\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/bulk-delete\")\n public ResponseEntity bulkDeleteMediaObjects(@RequestBody List ids) {\n for (long id : ids) {\n try{\n MediaModel media = mediaRepository\n .findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Media not found with id: \" + id));\n mediaRepository.delete(media);\n } catch (Exception e){\n errorLogger.error(e.getMessage());\n }\n }\n\n return ResponseEntity.ok(\"Deletes successful\");\n }\n\n /**\n * Sends requests to archive a list of media objects identified by their paths.\n *\n * @param paths The paths of the media objects to archive.\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/archive\")\n public ResponseEntity archiveMediaObjects(@RequestBody List paths) {\n for (String path : paths) {\n MediaModel media = mediaRepository.findByPath(path);\n if (!media.isArchiving() && !media.isRecovering()) {\n media.setArchiving(true);\n media.setUploadProgress(-1);\n media.setTarring(false);\n mediaRepository.save(media);\n jmsTemplate.convertAndSend(\"archivingQueue\", media.getPath());\n }\n }\n\n return ResponseEntity.ok(\"Archive requests sent successfully\");\n }\n\n /**\n * Prepares a list of media objects for download by sending the appropriate requests.\n *\n * @param paths The paths of the media objects to prepare for download.\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/prepare-download\")\n public ResponseEntity prepareMediaObjectsForDownload(@RequestBody List paths) {\n for (String path : paths) {\n MediaModel media = mediaRepository.findByPath(path);\n\n // Retrieve the associated library's storage class\n StorageClass storageClass = media.getLibrary().getStorageClass();\n prepareDownload(media, storageClass, jmsTemplate, mediaRepository);\n }\n\n return ResponseEntity.ok(\"Download preparation requests sent successfully\");\n }\n\n /**\n * Cancels ongoing jobs for a list of media objects identified by their IDs.\n *\n * @param ids The IDs of the media objects for which jobs are to be cancelled.\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/cancel-job\")\n public ResponseEntity cancelJobs(@RequestBody List ids) {\n for (long id : ids) {\n MediaModel media =\n mediaRepository\n .findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Media not found with id: \" + id));\n if (((media.isRecovering() && media.getDownloadSuccess() == null) || media.isArchiving())\n && !media.isJobCancelled()) {\n media.setJobCancelled(true);\n mediaRepository.save(media);\n }\n }\n\n return ResponseEntity.ok(\"Jobs cancelled\");\n }\n\n /**\n * Cancels all ongoing archive jobs for media objects.\n *\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/cancel-all-archive-jobs\")\n public ResponseEntity cancelAllArchiveJobs() {\n List medias = mediaRepository.findByIsArchiving(true);\n for (MediaModel media : medias) {\n if (!media.isJobCancelled()) {\n media.setJobCancelled(true);\n mediaRepository.save(media);\n }\n }\n\n return ResponseEntity.ok(\"Jobs cancelled\");\n }\n\n /**\n * Cancels all ongoing download jobs for media objects.\n *\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/cancel-all-download-jobs\")\n public ResponseEntity cancelAllDownloadJobs() {\n List medias = mediaRepository.findByIsRecovering(true);\n for (MediaModel media : medias) {\n if (!media.isJobCancelled() && media.getDownloadSuccess() == null) {\n media.setJobCancelled(true);\n mediaRepository.save(media);\n }\n }\n\n return ResponseEntity.ok(\"Jobs cancelled\");\n }\n\n /**\n * Clears the status of all media objects that have finished downloading.\n *\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/clear-all-finished\")\n public ResponseEntity clearAllFinishedDownloads() {\n List successes = mediaRepository.findByDownloadSuccess(true);\n List failures = mediaRepository.findByDownloadSuccess(false);\n\n for (MediaModel media : successes) {\n media.setDownloadSuccess(null);\n media.setRecovering(false);\n mediaRepository.save(media);\n }\n for (MediaModel media : failures) {\n media.setDownloadSuccess(null);\n media.setRecovering(false);\n mediaRepository.save(media);\n }\n return ResponseEntity.ok(\"Cleared finished downloads\");\n }\n\n /**\n * Clears the status of selected media objects that have finished downloading.\n *\n * @param ids The IDs of the media objects to clear.\n * @return A ResponseEntity with a confirmation message.\n */\n @PostMapping(\"/clear-finished\")\n public ResponseEntity clearFinishedDownloads(@RequestBody List ids) {\n for (long id : ids) {\n MediaModel media =\n mediaRepository\n .findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Media not found with id: \" + id));\n if ((media.isRecovering() || media.isArchiving()) && !media.isJobCancelled()) {\n media.setDownloadSuccess(null);\n media.setRecovering(false);\n mediaRepository.save(media);\n }\n }\n return ResponseEntity.ok(\"Cleared finished selected downloads\");\n }\n\n /**\n * Prepares a media object for download based on its storage class.\n *\n * @param media The media object to prepare for download.\n * @param storageClass The storage class of the media object's library.\n * @param jmsTemplate The JmsTemplate for sending messages.\n * @param mediaRepository The repository for saving changes to the media object.\n */\n public static void prepareDownload(\n MediaModel media,\n StorageClass storageClass,\n JmsTemplate jmsTemplate,\n MediaRepository mediaRepository) {\n if (!media.isRecovering() && media.getDownloadSuccess() == null && !media.isArchiving()) {\n media.setRecovering(true);\n mediaRepository.save(media);\n if (StorageClass.DEEP_ARCHIVE == storageClass || StorageClass.GLACIER == storageClass) {\n jmsTemplate.convertAndSend(\"restoreQueue\", media.getPath());\n } else {\n jmsTemplate.convertAndSend(\"downloadQueue\", media.getPath());\n }\n }\n }\n\n /**\n * Checks if a job related to a specific media object is cancelled.\n *\n * @param id The ID of the media object.\n * @return A Boolean indicating if the job is cancelled.\n * @throws ResourceNotFoundException If no media object is found with the given ID.\n */\n public Boolean getJobCancelled(@PathVariable Long id) {\n MediaModel media =\n mediaRepository\n .findById(id)\n .orElseThrow(() -> new ResourceNotFoundException(\"Media not found with id: \" + id));\n return media.isJobCancelled();\n }\n}", "answers": [" MediaController mediaController,"], "length": 1272, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "ca551429-ea31-4f57-b8c3-8083aff01eb6", "reasoning": "The constructor for MediaObjectTransferListener has begun with the opening parenthesis and the first parameter MediaRepository mediaRepository. The class fields include a MediaController, so the next parameter in the constructor should be MediaController mediaController, continuing the parameter list. Therefore the next line is the declaration of that parameter.", "reasoning_model_answer": "MediaController mediaController,", "assistant_with_reasoning": "\nThe constructor for MediaObjectTransferListener has begun with the opening parenthesis and the first parameter MediaRepository mediaRepository. The class fields include a MediaController, so the next parameter in the constructor should be MediaController mediaController, continuing the parameter list. Therefore the next line is the declaration of that parameter.\n\nMediaController mediaController,", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.086, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13238, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "MediaController mediaController,", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "from typing import Union\nfrom lightphe.models.Homomorphic import Homomorphic\nfrom lightphe.models.Algorithm import Algorithm\nfrom lightphe.cryptosystems.RSA import RSA\nfrom lightphe.cryptosystems.ElGamal import ElGamal\nfrom lightphe.cryptosystems.Paillier import Paillier\nfrom lightphe.cryptosystems.DamgardJurik import DamgardJurik\nfrom lightphe.cryptosystems.OkamotoUchiyama import OkamotoUchiyama\nfrom lightphe.cryptosystems.Benaloh import Benaloh\nfrom lightphe.cryptosystems.NaccacheStern import NaccacheStern\nfrom lightphe.cryptosystems.GoldwasserMicali import GoldwasserMicali\nfrom lightphe.cryptosystems.EllipticCurveElGamal import EllipticCurveElGamal\nfrom lightphe.commons import phe_utils\nfrom lightphe.commons.logger import Logger", "context": "lightphe/models/Ciphertext.py\n\nlogger = Logger(module=\"lightphe/models/Ciphertext.py\")\n\n# pylint: disable=too-few-public-methods, no-else-return\n\n\nclass Ciphertext:\n def __init__(self, algorithm_name: str, keys: dict, value: Union[int, tuple, list]):\n self.algorithm_name = algorithm_name\n self.keys = keys\n self.value = value\n\n if algorithm_name == Algorithm.RSA:\n cs = RSA(keys=keys)\n elif algorithm_name == Algorithm.ElGamal:\n cs = ElGamal(keys=keys)\n elif algorithm_name == Algorithm.ExponentialElGamal:\n cs = ElGamal(keys=keys, exponential=True)\n elif algorithm_name == Algorithm.EllipticCurveElGamal:\n\n\nlightphe/cryptosystems/Paillier.py\nclass Paillier(Homomorphic):\n \"\"\"\n Paillier algorithm is homomorphic with respect to the addition.\n Also, it supports power operation for ciphertext base and plaintext exponent\n Ref: https://sefiks.com/2023/04/03/a-step-by-step-partially-homomorphic-encryption-example-with-paillier-in-python/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size=1024):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n n = self.keys[\"public_key\"][\"n\"]\n self.plaintext_modulo = n\n self.ciphertext_modulo = n * n\n\n def generate_keys(self, key_size: int):\n \"\"\"\n Generate public and private keys of Paillier cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n # picking a prime modulus p\n p = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n # picking a prime modulus q\n q = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n n = p * q\n phi = (p - 1) * (q - 1)\n g = 1 + n\n\n keys[\"private_key\"][\"phi\"] = phi\n keys[\"public_key\"][\"g\"] = g\n keys[\"public_key\"][\"n\"] = n\n\n return keys\n\n def generate_random_key(self) -> int:\n \"\"\"\n Paillier requires to generate one-time random key per encryption\n Returns:\n random key (int): one time random key for encryption\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n while True:\n r = random.randint(0, n)\n if math.gcd(r, n) == 1:\n break\n return r\n\n def encrypt(self, plaintext: int, random_key: Optional[int] = None) -> int:\n \"\"\"\n Encrypt a given plaintext for optionally given random key with Paillier\n Args:\n plaintext (int): message to encrypt\n random_key (int): Paillier requires a random key that co-prime to n.\n Random key will be generated automatically if you do not set this.\n Returns:\n ciphertext (int): encrypted message\n \"\"\"\n g = self.keys[\"public_key\"][\"g\"]\n n = self.keys[\"public_key\"][\"n\"]\n r = random_key or self.generate_random_key()\n assert math.gcd(r, n) == 1\n return (pow(g, plaintext, n * n) * pow(r, n, n * n)) % (n * n)\n\n def decrypt(self, ciphertext: int):\n \"\"\"\n Decrypt a given ciphertext with Paillier\n Args:\n ciphertext (int): encrypted message\n Returns:\n plaintext (int): restored message\n \"\"\"\n phi = self.keys[\"private_key\"][\"phi\"]\n n = self.keys[\"public_key\"][\"n\"]\n mu = pow(phi, -1, n)\n\n return (self.lx(pow(ciphertext, phi, n * n)) * mu) % (n)\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic addition on encrypted data.\n Result of this must be equal to E(m1 + m2)\n Encryption calculations are done in module n squared.\n Args:\n ciphertext1 (int): 1st ciphertext created with Paillier\n ciphertext2 (int): 2nd ciphertext created with Paillier\n Returns:\n ciphertext3 (int): 3rd ciphertext created with Paillier\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return (ciphertext1 * ciphertext2) % (n * n)\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Paillier is not homomorphic with respect to the multiplication\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"Paillier is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n \"\"\"\n Multiply a ciphertext with a plain constant.\n Result of this must be equal to E(m1 * m2) where E(m1) = ciphertext\n Encryption calculations are done in module n squared.\n Args:\n ciphertext (int): ciphertext created with Paillier\n constant (int): known plain constant\n Returns:\n ciphertext (int): new ciphertext created with Paillier\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n\n if constant > self.plaintext_modulo:\n constant = constant % self.plaintext_modulo\n logger.debug(\n f\"Paillier can encrypt messages [1, {n}]. \"\n f\"Seems constant exceeded this limit. New constant is {constant}\"\n )\n\n return pow(ciphertext, constant, n * n)\n\n def reencrypt(self, ciphertext: int) -> int:\n \"\"\"\n Re-generate ciphertext with re-encryption. Many ciphertext will be decrypted to same plaintext.\n Args:\n ciphertext (int): given ciphertext\n Returns:\n new ciphertext (int): different ciphertext for same plaintext\n \"\"\"\n neutral_element = 0\n neutral_encrypted = self.encrypt(plaintext=neutral_element)\n return self.add(ciphertext1=ciphertext, ciphertext2=neutral_encrypted)\n\n def lx(self, x: int) -> int:\n \"\"\"\n Find logarithm over cyclic group\n Args:\n x (int): some integer\n Returns:\n lx (int): (x-1) / n\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n y = (x - 1) // n\n assert y - int(y) == 0\n return int(y)\n\nlightphe/cryptosystems/RSA.py\nclass RSA(Homomorphic):\n \"\"\"\n RSA algorithm is partially homomorphic with respect to the multiplication\n Ref: https://sefiks.com/2023/03/06/a-step-by-step-partially-homomorphic-encryption-example-with-rsa-in-python/\n \"\"\"\n\n def __init__(self, keys: Optional[dict] = None, key_size: int = 1024, encrypt_with_public=True):\n \"\"\"\n Args:\n keys (dict): private - public key pair.\n set this to None if you want to generate random keys.\n key_size (int): key size in bits\n encrypt_with_public (boolean): RSA has two keys: private (d) and public (e).\n If you encrypt a message with smo's public, then just that person can decrypt it\n with his private (secure message). Otherwise, if you encrypt it with your private,\n one can decrypt it with your public (digital signatures).\n Set this arg to True if you want to do encryption with public key e,\n and do decryption with private key d.\n \"\"\"\n self.keys = keys or self.generate_keys(key_size)\n self.plaintext_modulo = self.keys[\"public_key\"][\"n\"]\n self.ciphertext_modulo = self.keys[\"public_key\"][\"n\"]\n self.encrypt_with_public = encrypt_with_public\n\n def generate_keys(self, key_size: int) -> dict:\n \"\"\"\n Generate public and private keys of RSA cryptosystem\n Args:\n key_size (int): key size in bits\n Returns:\n keys (dict): having private_key and public_key keys\n \"\"\"\n keys = {}\n keys[\"private_key\"] = {}\n keys[\"public_key\"] = {}\n\n while True:\n try:\n # picking a prime modulus p and q\n p = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n q = sympy.randprime(200, 2 ** int(key_size / 2) - 1)\n\n n = p * q\n phi = (p - 1) * (q - 1)\n\n # select public exponent e\n while True:\n e = random.randint(1, phi - 1)\n if math.gcd(e, n) == 1:\n break\n\n d = pow(e, -1, phi)\n break\n except:\n pass\n\n keys[\"public_key\"][\"n\"] = n\n keys[\"public_key\"][\"e\"] = e\n keys[\"private_key\"][\"d\"] = d\n return keys\n\n def generate_random_key(self) -> int:\n pass\n\n def encrypt(self, plaintext: int) -> int:\n \"\"\"\n Encrypt plain messages with RSA\n Args:\n plaintext (int): plain message\n Returns:\n ciphertext (int): ciphertext encrypted with RSA\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n\n if plaintext > n:\n plaintext = plaintext % n\n logger.debug(\n f\"RSA can encrypt messages [1, {n}]. \"\n f\"Seems you exceeded this limit. New plaintext is {plaintext}\"\n )\n\n if self.encrypt_with_public is True:\n e = self.keys[\"public_key\"][\"e\"]\n c = pow(plaintext, e, n)\n else:\n d = self.keys[\"private_key\"][\"d\"]\n c = pow(plaintext, d, n)\n\n return c\n\n def decrypt(self, ciphertext: int) -> int:\n \"\"\"\n Decrypt ciphertexts with RSA\n Args:\n ciphertext (int): encrypted message\n decrypt_with_private (int): RSA has two keys: private (d) and public (e).\n If you encrypt a message with smo's public, then just that person can decrypt it\n with his private (secure message). Otherwise, if you encrypt it with your private,\n one can decrypt it with your public (digital signatures).\n Set this arg to True if you want to do encryption with public key e,\n and do decryption with private key d.\n Returns:\n plaintext (int): restored message\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n if self.encrypt_with_public is True:\n d = self.keys[\"private_key\"][\"d\"]\n p = pow(ciphertext, d, n)\n else:\n e = self.keys[\"public_key\"][\"e\"]\n p = pow(ciphertext, e, n)\n\n return p\n\n def multiply(self, ciphertext1: int, ciphertext2: int) -> int:\n \"\"\"\n Perform homomorphic multiplication on encrypted data.\n Result of this must be equal to E(m1 * m2)\n \"\"\"\n n = self.keys[\"public_key\"][\"n\"]\n return (ciphertext1 * ciphertext2) % n\n\n def add(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"RSA is not homomorphic with respect to the addition\")\n\n def xor(self, ciphertext1: int, ciphertext2: int) -> int:\n raise ValueError(\"RSA is not homomorphic with respect to the exclusive or\")\n\n def multiply_by_contant(self, ciphertext: int, constant: int) -> int:\n raise ValueError(\"RSA is not supporting multiplying ciphertext by a known constant\")\n\n def reencrypt(self, ciphertext: int) -> int:\n raise ValueError(\"RSA does not support re-encryption\")", "answers": [" cs = EllipticCurveElGamal(keys=keys)"], "length": 1317, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "864f2d3b-f461-4223-92bc-8837a6ea3929", "reasoning": "The __init__ method is selecting the appropriate cryptosystem class based on the algorithm_name. The last conditional checks for Algorithm.EllipticCurveElGamal, so the next line should instantiate the EllipticCurveElGamal class with the provided keys, matching the pattern of the previous branches.", "reasoning_model_answer": "cs = EllipticCurveElGamal(keys=keys)", "assistant_with_reasoning": "\nThe __init__ method is selecting the appropriate cryptosystem class based on the algorithm_name. The last conditional checks for Algorithm.EllipticCurveElGamal, so the next line should instantiate the EllipticCurveElGamal class with the provided keys, matching the pattern of the previous branches.\n\ncs = EllipticCurveElGamal(keys=keys)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.818, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 12291, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "cs = EllipticCurveElGamal(keys=keys)", "score": 0.86, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.math.BigDecimal;\r\nimport java.time.LocalDate;\r\nimport java.time.YearMonth;\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.SortedMap;\r\nimport java.util.TreeMap;\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.stereotype.Service;\r\nimport org.springframework.transaction.annotation.Propagation;\r\nimport org.springframework.transaction.annotation.Transactional;\r\nimport app.condominio.domain.Categoria;\r\nimport app.condominio.domain.Cobranca;\r\nimport app.condominio.domain.Conta;\r\nimport app.condominio.domain.Moradia;\r\nimport app.condominio.domain.Movimento;\r\nimport app.condominio.domain.Orcamento;\r\nimport app.condominio.domain.Periodo;\r\nimport app.condominio.domain.Subcategoria;\r\nimport app.condominio.domain.enums.TipoCategoria;\r", "context": "src/main/java/app/condominio/service/RelatorioServiceImpl.java\n\t\tif (resultado[1] == null) {\r\n\t\t\tresultado[1] = BigDecimal.ZERO.setScale(2);\r\n\t\t}\r\n\t\treturn resultado;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic BigDecimal[] receitaDespesaMesAtual() {\r\n\t\tList contas = contaService.listar();\r\n\t\tYearMonth mesAtual = YearMonth.from(LocalDate.now());\r\n\t\t// mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes\r\n\t\treturn receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth());\r\n\t}\r\n\r\n\t@Override\r\n\tpublic BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) {\r\n\t\tList contas = contaService.listar();\r\n\t\treturn receitaDespesaEntre(contas, inicio, fim);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic BigDecimal[] receitaDespesaRealizadaPeriodoAtual() {\r\n\t\tList contas = contaService.listar();\r\n\t\tPeriodo periodoAtual = periodoService.ler(LocalDate.now());\r\n\t\tif (periodoAtual != null) {\r\n\t\t\treturn receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim());\r\n\t\t} else {\r\n\t\t\tBigDecimal[] resultado = new BigDecimal[2];\r\n\t\t\tresultado[0] = BigDecimal.ZERO.setScale(2);\r\n\t\t\tresultado[1] = BigDecimal.ZERO.setScale(2);\r\n\t\t\treturn resultado;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic BigDecimal[] receitaDespesaOrcadaPeriodoAtual() {\r\n\t\tPeriodo periodoAtual = periodoService.ler(LocalDate.now());\r\n\t\tBigDecimal[] resultado = new BigDecimal[2];\r\n\t\tif (periodoAtual != null) {\r\n\t\t\tresultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R);\r\n\t\t\tresultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D);\r\n\t\t}\r\n\t\tif (resultado[0] == null) {\r\n\t\t\tresultado[0] = BigDecimal.ZERO.setScale(2);\r\n\t\t}\r\n\t\tif (resultado[1] == null) {\r\n\t\t\tresultado[1] = BigDecimal.ZERO.setScale(2);\r\n\t\t}\r\n\t\treturn resultado;\r\n\r\n\t}\r\n\r\n\t@Override\r\n\tpublic List lancamentosEntre(LocalDate inicio, LocalDate fim) {\r\n\t\tList contas = contaService.listar();\r\n\t\tif (!contas.isEmpty()) {\r\n\t\t\tList lancamentos = new ArrayList<>();\r\n\t\t\tlancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim));\r\n\t\t\treturn lancamentos;\r\n\t\t}\r\n\t\treturn new ArrayList<>();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic BigDecimal[] saldosAposMovimentos(List movimentos, BigDecimal saldoInicial) {\r\n\t\tif (saldoInicial == null) {\r\n\t\t\tsaldoInicial = BigDecimal.ZERO.setScale(2);\r\n\t\t}\r\n\t\tif (!movimentos.isEmpty()) {\r\n\t\t\tBigDecimal[] saldos = new BigDecimal[movimentos.size()];\r\n\t\t\tMovimento movimento = movimentos.get(0);\r\n\t\t\t// Preenche o primeiro saldo\r\n\t\t\tif (movimento.getReducao()) {\r\n\t\t\t\tsaldos[0] = saldoInicial.subtract(movimento.getValor());\r\n\t\t\t} else {\r\n\t\t\t\tsaldos[0] = saldoInicial.add(movimento.getValor());\r\n\t\t\t}\r\n\t\t\t// Preenche os outros saldos\r\n\t\t\tfor (int i = 1; i < saldos.length; i++) {\r\n\t\t\t\tmovimento = movimentos.get(i);\r\n\t\t\t\tif (movimento.getReducao()) {\r\n\t\t\t\t\tsaldos[i] = saldos[i - 1].subtract(movimento.getValor());\r\n\t\t\t\t} else {\r\n\t\t\t\t\tsaldos[i] = saldos[i - 1].add(movimento.getValor());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn saldos;\r\n\t\t} else {\r\n\t\t\tBigDecimal[] vazio = new BigDecimal[1];\r\n\t\t\tvazio[0] = saldoInicial;\r\n\t\t\treturn vazio;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic SortedMap somasPorTipoEntre(LocalDate inicio, LocalDate fim,\r\n\t\t\tTipoCategoria tipoCategoria) {\r\n\t\tSortedMap map = new TreeMap<>();\r\n\t\tList contas = contaService.listar();\r\n\t\tif (!contas.isEmpty()) {\r\n\t\t\tList subcategorias;\r\n\t\t\tif (TipoCategoria.R.equals(tipoCategoria)) {\r\n\t\t\t\tsubcategorias = subcategoriaService.listarReceitas();\r\n\t\t\t} else if (TipoCategoria.D.equals(tipoCategoria)) {\r\n\t\t\t\tsubcategorias = subcategoriaService.listarDespesas();\r\n\t\t\t} else {\r\n\t\t\t\treturn map;\r\n\t\t\t}\r\n\t\t\tfor (Subcategoria subcategoria : subcategorias) {\r\n\t\t\t\tBigDecimal soma = movimentoService.somaLancamentosEntre(contas, inicio, fim, subcategoria);\r\n\t\t\t\tif (soma != null && soma.compareTo(BigDecimal.ZERO) != 0) {\r\n\t\t\t\t\tmap.put(subcategoria, soma);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn map;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic SortedMap> inadimplenciaAtualDetalhada() {\r\n\nsrc/main/java/app/condominio/domain/Movimento.java\n@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"movimentos\")\r\n@Inheritance(strategy = InheritanceType.JOINED)\r\npublic class Movimento implements Serializable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idmovimento\")\r\n\tprivate Long idMovimento;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\tprivate LocalDate data;\r\n\r\n\t@NotNull\r\n\t@Min(0)\r\n\tprivate BigDecimal valor;\r\n\r\n\t@Size(max = 20)\r\n\tprivate String documento;\r\n\r\n\t@Size(max = 255)\r\n\tprivate String descricao;\r\n\r\n\tprivate Boolean reducao;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idconta\")\r\n\tprivate Conta conta;\r\n\r\n\tpublic Long getIdMovimento() {\r\n\t\treturn idMovimento;\r\n\t}\r\n\r\n\tpublic void setIdMovimento(Long idMovimento) {\r\n\t\tthis.idMovimento = idMovimento;\r\n\t}\r\n\r\n\tpublic LocalDate getData() {\r\n\t\treturn data;\r\n\t}\r\n\r\n\tpublic void setData(LocalDate data) {\r\n\t\tthis.data = data;\r\n\t}\r\n\r\n\tpublic BigDecimal getValor() {\r\n\t\treturn valor;\r\n\t}\r\n\r\n\tpublic void setValor(BigDecimal valor) {\r\n\t\tthis.valor = valor;\r\n\t}\r\n\r\n\tpublic String getDescricao() {\r\n\t\treturn descricao;\r\n\t}\r\n\r\n\tpublic void setDescricao(String descricao) {\r\n\t\tthis.descricao = descricao;\r\n\t}\r\n\r\n\tpublic String getDocumento() {\r\n\t\treturn documento;\r\n\t}\r\n\r\n\tpublic void setDocumento(String documento) {\r\n\t\tthis.documento = documento;\r\n\t}\r\n\r\n\tpublic Boolean getReducao() {\r\n\t\treturn reducao;\r\n\t}\r\n\r\n\tpublic void setReducao(Boolean reducao) {\r\n\t\tthis.reducao = reducao;\r\n\t}\r\n\r\n\tpublic Conta getConta() {\r\n\t\treturn conta;\r\n\t}\r\n\r\n\tpublic void setConta(Conta conta) {\r\n\t\tthis.conta = conta;\r\n\t}\r\n\r\n\tpublic String detalhe() {\r\n\t\tif (reducao) {\r\n\t\t\treturn \"Saída\";\r\n\t\t} else {\r\n\t\t\treturn \"Entrada\";\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tDateTimeFormatter formato = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\r\n\t\tString s = data.format(formato) + \" - \";\r\n\t\tif (documento != null) {\r\n\t\t\ts += documento + \" - \";\r\n\t\t}\r\n\t\ts += \"R$ \" + valor;\r\n\t\treturn s;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idMovimento == null) ? 0 : idMovimento.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tMovimento other = (Movimento) obj;\r\n\t\tif (idMovimento == null) {\r\n\t\t\tif (other.idMovimento != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idMovimento.equals(other.idMovimento)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r\n\nsrc/main/java/app/condominio/domain/Periodo.java\n@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"periodos\")\r\npublic class Periodo implements Serializable, Comparable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idperiodo\")\r\n\tprivate Long idPeriodo;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\tprivate LocalDate inicio;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\tprivate LocalDate fim;\r\n\r\n\tprivate Boolean encerrado;\r\n\r\n\t@OneToMany(mappedBy = \"periodo\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\t@OrderBy(value = \"subcategoria\")\r\n\tprivate List orcamentos = new ArrayList<>();\r\n\r\n\t@OneToMany(mappedBy = \"periodo\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\tprivate List lancamentos = new ArrayList<>();\r\n\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idcondominio\")\r\n\tprivate Condominio condominio;\r\n\r\n\tpublic Long getIdPeriodo() {\r\n\t\treturn idPeriodo;\r\n\t}\r\n\r\n\tpublic void setIdPeriodo(Long idPeriodo) {\r\n\t\tthis.idPeriodo = idPeriodo;\r\n\t}\r\n\r\n\tpublic LocalDate getInicio() {\r\n\t\treturn inicio;\r\n\t}\r\n\r\n\tpublic void setInicio(LocalDate inicio) {\r\n\t\tthis.inicio = inicio;\r\n\t}\r\n\r\n\tpublic LocalDate getFim() {\r\n\t\treturn fim;\r\n\t}\r\n\r\n\tpublic void setFim(LocalDate fim) {\r\n\t\tthis.fim = fim;\r\n\t}\r\n\r\n\tpublic Boolean getEncerrado() {\r\n\t\treturn encerrado;\r\n\t}\r\n\r\n\tpublic void setEncerrado(Boolean encerrado) {\r\n\t\tthis.encerrado = encerrado;\r\n\t}\r\n\r\n\tpublic Condominio getCondominio() {\r\n\t\treturn condominio;\r\n\t}\r\n\r\n\tpublic void setCondominio(Condominio condominio) {\r\n\t\tthis.condominio = condominio;\r\n\t}\r\n\r\n\tpublic List getOrcamentos() {\r\n\t\treturn orcamentos;\r\n\t}\r\n\r\n\tpublic void setOrcamentos(List orcamentos) {\r\n\t\tthis.orcamentos = orcamentos;\r\n\t}\r\n\r\n\tpublic List getLancamentos() {\r\n\t\treturn lancamentos;\r\n\t}\r\n\r\n\tpublic void setLancamentos(List lancamentos) {\r\n\t\tthis.lancamentos = lancamentos;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tDateTimeFormatter formato = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\r\n\t\treturn inicio.format(formato) + \" a \" + fim.format(formato);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idPeriodo == null) ? 0 : idPeriodo.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tPeriodo other = (Periodo) obj;\r\n\t\tif (idPeriodo == null) {\r\n\t\t\tif (other.idPeriodo != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idPeriodo.equals(other.idPeriodo)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int compareTo(Periodo arg0) {\r\n\t\treturn this.inicio.compareTo(arg0.getInicio());\r\n\t}\r\n}\r", "answers": ["\t\tSortedMap> map = new TreeMap<>();\r"], "length": 1044, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "d23142cb-2be0-41c2-a89c-1986064f06d0", "reasoning": "The method 'inadimplenciaAtualDetalhada' returns a SortedMap>. Following the pattern used earlier in the class (e.g., somasPorTipoEntre creates a TreeMap for its SortedMap result), the first line inside the method should instantiate a TreeMap of the appropriate generic types. Hence the next line is the declaration and initialization of that map.", "reasoning_model_answer": "SortedMap> map = new TreeMap<>();", "assistant_with_reasoning": "\nThe method 'inadimplenciaAtualDetalhada' returns a SortedMap>. Following the pattern used earlier in the class (e.g., somasPorTipoEntre creates a TreeMap for its SortedMap result), the first line inside the method should instantiate a TreeMap of the appropriate generic types. Hence the next line is the declaration and initialization of that map.\n\nSortedMap> map = new TreeMap<>();", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.065, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10624, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "SortedMap> map = new TreeMap<>();", "score": 0.97, "is_full_score": false, "is_nonzero_score": true}} {"input": "import mdteam.ait.AITMod;\nimport mdteam.ait.client.models.consoles.BorealisConsoleModel;\nimport mdteam.ait.client.models.consoles.ConsoleModel;\nimport mdteam.ait.client.registry.console.ClientConsoleVariantSchema;\nimport mdteam.ait.tardis.variant.console.AutumnVariant;\nimport net.minecraft.util.Identifier;", "context": "src/main/java/mdteam/ait/client/registry/console/impl/ClientAutumnVariant.java\npackage mdteam.ait.client.registry.console.impl;\n\n\npublic class ClientAutumnVariant extends ClientConsoleVariantSchema {\n public static final Identifier TEXTURE = new Identifier(AITMod.MOD_ID, (\"textures/blockentities/consoles/borealis_console_autumn.png\"));\n public static final Identifier EMISSION = new Identifier(AITMod.MOD_ID, (\"textures/blockentities/consoles/borealis_console_autumn_emission.png\"));\n public ClientAutumnVariant() {\n super(AutumnVariant.REFERENCE);\n }\n\n @Override\n public Identifier texture() {\n return TEXTURE;\n }\n\n @Override\n\nsrc/main/java/mdteam/ait/AITMod.java\npublic class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true;\n\n public static final AITConfig AIT_CONFIG = AITConfig.createAndLoad(); // if this doesnt exist for you run data gen\n public static final NeptuneItemGroup AIT_ITEM_GROUP = new NeptuneItemGroup(new Identifier(AITMod.MOD_ID, \"item_group\"), AITItems.TARDIS_ITEM.getDefaultStack());\n public static final ComponentKey RADIONBT =\n ComponentRegistry.getOrCreate(new Identifier(AITMod.MOD_ID, \"radionbt\"), RadioNBTComponent.class);\n\n @Override\n public void onInitialize() {\n ServerAITNetworkManager.init();\n ConsoleRegistry.init();\n DesktopRegistry.init();\n ExteriorRegistry.init();\n HumsRegistry.init();\n CreakRegistry.init();\n SequenceRegistry.init();\n\n // These 3 have client registries which also need registering to.\n ConsoleVariantRegistry.init();\n ExteriorVariantRegistry.init();\n DoorRegistry.init();\n\n NeptuneInitHandler.register(AITItems.class, MOD_ID);\n NeptuneInitHandler.register(AITBlocks.class, MOD_ID);\n NeptuneInitHandler.register(AITSounds.class, MOD_ID);\n NeptuneInitHandler.register(AITBlockEntityTypes.class, MOD_ID);\n NeptuneInitHandler.register(AITEntityTypes.class, MOD_ID);\n\n\n TardisUtil.init();\n TardisManager.getInstance();\n TardisManager.init();\n RiftChunkManager.init();\n TardisCriterions.init();\n\n entityAttributeRegister();\n\n // ip support\n if (DependencyChecker.hasPortals())\n PortalsHandler.init();\n\n if (DependencyChecker.hasRegeneration())\n RegenHandler.init();\n\n CommandRegistrationCallback.EVENT.register(((dispatcher, registryAccess, environment) -> {\n TeleportInteriorCommand.register(dispatcher);\n UnlockInteriorsCommand.register(dispatcher);\n SummonTardisCommand.register(dispatcher);\n SetLockedCommand.register(dispatcher);\n // SetHumCommand.register(dispatcher);\n SetFuelCommand.register(dispatcher);\n AddFuelCommand.register(dispatcher);\n RemoveFuelCommand.register(dispatcher);\n ToggleHumCommand.register(dispatcher);\n ToggleAlarmCommand.register(dispatcher);\n ToggleSiegeModeCommand.register(dispatcher);\n RiftChunkCommand.register(dispatcher);\n RealWorldCommand.register(dispatcher);\n }));\n\n ServerBlockEntityEvents.BLOCK_ENTITY_LOAD.register(((blockEntity, world) -> {\n // fixme this doesnt seem to run??\n if (blockEntity instanceof ConsoleBlockEntity console) {\n console.markNeedsSyncing();\n }\n }));\n\n TardisEvents.LANDED.register((tardis -> {\n // stuff for resetting the ExteriorAnimation\n if (tardis.getTravel().getPosition().getWorld().getBlockEntity(tardis.getTravel().getExteriorPos()) instanceof ExteriorBlockEntity entity) {\n entity.getAnimation().setupAnimation(tardis.getTravel().getState());\n }\n }));\n\n TardisEvents.DEMAT.register((tardis -> {\n if (tardis.isGrowth() || tardis.getHandlers().getInteriorChanger().isGenerating() || PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.HANDBRAKE) || PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.IS_FALLING) || tardis.isRefueling())\n return true; // cancelled\n\n if (tardis.getDoor().isOpen() /*|| !tardis.getDoor().locked()*/)\n return true;\n\n for (PlayerEntity player : TardisUtil.getPlayersInInterior(tardis)) {\n TardisCriterions.TAKEOFF.trigger((ServerPlayerEntity) player);\n }\n return false;\n }));\n\n TardisEvents.MAT.register((tardis -> {\n // Check that the tardis has finished flight\n boolean flightDone = tardis.getHandlers().getFlight().hasFinishedFlight();\n\n // Check if the Tardis is on cooldown\n boolean isCooldown = FlightUtil.isMaterialiseOnCooldown(tardis);\n\n // Check if the destination is already occupied\n boolean isDestinationOccupied = !tardis.getTravel().getPosition().equals(tardis.getTravel().getDestination()) && !tardis.getTravel().checkDestination();\n\n return /*!flightDone ||*/ isCooldown || isDestinationOccupied;\n }));\n\n TardisEvents.CRASH.register((tardis -> {\n for (PlayerEntity player : TardisUtil.getPlayersInInterior(tardis)) {\n TardisCriterions.CRASH.trigger((ServerPlayerEntity) player);\n }\n }));\n\n TardisEvents.OUT_OF_FUEL.register(Tardis::disablePower);\n TardisEvents.LOSE_POWER.register((tardis -> {\n if (tardis.getDesktop().getConsolePos() != null) {\n TardisUtil.getTardisDimension().playSound(null, tardis.getDesktop().getConsolePos(), AITSounds.SHUTDOWN, SoundCategory.AMBIENT, 10f, 1f);\n }\n\n // disabling protocols\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.AUTO_LAND, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.ANTIGRAVS_ENABLED, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.HAIL_MARY, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.HADS_ENABLED, false);\n }));\n TardisEvents.REGAIN_POWER.register((tardis -> {\n if (tardis.getDesktop().getConsolePos() != null) {\n TardisUtil.getTardisDimension().playSound(null, tardis.getDesktop().getConsolePos(), AITSounds.POWERUP, SoundCategory.AMBIENT, 10f, 1f);\n }\n }));\n\n ServerPlayNetworking.registerGlobalReceiver(ConsoleBlockEntity.ASK, ((server, player, handler, buf, responseSender) -> {\n if (player.getServerWorld().getRegistryKey() != AITDimensions.TARDIS_DIM_WORLD) return;\n\n BlockPos consolePos = buf.readBlockPos();\n // fixme the gotten block entity is always null, shit.\n if (player.getServerWorld().getBlockEntity(consolePos) instanceof ConsoleBlockEntity console)\n console.markNeedsSyncing();\n }));\n\n\n ServerPlayNetworking.registerGlobalReceiver(ServerHumHandler.RECEIVE, ((server, player, handler, buf, responseSender) -> {\n Tardis tardis = ServerTardisManager.getInstance().getTardis(buf.readUuid());\n HumSound hum = HumSound.fromName(buf.readString(), buf.readString());\n\n if (tardis == null || hum == null) return;\n\n tardis.getHandlers().getHum().setHum(hum);\n }));\n\n ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {\n DesktopRegistry.syncToClient(handler.getPlayer());\n });\n\n\n ServerPlayNetworking.registerGlobalReceiver(TardisDesktop.CACHE_CONSOLE, (server, player, handler, buf, responseSender) -> {\n Tardis tardis = ServerTardisManager.getInstance().getTardis(buf.readUuid());\n TardisUtil.getServer().execute(() -> {\n if (tardis == null) return;\n tardis.getDesktop().cacheConsole();\n });\n });\n\n AIT_ITEM_GROUP.initialize();\n }\n\n public void entityAttributeRegister() {\n FabricDefaultAttributeRegistry.register(AITEntityTypes.CONTROL_ENTITY_TYPE, ConsoleControlEntity.createControlAttributes());\n }\n\n public static final Identifier OPEN_SCREEN_TARDIS = new Identifier(AITMod.MOD_ID, \"open_screen_tardis\"); // fixes \"AITModClient in env type SERVER\"\n\n public static void openScreen(ServerPlayerEntity player, int id, UUID tardis) {\n PacketByteBuf buf = PacketByteBufs.create();\n buf.writeInt(id);\n buf.writeUuid(tardis);\n ServerPlayNetworking.send(player, OPEN_SCREEN_TARDIS, buf);\n }\n}\n\nsrc/main/java/mdteam/ait/client/registry/console/ClientConsoleVariantSchema.java\n@Environment(EnvType.CLIENT)\npublic abstract class ClientConsoleVariantSchema {\n private final Identifier parent;\n private final Identifier id;\n\n protected ClientConsoleVariantSchema(Identifier parent, Identifier id) {\n this.parent = parent;\n this.id = id;\n }\n protected ClientConsoleVariantSchema(Identifier parent) {\n this.id = parent;\n this.parent = parent;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() == null) return false;\n\n ClientConsoleVariantSchema that = (ClientConsoleVariantSchema) o;\n\n return id.equals(that.id);\n }\n\n public ConsoleVariantSchema parent() { return ConsoleVariantRegistry.REGISTRY.get(this.parent); }\n public Identifier id() { return id; }\n public abstract Identifier texture();\n public abstract Identifier emission();\n @Environment(EnvType.CLIENT)\n public abstract ConsoleModel model();\n\n public static Object serializer() {\n return new Serializer();\n }\n\n private static class Serializer implements JsonSerializer, JsonDeserializer {\n\n @Override\n public ClientConsoleVariantSchema deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {\n Identifier id;\n\n try {\n id = new Identifier(json.getAsJsonPrimitive().getAsString());\n } catch (InvalidIdentifierException e) {\n id = BorealisVariant.REFERENCE;\n }\n\n return ClientConsoleVariantRegistry.REGISTRY.get(id);\n }\n\n @Override\n public JsonElement serialize(ClientConsoleVariantSchema src, Type typeOfSrc, JsonSerializationContext context) {\n return new JsonPrimitive(src.id().toString());\n }\n }\n}\n\nsrc/main/java/mdteam/ait/client/models/consoles/ConsoleModel.java\n@SuppressWarnings(\"rawtypes\")\npublic abstract class ConsoleModel extends SinglePartEntityModel {\n public static int MAX_TICK_COUNT = 2 * 20;\n\n public ConsoleModel() {\n this(RenderLayer::getEntityCutoutNoCull);\n }\n\n public ConsoleModel(Function function) {\n super(function);\n }\n\n // Thanks craig for help w animation code\n public void animateTile(ConsoleBlockEntity console) {\n this.getPart().traverse().forEach(ModelPart::resetTransform);\n if (console.getTardis() == null)\n return;\n // System.out.println(getAnimationForState(console.getTardis().getTravel().getState()));\n\n TardisTravel.State state = console.getTardis().getTravel().getState();\n\n if (!console.getTardis().hasPower()) return;\n\n this.updateAnimation(console.ANIM_FLIGHT, getAnimationForState(state), console.animationTimer);\n /*if(console.getControlEntityFromName(\"direction\") != null && console.getControlEntityFromName(\"direction\").getControl() != null) {\n this.updateAnimation(console.getControlEntityFromName(\"direction\")\n .getControl().getAnimationState(HartnellAnimations.animationFromDirection(console.getTardis().getTravel())),\n console.getControlEntityFromName(\"direction\").getControl().getAnimation(HartnellAnimations.animationFromDirection(console.getTardis().getTravel())), console.animationTimer);\n }*/\n }\n\n public void renderWithAnimations(ConsoleBlockEntity console, ModelPart root, MatrixStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float pAlpha) {\n if (console.getTardis() == null) return;\n root.render(matrices, vertices, light, overlay, red, green, blue, pAlpha);\n }\n\n @Override\n public void setAngles(Entity entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) {\n }\n\n public abstract Animation getAnimationForState(TardisTravel.State state);\n}", "answers": [" public Identifier emission() {"], "length": 811, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "6aecf554-39a6-4653-bf14-7214184cac0c", "reasoning": "The class extends ClientConsoleVariantSchema which requires implementations for texture(), emission(), and model(). After overriding texture(), the next @Override will be for emission(). Therefore the next line should be the method signature for emission(): \"public Identifier emission() {\".", "reasoning_model_answer": "public Identifier emission() {", "assistant_with_reasoning": "\nThe class extends ClientConsoleVariantSchema which requires implementations for texture(), emission(), and model(). After overriding texture(), the next @Override will be for emission(). Therefore the next line should be the method signature for emission(): \"public Identifier emission() {\".\n\npublic Identifier emission() {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.978, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13407, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public Identifier emission() {", "score": 0.94, "is_full_score": false, "is_nonzero_score": true}} {"input": "import me.n1ar4.jar.analyzer.engine.CoreHelper;\nimport me.n1ar4.jar.analyzer.engine.SearchCondition;\nimport me.n1ar4.jar.analyzer.gui.MainForm;\nimport java.util.ArrayList;\nimport java.util.List;", "context": "src/main/java/me/n1ar4/jar/analyzer/gui/vul/HessianAction.java\npackage me.n1ar4.jar.analyzer.gui.vul;\n\n\n\npublic class HessianAction {\n public static void register() {\n MainForm instance = MainForm.getInstance();\n\n instance.getHessianButton().addActionListener(e -> {\n if (MainForm.getEngine() == null) {\n return;\n }\n\n List conditions = new ArrayList<>();\n\n // com/caucho/hessian/io/AbstractHessianInput.readObject\n SearchCondition ar = new SearchCondition();\n ar.setClassName(\"com/caucho/hessian/io/AbstractHessianInput\");\n ar.setMethodName(\"readObject\");\n conditions.add(ar);\n\n // com/caucho/hessian/io/HessianInput.readObject\n SearchCondition hr = new SearchCondition();\n hr.setClassName(\"com/caucho/hessian/io/HessianInput\");\n hr.setMethodName(\"readObject\");\n conditions.add(hr);\n\n // com/caucho/hessian/io/Hessian2Input.readObject\n SearchCondition h2r = new SearchCondition();\n\nsrc/main/java/me/n1ar4/jar/analyzer/engine/SearchCondition.java\npublic class SearchCondition {\n private String className;\n private String methodName;\n private String methodDesc;\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(String className) {\n this.className = className;\n }\n\n public String getMethodName() {\n return methodName;\n }\n\n public void setMethodName(String methodName) {\n this.methodName = methodName;\n }\n\n public String getMethodDesc() {\n return methodDesc;\n }\n\n public void setMethodDesc(String methodDesc) {\n this.methodDesc = methodDesc;\n }\n}\n\nsrc/main/java/me/n1ar4/jar/analyzer/engine/CoreHelper.java\n@SuppressWarnings(\"all\")\npublic class CoreHelper {\n public static void refreshAllMethods(String className) {\n ArrayList results = MainForm.getEngine().getMethodsByClass(className);\n if (results.size() == 0) {\n results = MainForm.getEngine().getMethodsByClassNoJar(className);\n }\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : results) {\n if (result.getMethodName().startsWith(\"access$\")) {\n continue;\n }\n methodsList.addElement(result);\n }\n MainForm.getInstance().getAllMethodList().setCellRenderer(new AllMethodsRender());\n MainForm.getInstance().getAllMethodList().setModel(methodsList);\n MainForm.getInstance().getAllMethodList().repaint();\n MainForm.getInstance().getAllMethodList().revalidate();\n }\n\n public static void refreshCallers(String className, String methodName, String methodDesc) {\n ArrayList results = MainForm.getEngine().getCallers(className, methodName, methodDesc);\n results.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : results) {\n methodsList.addElement(result);\n }\n MainForm.getInstance().getCallerList().setModel(methodsList);\n MainForm.getInstance().getCallerList().repaint();\n MainForm.getInstance().getCallerList().revalidate();\n }\n\n public static void refreshImpls(String className, String methodName, String methodDesc) {\n ArrayList results = MainForm.getEngine().getImpls(className, methodName, methodDesc);\n results.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : results) {\n methodsList.addElement(result);\n }\n MainForm.getInstance().getMethodImplList().setModel(methodsList);\n MainForm.getInstance().getMethodImplList().repaint();\n MainForm.getInstance().getMethodImplList().revalidate();\n }\n\n public static void refreshSuperImpls(String className, String methodName, String methodDesc) {\n ArrayList results = MainForm.getEngine().getSuperImpls(className, methodName, methodDesc);\n results.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : results) {\n methodsList.addElement(result);\n }\n MainForm.getInstance().getSuperImplList().setModel(methodsList);\n MainForm.getInstance().getSuperImplList().repaint();\n MainForm.getInstance().getSuperImplList().revalidate();\n }\n\n public static void refreshCallee(String className, String methodName, String methodDesc) {\n ArrayList results = MainForm.getEngine().getCallee(className, methodName, methodDesc);\n results.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : results) {\n methodsList.addElement(result);\n }\n MainForm.getInstance().getCalleeList().setModel(methodsList);\n MainForm.getInstance().getCalleeList().repaint();\n MainForm.getInstance().getCalleeList().revalidate();\n }\n\n public static void refreshSpringC() {\n ArrayList results = MainForm.getEngine().getAllSpringC();\n results.sort(Comparator.comparing(ClassResult::getClassName));\n DefaultListModel springCModel = new DefaultListModel<>();\n for (ClassResult result : results) {\n springCModel.addElement(result);\n }\n MainForm.getInstance().getSpringCList().setModel(springCModel);\n }\n\n public static void refreshSpringM(String className) {\n ArrayList results = MainForm.getEngine().getSpringM(className);\n results.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel springCModel = new DefaultListModel<>();\n for (MethodResult result : results) {\n springCModel.addElement(result);\n }\n MainForm.getInstance().getSpringMList().setModel(springCModel);\n }\n\n public static void refreshCallSearch(String className, String methodName, String methodDesc) {\n // java.lang.String java/lang/String\n if (className != null) {\n className = className.replace(\".\", \"/\");\n }\n ArrayList results = MainForm.getEngine().getCallers(className, methodName, methodDesc);\n\n // BALCK LIST\n ArrayList bl = ListParser.parse(MainForm.getInstance().getBlackArea().getText());\n ArrayList newReulst = new ArrayList<>();\n for (MethodResult m : results) {\n boolean filtered = false;\n for (String b : bl) {\n if (m.getClassName().equals(b)) {\n filtered = true;\n break;\n }\n }\n if (!filtered) {\n newReulst.add(m);\n }\n }\n\n newReulst.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : newReulst) {\n methodsList.addElement(result);\n }\n\n if (methodsList.isEmpty() || methodsList.size() == 0) {\n JOptionPane.showMessageDialog(MainForm.getInstance().getMasterPanel(),\n \"result is null\");\n }\n\n MainForm.getInstance().getSearchList().setModel(methodsList);\n MainForm.getInstance().getSearchList().repaint();\n MainForm.getInstance().getSearchList().revalidate();\n }\n\n public static void refreshCallSearchList(List conditions) {\n ArrayList totalResults = new ArrayList<>();\n for (SearchCondition condition : conditions) {\n String className = condition.getClassName();\n String methodName = condition.getMethodName();\n String methodDesc = condition.getMethodDesc();\n // java.lang.String java/lang/String\n if (className != null) {\n className = className.replace(\".\", \"/\");\n }\n ArrayList results = MainForm.getEngine().getCallers(className, methodName, methodDesc);\n totalResults.addAll(results);\n }\n // BALCK LIST\n ArrayList bl = ListParser.parse(MainForm.getInstance().getBlackArea().getText());\n ArrayList newReulst = new ArrayList<>();\n for (MethodResult m : totalResults) {\n boolean filtered = false;\n for (String b : bl) {\n if (m.getClassName().equals(b)) {\n filtered = true;\n break;\n }\n }\n if (!filtered) {\n newReulst.add(m);\n }\n }\n\n newReulst.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : newReulst) {\n methodsList.addElement(result);\n }\n\n if (methodsList.isEmpty() || methodsList.size() == 0) {\n JOptionPane.showMessageDialog(MainForm.getInstance().getMasterPanel(),\n \"result is null\");\n }\n\n MainForm.getInstance().getSearchList().setModel(methodsList);\n MainForm.getInstance().getSearchList().repaint();\n MainForm.getInstance().getSearchList().revalidate();\n }\n\n public static void refreshDefSearch(String className, String methodName, String methodDesc) {\n // java.lang.String java/lang/String\n if (className != null) {\n className = className.replace(\".\", \"/\");\n }\n ArrayList results = MainForm.getEngine().getMethod(className, methodName, methodDesc);\n\n // BALCK LIST\n ArrayList bl = ListParser.parse(MainForm.getInstance().getBlackArea().getText());\n ArrayList newReulst = new ArrayList<>();\n for (MethodResult m : results) {\n boolean filtered = false;\n for (String b : bl) {\n if (m.getClassName().equals(b)) {\n filtered = true;\n break;\n }\n }\n if (!filtered) {\n newReulst.add(m);\n }\n }\n\n newReulst.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : newReulst) {\n methodsList.addElement(result);\n }\n\n if (methodsList.isEmpty() || methodsList.size() == 0) {\n JOptionPane.showMessageDialog(MainForm.getInstance().getMasterPanel(),\n \"result is null\");\n }\n\n MainForm.getInstance().getSearchList().setModel(methodsList);\n MainForm.getInstance().getSearchList().repaint();\n MainForm.getInstance().getSearchList().revalidate();\n }\n\n public static void refreshStrSearch(String val) {\n ArrayList results = MainForm.getEngine().getMethodsByStr(val);\n\n // BALCK LIST\n ArrayList bl = ListParser.parse(MainForm.getInstance().getBlackArea().getText());\n ArrayList newReulst = new ArrayList<>();\n for (MethodResult m : results) {\n boolean filtered = false;\n for (String b : bl) {\n if (m.getClassName().equals(b)) {\n filtered = true;\n break;\n }\n }\n if (!filtered) {\n newReulst.add(m);\n }\n }\n\n newReulst.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : newReulst) {\n methodsList.addElement(result);\n }\n\n if (methodsList.isEmpty() || methodsList.size() == 0) {\n JOptionPane.showMessageDialog(MainForm.getInstance().getMasterPanel(),\n \"result is null\");\n }\n\n MainForm.getInstance().getSearchList().setModel(methodsList);\n MainForm.getInstance().getSearchList().repaint();\n MainForm.getInstance().getSearchList().revalidate();\n }\n\n public static void refreshHistory(String className, String methodName, String methodDesc) {\n DefaultListModel methodsList = MainForm.getHistoryListData();\n MethodResult methodResult = new MethodResult();\n methodResult.setClassName(className);\n methodResult.setMethodName(methodName);\n methodResult.setMethodDesc(methodDesc);\n methodsList.addElement(methodResult);\n MainForm.getInstance().getHistoryList().repaint();\n MainForm.getInstance().getHistoryList().revalidate();\n }\n\n public static void refreshCallSearchLike(String className, String methodName, String methodDesc) {\n // java.lang.String java/lang/String\n if (className != null) {\n className = className.replace(\".\", \"/\");\n }\n ArrayList results = MainForm.getEngine().getCallersLike(className, methodName, methodDesc);\n\n // BALCK LIST\n ArrayList bl = ListParser.parse(MainForm.getInstance().getBlackArea().getText());\n ArrayList newReulst = new ArrayList<>();\n for (MethodResult m : results) {\n boolean filtered = false;\n for (String b : bl) {\n if (m.getClassName().equals(b)) {\n filtered = true;\n break;\n }\n }\n if (!filtered) {\n newReulst.add(m);\n }\n }\n\n newReulst.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : newReulst) {\n methodsList.addElement(result);\n }\n\n if (methodsList.isEmpty() || methodsList.size() == 0) {\n JOptionPane.showMessageDialog(MainForm.getInstance().getMasterPanel(),\n \"result is null\");\n }\n\n MainForm.getInstance().getSearchList().setModel(methodsList);\n MainForm.getInstance().getSearchList().repaint();\n MainForm.getInstance().getSearchList().revalidate();\n }\n\n public static void refreshDefSearchLike(String className, String methodName, String methodDesc) {\n // java.lang.String java/lang/String\n if (className != null) {\n className = className.replace(\".\", \"/\");\n }\n ArrayList results = MainForm.getEngine().getMethodLike(className, methodName, methodDesc);\n\n // BALCK LIST\n ArrayList bl = ListParser.parse(MainForm.getInstance().getBlackArea().getText());\n ArrayList newReulst = new ArrayList<>();\n for (MethodResult m : results) {\n boolean filtered = false;\n for (String b : bl) {\n if (m.getClassName().equals(b)) {\n filtered = true;\n break;\n }\n }\n if (!filtered) {\n newReulst.add(m);\n }\n }\n\n newReulst.sort(Comparator.comparing(MethodResult::getMethodName));\n DefaultListModel methodsList = new DefaultListModel<>();\n for (MethodResult result : newReulst) {\n methodsList.addElement(result);\n }\n\n if (methodsList.isEmpty() || methodsList.size() == 0) {\n JOptionPane.showMessageDialog(MainForm.getInstance().getMasterPanel(),\n \"result is null\");\n }\n\n MainForm.getInstance().getSearchList().setModel(methodsList);\n MainForm.getInstance().getSearchList().repaint();\n MainForm.getInstance().getSearchList().revalidate();\n }\n}", "answers": [" h2r.setClassName(\"com/caucho/hessian/io/Hessian2Input\");"], "length": 1012, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "aabb98f7-f91c-41aa-9d1a-839634c662ed", "reasoning": "The method is building a list of SearchCondition objects for different Hessian readObject methods. After creating the third SearchCondition (h2r), the next logical step is to set its class name, mirroring the pattern used for the previous two conditions (ar and hr). Therefore the next line should set the class name for the Hessian2Input class.", "reasoning_model_answer": "h2r.setClassName(\"com/caucho/hessian/io/Hessian2Input\");", "assistant_with_reasoning": "\nThe method is building a list of SearchCondition objects for different Hessian readObject methods. After creating the third SearchCondition (h2r), the next logical step is to set its class name, mirroring the pattern used for the previous two conditions (ar and hr). Therefore the next line should set the class name for the Hessian2Input class.\n\nh2r.setClassName(\"com/caucho/hessian/io/Hessian2Input\");", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.162, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 16490, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "h2r.setClassName(\"com/caucho/hessian/io/Hessian2Input\");", "score": 0.9, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.List;\nimport javax.servlet.http.HttpServletResponse;\nimport com.ruoyi.studentInformation.mapper.ChangeMapper;\nimport com.ruoyi.studentInformation.mapper.StudentMapper;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PutMapping;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\nimport com.ruoyi.common.annotation.Log;\nimport com.ruoyi.common.core.controller.BaseController;\nimport com.ruoyi.common.core.domain.AjaxResult;\nimport com.ruoyi.common.enums.BusinessType;\nimport com.ruoyi.studentInformation.domain.Change;\nimport com.ruoyi.studentInformation.service.IChangeService;\nimport com.ruoyi.common.utils.poi.ExcelUtil;\nimport com.ruoyi.common.core.page.TableDataInfo;", "context": "ruoyi-admin/src/main/java/com/ruoyi/web/controller/studentInformation/ChangeController.java\npackage com.ruoyi.web.controller.studentInformation;\n\n\n\n/**\n * 学籍信息变更Controller\n *\n * @author ruoyi\n * @date 2023-11-05\n */\n@RestController\n@RequestMapping(\"/system/change\")\npublic class ChangeController extends BaseController\n{\n @Autowired\n private IChangeService changeService;\n\n @Autowired\n private StudentMapper studentMapper;\n\n\n // TODO 更改学籍信息的代码是否存在于学籍更改表中的检测功能\n\n /**\n * 查询学籍信息变更列表\n */\n @PreAuthorize(\"@ss.hasPermi('system:change:list')\")\n @GetMapping(\"/list\")\n public TableDataInfo list(Change change)\n {\n startPage();\n List list = changeService.selectChangeList(change);\n return getDataTable(list);\n }\n\n /**\n * 导出学籍信息变更列表\n */\n @PreAuthorize(\"@ss.hasPermi('system:change:export')\")\n @Log(title = \"学籍信息变更\", businessType = BusinessType.EXPORT)\n @PostMapping(\"/export\")\n public void export(HttpServletResponse response, Change change)\n {\n List list = changeService.selectChangeList(change);\n ExcelUtil util = new ExcelUtil(Change.class);\n util.exportExcel(response, list, \"学籍信息变更数据\");\n }\n\n /**\n * 获取学籍信息变更详细信息\n */\n @PreAuthorize(\"@ss.hasPermi('system:change:query')\")\n @GetMapping(value = \"/{id}\")\n public AjaxResult getInfo(@PathVariable(\"id\") Long id)\n {\n return success(changeService.selectChangeById(id));\n }\n\n /**\n * 新增学籍信息变更\n */\n @PreAuthorize(\"@ss.hasPermi('system:change:add')\")\n @Log(title = \"学籍信息变更\", businessType = BusinessType.INSERT)\n @PostMapping\n\nruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/service/IChangeService.java\npublic interface IChangeService\n{\n /**\n * 查询学籍信息变更\n *\n * @param id 学籍信息变更主键\n * @return 学籍信息变更\n */\n public Change selectChangeById(Long id);\n\n /**\n * 查询学籍信息变更列表\n *\n * @param change 学籍信息变更\n * @return 学籍信息变更集合\n */\n public List selectChangeList(Change change);\n\n /**\n * 新增学籍信息变更\n *\n * @param change 学籍信息变更\n * @return 结果\n */\n public int insertChange(Change change);\n\n /**\n * 修改学籍信息变更\n *\n * @param change 学籍信息变更\n * @return 结果\n */\n public int updateChange(Change change);\n\n /**\n * 批量删除学籍信息变更\n *\n * @param ids 需要删除的学籍信息变更主键集合\n * @return 结果\n */\n public int deleteChangeByIds(Long[] ids);\n\n /**\n * 删除学籍信息变更信息\n *\n * @param id 学籍信息变更主键\n * @return 结果\n */\n public int deleteChangeById(Long id);\n}\n\nruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/domain/Change.java\npublic class Change extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 记录号 */\n private Long id;\n\n /** 学号 */\n @Excel(name = \"学号\")\n private String studentId;\n\n /** 变更代码 */\n @Excel(name = \"变更代码\")\n private Long changes;\n\n /** 记录时间 */\n @JsonFormat(pattern = \"yyyy-MM-dd\")\n @Excel(name = \"记录时间\", width = 30, dateFormat = \"yyyy-MM-dd\")\n private Date recTime;\n\n /** 描述 */\n @Excel(name = \"描述\")\n private String description;\n\n public void setId(Long id)\n {\n this.id = id;\n }\n\n public Long getId()\n {\n return id;\n }\n public void setStudentId(String studentId)\n {\n this.studentId = studentId;\n }\n\n public String getStudentId()\n {\n return studentId;\n }\n public void setChanges(Long changes)\n {\n this.changes = changes;\n }\n\n public Long getChanges()\n {\n return changes;\n }\n public void setRecTime(Date recTime)\n {\n this.recTime = recTime;\n }\n\n public Date getRecTime()\n {\n return recTime;\n }\n public void setDescription(String description)\n {\n this.description = description;\n }\n\n public String getDescription()\n {\n return description;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"id\", getId())\n .append(\"studentId\", getStudentId())\n .append(\"changes\", getChanges())\n .append(\"recTime\", getRecTime())\n .append(\"description\", getDescription())\n .toString();\n }\n}\n\nruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/mapper/StudentMapper.java\npublic interface StudentMapper\n{\n /**\n * 查询学生信息\n *\n * @param id 学生信息主键\n * @return 学生信息\n */\n public Student selectStudentById(Long id);\n\n /**\n * 查询学生信息列表\n *\n * @param student 学生信息\n * @return 学生信息集合\n */\n public List selectStudentList(Student student);\n\n /**\n * 新增学生信息\n *\n * @param student 学生信息\n * @return 结果\n */\n public int insertStudent(Student student);\n\n /**\n * 修改学生信息\n *\n * @param student 学生信息\n * @return 结果\n */\n public int updateStudent(Student student);\n\n /**\n * 删除学生信息\n *\n * @param id 学生信息主键\n * @return 结果\n */\n public int deleteStudentById(Long id);\n\n /**\n * 批量删除学生信息\n *\n * @param ids 需要删除的数据主键集合\n * @return 结果\n */\n public int deleteStudentByIds(Long[] ids);\n\n @Select(\"select count(student_id) from student where student_id=#{studentId} \")\n Integer getStudentId(String studentId);\n}\n\nruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java\npublic class BaseController\r\n{\r\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\r\n\r\n /**\r\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\r\n */\r\n @InitBinder\r\n public void initBinder(WebDataBinder binder)\r\n {\r\n // Date 类型转换\r\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport()\r\n {\r\n @Override\r\n public void setAsText(String text)\r\n {\r\n setValue(DateUtils.parseDate(text));\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * 设置请求分页数据\r\n */\r\n protected void startPage()\r\n {\r\n PageUtils.startPage();\r\n }\r\n\r\n /**\r\n * 设置请求排序数据\r\n */\r\n protected void startOrderBy()\r\n {\r\n PageDomain pageDomain = TableSupport.buildPageRequest();\r\n if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))\r\n {\r\n String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());\r\n PageHelper.orderBy(orderBy);\r\n }\r\n }\r\n\r\n /**\r\n * 清理分页的线程变量\r\n */\r\n protected void clearPage()\r\n {\r\n PageUtils.clearPage();\r\n }\r\n\r\n /**\r\n * 响应请求分页数据\r\n */\r\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\r\n protected TableDataInfo getDataTable(List list)\r\n {\r\n TableDataInfo rspData = new TableDataInfo();\r\n rspData.setCode(HttpStatus.SUCCESS);\r\n rspData.setMsg(\"查询成功\");\r\n rspData.setRows(list);\r\n rspData.setTotal(new PageInfo(list).getTotal());\r\n return rspData;\r\n }\r\n\r\n /**\r\n * 返回成功\r\n */\r\n public AjaxResult success()\r\n {\r\n return AjaxResult.success();\r\n }\r\n\r\n /**\r\n * 返回失败消息\r\n */\r\n public AjaxResult error()\r\n {\r\n return AjaxResult.error();\r\n }\r\n\r\n /**\r\n * 返回成功消息\r\n */\r\n public AjaxResult success(String message)\r\n {\r\n return AjaxResult.success(message);\r\n }\r\n \r\n /**\r\n * 返回成功消息\r\n */\r\n public AjaxResult success(Object data)\r\n {\r\n return AjaxResult.success(data);\r\n }\r\n\r\n /**\r\n * 返回失败消息\r\n */\r\n public AjaxResult error(String message)\r\n {\r\n return AjaxResult.error(message);\r\n }\r\n\r\n /**\r\n * 返回警告消息\r\n */\r\n public AjaxResult warn(String message)\r\n {\r\n return AjaxResult.warn(message);\r\n }\r\n\r\n /**\r\n * 响应返回结果\r\n * \r\n * @param rows 影响行数\r\n * @return 操作结果\r\n */\r\n protected AjaxResult toAjax(int rows)\r\n {\r\n return rows > 0 ? AjaxResult.success() : AjaxResult.error();\r\n }\r\n\r\n /**\r\n * 响应返回结果\r\n * \r\n * @param result 结果\r\n * @return 操作结果\r\n */\r\n protected AjaxResult toAjax(boolean result)\r\n {\r\n return result ? success() : error();\r\n }\r\n\r\n /**\r\n * 页面跳转\r\n */\r\n public String redirect(String url)\r\n {\r\n return StringUtils.format(\"redirect:{}\", url);\r\n }\r\n\r\n /**\r\n * 获取用户缓存信息\r\n */\r\n public LoginUser getLoginUser()\r\n {\r\n return SecurityUtils.getLoginUser();\r\n }\r\n\r\n /**\r\n * 获取登录用户id\r\n */\r\n public Long getUserId()\r\n {\r\n return getLoginUser().getUserId();\r\n }\r\n\r\n /**\r\n * 获取登录部门id\r\n */\r\n public Long getDeptId()\r\n {\r\n return getLoginUser().getDeptId();\r\n }\r\n\r\n /**\r\n * 获取登录用户名\r\n */\r\n public String getUsername()\r\n {\r\n return getLoginUser().getUsername();\r\n }\r\n}\r", "answers": [" public AjaxResult add(@RequestBody Change change)"], "length": 825, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "730d3d69-0a3f-42cc-95f6-c1b0fd0b38d4", "reasoning": "The controller is defining the endpoint for adding a new Change record. After the @PostMapping annotation, the next line should be the method signature that handles the POST request, matching the typical pattern in Ruoyi controllers (e.g., public AjaxResult add(@RequestBody Entity entity)). Therefore the next line is the method declaration for adding a Change.", "reasoning_model_answer": "public AjaxResult add(@RequestBody Change change)", "assistant_with_reasoning": "\nThe controller is defining the endpoint for adding a new Change record. After the @PostMapping annotation, the next line should be the method signature that handles the POST request, matching the typical pattern in Ruoyi controllers (e.g., public AjaxResult add(@RequestBody Entity entity)). Therefore the next line is the method declaration for adding a Change.\n\npublic AjaxResult add(@RequestBody Change change)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.209, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10151, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public AjaxResult add(@RequestBody Change change)", "score": 0.96, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.badlogic.gdx.utils.Json;\nimport com.badlogic.gdx.utils.JsonValue;\nimport com.csse3200.game.areas.terrain.CropTileComponent;\nimport com.csse3200.game.components.Component;\nimport com.csse3200.game.entities.Entity;\nimport com.csse3200.game.missions.MissionManager;\nimport com.csse3200.game.physics.components.ColliderComponent;\nimport com.csse3200.game.physics.components.HitboxComponent;\nimport com.csse3200.game.rendering.AnimationRenderComponent;\nimport com.csse3200.game.services.FactoryService;\nimport com.csse3200.game.services.ServiceLocator;\nimport com.csse3200.game.services.sound.EffectSoundFile;\nimport com.csse3200.game.services.sound.InvalidSoundFileException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport java.text.DecimalFormat;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.function.Supplier;\nimport static com.badlogic.gdx.math.MathUtils.random;", "context": "source/core/src/main/com/csse3200/game/components/plants/PlantComponent.java\npackage com.csse3200.game.components.plants;\n\n\n\n\n/**\n * Class for all plants in the game.\n */\npublic class PlantComponent extends Component {\n\n\t/**\n\t * Initial plant health\n\t */\n\tprivate int plantHealth;\n\n\t/**\n\t * Maximum health that this plant can reach as an adult\n\t */\n\tprivate final int maxHealth;\n\n\t/**\n\t * User facing plant name\n\t */\n\tprivate final String plantName;\n\n\t/**\n\t * The type of plant (food, health, repair, defence, production, deadly)\n\t */\n\tprivate final String plantType;\n\n\t/**\n\t * The alive growth stage of the plant\n\t */\n\tprivate static final String ALIVE = \"ALIVE\";\n\n\t/**\n\t * The decaying growth stage of the plant\n\t */\n\tprivate static final String DECAY = \"decay\";\n\n\t/**\n\t * The decaying growth stage of the plant\n\t */\n\tprivate static final String DECAYS = DECAY + \"s\";\n\n\t/**\n\t * The destroyed growth stage of the plant\n\t */\n\tprivate static final String DESTROY = \"destroy\";\n\n\n\t/**\n\t * User facing description of the plant\n\t */\n\tprivate final String plantDescription;\n\n\t/**\n\t * Ideal water level of the plant. A factor when determining the growth rate.\n\t */\n\tprivate final float idealWaterLevel;\n\n\t/**\n\t * The growth stage of the plant\n\t */\n\tpublic enum GrowthStage {\n\t\tSEEDLING(1),\n\t\tSPROUT(2),\n\t\tJUVENILE(3),\n\t\tADULT(4),\n\t\tDECAYING(5),\n\t\tDEAD(6);\n\n\t\tprivate int value;\n\n\t\tGrowthStage(int value) {\n\t\t\tthis.value = value;\n\t\t}\n\n\t\tpublic int getValue() {\n\t\t\treturn value;\n\t\t}\n\t}\n\n\t/**\n\t * The growth stage of the plant\n\t */\n\tprivate GrowthStage growthStages;\n\n\t/**\n\t * How long a plant lives as an adult before starting to decay from old age.\n\t */\n\tprivate int adultLifeSpan;\n\n\t/**\n\t * Used to determine when a plant enters a new growth stage (for growth stages 2, 3, 4)\n\t */\n\tprivate int currentGrowthLevel;\n\n\t/**\n\t * The crop tile on which this plant is planted on.\n\t */\n\nsource/core/src/main/com/csse3200/game/physics/components/HitboxComponent.java\npublic class HitboxComponent extends ColliderComponent {\n\t@Override\n\tpublic void create() {\n\t\tsetSensor(true);\n\t\tsuper.create();\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/services/sound/InvalidSoundFileException.java\npublic class InvalidSoundFileException extends Exception {\n\n\tpublic InvalidSoundFileException() {\n\t\tsuper(\"The SoundFile provided is not an EffectSoundFile\");\n\t}\n\n\tpublic InvalidSoundFileException(String errorMessage) {\n\t\tsuper(errorMessage);\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/services/sound/EffectSoundFile.java\npublic enum EffectSoundFile implements SoundFile {\n\tTRACTOR_HONK(\"sounds/car-horn-6408.mp3\"),\n\tTRACTOR_START_UP(\"sounds/tractor-start-up.wav\"),\n\tSHOVEL(\"sounds/shovel.wav\"),\n\tHOE(\"sounds/hoe.wav\"),\n\tSCYTHE(\"sounds/hoe.wav\"),\n\tWATERING_CAN(\"sounds/watering-can.wav\"),\n\tFISHING_CAST(\"sounds/fishing-cast.wav\"),\n\tFISHING_CATCH(\"sounds/applause.wav\"),\n\tPLACE(\"sounds/place.wav\"),\n\tGATE_INTERACT(\"sounds/gate-interact.wav\"),\n\tIMPACT(\"sounds/Impact4.ogg\"),\n\tATTACK_MISS(\"sounds/weapons/SwordSwing.mp3\"),\n\tATTACK_HIT(\"sounds/weapons/SwordHitEntity.mp3\"),\n\tGUN_ATTACK(\"sounds/weapons/GunAttack.mp3\"),\n\tINVENTORY_OPEN(\"sounds/open-bag-sound-effect.mp3\"),\n\tACID_BURN(\"sounds/weather/AcidBurn.wav\"),\n\tBLIZZARD(\"sounds/weather/Blizzard.wav\"),\n\tLIGHTNING_STRIKE(\"sounds/weather/LightningStrike.wav\"),\n\tSOLAR_SURGE(\"sounds/weather/SolarSurge.wav\"),\n\tSTORM(\"sounds/weather/Storm.wav\"),\n\tSURGE(\"sounds/weather/Surge.wav\"),\n\tHOTKEY_SELECT(\"sounds/take-item-sound-effect.mp3\"),\n\tSWITCH_TOOLBAR(\"sounds/switchToolbar.wav\"),\n\tDRAG_ITEM(\"sounds/hold.wav\"),\n\tDROP_ITEM(\"sounds/drop.wav\"),\n\tDELETE_ITEM(\"sounds/bin.wav\"),\n\tCHICKEN_FEED(\"sounds/animals/ChickenFeed.mp3\"),\n\tCOW_FEED(\"sounds/animals/CowFeed.mp3\"),\n\tASTROLOTL_FEED(\"sounds/animals/AstrolotlFeed.mp3\"),\n\tTAMED_ANIMAL(\"sounds/animals/TamedAnimal.mp3\"),\n\tCOW_DEATH(\"sounds/animals/CowDeath.mp3\"),\n\tOXYGEN_EAT_DEATH(\"sounds/animals/DeathOxygenEater.mp3\"),\n\tDRAGONFLY_DEATH(\"sounds/animals/DeathDragonFly.mp3\"),\n\tDEATH_BATS(\"sounds/animals/DeathBats.mp3\"),\n\tPLAYER_DEATH(\"sounds/player/PlayerDeath.mp3\"),\n\tGUN_RELOAD(\"sounds/weapons/GunReload.mp3\"),\n\tPLAYER_DAMAGE(\"sounds/player/PlayerGetsHit.mp3\"),\n\tBAT_ATTACK(\"sounds/animals/BatAttack.mp3\"),\n\tOXYGEN_ATTACK(\"sounds/animals/OxygenEaterAttack.mp3\"),\n\tDRAGONFLY_ATTACK_PLANT(\"sounds/animals/DragonflyAttackPlant.mp3\"),\n\tDRAGONFLY_ATTACK_PLAYER(\"sounds/animals/DragonFlyAttackPlayer.mp3\"),\n\tCHICKEN_DEATH(\"sounds/animals/ChickenDeath.mp3\"),\n\tGOD_DID(\"sounds/god-did.mp3\"),\n\tSHIP_CRASH(\"sounds/sound-effects/intro-animation/crash.wav\"),\n\tSHIP_RATTLE(\"sounds/sound-effects/intro-animation/rattle_short.wav\"),\n\tLEGO_BREAK(\"sounds/sound-effects/intro-animation/lego-breaking.wav\"),\n\tPLANT_CLICK(\"sounds/plants/click.wav\"),\n\tPLANT_DECAY(\"sounds/plants/decay.wav\"),\n\tPLANT_DESTROY(\"sounds/plants/destroy.wav\"),\n\tPLANT_NEARBY(\"sounds/plants/nearby.wav\"),\n\tALOE_VERA_CLICK_LORE(\"sounds/plants/aloeVera/clickLore.wav\"),\n\tALOE_VERA_DECAY_LORE(\"sounds/plants/aloeVera/decayLore.wav\"),\n\tALOE_VERA_DESTROY_LORE(\"sounds/plants/aloeVera/destroyLore.wav\"),\n\tALOE_VERA_NEARBY_LORE(\"sounds/plants/aloeVera/nearbyLore.wav\"),\n\tCOSMIC_COB_CLICK_LORE(\"sounds/plants/cosmicCob/clickLore.wav\"),\n\tCOSMIC_COB_DECAY_LORE(\"sounds/plants/cosmicCob/decayLore.wav\"),\n\tCOSMIC_COB_DESTROY_LORE(\"sounds/plants/cosmicCob/destroyLore.wav\"),\n\tCOSMIC_COB_NEARBY_LORE(\"sounds/plants/cosmicCob/nearbyLore.wav\"),\n\tHAMMER_PLANT_CLICK_LORE(\"sounds/plants/hammerPlant/clickLore.wav\"),\n\tHAMMER_PLANT_DECAY_LORE(\"sounds/plants/hammerPlant/decayLore.wav\"),\n\tHAMMER_PLANT_DESTROY_LORE(\"sounds/plants/hammerPlant/destroyLore.wav\"),\n\tHAMMER_PLANT_NEARBY_LORE(\"sounds/plants/hammerPlant/nearbyLore.wav\"),\n\tDEADLY_NIGHTSHADE_CLICK_LORE(\"sounds/plants/nightshade/clickLore.wav\"),\n\tDEADLY_NIGHTSHADE_DECAY_LORE(\"sounds/plants/nightshade/decayLore.wav\"),\n\tDEADLY_NIGHTSHADE_DESTROY_LORE(\"sounds/plants/nightshade/destroyLore.wav\"),\n\tDEADLY_NIGHTSHADE_NEARBY_LORE(\"sounds/plants/nightshade/nearbyLore.wav\"),\n\tSPACE_SNAPPER_CLICK_LORE(\"sounds/plants/spaceSnapper/clickLore.wav\"),\n\tSPACE_SNAPPER_DECAY_LORE(\"sounds/plants/spaceSnapper/decayLore.wav\"),\n\tSPACE_SNAPPER_DESTROY_LORE(\"sounds/plants/spaceSnapper/destroyLore.wav\"),\n\tSPACE_SNAPPER_NEARBY_LORE(\"sounds/plants/spaceSnapper/nearbyLore.wav\"),\n\tATOMIC_ALGAE_CLICK_LORE(\"sounds/plants/atomicAlgae/clickLore.wav\"),\n\tATOMIC_ALGAE_DECAY_LORE(\"sounds/plants/atomicAlgae/decayLore.wav\"),\n\tATOMIC_ALGAE_DESTROY_LORE(\"sounds/plants/atomicAlgae/destroyLore.wav\"),\n\tATOMIC_ALGAE_NEARBY_LORE(\"sounds/plants/atomicAlgae/nearbyLore.wav\"),\n\tSHIP_CLUE_SOLVED(\"sounds/ship-clue-solved.wav\"),\n\tSHIP_INSTALL_PART(\"sounds/install-ship-part.wav\"),\n\tSHIP_FEATURE_UNLOCKED(\"sounds/ship-feature-unlocked.wav\"),\n\tSHIP_TELEPORT(\"sounds/ship-teleport.wav\"),\n\tSHIP_EATER_ATTACK(\"sounds/ship-eater-attack.wav\"),\n\tSHIP_EATER_HIDE(\"sounds/ship-eater-hide.wav\");\n\n\tprivate final String filePath;\n\n\tEffectSoundFile(String filePath) {\n\t\tthis.filePath = filePath;\n\t}\n\n\t@Override\n\tpublic String getFilePath() {\n\t\treturn this.filePath;\n\t}\n}\n\nsource/core/src/main/com/csse3200/game/physics/components/ColliderComponent.java\npublic class ColliderComponent extends Component {\n\tprivate static final Logger logger = LoggerFactory.getLogger(ColliderComponent.class);\n\n\tprivate final FixtureDef fixtureDef;\n\tprivate Fixture fixture;\n\n\tpublic ColliderComponent() {\n\t\tfixtureDef = new FixtureDef();\n\t}\n\n\t@Override\n\tpublic void create() {\n\t\tif (fixtureDef.shape == null) {\n\t\t\tlogger.trace(\"{} Setting default bounding box\", this);\n\t\t\tfixtureDef.shape = makeBoundingBox();\n\t\t}\n\n\t\tBody physBody = entity.getComponent(PhysicsComponent.class).getBody();\n\t\tfixture = physBody.createFixture(fixtureDef);\n\t}\n\n\t/**\n\t * Set physics as a box with a given size. Box is centered around the entity.\n\t *\n\t * @param size size of the box\n\t * @return self\n\t */\n\tpublic ColliderComponent setAsBox(Vector2 size) {\n\t\treturn setAsBox(size, entity.getCenterPosition());\n\t}\n\n\t/**\n\t * Set physics as a box with a given size. Box is aligned based on alignment.\n\t *\n\t * @param size size of the box\n\t * @param alignX how to align x relative to entity\n\t * @param alignY how to align y relative to entity\n\t * @return self\n\t */\n\tpublic ColliderComponent setAsBoxAligned(Vector2 size, AlignX alignX, AlignY alignY) {\n\t\tVector2 position = new Vector2();\n\t\tswitch (alignX) {\n\t\t\tcase LEFT:\n\t\t\t\tposition.x = size.x / 2;\n\t\t\t\tbreak;\n\t\t\tcase CENTER:\n\t\t\t\tposition.x = entity.getCenterPosition().x;\n\t\t\t\tbreak;\n\t\t\tcase RIGHT:\n\t\t\t\tposition.x = entity.getScale().x - (size.x / 2);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tswitch (alignY) {\n\t\t\tcase BOTTOM:\n\t\t\t\tposition.y = size.y / 2;\n\t\t\t\tbreak;\n\t\t\tcase CENTER:\n\t\t\t\tposition.y = entity.getCenterPosition().y;\n\t\t\t\tbreak;\n\t\t\tcase TOP:\n\t\t\t\tposition.y = entity.getScale().y - (size.y / 2);\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn setAsBox(size, position);\n\t}\n\n\t/**\n\t * Set physics as a box with a given size and local position. Box is centered around the position.\n\t *\n\t * @param size size of the box\n\t * @param position position of the box center relative to the entity.\n\t * @return self\n\t */\n\tpublic ColliderComponent setAsBox(Vector2 size, Vector2 position) {\n\t\tPolygonShape bbox = new PolygonShape();\n\t\tbbox.setAsBox(size.x / 2, size.y / 2, position, 0f);\n\t\tsetShape(bbox);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set friction. This affects the object when touching other objects, but does not affect friction\n\t * with the ground.\n\t *\n\t * @param friction friction, default = 0\n\t * @return self\n\t */\n\tpublic ColliderComponent setFriction(float friction) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.friction = friction;\n\t\t} else {\n\t\t\tfixture.setFriction(friction);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set whether this physics component is a sensor. Sensors don't collide with other objects but\n\t * still trigger collision events. See: https://www.iforce2d.net/b2dtut/sensors\n\t *\n\t * @param isSensor true if sensor, false if not. default = false.\n\t * @return self\n\t */\n\tpublic ColliderComponent setSensor(boolean isSensor) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.isSensor = isSensor;\n\t\t} else {\n\t\t\tfixture.setSensor(isSensor);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set density\n\t *\n\t * @param density Density and size of the physics component determine the object's mass. default =\n\t * 0\n\t * @return self\n\t */\n\tpublic ColliderComponent setDensity(float density) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.density = density;\n\t\t} else {\n\t\t\tfixture.setDensity(density);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set restitution\n\t *\n\t * @param restitution restitution is the 'bounciness' of an object, default = 0\n\t * @return self\n\t */\n\tpublic ColliderComponent setRestitution(float restitution) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.restitution = restitution;\n\t\t} else {\n\t\t\tfixture.setRestitution(restitution);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Set shape\n\t *\n\t * @param shape shape, default = bounding box the same size as the entity\n\t * @return self\n\t */\n\tpublic ColliderComponent setShape(Shape shape) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.shape = shape;\n\t\t} else {\n\t\t\tlogger.error(\"{} Cannot set Collider shape after create(), ignoring.\", this);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return Physics fixture of this collider. Null before created()\n\t */\n\tpublic Fixture getFixture() {\n\t\treturn fixture;\n\t}\n\n\t/**\n\t * Set the collider layer, used in collision logic\n\t *\n\t * @param layerMask Bitmask of {@link PhysicsLayer} this collider belongs to\n\t * @return self\n\t */\n\tpublic ColliderComponent setLayer(short layerMask) {\n\t\tif (fixture == null) {\n\t\t\tfixtureDef.filter.categoryBits = layerMask;\n\t\t} else {\n\t\t\tFilter filter = fixture.getFilterData();\n\t\t\tfilter.categoryBits = layerMask;\n\t\t\tfixture.setFilterData(filter);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return The {@link PhysicsLayer} this collider belongs to\n\t */\n\tpublic short getLayer() {\n\t\tif (fixture == null) {\n\t\t\treturn fixtureDef.filter.categoryBits;\n\t\t}\n\t\treturn fixture.getFilterData().categoryBits;\n\t}\n\n\t@Override\n\tpublic void dispose() {\n\t\tsuper.dispose();\n\t\tBody physBody = entity.getComponent(PhysicsComponent.class).getBody();\n\t\tif (physBody.getFixtureList().contains(fixture, true)) {\n\t\t\tphysBody.destroyFixture(fixture);\n\t\t}\n\t}\n\n\tprivate Shape makeBoundingBox() {\n\t\tPolygonShape bbox = new PolygonShape();\n\t\tVector2 center = entity.getScale().scl(0.5f);\n\t\tbbox.setAsBox(center.x, center.y, center, 0f);\n\t\treturn bbox;\n\t}\n}", "answers": ["\tprivate final CropTileComponent cropTile;"], "length": 1157, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "a95a3066-6147-4bd9-9888-67de8643ad2b", "reasoning": "The PlantComponent class ends with a comment describing a field: \"The crop tile on which this plant is planted on.\" The next logical line is the declaration of that field, matching the comment. Following typical Java naming conventions in this codebase, the field should be of type CropTileComponent and named cropTile.", "reasoning_model_answer": "private CropTileComponent cropTile;", "assistant_with_reasoning": "\nThe PlantComponent class ends with a comment describing a field: \"The crop tile on which this plant is planted on.\" The next logical line is the declaration of that field, matching the comment. Following typical Java naming conventions in this codebase, the field should be of type CropTileComponent and named cropTile.\n\nprivate CropTileComponent cropTile;", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.977, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13272, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "private CropTileComponent cropTile;", "score": 0.91, "is_full_score": false, "is_nonzero_score": true}} {"input": "import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_STOP;\nimport static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_SYNC;\nimport static com.datalinkx.common.utils.IdUtils.genKey;\nimport static com.datalinkx.common.utils.JsonUtils.toJson;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport javax.annotation.Resource;\nimport com.datalinkx.common.constants.MessageHubConstants;\nimport com.datalinkx.common.constants.MetaConstants;\nimport com.datalinkx.driver.dsdriver.DsDriverFactory;\nimport com.datalinkx.driver.dsdriver.IDsReader;\nimport com.datalinkx.driver.dsdriver.base.model.TableField;\nimport com.datalinkx.driver.model.DataTransJobDetail;\nimport com.datalinkx.common.result.StatusCode;\nimport com.datalinkx.common.utils.JsonUtils;\nimport com.datalinkx.dataserver.bean.domain.DsBean;\nimport com.datalinkx.dataserver.bean.domain.DsTbBean;\nimport com.datalinkx.dataserver.bean.domain.JobBean;\nimport com.datalinkx.dataserver.bean.domain.JobLogBean;\nimport com.datalinkx.dataserver.bean.dto.JobDto;\nimport com.datalinkx.dataserver.bean.vo.JobVo;\nimport com.datalinkx.dataserver.bean.vo.PageVo;\nimport com.datalinkx.dataserver.client.xxljob.JobClientApi;\nimport com.datalinkx.dataserver.client.xxljob.request.DataTransJobParam;\nimport com.datalinkx.dataserver.controller.form.JobForm;\nimport com.datalinkx.dataserver.controller.form.JobStateForm;\nimport com.datalinkx.common.exception.DatalinkXServerException;\nimport com.datalinkx.dataserver.repository.DsRepository;\nimport com.datalinkx.dataserver.repository.DsTbRepository;\nimport com.datalinkx.dataserver.repository.JobLogRepository;\nimport com.datalinkx.dataserver.repository.JobRepository;\nimport com.datalinkx.dataserver.service.DtsJobService;\nimport com.datalinkx.messagehub.bean.form.ProducerAdapterForm;\nimport com.datalinkx.messagehub.service.MessageHubService;\nimport lombok.SneakyThrows;\nimport lombok.extern.log4j.Log4j2;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.PageRequest;\nimport org.springframework.stereotype.Component;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\nimport org.springframework.util.ObjectUtils;", "context": "datalinkx-server/src/main/java/com/datalinkx/dataserver/service/impl/JobService.java\npackage com.datalinkx.dataserver.service.impl;\n\n\n\n\n\n\n\n\n\n@Component\n@Service\n@Log4j2\npublic class JobService implements DtsJobService {\n\tprivate static final int FAILED = 3;\n\tprivate static final int SUCCESS = 2;\n\n\t@Autowired\n\tprivate JobRepository jobRepository;\n\n\t@Autowired\n\tDsService dsService;\n\n\t@Autowired\n\tDsRepository dsRepository;\n\n\t@Autowired\n\tDsTbRepository dsTbRepository;\n\n\t@Autowired\n\tJobLogRepository jobLogRepository;\n\n\t@Autowired\n\tJobClientApi jobClientApi;\n\n\t@Resource(name = \"messageHubServiceImpl\")\n\tMessageHubService messageHubService;\n\n\t@Transactional(rollbackFor = Exception.class)\n\tpublic String jobCreate(JobForm.JobCreateForm form) {\n\t\tthis.validJobForm(form);\n\t\tString jobId = genKey(\"job\");\n\t\tJobBean jobBean = new JobBean();\n\t\tjobBean.setJobId(jobId);\n\n\t\tjobBean.setReaderDsId(form.getFromDsId());\n\t\tjobBean.setWriterDsId(form.getToDsId());\n\n\t\tjobBean.setConfig(toJson(form.getFieldMappings()));\n\t\tjobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId()));\n\t\tjobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId()));\n\t\tjobBean.setStatus(MetaConstants.JobStatus.JOB_TABLE_CREATE);\n\t\tjobBean.setCrontab(form.getSchedulerConf());\n\t\tjobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode()));\n\n\t\t// 创建 xxljob\n\t\tString xxlJobId = jobClientApi.add(jobId, form.getSchedulerConf(), DataTransJobParam.builder().jobId(jobId).build());\n\n\t\tjobBean.setXxlId(xxlJobId);\n\t\tjobRepository.save(jobBean);\n\t\treturn jobId;\n\t}\n\n\n\tpublic String jobModify(JobForm.JobModifyForm form) {\n\t\tthis.validJobForm(form);\n\t\tJobBean jobBean = jobRepository.findByJobId(form.getJobId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.JOB_NOT_EXISTS, \"job not exist\"));\n\t\tjobBean.setReaderDsId(form.getFromDsId());\n\t\tjobBean.setWriterDsId(form.getToDsId());\n\t\tjobBean.setConfig(toJson(form.getFieldMappings()));\n\t\tjobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId()));\n\t\tjobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId()));\n\t\tjobBean.setCrontab(form.getSchedulerConf());\n\t\tjobBean.setSyncMode(JsonUtils.toJson(form.getSyncMode()));\n\t\tjobRepository.save(jobBean);\n\t\treturn form.getJobId();\n\t}\n\n\n\tprivate void validJobForm(JobForm.JobCreateForm form) {\n\t\tDsBean fromDsBean = dsRepository.findByDsId(form.getFromDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, \"来源数据源不存在\"));\n\t\tDsBean toBean = dsRepository.findByDsId(form.getToDsId()).orElseThrow(() -> new DatalinkXServerException(StatusCode.DS_NOT_EXISTS, \"目标数据源不存在\"));\n\n\n\t\tif (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode()) && ObjectUtils.isEmpty(form.getSyncMode().getIncreateField())) {\n\t\t\tthrow new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, \"增量模式必须指定增量字段\");\n\t\t}\n\n\t\tif (MetaConstants.JobSyncMode.INCREMENT_MODE.equals(form.getSyncMode().getMode())) {\n\t\t\ttry {\n\t\t\t\tIDsReader dsReader = DsDriverFactory.getDsReader(dsService.getConnectId(fromDsBean));\n\t\t\t\tBoolean isIncremental = dsReader.judgeIncrementalField(fromDsBean.getDatabase(), fromDsBean.getSchema(), form.getFromTbName(), form.getSyncMode().getIncreateField());\n\t\t\t\tif (!isIncremental) {\n\t\t\t\t\tthrow new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, \"增量字段必须是日期或数值类型\");\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\ndatalinkx-common/src/main/java/com/datalinkx/common/constants/MetaConstants.java\npublic final class MetaConstants {\n private MetaConstants() {\n }\n /**\n * 数据源类型管理\n */\n public static class DsType {\n // 数据源类型\n public static final Integer MYSQL = 1;\n public static final Integer ELASTICSEARCH = 2;\n }\n\n public static class JobStatus {\n public static final int JOB_TABLE_CREATE = 0;\n public static final int JOB_TABLE_SYNCING = 1;\n public static final int JOB_TABLE_NORMAL = 2;\n public static final int JOB_TABLE_ERROR = 3;\n public static final int JOB_TABLE_QUEUE = 4;\n public static final int JOB_TABLE_STOP = 5;\n\n public static final int JOB_STATUS_CREATE = 0;\n public static final int JOB_STATUS_SYNC = 1;\n public static final int JOB_STATUS_SUCCESS = 2;\n public static final int JOB_STATUS_ERROR = 3;\n public static final int JOB_STATUS_QUEUE = 4;\n public static final int JOB_STATUS_STOP = 5;\n\n public static final String SSE_JOB_STATUS = \"jobList\";\n }\n\n public static class JobSyncMode {\n public static final String INCREMENT_MODE = \"increment\";\n public static final String OVERWRITE_MODE = \"overwrite\";\n }\n\n public static class CommonConstant {\n public static final String TRACE_ID = \"trace_id\";\n }\n}\n\ndatalinkx-server/src/main/java/com/datalinkx/dataserver/bean/vo/PageVo.java\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PageVo {\n\t//当前查询的页码\n\tprivate Integer pageNo;\n\t//每页条数\n\tprivate Integer pageSize;\n\t//总数据量\n\tprivate Long total;\n\n\tprivate Integer totalPage;\n\n\tprivate T data;\n\n}\n\ndatalinkx-common/src/main/java/com/datalinkx/common/utils/JsonUtils.java\npublic final class JsonUtils {\n\tprivate static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\tstatic {\n\t\tOBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\t}\n\n\t/**\n\t * 防止反射调用构造器创建对象\n\t */\n\tprivate JsonUtils() {\n\t\tthrow new AssertionError();\n\t}\n\n\t/**\n\t * 自定义日期反序列化处理类\n\t * LocalDate\n\t * jdk8 support\n\t */\n\tpublic static class JsonLocalDateDeserializer extends JsonDeserializer {\n\t\t@Override\n\t\tpublic LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {\n\t\t\tString str = jsonParser.getText().trim();\n\t\t\treturn LocalDate.parse(str, DateTimeFormatter.ISO_DATE);\n\t\t}\n\t}\n\n\t/**\n\t * 自定义日期序列化类\n\t * LocalDate\n\t * jdk8 support\n\t */\n\tpublic static class JsonLocalDateSerializer extends JsonSerializer {\n\t\t@Override\n\t\tpublic void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {\n\t\t\tString localdateStr = localDate.format(DateTimeFormatter.ISO_DATE);\n\t\t\tjsonGenerator.writeString(localdateStr);\n\t\t}\n\t}\n\n\t/**\n\t * json数据转pojo\n\t *\n\t * @param jsonStr json字符串\n\t * @param cls 映射类型\n\t * @param 推导类型\n\t * @return 推导类型json对象\n\t */\n\tpublic static T toObject(String jsonStr, Class cls) {\n\t\tT object = null;\n\t\ttry {\n\t\t\tif (StringUtils.isEmpty(jsonStr)) {\n\t\t\t\treturn cls.newInstance();\n\t\t\t}\n\t\t\tobject = OBJECT_MAPPER.readValue(jsonStr, cls);\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn object;\n\t}\n\n\n\t/**\n\t * json数据转PojoList\n\t *\n\t * @param jsonArray json数据\n\t * @param cls 类型\n\t * @param 推导类型\n\t * @return pojoList\n\t */\n\tpublic static List toList(String jsonArray, Class cls) {\n\t\tList pojoList = null;\n\t\ttry {\n\t\t\tCollectionType listType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, cls);\n\t\t\tpojoList = OBJECT_MAPPER.readValue(jsonArray, listType);\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn pojoList;\n\t}\n\n\n\t/**\n\t * pojo转json\n\t *\n\t * @param obj pojo\n\t * @return json字符串\n\t */\n\tpublic static String toJson(Object obj) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(obj);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\t/**\n\t * json转listMap\n\t *\n\t * @param jsonArray jsonArray字符串\n\t * @return Listmap对象\n\t */\n\tpublic static List> toListMap(String jsonArray) {\n\t\tList> convertedListMap = null;\n\t\ttry {\n\t\t\tconvertedListMap = OBJECT_MAPPER.readValue(jsonArray, new TypeReference>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn convertedListMap;\n\t}\n\n\t/**\n\t * json转map\n\t *\n\t * @param json json字符串\n\t * @return map对象\n\t */\n\tpublic static Map> toInnerMap(String json) {\n\t\tMap> convertedMap = null;\n\t\ttry {\n\t\t\tconvertedMap = OBJECT_MAPPER.readValue(json, new TypeReference>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn convertedMap;\n\t}\n\n\t/**\n\t * json转map\n\t *\n\t * @param json json字符串\n\t * @return map对象\n\t */\n\tpublic static Map json2Map(String json) {\n\t\tMap convertedMap = null;\n\t\ttry {\n\t\t\tconvertedMap = OBJECT_MAPPER.readValue(json, new TypeReference>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn convertedMap;\n\t}\n\n\t/**\n\t * json转map\n\t *\n\t * @param json json字符串\n\t * @return map对象\n\t */\n\tpublic static Map> json2MapMap(String json) {\n\t\tMap> convertedMap = null;\n\t\ttry {\n\t\t\tconvertedMap = OBJECT_MAPPER.readValue(json, new TypeReference>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn convertedMap;\n\t}\n\n\n\t/**\n\t * listMap转json\n\t *\n\t * @param listMap listMap\n\t * @return\n\t */\n\tpublic static String listMap2JsonArray(List> listMap) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(listMap);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\t/**\n\t * 将json转为JsonNode对象\n\t * @param json\n\t * @return\n\t */\n\tpublic static JsonNode toJsonNode(String json) {\n\t\tJsonNode jsonNode = null;\n\t\ttry {\n\t\t\tjsonNode = OBJECT_MAPPER.readTree(json);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\n\t\treturn jsonNode;\n\t}\n\n\t/**\n\t * 获取 ObjectNode\n\t * @return\n\t */\n\tpublic static ObjectNode getObjectNode() {\n\t\treturn OBJECT_MAPPER.createObjectNode();\n\t}\n\n\t/**\n\t * 获取 ArrayNode\n\t * @return\n\t */\n\tpublic static ArrayNode getArrayNode() {\n\t\treturn OBJECT_MAPPER.createArrayNode();\n\t}\n\n\tpublic static String map2Json(Map map) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(map);\n\t\t} catch (JsonProcessingException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\tpublic static String list2Json(List list) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(list);\n\t\t} catch (JsonProcessingException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\tpublic static List json2List(String json) {\n\t\tList convertedList = null;\n\t\ttry {\n\t\t\tconvertedList = OBJECT_MAPPER.readValue(json, new TypeReference>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn convertedList;\n\t}\n}", "answers": ["\t\t\t\tthrow new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, e.getMessage());"], "length": 1106, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "034eca6c-9ab9-402a-a20e-c296a3401024", "reasoning": "The method validJobForm validates job creation parameters. Inside the increment mode block, it tries to check the incremental field using a DsReader. If any exception occurs, the method should abort validation by throwing a DatalinkXServerException with an appropriate error code. The imports already include DatalinkXServerException and StatusCode, so the next line after the opening catch block should be a throw statement that wraps the caught exception.", "reasoning_model_answer": "throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, e.getMessage());", "assistant_with_reasoning": "\nThe method validJobForm validates job creation parameters. Inside the increment mode block, it tries to check the incremental field using a DsReader. If any exception occurs, the method should abort validation by throwing a DatalinkXServerException with an appropriate error code. The imports already include DatalinkXServerException and StatusCode, so the next line after the opening catch block should be a throw statement that wraps the caught exception.\n\nthrow new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, e.getMessage());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.353, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 13160, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "throw new DatalinkXServerException(StatusCode.JOB_CONFIG_ERROR, e.getMessage());", "score": 0.98, "is_full_score": false, "is_nonzero_score": true}} {"input": "import com.amazonaws.services.dynamodbv2.model.LockCurrentlyUnavailableException;\nimport com.amazonaws.services.dynamodbv2.model.LockNotGrantedException;\nimport com.amazonaws.services.dynamodbv2.util.LockClientUtils;\nimport momento.lock.client.LockItemUtils;\nimport momento.lock.client.LockStorage;\nimport momento.lock.client.MomentoDynamoDBLockClientOptions;\nimport momento.lock.client.MomentoLockClient;\nimport momento.lock.client.MomentoLockClientHeartbeatHandler;\nimport momento.lock.client.MomentoLockItem;\nimport momento.lock.client.NoopDynamoDbClient;\nimport momento.lock.client.model.MomentoClientException;\nimport momento.sdk.CacheClient;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport software.amazon.awssdk.core.exception.SdkClientException;\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.TimeUnit;\nimport java.util.function.Function;\nimport java.util.stream.Stream;", "context": "src/main/java/com/amazonaws/services/dynamodbv2/MomentoDynamoDBLockClient.java\n/*\n * This Java source file was generated by the Gradle 'init' task.\n */\npackage com.amazonaws.services.dynamodbv2;\n\n\n\n/**\n *

\n * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks.\n *

\n *

\n * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method\n * for creating that cache (createLockCache.)\n *

\n *

\n * Here is some example code for how to use the lock client for leader election to work on a resource called \"host-2\" (it\n * assumes you already have a Momento cache named lockCache, which can be created with the\n * {@code createLockCache} helper method):\n *

\n *
\n * {@code\n *  AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient(\n *      MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, \"lockTable\").build();\n *  try {\n *      // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock\n *      LockItem lockItem = lockClient.acquireLock(\n *          AcquireLockOptions.builder(\"host-2\")\n *              .withRefreshPeriod(120L)\n *              .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L)\n *              .withTimeUnit(TimeUnit.MILLISECONDS)\n *              .build());\n *      if (!lockItem.isExpired()) {\n *          // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock\n *          // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds)\n *      }\n *  } catch (LockNotGrantedException x) {\n *      // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds.\n *  }\n * }\n * 
\n */\npublic class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable {\n private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class);\n\n private final String lockCacheName;\n private final CacheClient cacheClient;\n private static final long DEFAULT_BUFFER_MS = 1000;\n private static final int TTL_GRACE_MILLIS = 200;\n\n private final long leaseDurationMillis;\n private final long heartbeatPeriodInMilliseconds;\n private final String owner;\n private final ConcurrentHashMap sessionMonitors;\n private final LockStorage lockStorage;\n private final Function namedThreadCreator;\n\n private ScheduledExecutorService heartbeatExecutor;\n private MomentoLockClientHeartbeatHandler heartbeatHandler;\n\n private final MomentoLockClient momentoLockClient;\n private final Boolean holdLockOnServiceUnavailable;\n\n private final ScheduledExecutorService executorService;\n\n\nsrc/main/java/momento/lock/client/model/MomentoClientException.java\npublic class MomentoClientException extends RuntimeException {\n public MomentoClientException(String message) {\n super(message);\n }\n\n public MomentoClientException(String message, Throwable t) {\n super(message, t);\n }\n}\n\nsrc/main/java/momento/lock/client/MomentoLockClient.java\npublic class MomentoLockClient {\n\n private final CacheClient client;\n private final String cacheName;\n private static final Duration MOMENTO_TIMEOUT = Duration.ofSeconds(10);\n\n public MomentoLockClient(final CacheClient client,\n final String cacheName) {\n this.client = client;\n this.cacheName = cacheName;\n }\n\n public Optional getLockFromMomento(final String cacheKey) {\n try {\n final GetResponse getResponse = this.client.get(this.cacheName, cacheKey)\n .get(MOMENTO_TIMEOUT.getSeconds(), TimeUnit.SECONDS);\n if (getResponse instanceof GetResponse.Hit) {\n final MomentoLockItem momentoLockItem = LockItemUtils.deserialize(((GetResponse.Hit) getResponse).valueByteArray());\n return Optional.of(momentoLockItem);\n }\n } catch (TimeoutException e) {\n throw new MomentoClientException(\"Exceeded client side timeout of 10 seconds while retrieving from Momento \" +\n \"for cache key \" + cacheKey);\n } catch (InterruptedException | ExecutionException e) {\n throw new MomentoClientException(\"Caught unexpected exception while retrieving from Momento \" +\n \"for cache key \" + cacheKey);\n }\n return Optional.empty();\n }\n\n\n public boolean acquireLockInMomento(final MomentoLockItem lockItem) {\n\n try {\n final SetIfNotExistsResponse response = this.client.setIfNotExists(this.cacheName, lockItem.getCacheKey(),\n LockItemUtils.serialize(lockItem)).get(MOMENTO_TIMEOUT.getSeconds(), TimeUnit.SECONDS);\n\n if (response instanceof SetIfNotExistsResponse.Stored) {\n return true;\n } else if (response instanceof SetIfNotExistsResponse.Error) {\n throw new MomentoClientException(((SetIfNotExistsResponse.Error) response).getMessage(),\n ((SetIfNotExistsResponse.Error) response).getCause());\n }\n } catch (TimeoutException e) {\n throw new MomentoClientException(\"Exceeded client side timeout of 10 seconds while retrieving from Momento \" +\n \"for cache key \" + lockItem.getCacheKey());\n } catch (InterruptedException | ExecutionException e) {\n throw new MomentoClientException(\"Caught unexpected exception while retrieving from Momento \" +\n \"for cache key \" + lockItem.getCacheKey());\n }\n\n return false;\n }\n\n public boolean deleteLockFromMomento(final MomentoLockItem lockItem) {\n\n try {\n final DeleteResponse response = this.client.delete(this.cacheName, lockItem.getCacheKey())\n .get(MOMENTO_TIMEOUT.getSeconds(), TimeUnit.SECONDS);\n\n if (response instanceof DeleteResponse.Success) {\n return true;\n } else if (response instanceof DeleteResponse.Error) {\n throw new MomentoClientException(((DeleteResponse.Error) response).getMessage(),\n ((DeleteResponse.Error) response).getCause());\n }\n } catch (TimeoutException e) {\n throw new MomentoClientException(\"Exceeded client side timeout of 10 seconds while retrieving from Momento \" +\n \"for cache key \" + lockItem.getCacheKey());\n } catch (InterruptedException | ExecutionException e) {\n throw new MomentoClientException(\"Caught unexpected exception while retrieving from Momento \" +\n \"for cache key \" + lockItem.getCacheKey());\n }\n\n return false;\n }\n\n public Long getLockRemainingTtl(final MomentoLockItem momentoLockItem) {\n\n try {\n final ItemGetTtlResponse itemGetTtlResponse =\n this.client.itemGetTtl(cacheName, momentoLockItem.getCacheKey())\n .get(MOMENTO_TIMEOUT.getSeconds(), TimeUnit.SECONDS);\n\n // check remaining ttl more than window; this gives another item exists semantics\n if (itemGetTtlResponse instanceof ItemGetTtlResponse.Hit) {\n return ((ItemGetTtlResponse.Hit) itemGetTtlResponse).remainingTtlMillis();\n } else if (itemGetTtlResponse instanceof ItemGetTtlResponse.Error) {\n throw new MomentoClientException(((ItemGetTtlResponse.Error) itemGetTtlResponse).getMessage(),\n ((ItemGetTtlResponse.Error) itemGetTtlResponse).getCause());\n }\n\n } catch (TimeoutException e) {\n throw new MomentoClientException(\"Exceeded client side timeout of 10 seconds while retrieving from Momento \" +\n \"for cache key \" + momentoLockItem.getCacheKey());\n } catch (InterruptedException | ExecutionException e) {\n throw new MomentoClientException(\"Caught unexpected exception while retrieving from Momento \" +\n \"for cache key \" + momentoLockItem.getCacheKey());\n }\n\n return null;\n }\n\n public boolean createLockCache(final String cacheName) {\n try {\n final CacheCreateResponse createResponse = this.client.createCache(cacheName)\n .get(MOMENTO_TIMEOUT.getSeconds(), TimeUnit.SECONDS);\n\n if (createResponse instanceof CacheCreateResponse.Error) {\n return false;\n }\n } catch (TimeoutException e) {\n throw new MomentoClientException(\"Exceeded client side timeout of 10 seconds while creating cache in Momento \" +\n \"for cache name \" + cacheName);\n } catch (InterruptedException | ExecutionException e) {\n throw new MomentoClientException(\"Caught unexpected exception while while creating cache in Momento \" +\n \"for cache name \" + cacheName);\n }\n\n return true;\n }\n\n public boolean lockCacheExists(final String cacheName) {\n try {\n final CacheListResponse response = this.client.listCaches()\n .get(MOMENTO_TIMEOUT.getSeconds(), TimeUnit.SECONDS);\n\n if (response instanceof CacheListResponse.Success) {\n List cacheInfoList = ((CacheListResponse.Success) response).getCaches();\n return cacheInfoList.stream().map(CacheInfo::name).anyMatch(name -> name.equals(cacheName));\n } else if (response instanceof CacheListResponse.Error) {\n throw new MomentoClientException(((CacheListResponse.Error) response).getMessage(),\n ((CacheListResponse.Error) response).getCause());\n }\n } catch (TimeoutException e) {\n throw new MomentoClientException(\"Exceeded client side timeout of 10 seconds while checking cache existence in Momento \" +\n \"for cache name \" + cacheName);\n } catch (InterruptedException | ExecutionException e) {\n throw new MomentoClientException(\"Caught unexpected exception while while checking cache existence in Momento \" +\n \"for cache name \" + cacheName);\n }\n\n return false;\n }\n}", "answers": [" public MomentoDynamoDBLockClient(final MomentoDynamoDBLockClientOptions lockClientOptions) {"], "length": 1002, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "eebc108b-6cc3-45d7-bd5d-d82a40814ff4", "reasoning": "After the import statements, the next logical element in a Java class is typically a constructor or method definition. The class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient and is used via a builder pattern shown in the documentation comment, which creates an instance with MomentoDynamoDBLockClientOptions. Therefore, the next line should be the public constructor that accepts a MomentoDynamoDBLockClientOptions argument.", "reasoning_model_answer": "public MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions options) {", "assistant_with_reasoning": "\nAfter the import statements, the next logical element in a Java class is typically a constructor or method definition. The class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient and is used via a builder pattern shown in the documentation comment, which creates an instance with MomentoDynamoDBLockClientOptions. Therefore, the next line should be the public constructor that accepts a MomentoDynamoDBLockClientOptions argument.\n\npublic MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions options) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 4.973, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11782, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions options) {", "score": 0.88, "is_full_score": false, "is_nonzero_score": true}} {"input": "from asgiref.sync import async_to_sync\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models.deletion import ProtectedError\nfrom django.views.generic import TemplateView\nfrom django.views.decorators.cache import never_cache\nfrom dramatiq_abort import abort\nfrom rest_framework import status\nfrom rest_framework.exceptions import APIException\nfrom rest_framework.exceptions import NotFound\nfrom rest_framework.exceptions import ValidationError as DRFValidationError\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom slugify import slugify\nfrom .bootstrap import fetch_and_store_block, update_blockchain_progress\nfrom .exceptions import UpdateBlockchainProgressError\nfrom .helpers import get_filter_backends, load_data_from_redis\nfrom .filters import (\n BlockFilter,\n CustomBlockSearchFilter,\n NodeFilter,\n NodeGroupFilter,\n)\nfrom .mixins import CustomModelViewSet\nfrom .models import Blockchain, Block, Reorg, Node, NodeGroup, DramatiqTask\nfrom .serializers import (\n BlockchainSerializer,\n BlockchainExtendedSerializer,\n BlockSerializer,\n BlockDetailSerializer,\n NodeSerializer,\n NodeGroupSerializer,\n DramatiqTaskSerializer,\n)\nfrom .tasks import bootstrap_blockchain, delete_blockchain\nimport channels\nimport logging\nimport pytz", "context": "backend/api/views.py\n\n\n\n\n\nlogger = logging.getLogger(__name__)\n\n\n# Serve Vue Application\nindex_view = never_cache(TemplateView.as_view(template_name='index.html'))\n\n\nclass NodeGroupViewSet(CustomModelViewSet):\n \"\"\"API endpoint for NodeGroup.\"\"\"\n queryset = NodeGroup.objects.all()\n filterset_class = NodeGroupFilter\n serializer_class = NodeGroupSerializer\n lookup_field = 'slug'\n permission_classes = [IsAuthenticated]\n\n def create(self, request, *args, **kwargs):\n slug = request.data.get('slug')\n if not slug:\n request.data['slug'] = slugify(request.data['name'], to_lower=True)\n return super().create(request, *args, **kwargs)\n\n def destroy(self, request, *args, **kwargs):\n try:\n return super().destroy(request, *args, **kwargs)\n except ProtectedError as e:\n raise DRFValidationError(\n detail='Node group is related to nodes, delete them first')\n\n\nclass NodeViewSet(CustomModelViewSet):\n \"\"\"API endpoint for Node.\"\"\"\n queryset = Node.objects.all()\n filterset_class = NodeFilter\n serializer_class = NodeSerializer\n # currently all node views require authentication\n permission_classes = [IsAuthenticated]\n lookup_field = 'slug'\n\n def create(self, request, *args, **kwargs):\n slug = request.data.get('slug')\n if not slug:\n request.data['slug'] = slugify(request.data['name'], to_lower=True)\n request.data['group'] = NodeGroup.objects.get(slug=request.data['group']).pk\n return super().create(request, *args, **kwargs)\n\n def update(self, request, *args, **kwargs):\n # NOTE: super().partial_update calls update(..., partial=True)\n if not kwargs.get('partial'):\n # we don't allow full updates - aka PUT\n raise DRFPermissionDenied()\n return super().update(request, *args, **kwargs)\n\n def partial_update(self, request, slug=None):\n request.data['group'] = NodeGroup.objects.get(slug=request.data['group']).pk\n return super().partial_update(request, slug=slug)\n\n @action(detail=True, methods=['get'])\n def reachable(self, request, slug=None):\n node = self.get_object()\n try:\n res = node.is_reachable()\n except Exception as e:\n logger.exception('Unreachable node')\n res = False\n return Response(res, status=status.HTTP_200_OK)\n\n def destroy(self, request, *args, **kwargs):\n try:\n return super().destroy(request, *args, **kwargs)\n except ProtectedError as e:\n raise DRFValidationError(\n detail='Node is related to blockchains, delete them first')\n\n\nclass BlockchainViewSet(CustomModelViewSet):\n \"\"\"API endpoint for Blockchain.\"\"\"\n\n\nbackend/api/bootstrap.py\ndef update_blockchain_progress(blockchain):\n try:\n start_height, end_height = blockchain.get_bootstrap_heights()\n except Exception as e:\n logger.warning(\n 'Failed to get bootstrap heights',\n extra={ 'blockchain': blockchain.slug },\n )\n raise UpdateBlockchainProgressError(blockchain.slug)\n expected_heights = set(range(start_height, end_height + 1))\n existing_heights = set(list(\n blockchain.blocks\\\n .filter(reorg__isnull=True)\\\n .values_list('height', flat=True)\n ))\n missing_heights = expected_heights - existing_heights\n update_load_progress(\n blockchain, \n len(missing_heights),\n end_height - start_height + 1,\n 1,\n 1,\n 2,\n verbose=True\n )\n\nbackend/api/helpers.py\ndef get_filter_backends(replacements):\n \"\"\"\n Returns a tuple of filter backends where default ones, from DefaultMixin,\n are replaced with the given replacements.\n\n Args:\n replacements: dict where key is an existing filter backend class's\n __name__ and value is its replacement filter backend class\n \"\"\"\n current_filters = DefaultMixin.filter_backends\n return tuple([\n filter if filter.__name__ not in replacements else replacements[filter.__name__]\n for filter in list(current_filters)\n ])\n\nbackend/api/serializers.py\nclass DramatiqTaskSerializer(serializers.ModelSerializer):\n content_object = serializers.SerializerMethodField()\n\n class Meta:\n model = DramatiqTask\n fields = (\n 'id',\n 'message_id',\n 'type',\n 'status',\n 'failure_reason',\n 'content_object',\n )\n\n def get_content_object(self, task):\n from .serializers import BlockchainSerializer\n serializer_mapper = {\n 'Blockchain': BlockchainSerializer,\n }\n klass = task.content_object.__class__\n return {\n 'model': klass._meta.model_name,\n 'data': serializer_mapper[klass.__name__](task.content_object).data,\n }\n\nbackend/api/serializers.py\nclass BlockchainSerializer(serializers.ModelSerializer):\n node = serializers.PrimaryKeyRelatedField(queryset=Node.objects.all(), write_only=True)\n\n class Meta:\n model = Blockchain\n fields = ('name', 'slug', 'default', 'node', 'load_progress', 'fetch_price')\n\nbackend/api/tasks.py\n@dramatiq.actor(max_retries=0, time_limit=float(\"inf\"))\ndef delete_blockchain(blockchain_slug):\n # import here to avoid cyclic import\n from .models import Blockchain\n Blockchain.objects.get(slug=blockchain_slug).delete()\n async_to_sync(get_channel_layer().group_send)(\n 'admin_group',\n {\n 'type': 'blockchain_deleted',\n 'message': {\n 'slug': blockchain_slug,\n },\n }\n )\n\nbackend/api/serializers.py\nclass BlockchainExtendedSerializer(serializers.ModelSerializer):\n tasks = serializers.SerializerMethodField()\n\n class Meta:\n model = Blockchain\n fields = ('name', 'slug', 'node', 'default', 'load_progress', 'fetch_price', 'tasks')\n\n def to_representation(self, obj):\n self.fields['node'] = NodeSerializer()\n return super().to_representation(obj)\n\n def get_tasks(self, blockchain):\n content_type = ContentType.objects.get_for_model(blockchain)\n tasks = DramatiqTask.objects.filter(\n content_type=content_type,\n object_id=blockchain.id,\n )\n return DramatiqTaskSimpleSerializer(tasks, many=True).data\n\nbackend/api/models.py\nclass NodeGroup(models.Model):\n \"\"\"\n NodeGroup represents a group of nodes. These nodes should be on the same\n network.:\n \"\"\"\n id = models.BigAutoField(primary_key=True)\n # name is probably mainnet, testnet or smth similar\n name = models.CharField(max_length=255, unique=True)\n # by default that's slug of the name\n slug = models.SlugField(max_length=255, unique=True)\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name, to_lower=True)\n else:\n self.slug = self.slug.lower()\n self.full_clean()\n return super().save(*args, **kwargs)\n\nbackend/api/models.py\nclass Reorg(TimeStampedModel):\n id = models.BigAutoField(primary_key=True)\n blockchain = models.ForeignKey(\n Blockchain, related_name='reorgs', on_delete=models.CASCADE)\n # start_reorg_block and end_reorg_block define starting and ending block,\n # which were reorged\n start_reorg_block = models.ForeignKey(\n Block, related_name='start_reorgs', on_delete=models.CASCADE)\n end_reorg_block = models.ForeignKey(\n Block, related_name='end_reorgs', on_delete=models.CASCADE)\n # start_main_block defines starting block which is the new start of the main\n # chain - the block that replaced start_reorg_block. We usually don't know\n # which the ending block is when we spot the reorg, so we don't store it\n # (we don't even have it in DB at that time yet since we usually get them\n # incrementally in the order they're accepted).\n start_main_block = models.ForeignKey(\n Block, related_name='start_mains', on_delete=models.CASCADE)\n\n def __str__(self):\n return '{}: start: {}, end: {}'.format(\n self.blockchain.slug, self.start_reorg_block, self.end_reorg_block)\n\nbackend/api/filters.py\nclass CustomBlockSearchFilter(DRFfilters.SearchFilter):\n \"\"\"\n Alongside the given search_fields this filter filters also by:\n - keyword 'reorgs' --> return only blocks where reorgs happened\n - ['inputs', 'outputs', 'kernels'] ['=', '<', '>', '<=', '>='] [value] -->\n return only blocks matching this computation, eg: 'inputs > 2'\n You cannot combine different types of search (eg. 'reorgs' + 'computation')\n \"\"\"\n\n def filter_queryset(self, request, queryset, view):\n queryset = super().filter_queryset(request, queryset, view)\n blockchain_slug = view.kwargs['blockchain_slug']\n original_search_terms = self.get_search_terms(request)\n search_terms = self._get_normalized_search_terms(original_search_terms)\n if len(search_terms) == 0:\n # searches:\n # - height --> add filter reorg=None\n # - hash --> nothing to add\n # - outputhash --> add filter reorg=None\n # - block-detail --> nothing to add\n # - block-list --> add filter reorg=None\n if len(original_search_terms) > 1:\n raise APIException('Too many standard search terms')\n if not original_search_terms:\n # it's either an unfiltered block-list or block-detail\n if view.action == 'list':\n queryset = queryset.filter(reorg=None)\n else:\n # there's only 1 original search term, figure out which one\n if len(original_search_terms[0]) != 64:\n # it's not block hash but either block height or output hash\n # in both cases we need to filter out reorgs\n queryset = queryset.filter(reorg=None)\n return queryset\n searched_types = set(map(lambda x: x['type'], search_terms))\n if len(searched_types) > 1:\n raise APIException('Cannot combine different types of searches')\n if searched_types == { 'reorgs' }:\n return self._get_reorgs_qs(blockchain_slug)\n elif searched_types == { 'computation' }:\n return self._get_computations_qs(search_terms, blockchain_slug)\n elif searched_types == { 'hash' }:\n return self._get_hash_qs(search_terms[0]['value'], blockchain_slug, queryset)\n elif searched_types == { 'height' }:\n return self._get_height_qs(search_terms[0]['value'], blockchain_slug)\n elif searched_types == { 'kernel_or_output' }:\n return self._get_kernel_or_output_qs(\n search_terms[0]['value'], blockchain_slug)\n else:\n logger.exception(\n 'Invalid search terms',\n exc_info=e,\n extra={'search_terms': search_terms}\n )\n raise APIException('Invalid search terms')\n\n def _get_normalized_search_terms(self, search_terms):\n \"\"\"\n Search terms of format ['outputs>1'] are not supported. Instead, the\n operators should be surrounded by spaces, eg. ['outputs', '>', '1'].\n Supported operators are ['=', '>', '<', '<=', '>=']\n \"\"\"\n supported_operators = ['=', '>', '<', '<=', '>=']\n normalized_terms = []\n i = 0\n while i <= len(search_terms) - 1:\n if isinstance(search_terms[i], str) and search_terms[i].lower() in ['inputs', 'outputs', 'kernels']:\n operator = search_terms[i+1]\n if operator not in supported_operators:\n raise APIException('Invalid search operator')\n value = int(search_terms[i+2])\n if value < 0:\n raise APIException('Invalid search computation')\n normalized_terms.append({\n 'type': 'computation',\n 'source': search_terms[i],\n 'op': operator,\n 'value': value,\n })\n i += 3\n elif isinstance(search_terms[i], str) and search_terms[i].lower() == 'reorgs':\n normalized_terms.append({ 'type': 'reorgs' })\n i += 1\n elif len(search_terms[i]) == 64:\n # hash\n normalized_terms.append({\n 'type': 'hash',\n 'value': search_terms[i],\n })\n i += 1\n elif len(search_terms[i]) == 66:\n # kernel excess or output commitment\n normalized_terms.append({\n 'type': 'kernel_or_output',\n 'value': search_terms[i],\n })\n i += 1\n else:\n try:\n value = int(search_terms[i])\n except ValueError:\n value = None\n if value >= 0:\n normalized_terms.append({\n 'type': 'height',\n 'value': value,\n })\n i += 1\n else:\n # term which is not for this custom search, eg. block hash\n i += 1\n return normalized_terms\n\n def _get_reorgs_qs(self, blockchain_slug):\n # NOTE: we first filter, then calculate reorg_len on filtered data and\n # then filter on annotated data that we've calculated\n reorg_heights = list(Reorg.objects\\\n .select_related('start_main_block')\\\n .filter(\n blockchain__slug=blockchain_slug,\n start_main_block__reorg=None,\n )\\\n .annotate(reorg_len=F('end_reorg_block__height') - F('start_reorg_block__height') + 1)\\\n .filter(reorg_len__gte=settings.MIN_REORG_LEN)\\\n .values_list('start_main_block__height', flat=True)\n )\n queryset = Block.objects\\\n .filter(\n blockchain__slug=blockchain_slug,\n reorg=None,\n height__in=reorg_heights,\n )\\\n .order_by('-height')\n return queryset\n\n def _get_hash_qs(self, hash, blockchain_slug, queryset):\n return queryset.filter(\n blockchain__slug=blockchain_slug,\n hash=hash,\n )\n\n def _get_height_qs(self, height, blockchain_slug):\n return Block.objects.filter(\n blockchain__slug=blockchain_slug,\n height=height,\n )\n\n def _get_kernel_or_output_qs(self, kernel_or_output, blockchain_slug):\n kernel = Kernel.objects.filter(\n excess=kernel_or_output,\n block__blockchain__slug=blockchain_slug,\n ).first()\n if kernel:\n return Block.objects.filter(hash=kernel.block.hash)\n output = Output.objects.filter(\n commitment=kernel_or_output,\n block__blockchain__slug=blockchain_slug,\n ).first()\n if output:\n return Block.objects.filter(hash=output.block.hash)\n return Block.objects.none()\n\n def _get_computations_qs(self, search_terms, blockchain_slug):\n operator_mapping = {\n '=': '',\n '>': '__gt',\n '<': '__lt',\n '<=': '__lte',\n '>=': '__gte',\n }\n possible_sources = ['inputs', 'outputs', 'kernels']\n searched_sources = set(map(lambda x: x['source'], search_terms))\n op_searched_types = set(possible_sources) & set(searched_sources)\n op_qs = Blockchain.objects.get(slug=blockchain_slug).blocks.all()\n for search_term in search_terms:\n filters = {\n 'blockchain__slug': blockchain_slug,\n 'reorg': None,\n }\n op_map = operator_mapping[search_term['op']]\n filters[f'nr_{search_term[\"source\"]}{op_map}'] = search_term['value']\n op_qs = op_qs.filter(**filters).order_by('-height')\n return op_qs", "answers": [" queryset = Blockchain.objects.all()"], "length": 1389, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "dfdd9baf-3a79-4016-9062-13848df94f2a", "reasoning": "The file defines a BlockchainViewSet class earlier with only a docstring. After the import block, the next logical line is to start filling in that class's attributes. Following the pattern of other viewsets, the first attribute should be the queryset for the viewset, i.e., all Blockchain objects.", "reasoning_model_answer": "queryset = Blockchain.objects.all()", "assistant_with_reasoning": "\nThe file defines a BlockchainViewSet class earlier with only a docstring. After the import block, the next logical line is to start filling in that class's attributes. Following the pattern of other viewsets, the first attribute should be the queryset for the viewset, i.e., all Blockchain objects.\n\nqueryset = Blockchain.objects.all()", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.391, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 17690, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "queryset = Blockchain.objects.all()", "score": 0.95, "is_full_score": false, "is_nonzero_score": true}} {"input": "import random\nimport copy\nimport sys\nimport os\nimport bitsandbytes as bnb\nimport torch.nn as nn\nimport transformers\nimport torch\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import CUDA_VISIBLE_DEVICES, USE_TORCH, CPU_NUMS # from config\nfrom transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES\nfrom peft import (get_peft_model_state_dict, get_peft_model, LoraConfig)\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom transformers.modeling_utils import unwrap_model\nfrom tensorboardX import SummaryWriter\nfrom datasets import load_dataset\nfrom macro_gpt.models.llama.modeling_llama import LlamaForCausalLM as LLMForCausalLM\nfrom macro_gpt.models.llama.tokenization_llama import LlamaTokenizer as LLMTokenizer\nfrom macro_gpt.models.llama.modeling_llama import LlamaConfig as LLMConfig\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_PRETRAIN, DATA_PATH, MODEL_SAVE_DIR, REPO_ID\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MICRO_BATCH_SIZE, BATCH_SIZE, GRADIENT_ACCUMULATION_STEPS\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LEARNING_RATE, EPOCHS, SAVE_STEPS, VAL_SET_SIZE, TARGET_MODULES\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import IS_PARALLELIZABLE, MODEL_PARALLEL, USE_CACHE\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MAX_LENGTH_Q, MAX_LENGTH_A, MAX_LENGTH_QA\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LORA_DROPOUT, LORA_ALPHA, LORA_R\nfrom macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_CONFIG, PATH_TOKENIZER_PRETRAIN", "context": "macro_gpt/ft_gpt/train.pt.py\n# !/usr/bin/python\n# -*- coding: utf-8 -*-\n# @time : 2023/3/5 21:04\n# @author : Mo\n# @function: macro-gpt\n\n\npath_root = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../..\"))\nsys.path.append(path_root)\nos.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"max_split_size_mb:3072\"\n\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMODEL_PARALLEL = False\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nLORA_DROPOUT = 0.05\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMODEL_SAVE_DIR = \"model_macrogpt_1b3_float32\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nTARGET_MODULES = [\"query_key_value\"]\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nCPU_NUMS = \"9\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMAX_LENGTH_Q = 1024 - 2 # default=128 - 2\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nPATH_TOKENIZER_PRETRAIN = REPO_ID or \"./macrogpt.model\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMICRO_BATCH_SIZE = 4 # default=4 # this could actually be 5 but i like powers of 2\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMAX_LENGTH_QA = MAX_LENGTH_Q + MAX_LENGTH_A + 4\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nLORA_R = 8\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nLORA_ALPHA = 16\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nMAX_LENGTH_A = 1024 - 2 # default=128 - 2\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nCUDA_VISIBLE_DEVICES = \"0\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nSAVE_STEPS = 384\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nUSE_CACHE = False\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nLEARNING_RATE = 3e-4 # default=3e-4 # the Karpathy constant\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nPATH_MODEL_PRETRAIN = \"\"\n\nmacro_gpt/ft_gpt/config_macrogpt_1b3_float32.py\nBATCH_SIZE = 128\n\nmacro_gpt/models/llama/modeling_llama.py\nclass LlamaForCausalLM(LlamaPreTrainedModel):\n _tied_weights_keys = [\"lm_head.weight\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.model = LlamaModel(config)\n self.vocab_size = config.vocab_size\n self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_input_embeddings(self):\n return self.model.embed_tokens\n\n def set_input_embeddings(self, value):\n self.model.embed_tokens = value\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def set_output_embeddings(self, new_embeddings):\n self.lm_head = new_embeddings\n\n def set_decoder(self, decoder):\n self.model = decoder\n\n def get_decoder(self):\n return self.model\n\n @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids: torch.LongTensor = None,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n past_key_values: Optional[List[torch.FloatTensor]] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithPast]:\n r\"\"\"\n Args:\n labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, LlamaForCausalLM\n\n >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)\n >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)\n\n >>> prompt = \"Hey, are you conscious? Can you talk to me?\"\n >>> inputs = tokenizer(prompt, return_tensors=\"pt\")\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n \"Hey, are you conscious? Can you talk to me?\\nI'm not conscious, but I can talk to you.\"\n ```\"\"\"\n\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n if self.config.pretraining_tp > 1:\n lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)\n logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]\n logits = torch.cat(logits, dim=-1)\n else:\n # logits = self.lm_head(hidden_states)\n logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype))\n logits = logits.float()\n\n loss = None\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss()\n shift_logits = shift_logits.view(-1, self.config.vocab_size)\n shift_labels = shift_labels.view(-1)\n # Enable model parallelism\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return (loss,) + output if loss is not None else output\n\n return CausalLMOutputWithPast(\n loss=loss,\n logits=logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def prepare_inputs_for_generation(\n self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n ):\n if past_key_values is not None:\n past_length = past_key_values[0][0].shape[2]\n\n # Some generation methods already pass only the last input ID\n if input_ids.shape[1] > past_length:\n remove_prefix_length = past_length\n else:\n # Default to old behavior: keep only final ID\n remove_prefix_length = input_ids.shape[1] - 1\n\n input_ids = input_ids[:, remove_prefix_length:]\n\n position_ids = kwargs.get(\"position_ids\", None)\n if attention_mask is not None and position_ids is None:\n # create position_ids on the fly for batch generation\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n if past_key_values:\n position_ids = position_ids[:, -input_ids.shape[1] :]\n\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step\n if inputs_embeds is not None and past_key_values is None:\n model_inputs = {\"inputs_embeds\": inputs_embeds}\n else:\n model_inputs = {\"input_ids\": input_ids}\n\n model_inputs.update(\n {\n \"position_ids\": position_ids,\n \"past_key_values\": past_key_values,\n \"use_cache\": kwargs.get(\"use_cache\"),\n \"attention_mask\": attention_mask,\n }\n )\n return model_inputs\n\n @staticmethod\n def _reorder_cache(past_key_values, beam_idx):\n reordered_past = ()\n for layer_past in past_key_values:\n reordered_past += (\n tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),\n )\n return reordered_past", "answers": ["os.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES"], "length": 817, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "c20d47be-6131-4a51-88ff-24629841c1ce", "reasoning": "The script has just imported CUDA_VISIBLE_DEVICES from the config file. In many training scripts the next step is to set the CUDA_VISIBLE_DEVICES environment variable so that only the specified GPUs are visible to PyTorch. Therefore the appropriate next line is assigning the imported value to the environment variable.", "reasoning_model_answer": "os.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES", "assistant_with_reasoning": "\nThe script has just imported CUDA_VISIBLE_DEVICES from the config file. In many training scripts the next step is to set the CUDA_VISIBLE_DEVICES environment variable so that only the specified GPUs are visible to PyTorch. Therefore the appropriate next line is assigning the imported value to the environment variable.\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.69, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10613, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "os.environ[\"CUDA_VISIBLE_DEVICES\"] = CUDA_VISIBLE_DEVICES", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;\nimport com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;\nimport com.baomidou.mybatisplus.core.toolkit.Wrappers;\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport org.tinycloud.bean.entity.UcUser;\nimport org.tinycloud.bean.param.UcUserPageQuery;\nimport org.tinycloud.bean.vo.UcUserVo;\nimport org.tinycloud.common.consts.GlobalConstant;\nimport org.tinycloud.common.model.PageModel;\nimport org.tinycloud.common.utils.LambdaUtils;\nimport org.tinycloud.common.utils.StringUtils;\nimport org.tinycloud.common.utils.bean.BeanUtils;\nimport org.tinycloud.user.mapper.UcUserMapper;\nimport org.tinycloud.user.service.UcUserService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.CollectionUtils;\nimport java.util.stream.Collectors;", "context": "tinycloud-user/src/main/java/org/tinycloud/user/service/impl/UcUserServiceImpl.java\npackage org.tinycloud.user.service.impl;\n\n\n\n\n@Service\npublic class UcUserServiceImpl implements UcUserService {\n\n @Autowired\n private UcUserMapper ucUserMapper;\n\n /**\n * 根据id查询详情\n * @param userId\n * @return\n */\n @Override\n public UcUserVo detail(String userId) {\n UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.lambdaQuery()\n .eq(UcUser::getUserId, userId)\n .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED));\n if (ucUser != null) {\n return BeanUtils.transformBean(ucUser, UcUserVo.class);\n }\n return null;\n }\n\n\n /**\n * 第二种动态排序的方法\n * @param pageQuery UcUserPageQuery\n * @return PageModel\n */\n @Override\n public PageModel query(UcUserPageQuery pageQuery) {\n PageModel responsePage = new PageModel<>(pageQuery.getPageNo(), pageQuery.getPageSize());\n LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();\n\n boolean isAsc = false;\n if (GlobalConstant.ASC.equalsIgnoreCase(pageQuery.getSortType())) {\n isAsc = true;\n }\n\n wrapper.like(StringUtils.isNotEmpty(pageQuery.getUsername()), UcUser::getUsername, pageQuery.getUsername());\n wrapper.like(StringUtils.isNotEmpty(pageQuery.getNickname()), UcUser::getNickname, pageQuery.getNickname());\n wrapper.orderBy(StringUtils.isNotEmpty(pageQuery.getSortType()) && StringUtils.isNotEmpty(pageQuery.getSortFiled()),\n isAsc,\n LambdaUtils.getLambdaGetter(UcUser.class, pageQuery.getSortFiled()));\n\n Page page = this.ucUserMapper.selectPage(new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize()), wrapper);\n if (page != null && !CollectionUtils.isEmpty(page.getRecords())) {\n responsePage.setTotalPage((int) page.getPages());\n\ntinycloud-bean/src/main/java/org/tinycloud/bean/param/UcUserPageQuery.java\n@Getter\n@Setter\npublic class UcUserPageQuery extends BasePageParam {\n private static final long serialVersionUID = -1L;\n\n @ApiModelProperty(\"用户账号\")\n private String username;\n\n @ApiModelProperty(\"用户昵称(中文姓名)\")\n private String nickname;\n}\n\ntinycloud-common/src/main/java/org/tinycloud/common/consts/GlobalConstant.java\npublic final class GlobalConstant {\n\n /**\n * 系统包名前缀(用于扫描包的配置)\n */\n public static final String BASE_PACKAGE_PREFIX = \"org.tinycloud\";\n\n /**\n * Feign包名前缀(用于扫描Feign的配置)\n */\n public static final String FEIGN_PACKAGE_PREFIX = \"org.tinycloud.api\";\n\n /**\n * 前端请求头的的请求客户端\n */\n public static final String HEADER_CLIENT_TYPE = \"client-type\";\n\n /**\n * 已删除标记\n */\n public static final Integer DELETED = 1;\n\n /**\n * 未删除标记\n */\n public static final Integer NOT_DELETED = 0;\n\n /**\n * 升序排序\n */\n public static final String ASC = \"asc\";\n\n /**\n * 降序排序\n */\n public static final String DESC = \"desc\";\n\n /**\n * 统一接口限流 redis-key\n */\n public static final String LIMIT_KEY = \"tinycloud:limit\";\n}\n\ntinycloud-common/src/main/java/org/tinycloud/common/utils/LambdaUtils.java\npublic class LambdaUtils {\n private static final Logger logger = LoggerFactory.getLogger(LambdaUtils.class);\n\n\n public static final Map, PropertyDescriptor[]> cache = new HashMap<>();\n\n public static SFunction getLambdaGetter(Class clazz, String prop) {\n try {\n PropertyDescriptor[] beanGetters;\n if (cache.containsKey(clazz)) {\n beanGetters = cache.get(clazz);\n } else {\n beanGetters = ReflectUtils.getBeanGetters(clazz);\n cache.put(clazz, beanGetters);\n }\n\n MethodHandles.Lookup lookup = MethodHandles.lookup();\n Optional optional = Arrays.stream(beanGetters)\n .filter(pd -> pd.getName().equals(prop))\n .findFirst();\n if (optional.isPresent()) {\n // 反射获取getter方法\n Method readMethod = optional.get().getReadMethod();\n // 拿到方法句柄\n final MethodHandle methodHandle = lookup.unreflect(readMethod);\n // 创建动态调用链\n CallSite callSite = LambdaMetafactory.altMetafactory(\n lookup,\n \"apply\",\n MethodType.methodType(SFunction.class),\n MethodType.methodType(Object.class, Object.class),\n methodHandle,\n MethodType.methodType(readMethod.getReturnType(), clazz),\n LambdaMetafactory.FLAG_SERIALIZABLE\n );\n return (SFunction) callSite.getTarget().invokeExact();\n }\n } catch (Throwable throwable) {\n logger.error(\"getLambdaGetter Throwable: \", throwable);\n }\n\n return null;\n }\n\n}\n\ntinycloud-common/src/main/java/org/tinycloud/common/model/PageModel.java\npublic class PageModel implements Serializable {\n private static final long serialVersionUID = 1L;\n\n // 总记录数\n private Integer totalCount;\n\n // 总页数\n private Integer totalPage;\n\n // 结果集\n private List records;\n\n // 当前页码\n private Integer pageNo;\n\n // 当前页大小\n private Integer pageSize;\n\n public Integer getTotalCount() {\n return totalCount;\n }\n\n public void setTotalCount(Integer totalCount) {\n this.totalCount = totalCount;\n }\n\n public Integer getTotalPage() {\n return totalPage;\n }\n\n public void setTotalPage(Integer totalPage) {\n this.totalPage = totalPage;\n }\n\n public List getRecords() {\n return records;\n }\n\n public void setRecords(List records) {\n this.records = records;\n }\n\n public Integer getPageNo() {\n return pageNo;\n }\n\n public void setPageNo(Integer pageNo) {\n this.pageNo = pageNo;\n }\n\n public Integer getPageSize() {\n return pageSize;\n }\n\n public void setPageSize(Integer pageSize) {\n this.pageSize = pageSize;\n }\n\n public PageModel() {\n }\n\n public PageModel(Integer pageNo, Integer pageSize) {\n this.pageNo = pageNo;\n this.pageSize = pageSize;\n }\n\n public PageModel(Integer pageNo, Integer pageSize, List records, Integer totalCount) {\n this.pageNo = pageNo;\n this.pageSize = pageSize;\n this.records = records;\n this.totalCount = totalCount;\n // 自动计算出总页数\n if (totalCount != 0) {\n this.totalPage = (totalCount - 1) / pageSize + 1;\n } else {\n this.totalPage = 0;\n }\n }\n\n public PageModel(Integer pageNo, Integer pageSize, List records, Integer totalCount, Integer totalPage) {\n this.pageNo = pageNo;\n this.pageSize = pageSize;\n this.records = records;\n this.totalCount = totalCount;\n this.totalPage = totalPage;\n }\n\n public static PageModel build(Integer page, Integer size, List list, Integer totalCount, Integer totalPage) {\n return new PageModel<>(page, size, list, totalCount, totalPage);\n }\n}\n\ntinycloud-common/src/main/java/org/tinycloud/common/utils/bean/BeanUtils.java\npublic class BeanUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);\n\n\n /**\n * 批量copy两个bean属性\n *\n * @param source 源\n * @param tClass 目标类型\n * @return List 目标类型列表中\n */\n public static List batchTransformBean(List source, Class tClass) {\n List result = new ArrayList<>();\n try {\n for (S co : source) {\n T t = tClass.newInstance();\n\n org.springframework.beans.BeanUtils.copyProperties(co, t);\n result.add(t);\n }\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n throw new RuntimeException(\"转换失败\");\n }\n return result;\n }\n\n /**\n * 拷贝两个bean属性\n *\n * @param source 源\n * @param tClass 目标类型\n * @return 目标类型实例\n */\n public static T transformBean(S source, Class tClass) {\n T t;\n try {\n t = tClass.newInstance();\n org.springframework.beans.BeanUtils.copyProperties(source, t);\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n throw new RuntimeException(\"转换失败\");\n }\n return t;\n }\n\n /**\n * Bean属性复制工具方法\n *\n * @param source 源对象\n * @param target 目标对象\n */\n public static void copyProperties(Object source, Object target) {\n try {\n org.springframework.beans.BeanUtils.copyProperties(source, target);\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n throw new RuntimeException(\"拷贝bean失败\");\n }\n }\n\n /**\n * bean转map\n *\n * @param source bean\n * @param 传入的bean类型\n * @return Map\n */\n public static Map beanToMap(T source) {\n Map map = new HashMap<>(16);\n if (source != null) {\n BeanMap beanMap = BeanMap.create(source);\n for (Object key : beanMap.keySet()) {\n map.put(key + \"\", beanMap.get(key));\n }\n }\n return map;\n }\n\n /**\n * map转为javaBean\n *\n * @param map 要转换的map\n * @param clazz 转换成的bean类\n * @return 转换后的bean\n */\n public static T mapToBean(Map map, Class clazz) {\n try {\n T bean = clazz.newInstance();\n BeanMap beanMap = BeanMap.create(bean);\n for (String key : map.keySet()) {\n if (key.contains(\"_\")) {\n String newKey = StringUtils.toLowerCaseFirstOne(StringUtils.lineToHump(key));\n beanMap.put(newKey, map.get(key));\n } else {\n beanMap.put(key, map.get(key));\n }\n }\n return bean;\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n }\n return null;\n }\n\n /**\n * 批量转换map为javaBean\n *\n * @param list map\n * @param clazz 类型\n * @return 转换后的list\n */\n public static List batchMapToBean(List> list, Class clazz) {\n List result = new ArrayList<>();\n for (Map map : list) {\n result.add(mapToBean(map, clazz));\n }\n return result;\n }\n}", "answers": [" responsePage.setTotalCount((int) page.getTotal());"], "length": 956, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "62163b85-0307-4d40-b498-658fed29f8b4", "reasoning": "The query method builds a PageModel response. Inside the if block after setting totalPage, the next logical step is to set the total record count before populating the records list. The Page object provides getTotal() for total records, so the next line should assign this to responsePage.", "reasoning_model_answer": "responsePage.setTotalCount((int) page.getTotal());", "assistant_with_reasoning": "\nThe query method builds a PageModel response. Inside the if block after setting totalPage, the next logical step is to set the total record count before populating the records list. The Page object provides getTotal() for total records, so the next line should assign this to responsePage.\n\nresponsePage.setTotalCount((int) page.getTotal());", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 5.622, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 3, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11668, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "responsePage.setTotalCount((int) page.getTotal());", "score": 0.89, "is_full_score": false, "is_nonzero_score": true}} {"input": "import java.util.function.Function;\nimport java.util.function.Supplier;\nimport net.minecraft.world.item.BlockItem;\nimport net.minecraft.world.item.Item;\nimport net.minecraft.world.level.block.Block;\nimport net.minecraft.world.level.block.entity.BlockEntity;\nimport com.tom.peripherals.block.GPUBlock;\nimport com.tom.peripherals.block.MonitorBlock;\nimport com.tom.peripherals.block.RedstonePortBlock;\nimport com.tom.peripherals.block.WatchDogTimerBlock;\nimport com.tom.peripherals.block.entity.GPUBlockEntity;\nimport com.tom.peripherals.block.entity.MonitorBlockEntity;\nimport com.tom.peripherals.block.entity.RedstonePortBlockEntity;\nimport com.tom.peripherals.block.entity.WatchDogTimerBlockEntity;\nimport com.tom.peripherals.platform.GameObject;\nimport com.tom.peripherals.platform.GameObject.GameObjectBlockEntity;\nimport com.tom.peripherals.platform.GameObject.GameRegistryBE.BlockEntityFactory;\nimport com.tom.peripherals.platform.Platform;", "context": "Forge/src/platform-shared/java/com/tom/peripherals/Content.java\npackage com.tom.peripherals;\n\n\n\n\npublic class Content {\n\tpublic static final GameObject gpu = blockWithItem(\"gpu\", GPUBlock::new);\n\tpublic static final GameObject monitor = blockWithItem(\"monitor\", MonitorBlock::new);\n\tpublic static final GameObject wdt = blockWithItem(\"wdt\", WatchDogTimerBlock::new);\n\tpublic static final GameObject redstonePort = blockWithItem(\"redstone_port\", RedstonePortBlock::new);\n\n\tpublic static final GameObject gpuChip = item(\"gpu_chip\", () -> new Item(new Item.Properties()));\n\tpublic static final GameObject gpuChipRaw = item(\"gpu_chip_raw\", () -> new Item(new Item.Properties()));\n\n\tpublic static final GameObjectBlockEntity gpuBE = blockEntity(\"gpu\", GPUBlockEntity::new, gpu);\n\nFabric/src/main/java/com/tom/peripherals/platform/GameObject.java\npublic static class GameObjectBlockEntity extends GameObject> {\n\tprivate BlockEntityType value;\n\tprivate List> blocks;\n\tprivate BlockEntityFactory factory;\n\tprivate GameRegistryBE registry;\n\tprivate String name;\n\n\tpublic GameObjectBlockEntity(GameRegistryBE registry, String name, List> blocks, BlockEntityFactory factory) {\n\t\tsuper(null);\n\t\tthis.name = name;\n\t\tthis.blocks = blocks;\n\t\tthis.factory = factory;\n\t\tthis.registry = registry;\n\t}\n\n\tprotected void register() {\n\t\tvalue = FabricBlockEntityTypeBuilder.create((a, b) -> factory.create(value, a, b), blocks.stream().map(GameObject::get).toArray(Block[]::new)).build(null);\n\t\tRegistry.register(registry.registry, new ResourceLocation(PeripheralsMod.ID, name), value);\n\t}\n\n\t@Override\n\tpublic BlockEntityType get() {\n\t\treturn value;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void addBlocks(GameObject... blocks) {\n\t\tthis.blocks.addAll(Arrays.asList(blocks));\n\t}\n}\n\nForge/src/platform-shared/java/com/tom/peripherals/block/entity/RedstonePortBlockEntity.java\npublic class RedstonePortBlockEntity extends AbstractPeripheralBlockEntity implements TickableServer {\n\tprivate static final Object[] SIDES = Arrays.stream(Direction.values()).map(e -> e.getSerializedName()).toArray();\n\tprivate ObjectWrapper peripheral;\n\n\tprivate boolean internalOutputChanged = false;\n\tprivate final int[] internalOutput = new int[6];\n\tprivate final int[] internalBundledOutput = new int[6];\n\tprivate final int[] externalOutput = new int[6];\n\tprivate final int[] externalBundledOutput = new int[6];\n\tprivate boolean inputChanged = false;\n\tprivate final int[] input = new int[6];\n\tprivate final int[] bundledInput = new int[6];\n\n\tpublic RedstonePortBlockEntity(BlockEntityType p_155228_, BlockPos p_155229_, BlockState p_155230_) {\n\t\tsuper(p_155228_, p_155229_, p_155230_);\n\t}\n\n\t@Override\n\tpublic ObjectWrapper getPeripheral() {\n\t\tif(peripheral == null)peripheral = new ObjectWrapper(\"tm_rsPort\", new RSPort());\n\t\treturn peripheral;\n\t}\n\n\tpublic class RSPort extends TMLuaObject {\n\n\t\t@LuaMethod\n\t\tpublic Object[] getSides() throws LuaException {\n\t\t\treturn SIDES;\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic boolean getInput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction)\");\n\t\t\t}\n\t\t\treturn RedstonePortBlockEntity.this.getInput(getDir(args[0])) > 0;\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic int getAnalogInput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction)\");\n\t\t\t}\n\t\t\treturn RedstonePortBlockEntity.this.getInput(getDir(args[0]));\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic int getAnalogueInput(Object[] args) throws LuaException {\n\t\t\treturn getAnalogInput(args);\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic int getBundledInput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction)\");\n\t\t\t}\n\t\t\treturn RedstonePortBlockEntity.this.getBundledInput(getDir(args[0]));\n\t\t}\n\n\n\n\t\t@LuaMethod\n\t\tpublic boolean getOutput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction)\");\n\t\t\t}\n\t\t\treturn RedstonePortBlockEntity.this.getOutput(getDir(args[0])) > 0;\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic int getAnalogOutput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction)\");\n\t\t\t}\n\t\t\treturn RedstonePortBlockEntity.this.getOutput(getDir(args[0]));\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic int getAnalogueOutput(Object[] args) throws LuaException {\n\t\t\treturn getAnalogOutput(args);\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic int getBundledOutput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction)\");\n\t\t\t}\n\t\t\treturn RedstonePortBlockEntity.this.getBundledOutput(getDir(args[0]));\n\t\t}\n\n\n\t\t@LuaMethod\n\t\tpublic void setOutput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 2) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction, value)\");\n\t\t\t}\n\t\t\tif (!(args[1] instanceof Boolean v))\n\t\t\t\tthrow new LuaException(\"Bad argument #2 (expected Boolean)\");\n\t\t\tRedstonePortBlockEntity.this.setOutput(getDir(args[0]), v ? 15 : 0);\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic void setAnalogOutput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 2) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction, value)\");\n\t\t\t}\n\t\t\tif (!(args[1] instanceof Double v))\n\t\t\t\tthrow new LuaException(\"Bad argument #2 (expected Number)\");\n\t\t\tDirection dir = getDir(args[0]);\n\t\t\tint out = Mth.floor(v);\n\t\t\tif (out < 0 || out > 15)\n\t\t\t\tthrow new LuaException(\"Bad argument #2: Expected number in range 0-15\");\n\n\t\t\tRedstonePortBlockEntity.this.setOutput(dir, out);\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic void setAnalogueOutput(Object[] args) throws LuaException {\n\t\t\tsetAnalogOutput(args);\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic void setBundledOutput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 2) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction, value)\");\n\t\t\t}\n\t\t\tif (!(args[1] instanceof Double v))\n\t\t\t\tthrow new LuaException(\"Bad argument #2 (expected Number)\");\n\t\t\tDirection dir = getDir(args[0]);\n\t\t\tint out = Mth.floor(v);\n\n\t\t\tRedstonePortBlockEntity.this.setBundledOutput(dir, out);\n\t\t}\n\n\n\t\t@LuaMethod\n\t\tpublic boolean testBundledInput(Object[] args) throws LuaException {\n\t\t\tif (args.length < 2) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected direction, mask)\");\n\t\t\t}\n\t\t\tif (!(args[1] instanceof Double md))\n\t\t\t\tthrow new LuaException(\"Bad argument #2 (expected Number)\");\n\t\t\tint value = RedstonePortBlockEntity.this.getBundledInput(getDir(args[0]));\n\t\t\tint mask = Mth.floor(md);\n\t\t\treturn (value & mask) == mask;\n\t\t}\n\n\t\tprivate Direction getDir(Object in) throws LuaException {\n\t\t\tString side = String.valueOf(in);\n\t\t\tDirection dir = null;\n\t\t\tfor(Direction d : Direction.values()) {\n\t\t\t\tif (d.getName().equalsIgnoreCase(side)) {\n\t\t\t\t\tdir = d;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dir == null)throw new LuaException(\"Bad argument #1: expected one of: up, down, north, south, east, west\");\n\t\t\treturn dir;\n\t\t}\n\t}\n\n\tpublic boolean updateOutput() {\n\t\tsynchronized (this.internalOutput) {\n\t\t\tif (!this.internalOutputChanged) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tboolean changed = false;\n\n\t\t\t\tfor (int i = 0; i < 6; ++i) {\n\t\t\t\t\tif (this.externalOutput[i] != this.internalOutput[i]) {\n\t\t\t\t\t\tthis.externalOutput[i] = this.internalOutput[i];\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.externalBundledOutput[i] != this.internalBundledOutput[i]) {\n\t\t\t\t\t\tthis.externalBundledOutput[i] = this.internalBundledOutput[i];\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.internalOutputChanged = false;\n\t\t\t\treturn changed;\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void updateServer() {\n\t\tif (inputChanged) {\n\t\t\tinputChanged = false;\n\t\t\tgetPeripheral().queueEvent(\"tm_redstone\", new Object[0]);\n\t\t}\n\t\tif (updateOutput()) {\n\t\t\tfor (var dir : DirectionUtil.FACINGS) RedstoneUtil.propagateRedstoneOutput(getLevel(), getBlockPos(), dir);\n\t\t\tupdateRedstoneInputs();\n\t\t}\n\t}\n\n\tpublic int getInput(Direction side) {\n\t\treturn input[side.ordinal()];\n\t}\n\n\tpublic int getBundledInput(Direction side) {\n\t\treturn bundledInput[side.ordinal()];\n\t}\n\n\tpublic void setOutput(Direction side, int output) {\n\t\tvar index = side.ordinal();\n\t\tsynchronized (internalOutput) {\n\t\t\tif (internalOutput[index] != output) {\n\t\t\t\tinternalOutput[index] = output;\n\t\t\t\tinternalOutputChanged = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic int getOutput(Direction side) {\n\t\tsynchronized (internalOutput) {\n\t\t\treturn internalOutput[side.ordinal()];\n\t\t}\n\t}\n\n\tpublic void setBundledOutput(Direction side, int output) {\n\t\tvar index = side.ordinal();\n\t\tsynchronized (internalOutput) {\n\t\t\tif (internalBundledOutput[index] != output) {\n\t\t\t\tinternalBundledOutput[index] = output;\n\t\t\t\tinternalOutputChanged = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic int getBundledOutput(Direction side) {\n\t\tsynchronized (internalOutput) {\n\t\t\treturn internalBundledOutput[side.ordinal()];\n\t\t}\n\t}\n\n\tpublic int getExternalRedstoneOutput(Direction side) {\n\t\treturn externalOutput[side.ordinal()];\n\t}\n\n\tpublic int getExternalBundledRedstoneOutput(Direction side) {\n\t\treturn externalBundledOutput[side.ordinal()];\n\t}\n\n\tpublic void setRedstoneInput(Direction side, int level) {\n\t\tvar index = side.ordinal();\n\t\tif (input[index] != level) {\n\t\t\tinput[index] = level;\n\t\t\tinputChanged = true;\n\t\t}\n\t}\n\n\tpublic void setBundledRedstoneInput(Direction side, int combination) {\n\t\tvar index = side.ordinal();\n\t\tif (bundledInput[index] != combination) {\n\t\t\tbundledInput[index] = combination;\n\t\t\tinputChanged = true;\n\t\t}\n\t}\n\n\tprivate void updateRedstoneInput(Direction dir, BlockPos targetPos) {\n\t\tvar offsetSide = dir.getOpposite();\n\n\t\tsetRedstoneInput(dir, RedstoneUtil.getRedstoneInput(level, targetPos, dir));\n\t\tsetBundledRedstoneInput(dir, BundledRedstone.getOutput(getLevel(), targetPos, offsetSide));\n\t}\n\n\tprivate void updateRedstoneInputs() {\n\t\tvar pos = getBlockPos();\n\t\tfor (var dir : DirectionUtil.FACINGS) updateRedstoneInput(dir, pos.relative(dir));\n\t}\n\n\tpublic void neighborChanged(BlockPos neighbour) {\n\t\tupdateInputAt(neighbour);\n\t}\n\n\tprivate void updateInputAt(BlockPos neighbour) {\n\t\tfor (var dir : DirectionUtil.FACINGS) {\n\t\t\tvar offset = getBlockPos().relative(dir);\n\t\t\tif (offset.equals(neighbour)) {\n\t\t\t\tupdateRedstoneInput(dir, offset);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// If the position is not any adjacent one, update all inputs. This is pretty terrible, but some redstone mods\n\t\t// handle this incorrectly.\n\t\tupdateRedstoneInputs();\n\t}\n}", "answers": ["\tpublic static final GameObjectBlockEntity monitorBE = blockEntity(\"monitor\", MonitorBlockEntity::new, monitor);"], "length": 1092, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "a36ceb21-35bc-4ba6-8296-b1d3c9513db5", "reasoning": "In Content.java the static fields for blocks and items are being declared. After the gpuBE field, the next logical declaration is the block entity for the monitor block, following the same pattern as gpuBE. The method blockEntity is used to create a GameObjectBlockEntity, taking the name, a factory, and the associated block GameObject. Therefore the next line should declare monitorBE accordingly.", "reasoning_model_answer": "public static final GameObjectBlockEntity monitorBE = blockEntity(\"monitor\", MonitorBlockEntity::new, monitor);", "assistant_with_reasoning": "\nIn Content.java the static fields for blocks and items are being declared. After the gpuBE field, the next logical declaration is the block entity for the monitor block, following the same pattern as gpuBE. The method blockEntity is used to create a GameObjectBlockEntity, taking the name, a factory, and the associated block GameObject. Therefore the next line should declare monitorBE accordingly.\n\npublic static final GameObjectBlockEntity monitorBE = blockEntity(\"monitor\", MonitorBlockEntity::new, monitor);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 6.142, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 11609, "fewshot_ids": ["61d9b2af134b51dca9dac5b2bcfb82c522215a321479821c"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public static final GameObjectBlockEntity monitorBE = blockEntity(\"monitor\", MonitorBlockEntity::new, monitor);", "score": 1.0, "is_full_score": true, "is_nonzero_score": true}} {"input": "import java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport routing.maxprop.MaxPropDijkstra;\nimport routing.maxprop.MeetingProbabilitySet;\nimport routing.util.RoutingInfo;\nimport util.Tuple;\nimport core.Connection;\nimport core.DTNHost;\nimport core.Message;\nimport core.Settings;\nimport core.SimClock;", "context": "src/routing/MaxPropRouterWithEstimation.java\n/*\n * Copyright 2010 Aalto University, ComNet\n * Released under GPLv3. See LICENSE.txt for details.\n */\npackage routing;\n\n\n\n/**\n * Implementation of MaxProp router as described in\n * MaxProp: Routing for Vehicle-Based Disruption-Tolerant Networks by\n * John Burgess et al.\n *\n * but with parameter estimation for finding an alpha based on timescale\n * definition:\n *\n * Extension of the protocol by adding a parameter alpha (default 1)\n * By new connection, the delivery likelihood is increased by alpha\n * and divided by 1+alpha. Using the default results in the original\n * algorithm. Refer to Karvo and Ott, Time Scales and Delay-Tolerant Routing\n * Protocols Chants, 2008\n *\n * This version tries to estimate a good value of alpha from a timescale parameter\n * given by the user, and from the encounters the node sees during simulation.\n *\n * @version 1.0\n */\npublic class MaxPropRouterWithEstimation extends ActiveRouter {\n\t/** probabilities of meeting hosts */\n\tprivate MeetingProbabilitySet probs;\n\t/** meeting probabilities of all hosts from this host's point of view\n\t * mapped using host's network address */\n\tprivate Map allProbs;\n\t/** the cost-to-node calculator */\n\tprivate MaxPropDijkstra dijkstra;\n\t/** IDs of the messages that are known to have reached the final dst */\n\tprivate Set ackedMessageIds;\n\t/** mapping of the current costs for all messages. This should be set to\n\t * null always when the costs should be updated (a host is met or a new\n\t * message is received) */\n\tprivate Map costsForMessages;\n\t/** From host of the last cost calculation */\n\tprivate DTNHost lastCostFrom;\n\n\t/** Over how many samples the \"average number of bytes transferred per\n\t * transfer opportunity\" is taken */\n\tpublic static int BYTES_TRANSFERRED_AVG_SAMPLES = 10;\n\tprivate int[] avgSamples;\n\tprivate int nextSampleIndex = 0;\n\t/** current value for the \"avg number of bytes transferred per transfer\n\t * opportunity\" */\n\tprivate int avgTransferredBytes = 0;\n\n\t/** MaxPROP router's setting namespace ({@value})*/\n\tpublic static final String MAXPROP_NS = \"MaxPropRouterWithEstimation\";\n\n\t/* Number of seconds in time scale.*/\n\tpublic static final String TIME_SCALE_S =\"timeScale\";\n\n\t/** The alpha variable, default = 1;\n\t*/\n\tprivate double alpha;\n\n\t/** The default value for alpha\n\t*/\n\tpublic static final double DEFAULT_ALPHA = 1.0;\n\n\t/** value of time scale variable */\n\tprivate int timescale;\n\n\t/** last meeting time with a node */\n\tprivate Map meetings;\n\tprivate int nrofSamplesIET;\n\tprivate double meanIET;\n\n\t/** number of encounters between encounters */\n\tprivate Map encounters;\n\tprivate int nrofSamplesENC;\n\tprivate double meanENC;\n\tprivate int nrofTotENC;\n\n\t/**\n\t * Constructor. Creates a new prototype router based on the settings in\n\t * the given Settings object.\n\t * @param settings The settings object\n\t */\n\tpublic MaxPropRouterWithEstimation(Settings settings) {\n\t\tsuper(settings);\n\t\tSettings maxPropSettings = new Settings(MAXPROP_NS);\n\t\talpha = DEFAULT_ALPHA;\n\t\ttimescale = maxPropSettings.getInt(TIME_SCALE_S);\n\t\tinitMeetings();\n\t}\n\n\t/**\n\t * Copy constructor. Creates a new router based on the given prototype.\n\t * @param r The router prototype where setting values are copied from\n\t */\n\tprotected MaxPropRouterWithEstimation(MaxPropRouterWithEstimation r) {\n\t\tsuper(r);\n\t\tthis.alpha = r.alpha;\n\t\tthis.timescale = r.timescale;\n\t\tthis.probs = new MeetingProbabilitySet(\n\t\t\t\tMeetingProbabilitySet.INFINITE_SET_SIZE, this.alpha);\n\t\tthis.allProbs = new HashMap();\n\t\tthis.dijkstra = new MaxPropDijkstra(this.allProbs);\n\t\tthis.ackedMessageIds = new HashSet();\n\t\tthis.avgSamples = new int[BYTES_TRANSFERRED_AVG_SAMPLES];\n\t\tinitMeetings();\n\t}\n\n\t/**\n\t * Initializes interencounter estimators\n\t */\n\tprivate void initMeetings() {\n\t\tthis.meetings = new HashMap();\n\t\tthis.encounters = new HashMap();\n\t\tthis.meanIET = 0;\n\t\tthis.nrofSamplesIET = 0;\n\t\tthis.meanENC = 0;\n\t\tthis.nrofSamplesENC = 0;\n\t\tthis.nrofTotENC = 0;\n\t}\n\n\t@Override\n\nsrc/routing/util/RoutingInfo.java\npublic class RoutingInfo {\n\tprivate String text;\n\tprivate List moreInfo = null;\n\n\t/**\n\t * Creates a routing info based on a text.\n\t * @param infoText The text of the info\n\t */\n\tpublic RoutingInfo(String infoText) {\n\t\tthis.text = infoText;\n\t}\n\n\t/**\n\t * Creates a routing info based on any object. Object's\n\t * toString() method's output is used as the info text.\n\t * @param o The object this info is based on\n\t */\n\tpublic RoutingInfo(Object o) {\n\t\tthis.text = o.toString();\n\t}\n\n\t/**\n\t * Adds child info object for this routing info.\n\t * @param info The info object to add.\n\t */\n\tpublic void addMoreInfo(RoutingInfo info) {\n\t\tif (this.moreInfo == null) { // lazy creation\n\t\t\tthis.moreInfo = new ArrayList();\n\t\t}\n\t\tthis.moreInfo.add(info);\n\t}\n\n\t/**\n\t * Returns the child routing infos of this info.\n\t * @return The children of this info or an empty list if this info\n\t * doesn't have any children.\n\t */\n\tpublic List getMoreInfo() {\n\t\tif (this.moreInfo == null) {\n\t\t\treturn new ArrayList(0);\n\t\t}\n\t\treturn this.moreInfo;\n\t}\n\n\t/**\n\t * Returns the info text of this routing info.\n\t * @return The info text\n\t */\n\tpublic String toString() {\n\t\treturn this.text;\n\t}\n\n}\n\nsrc/routing/maxprop/MeetingProbabilitySet.java\npublic class MeetingProbabilitySet {\n\tpublic static final int INFINITE_SET_SIZE = Integer.MAX_VALUE;\n\t/** meeting probabilities (probability that the next node one meets is X) */\n\tprivate Map probs;\n\t/** the time when this MPS was last updated */\n\tprivate double lastUpdateTime;\n\t/** the alpha parameter */\n\tprivate double alpha;\n private int maxSetSize;\n\n\t/**\n\t * Constructor. Creates a probability set with empty node-probability\n\t * mapping.\n\t * @param maxSetSize Maximum size of the probability set; when the set is\n\t * full, smallest values are dropped when new are added\n\t */\n\tpublic MeetingProbabilitySet(int maxSetSize, double alpha) {\n\t\tthis.alpha = alpha;\n\t\tthis.probs = new HashMap();\n if (maxSetSize == INFINITE_SET_SIZE || maxSetSize < 1) {\n\tthis.probs = new HashMap();\n\tthis.maxSetSize = INFINITE_SET_SIZE;\n } else {\n\tthis.probs = new HashMap(maxSetSize);\n this.maxSetSize = maxSetSize;\n }\n\t\tthis.lastUpdateTime = 0;\n\t}\n\n\t/**\n\t * Constructor. Creates a probability set with empty node-probability\n\t * mapping and infinite set size\n\t */\n\tpublic MeetingProbabilitySet() {\n\t\tthis(INFINITE_SET_SIZE, 1);\n\t}\n\n\t/**\n\t * Constructor. Creates a probability set with equal probability for\n\t * all the given node indexes.\n\t */\n\tpublic MeetingProbabilitySet(double alpha,\n\t\t\t\tList initiallyKnownNodes) {\n\t\tthis(INFINITE_SET_SIZE, alpha);\n\t\tdouble prob = 1.0/initiallyKnownNodes.size();\n\t\tfor (Integer i : initiallyKnownNodes) {\n\t\t\tthis.probs.put(i, prob);\n\t\t}\n\t}\n\n\t/**\n\t * Updates meeting probability for the given node index.\n\t *
 P(b) = P(b)_old + alpha\n\t * Normalize{P}
\n\t * I.e., The probability of the given node index is increased by one and\n\t * then all the probabilities are normalized so that their sum equals to 1.\n\t * @param index The node index to update the probability for\n\t */\n\tpublic void updateMeetingProbFor(Integer index) {\n Map.Entry smallestEntry = null;\n double smallestValue = Double.MAX_VALUE;\n\n\t\tthis.lastUpdateTime = SimClock.getTime();\n\n\t\tif (probs.size() == 0) { // first entry\n\t\t\tprobs.put(index, 1.0);\n\t\t\treturn;\n\t\t}\n\n\t\tdouble newValue = getProbFor(index) + alpha;\n\t\tprobs.put(index, newValue);\n\n\t\t/* now the sum of all entries is 1+alpha;\n\t\t * normalize to one by dividing all the entries by 1+alpha */\n\t\tfor (Map.Entry entry : probs.entrySet()) {\n\t\t\tentry.setValue(entry.getValue() / (1+alpha));\n if (entry.getValue() < smallestValue) {\n smallestEntry = entry;\n smallestValue = entry.getValue();\n }\n\n\t\t}\n\n if (probs.size() >= maxSetSize) {\n if (DEBUG) core.Debug.p(\"Probsize: \" + probs.size() + \" dropping \" +\n\t\t\t\t\tprobs.remove(smallestEntry.getKey()));\n }\n\t}\n\n\tpublic void updateMeetingProbFor(Integer index, double iet)\t{\n\t\tprobs.put(index, iet);\n\t}\n\n\t/**\n\t * Returns the current delivery probability value for the given node index\n\t * @param index The index of the node to look the P for\n\t * @return the current delivery probability value\n\t */\n\tpublic double getProbFor(Integer index) {\n\t\tif (probs.containsKey(index)) {\n\t\t\treturn probs.get(index);\n\t\t}\n\t\telse {\n\t\t\t/* the node with the given index has not been met */\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a reference to the probability map of this probability set\n\t * @return a reference to the probability map of this probability set\n\t */\n\tpublic Map getAllProbs() {\n\t\treturn this.probs;\n\t}\n\n\t/**\n\t * Returns the time when this probability set was last updated\n\t * @return the time when this probability set was last updated\n\t */\n\tpublic double getLastUpdateTime() {\n\t\treturn this.lastUpdateTime;\n\t}\n\n\t/**\n\t * Enables changing the alpha parameter dynamically\n\t */\n\tpublic void setAlpha(double alpha) {\n\t\tthis.alpha = alpha;\n\t}\n\n\t/**\n\t * Returns a deep copy of the probability set\n\t * @return a deep copy of the probability set\n\t */\n\tpublic MeetingProbabilitySet replicate() {\n\t\tMeetingProbabilitySet replica = new MeetingProbabilitySet(\n\t\t\t\tthis.maxSetSize, alpha);\n\n\t\t// do a deep copy\n\t\tfor (Map.Entry e : probs.entrySet()) {\n\t\t\treplica.probs.put(e.getKey(), e.getValue().doubleValue());\n\t\t}\n\n\t\treplica.lastUpdateTime = this.lastUpdateTime;\n\t\treturn replica;\n\t}\n\n\t/**\n\t * Returns a String presentation of the probabilities\n\t * @return a String presentation of the probabilities\n\t */\n @Override\n\tpublic String toString() {\n\t\treturn \"probs: \" +\tthis.probs.toString();\n\t}\n}", "answers": ["\tpublic void changedConnection(Connection con) {"], "length": 1376, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "bab8d18d-01b4-40ca-b2ea-fa2d5b07fdf9", "reasoning": "The file ends with an @Override annotation, which in Java precedes a method definition. In the MaxProp router implementations, the next overridden method after initMeetings is the changedConnection handler. Therefore the next line should be the method signature for changedConnection.", "reasoning_model_answer": "public void changedConnection(Connection con) {", "assistant_with_reasoning": "\nThe file ends with an @Override annotation, which in Java precedes a method definition. In the MaxProp router implementations, the next overridden method after initMeetings is the changedConnection handler. Therefore the next line should be the method signature for changedConnection.\n\npublic void changedConnection(Connection con) {", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 2.91, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 10587, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "public void changedConnection(Connection con) {", "score": 0.99, "is_full_score": false, "is_nonzero_score": true}} {"input": "import android.annotation.SuppressLint;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.Toast;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport com.daominh.quickmem.adapter.group.ClassAdapter;\nimport com.daominh.quickmem.adapter.folder.FolderAdapter;\nimport com.daominh.quickmem.adapter.flashcard.SetsAdapter;\nimport com.daominh.quickmem.data.dao.FlashCardDAO;\nimport com.daominh.quickmem.data.dao.FolderDAO;\nimport com.daominh.quickmem.data.dao.GroupDAO;\nimport com.daominh.quickmem.data.model.FlashCard;\nimport com.daominh.quickmem.data.model.Folder;\nimport com.daominh.quickmem.data.model.Group;\nimport com.daominh.quickmem.databinding.FragmentHomeBinding;\nimport com.daominh.quickmem.preferen.UserSharePreferences;\nimport com.daominh.quickmem.ui.activities.create.CreateSetActivity;\nimport com.daominh.quickmem.ui.activities.search.ViewSearchActivity;\nimport org.jetbrains.annotations.NotNull;\nimport java.util.ArrayList;", "context": "app/src/main/java/com/daominh/quickmem/ui/fragments/home/HomeFragment.java\npackage com.daominh.quickmem.ui.fragments.home;\n\n\n\n\n\n\n\npublic class HomeFragment extends Fragment {\n private FragmentHomeBinding binding;\n private UserSharePreferences userSharePreferences;\n private SetsAdapter setsAdapter;\n private FolderAdapter folderAdapter;\n private ClassAdapter classAdapter;\n private ArrayList flashCards;\n private ArrayList folders;\n private ArrayList classes;\n private FlashCardDAO flashCardDAO;\n private FolderDAO folderDAO;\n private GroupDAO groupDAO;\n private String idUser;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n userSharePreferences = new UserSharePreferences(requireActivity());\n idUser = userSharePreferences.getId();\n flashCardDAO = new FlashCardDAO(requireActivity());\n folderDAO = new FolderDAO(requireActivity());\n groupDAO = new GroupDAO(requireActivity());\n }\n\n @Override\n public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n binding = FragmentHomeBinding.inflate(inflater, container, false);\n return binding.getRoot();\n }\n\n @Override\n public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n userSharePreferences = new UserSharePreferences(requireActivity());\n idUser = userSharePreferences.getId();\n\n setupFlashCards();\n setupFolders();\n setupClasses();\n setupVisibility();\n setupSwipeRefreshLayout();\n setupSearchBar();\n setupCreateSetsButton();\n\n binding.swipeRefreshLayout.setOnRefreshListener(() -> {\n refreshData();\n binding.swipeRefreshLayout.setRefreshing(false);\n Toast.makeText(requireActivity(), \"Refreshed\", Toast.LENGTH_SHORT).show();\n });\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupFlashCards() {\n flashCards = flashCardDAO.getAllFlashCardByUserId(idUser);\n LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false);\n binding.setsRv.setLayoutManager(linearLayoutManager);\n setsAdapter = new SetsAdapter(requireActivity(), flashCards, false);\n binding.setsRv.setAdapter(setsAdapter);\n setsAdapter.notifyDataSetChanged();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupFolders() {\n folders = folderDAO.getAllFolderByUserId(idUser);\n folderAdapter = new FolderAdapter(requireActivity(), folders);\n LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false);\n binding.foldersRv.setLayoutManager(linearLayoutManager1);\n binding.foldersRv.setAdapter(folderAdapter);\n folderAdapter.notifyDataSetChanged();\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupClasses() {\n classes = groupDAO.getClassesOwnedByUser(idUser);\n classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser));\n classAdapter = new ClassAdapter(requireActivity(), classes);\n LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false);\n binding.classesRv.setLayoutManager(linearLayoutManager2);\n binding.classesRv.setAdapter(classAdapter);\n classAdapter.notifyDataSetChanged();\n }\n\n private void setupVisibility() {\n if (flashCards.isEmpty()) {\n binding.setsCl.setVisibility(View.GONE);\n } else {\n binding.setsCl.setVisibility(View.VISIBLE);\n }\n if (folders.isEmpty()) {\n binding.folderCl.setVisibility(View.GONE);\n } else {\n binding.folderCl.setVisibility(View.VISIBLE);\n }\n if (classes.isEmpty()) {\n binding.classCl.setVisibility(View.GONE);\n } else {\n binding.classCl.setVisibility(View.VISIBLE);\n }\n }\n\n private void setupSwipeRefreshLayout() {\n binding.swipeRefreshLayout.setOnRefreshListener(() -> {\n refreshData();\n binding.swipeRefreshLayout.setRefreshing(false);\n });\n }\n\n private void setupSearchBar() {\n binding.searchBar.setOnClickListener(v -> {\n\napp/src/main/java/com/daominh/quickmem/adapter/flashcard/SetsAdapter.java\npublic class SetsAdapter extends RecyclerView.Adapter {\n\n private final Context context;\n private final ArrayList sets;\n private final Boolean isLibrary;\n\n public SetsAdapter(Context context, ArrayList sets, Boolean isLibrary) {\n this.context = context;\n this.sets = sets;\n this.isLibrary = isLibrary;\n }\n\n @NonNull\n @NotNull\n @Override\n public SetsAdapter.SetsViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {\n LayoutInflater inflater = LayoutInflater.from(context);\n ItemSetBinding binding = ItemSetBinding.inflate(inflater, parent, false);\n return new SetsViewHolder(binding.getRoot());\n }\n\n @SuppressLint(\"SetTextI18n\")\n @Override\n public void onBindViewHolder(@NonNull @NotNull SetsAdapter.SetsViewHolder holder, int position) {\n if (isLibrary){\n //set weight of card\n ViewGroup.LayoutParams params = holder.binding.setCv.getLayoutParams();\n params.width = ViewGroup.LayoutParams.MATCH_PARENT;\n\n }\n FlashCard set = sets.get(position);\n UserSharePreferences userSharePreferences = new UserSharePreferences(context);\n CardDAO cardDAO = new CardDAO(context);\n int count = cardDAO.countCardByFlashCardId(set.getId());\n String avatar = userSharePreferences.getAvatar();\n String userNames = userSharePreferences.getUserName();\n\n holder.binding.setNameTv.setText(set.getName());\n holder.binding.termCountTv.setText(count + \" terms\");\n holder.binding.userNameTv.setText(userNames);\n Picasso.get().load(avatar).into(holder.binding.avatarIv);\n holder.binding.createdDateTv.setText(set.getCreated_at());\n\n holder.itemView.setOnClickListener(v -> {\n Intent intent = new Intent(context, ViewSetActivity.class);\n intent.putExtra(\"id\", set.getId());\n\n context.startActivity(intent);\n });\n\n }\n\n @Override\n public int getItemCount() {\n return sets.size();\n }\n\n public static class SetsViewHolder extends RecyclerView.ViewHolder {\n private final ItemSetBinding binding;\n\n public SetsViewHolder(@NonNull @NotNull View itemView) {\n super(itemView);\n binding = ItemSetBinding.bind(itemView);\n }\n }\n\n}\n\napp/src/main/java/com/daominh/quickmem/ui/activities/create/CreateSetActivity.java\npublic class CreateSetActivity extends AppCompatActivity {\n private CardAdapter cardAdapter;\n private ArrayList cards;\n private ActivityCreateSetBinding binding;\n private final String id = genUUID();\n\n @SuppressLint(\"NotifyDataSetChanged\")\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n binding = ActivityCreateSetBinding.inflate(getLayoutInflater());\n final View view = binding.getRoot();\n setContentView(view);\n\n setupToolbar();\n setupSubjectEditText();\n setupDescriptionTextView();\n setupCardsList();\n setupCardAdapter();\n setupAddFab();\n setupItemTouchHelper();\n }\n\n private void setupToolbar() {\n setSupportActionBar(binding.toolbar);\n binding.toolbar.setNavigationOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());\n }\n\n private void setupSubjectEditText() {\n if (binding.subjectEt.getText().toString().isEmpty()) {\n binding.subjectEt.requestFocus();\n }\n }\n\n private void setupDescriptionTextView() {\n binding.descriptionTv.setOnClickListener(v -> {\n if (binding.descriptionTil.getVisibility() == View.GONE) {\n binding.descriptionTil.setVisibility(View.VISIBLE);\n } else {\n binding.descriptionTil.setVisibility(View.GONE);\n }\n });\n }\n\n private void setupCardsList() {\n //create list two set\n cards = new ArrayList<>();\n cards.add(new Card());\n cards.add(new Card());\n updateTotalCards();\n }\n\n private void updateTotalCards() {\n binding.totalCardsTv.setText(String.format(\"Total Cards: %s\", cards.size()));\n }\n\n @SuppressLint(\"NotifyDataSetChanged\")\n private void setupCardAdapter() {\n cardAdapter = new CardAdapter(this, cards);\n binding.cardsLv.setAdapter(cardAdapter);\n binding.cardsLv.setLayoutManager(new LinearLayoutManager(this));\n binding.cardsLv.setHasFixedSize(true);\n cardAdapter.notifyDataSetChanged();\n\n }\n\n private void setupAddFab() {\n binding.addFab.setOnClickListener(v -> {\n if (!checkTwoCardsEmpty()) {\n\n Card newCard = new Card();\n cards.add(newCard);\n //scroll to last item\n binding.cardsLv.smoothScrollToPosition(cards.size() - 1);\n //notify adapter\n cardAdapter.notifyItemInserted(cards.size() - 1);\n updateTotalCards();\n\n } else {\n Toast.makeText(this, \"Please enter front and back\", Toast.LENGTH_SHORT).show();\n }\n\n });\n }\n\n\n private void setupItemTouchHelper() {\n ItemTouchHelper.SimpleCallback callback = createItemTouchHelperCallback();\n ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);\n itemTouchHelper.attachToRecyclerView(binding.cardsLv);\n }\n\n private ItemTouchHelper.SimpleCallback createItemTouchHelperCallback() {\n return new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {\n @Override\n public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {\n return false;\n }\n\n @Override\n public void onSwiped(@NotNull RecyclerView.ViewHolder viewHolder, int direction) {\n handleOnSwiped(viewHolder);\n }\n\n @Override\n public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {\n handleOnChildDraw(c, viewHolder, dX);\n }\n };\n }\n\n private void handleOnSwiped(RecyclerView.ViewHolder viewHolder) {\n int position = viewHolder.getBindingAdapterPosition();\n\n // Backup of removed item for undo purpose\n Card deletedItem = cards.get(position);\n\n // Removing item from recycler view\n cards.remove(position);\n updateTotalCards();\n cardAdapter.notifyItemRemoved(position);\n\n // Showing Snack bar with an Undo option\n Snackbar snackbar = Snackbar.make(binding.getRoot(), \"Item was removed from the list.\", Snackbar.LENGTH_LONG);\n snackbar.setAction(\"UNDO\", view -> {\n\n // Check if the position is valid before adding the item back\n if (position >= 0 && position <= cards.size()) {\n cards.add(position, deletedItem);\n cardAdapter.notifyItemInserted(position);\n updateTotalCards();\n } else {\n // If the position isn't valid, show a message or handle the error appropriately\n Toast.makeText(getApplicationContext(), \"Error restoring item\", Toast.LENGTH_LONG).show();\n }\n });\n snackbar.setActionTextColor(Color.YELLOW);\n snackbar.show();\n }\n\n private void handleOnChildDraw(@NotNull Canvas c, @NotNull RecyclerView.ViewHolder viewHolder, float dX) {\n Drawable icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_delete);\n View itemView = viewHolder.itemView;\n assert icon != null;\n int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;\n int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;\n int iconBottom = iconTop + icon.getIntrinsicHeight();\n\n if (dX < 0) { // Swiping to the left\n int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();\n int iconRight = itemView.getRight() - iconMargin;\n icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);\n\n final ColorDrawable background = new ColorDrawable(Color.WHITE);\n background.setBounds(itemView.getRight() + ((int) dX), itemView.getTop(), itemView.getRight(), itemView.getBottom());\n background.draw(c);\n } else { // No swipe\n icon.setBounds(0, 0, 0, 0);\n }\n\n icon.draw(c);\n }\n\n @Override\n public boolean onPrepareOptionsMenu(Menu menu) {\n return super.onPrepareOptionsMenu(menu);\n\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_create_set, menu);\n return true;\n\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n if (item.getItemId() == R.id.done) {\n saveChanges();\n return true;\n }\n return super.onOptionsItemSelected(item);\n\n }\n\n private void saveChanges() {\n String subject = binding.subjectEt.getText().toString();\n String description = binding.descriptionEt.getText().toString();\n\n if (subject.isEmpty()) {\n binding.subjectTil.setError(\"Please enter subject\");\n binding.subjectEt.requestFocus();\n return;\n } else {\n binding.subjectTil.setError(null);\n }\n\n if (!saveAllCards()) {\n return;\n }\n\n if (!saveFlashCard(subject, description)) {\n Toast.makeText(this, \"Insert flashcard failed\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n Intent intent = new Intent(this, ViewSetActivity.class);\n intent.putExtra(\"id\", id);\n startActivity(intent);\n finish();\n }\n\n private boolean saveAllCards() {\n for (Card card : cards) {\n if (!saveCard(card)) {\n return false;\n }\n }\n return true;\n }\n\n private boolean saveCard(Card card) {\n String front = card.getFront();\n String back = card.getBack();\n\n if (front == null || front.isEmpty()) {\n binding.cardsLv.requestFocus();\n Toast.makeText(this, \"Please enter front\", Toast.LENGTH_SHORT).show();\n return false;\n }\n\n if (back == null || back.isEmpty()) {\n binding.cardsLv.requestFocus();\n Toast.makeText(this, \"Please enter back\", Toast.LENGTH_SHORT).show();\n return false;\n }\n\n CardDAO cardDAO = new CardDAO(this);\n card.setId(genUUID());\n card.setFront(front);\n card.setBack(back);\n card.setStatus(0);\n card.setIsLearned(0);\n card.setFlashcard_id(id);\n card.setCreated_at(getCurrentDate());\n card.setUpdated_at(getCurrentDate());\n if (cardDAO.insertCard(card) <= 0) {\n Toast.makeText(this, \"Insert card failed\" + id, Toast.LENGTH_SHORT).show();\n return false;\n }\n\n return true;\n }\n\n private boolean saveFlashCard(String subject, String description) {\n FlashCardDAO flashCardDAO = new FlashCardDAO(this);\n FlashCard flashCard = new FlashCard();\n flashCard.setName(subject);\n flashCard.setDescription(description);\n UserSharePreferences userSharePreferences = new UserSharePreferences(this);\n flashCard.setUser_id(userSharePreferences.getId());\n flashCard.setCreated_at(getCurrentDate());\n flashCard.setUpdated_at(getCurrentDate());\n flashCard.setId(id);\n binding.privateSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {\n if (isChecked) {\n Toast.makeText(this, \"Public\", Toast.LENGTH_SHORT).show();\n flashCard.setIs_public(1);\n } else {\n Toast.makeText(this, \"Private\", Toast.LENGTH_SHORT).show();\n flashCard.setIs_public(0);\n }\n });\n\n return flashCardDAO.insertFlashCard(flashCard) > 0;\n }\n\n private String getCurrentDate() {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n return getCurrentDateNewApi();\n } else {\n return getCurrentDateOldApi();\n }\n }\n\n public boolean checkTwoCardsEmpty() {\n // check if 2 cards are empty return true\n int emptyCount = 0;\n for (Card card : cards) {\n if (card.getFront() == null || card.getFront().isEmpty() || card.getBack() == null || card.getBack().isEmpty()) {\n emptyCount++;\n if (emptyCount == 2) {\n return true;\n }\n }\n }\n return false;\n }\n\n private String genUUID() {\n return java.util.UUID.randomUUID().toString();\n }\n\n @RequiresApi(api = Build.VERSION_CODES.O)\n private String getCurrentDateNewApi() {\n LocalDate currentDate = LocalDate.now();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\n return currentDate.format(formatter);\n }\n\n private String getCurrentDateOldApi() {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd/MM/yyyy\");\n return sdf.format(new Date());\n }\n}", "answers": [" Intent intent = new Intent(requireActivity(), ViewSearchActivity.class);"], "length": 1284, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "e57e4b27-33c2-4803-8a22-31b7d3fef283", "reasoning": "In HomeFragment, the setupSearchBar method opens a click listener on the search bar. The next logical statement is to create an Intent to launch the search activity (ViewSearchActivity) using the fragment's activity context. Therefore the next line should instantiate the Intent.", "reasoning_model_answer": "Intent intent = new Intent(requireActivity(), ViewSearchActivity.class);", "assistant_with_reasoning": "\nIn HomeFragment, the setupSearchBar method opens a click listener on the search bar. The next logical statement is to create an Intent to launch the search activity (ViewSearchActivity) using the fragment's activity context. Therefore the next line should instantiate the Intent.\n\nIntent intent = new Intent(requireActivity(), ViewSearchActivity.class);", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.132, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 2, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 19455, "fewshot_ids": ["f1eb8061d68130bb246d80f0c973a61e0e65bd181df5ccd3"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "Intent intent = new Intent(requireActivity(), ViewSearchActivity.class);", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}} {"input": "import itertools\nimport logging\nimport numpy as np\nimport operator\nimport pickle\nimport torch\nimport torch.utils.data as torchdata\nfrom collections import OrderedDict, defaultdict\nfrom typing import Any, Callable, Dict, List, Optional, Union\nfrom tabulate import tabulate\nfrom termcolor import colored\nfrom ..config import configurable\nfrom ..structures import BoxMode\nfrom ..utils.comm import get_world_size\nfrom ..utils.env import seed_all_rng\nfrom ..utils.file_io import PathManager\nfrom ..utils.logger import _log_api_usage, log_first_n\nfrom .catalog import DatasetCatalog, MetadataCatalog\nfrom .common import AspectRatioGroupedDataset, DatasetFromList, MapDataset, ToIterableDataset\nfrom .dataset_mapper import DatasetMapper\nfrom .detection_utils import check_metadata_consistency\nfrom .samplers import (\n InferenceSampler,\n RandomSubsetTrainingSampler,\n RepeatFactorTrainingSampler,\n TrainingSampler,\n)", "context": "nativedancer/third_part/detectron2/data/build.py\n sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces\n indices to be applied on ``dataset``.\n If ``dataset`` is map-style, the default sampler is a :class:`TrainingSampler`,\n which coordinates an infinite random shuffle sequence across all workers.\n Sampler must be None if ``dataset`` is iterable.\n total_batch_size (int): total batch size across all workers.\n aspect_ratio_grouping (bool): whether to group images with similar\n aspect ratio for efficiency. When enabled, it requires each\n element in dataset be a dict with keys \"width\" and \"height\".\n num_workers (int): number of parallel data loading workers\n collate_fn: a function that determines how to do batching, same as the argument of\n `torch.utils.data.DataLoader`. Defaults to do no collation and return a list of\n data. No collation is OK for small batch size and simple data structures.\n If your batch size is large and each sample contains too many small tensors,\n it's more efficient to collate them in data loader.\n\n Returns:\n torch.utils.data.DataLoader:\n a dataloader. Each output from it is a ``list[mapped_element]`` of length\n ``total_batch_size / num_workers``, where ``mapped_element`` is produced\n by the ``mapper``.\n \"\"\"\n if isinstance(dataset, list):\n dataset = DatasetFromList(dataset, copy=False)\n if mapper is not None:\n dataset = MapDataset(dataset, mapper)\n\n if isinstance(dataset, torchdata.IterableDataset):\n assert sampler is None, \"sampler must be None if dataset is IterableDataset\"\n else:\n if sampler is None:\n sampler = TrainingSampler(len(dataset))\n assert isinstance(sampler, torchdata.Sampler), f\"Expect a Sampler but got {type(sampler)}\"\n return build_batch_data_loader(\n dataset,\n sampler,\n total_batch_size,\n aspect_ratio_grouping=aspect_ratio_grouping,\n num_workers=num_workers,\n collate_fn=collate_fn,\n **kwargs\n )\n\n\ndef _test_loader_from_config(cfg, dataset_name, mapper=None):\n \"\"\"\n Uses the given `dataset_name` argument (instead of the names in cfg), because the\n standard practice is to evaluate each test set individually (not combining them).\n \"\"\"\n if isinstance(dataset_name, str):\n dataset_name = [dataset_name]\n\n dataset = get_detection_dataset_dicts(\n dataset_name,\n filter_empty=False,\n proposal_files=[\n cfg.DATASETS.PROPOSAL_FILES_TEST[list(cfg.DATASETS.TEST).index(x)] for x in dataset_name\n ]\n if cfg.MODEL.LOAD_PROPOSALS\n else None,\n )\n if mapper is None:\n mapper = DatasetMapper(cfg, False)\n return {\n \"dataset\": dataset,\n \"mapper\": mapper,\n \"num_workers\": cfg.DATALOADER.NUM_WORKERS,\n \"sampler\": InferenceSampler(len(dataset))\n if not isinstance(dataset, torchdata.IterableDataset)\n else None,\n }\n\n\n@configurable(from_config=_test_loader_from_config)\ndef build_detection_test_loader(\n dataset: Union[List[Any], torchdata.Dataset],\n *,\n mapper: Callable[[Dict[str, Any]], Any],\n sampler: Optional[torchdata.Sampler] = None,\n batch_size: int = 1,\n num_workers: int = 0,\n collate_fn: Optional[Callable[[List[Any]], Any]] = None,\n) -> torchdata.DataLoader:\n \"\"\"\n Similar to `build_detection_train_loader`, with default batch size = 1,\n and sampler = :class:`InferenceSampler`. This sampler coordinates all workers\n to produce the exact set of all samples.\n\n Args:\n dataset: a list of dataset dicts,\n or a pytorch dataset (either map-style or iterable). They can be obtained\n by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`.\n mapper: a callable which takes a sample (dict) from dataset\n and returns the format to be consumed by the model.\n When using cfg, the default choice is ``DatasetMapper(cfg, is_train=False)``.\n sampler: a sampler that produces\n indices to be applied on ``dataset``. Default to :class:`InferenceSampler`,\n which splits the dataset across all workers. Sampler must be None\n if `dataset` is iterable.\n batch_size: the batch size of the data loader to be created.\n Default to 1 image per worker since this is the standard when reporting\n inference time in papers.\n num_workers: number of parallel data loading workers\n collate_fn: same as the argument of `torch.utils.data.DataLoader`.\n Defaults to do no collation and return a list of data.\n\n Returns:\n DataLoader: a torch DataLoader, that loads the given detection\n dataset, with test-time transformation and batching.\n\n Examples:\n ::\n data_loader = build_detection_test_loader(\n DatasetRegistry.get(\"my_test\"),\n mapper=DatasetMapper(...))\n\n # or, instantiate with a CfgNode:\n data_loader = build_detection_test_loader(cfg, \"my_test\")\n \"\"\"\n if isinstance(dataset, list):\n\n\nnativedancer/third_part/detectron2/data/samplers/distributed_sampler.py\nclass TrainingSampler(Sampler):\n \"\"\"\n In training, we only care about the \"infinite stream\" of training data.\n So this sampler produces an infinite stream of indices and\n all workers cooperate to correctly shuffle the indices and sample different indices.\n\n The samplers in each worker effectively produces `indices[worker_id::num_workers]`\n where `indices` is an infinite stream of indices consisting of\n `shuffle(range(size)) + shuffle(range(size)) + ...` (if shuffle is True)\n or `range(size) + range(size) + ...` (if shuffle is False)\n\n Note that this sampler does not shard based on pytorch DataLoader worker id.\n A sampler passed to pytorch DataLoader is used only with map-style dataset\n and will not be executed inside workers.\n But if this sampler is used in a way that it gets execute inside a dataloader\n worker, then extra work needs to be done to shard its outputs based on worker id.\n This is required so that workers don't produce identical data.\n :class:`ToIterableDataset` implements this logic.\n This note is true for all samplers in detectron2.\n \"\"\"\n\n def __init__(self, size: int, shuffle: bool = True, seed: Optional[int] = None):\n \"\"\"\n Args:\n size (int): the total number of data of the underlying dataset to sample from\n shuffle (bool): whether to shuffle the indices or not\n seed (int): the initial seed of the shuffle. Must be the same\n across all workers. If None, will use a random seed shared\n among workers (require synchronization among all workers).\n \"\"\"\n if not isinstance(size, int):\n raise TypeError(f\"TrainingSampler(size=) expects an int. Got type {type(size)}.\")\n if size <= 0:\n raise ValueError(f\"TrainingSampler(size=) expects a positive int. Got {size}.\")\n self._size = size\n self._shuffle = shuffle\n if seed is None:\n seed = comm.shared_random_seed()\n self._seed = int(seed)\n\n self._rank = comm.get_rank()\n self._world_size = comm.get_world_size()\n\n def __iter__(self):\n start = self._rank\n yield from itertools.islice(self._infinite_indices(), start, None, self._world_size)\n\n def _infinite_indices(self):\n g = torch.Generator()\n g.manual_seed(self._seed)\n while True:\n if self._shuffle:\n yield from torch.randperm(self._size, generator=g).tolist()\n else:\n yield from torch.arange(self._size).tolist()", "answers": [" dataset = DatasetFromList(dataset, copy=False)"], "length": 943, "dataset": "repobench-p", "language": "java", "all_classes": null, "_id": "78d80e08-8590-400d-8e93-ce2049bb5785", "reasoning": "In build_detection_test_loader, after checking if the provided dataset is a list, the code must convert that list into a Detectron2 Dataset object. The standard utility for this is DatasetFromList, used with copy=False to avoid unnecessary copying. Therefore the next line should perform this conversion.", "reasoning_model_answer": "dataset = DatasetFromList(dataset, copy=False)", "assistant_with_reasoning": "\nIn build_detection_test_loader, after checking if the provided dataset is a list, the code must convert that list into a Detectron2 Dataset object. The standard utility for this is DatasetFromList, used with copy=False to avoid unnecessary copying. Therefore the next line should perform this conversion.\n\ndataset = DatasetFromList(dataset, copy=False)", "_reasoning_meta": {"parse_status": "json_ok", "latency_sec": 3.75, "model": "gpt-oss", "prompt_version": "reasoning_v5_1_fewshot_no_gold_compact", "status": "ok", "attempt": 1, "max_retries": 3, "dataset_key": "repobench-p", "prompt_source": "benchmark_template", "task_family": "code", "benchmark_prompt_chars": 8908, "fewshot_ids": ["6ba8a29ca25773e35d8a22904ef8cf1009eeda97e03e30fa"], "fewshot_dataset_keys": ["repobench-p"], "fewshot_count": 1}, "_gptoss_eval": {"dataset_key": "repobench-p", "pred_field": "reasoning_model_answer", "pred_used": "dataset = DatasetFromList(dataset, copy=False)", "score": 0.92, "is_full_score": false, "is_nonzero_score": true}}