type
stringclasses 1
value | dataset
stringclasses 1
value | input
stringlengths 75
160k
| instruction
stringlengths 117
171
| output
stringlengths 88
168k
|
---|---|---|---|---|
Inversion-Mutation | megadiff | "@Override
public void handleEvent(OperationEvent event) {
if(event instanceof AuditTrailResult) {
AuditTrailResult auditResult = (AuditTrailResult) event;
if (!auditResult.getCollectionID().equals(collectionID)) {
log.warn("Received bad collection id! Expected '" + collectionID + "', but got '"
+ auditResult.getCollectionID() + "'.");
return;
}
if (auditResult.isPartialResult()) {
contributorsWithPartialResults.add(auditResult.getContributorID());
}
AuditTrailEvents events = auditResult.getAuditTrailEvents().getAuditTrailEvents();
store.addAuditTrails(events, collectionID);
if (events != null && events.getAuditTrailEvent() != null) {
collectedAudits += events.getAuditTrailEvent().size();
log.debug("Collected and stored " + events.getAuditTrailEvent().size() +
" audit trail event from " + auditResult.getContributorID() + " in " +
TimeUtils.millisecondsToHuman(System.currentTimeMillis() - startTime)
+ " (PartialResult=" + auditResult.isPartialResult() + ".");
}
} else if (event.getEventType() == OperationEvent.OperationEventType.COMPONENT_FAILED ||
event.getEventType() == OperationEvent.OperationEventType.FAILED ||
event.getEventType() == OperationEvent.OperationEventType.IDENTIFY_TIMEOUT) {
log.warn("Event: " + event.toString());
} else {
log.debug("Event:" + event.toString());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleEvent" | "@Override
public void handleEvent(OperationEvent event) {
if(event instanceof AuditTrailResult) {
AuditTrailResult auditResult = (AuditTrailResult) event;
if (!auditResult.getCollectionID().equals(collectionID)) {
log.warn("Received bad collection id! Expected '" + collectionID + "', but got '"
+ auditResult.getCollectionID() + "'.");
return;
}
if (auditResult.isPartialResult()) {
contributorsWithPartialResults.add(auditResult.getContributorID());
}
AuditTrailEvents events = auditResult.getAuditTrailEvents().getAuditTrailEvents();
<MASK>collectedAudits += events.getAuditTrailEvent().size();</MASK>
store.addAuditTrails(events, collectionID);
if (events != null && events.getAuditTrailEvent() != null) {
log.debug("Collected and stored " + events.getAuditTrailEvent().size() +
" audit trail event from " + auditResult.getContributorID() + " in " +
TimeUtils.millisecondsToHuman(System.currentTimeMillis() - startTime)
+ " (PartialResult=" + auditResult.isPartialResult() + ".");
}
} else if (event.getEventType() == OperationEvent.OperationEventType.COMPONENT_FAILED ||
event.getEventType() == OperationEvent.OperationEventType.FAILED ||
event.getEventType() == OperationEvent.OperationEventType.IDENTIFY_TIMEOUT) {
log.warn("Event: " + event.toString());
} else {
log.debug("Event:" + event.toString());
}
}" |
Inversion-Mutation | megadiff | "private String buildFile (IPath filePath, IFile makefile, IManagedBuildInfo info) {
String outString = "";
IPath dir = makefile.getFullPath().removeLastSegments(1);
IPath relFilePath = filePath.removeFirstSegments(dir.segmentCount());
CommandLauncher launcher = new CommandLauncher();
String[] env = null;
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = stdout;
IPath makeCommandPath = new Path(info.getBuildCommand());
ITool tool = info.getToolFromOutputExtension("status"); // $NON-NLS-1$
IOption[] options = tool.getOptions();
IPath runPath = null;
boolean done = false;
for (int i = 0; i < options.length && !done; ++i) {
try {
if (options[i].getValueType() == IOption.STRING) {
String value = (String) options[i].getValue();
String id = options[i].getId();
if (id.indexOf("builddir") > 0) { // $NON-NLS-1$
runPath = makefile.getProject().getLocation().append(value.trim());
done = true;
}
}
} catch (BuildException e) {
// do nothing
}
}
IProgressMonitor monitor = new NullProgressMonitor();
String errMsg = null;
String[] makeArgs = new String[3];
makeArgs[0] = "-n"; // $NON-NLS-1$
makeArgs[1] = "all"; // $NON-NLS-1$
makeArgs[2] = "MAKE=make -W " + relFilePath.toOSString(); //$NON-NLS-1$
try {
Process proc = launcher.execute(makeCommandPath, makeArgs, env,
runPath, new NullProgressMonitor());
if (proc != null) {
try {
// Close the input of the process since we will never write to
// it
proc.getOutputStream().close();
} catch (IOException e) {
}
if (launcher.waitAndRead(stdout, stderr, new SubProgressMonitor(
monitor, IProgressMonitor.UNKNOWN)) != CommandLauncher.OK) {
errMsg = launcher.getErrorMessage();
}
outString = stdout.toString();
} else {
errMsg = launcher.getErrorMessage();
}
} catch (CoreException e) {
errMsg = e.getLocalizedMessage();
AutotoolsPlugin.logErrorMessage(errMsg);
}
return outString;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildFile" | "private String buildFile (IPath filePath, IFile makefile, IManagedBuildInfo info) {
String outString = "";
IPath dir = makefile.getFullPath().removeLastSegments(1);
IPath relFilePath = filePath.removeFirstSegments(dir.segmentCount());
CommandLauncher launcher = new CommandLauncher();
String[] env = null;
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = stdout;
IPath makeCommandPath = new Path(info.getBuildCommand());
ITool tool = info.getToolFromOutputExtension("status"); // $NON-NLS-1$
IOption[] options = tool.getOptions();
IPath runPath = null;
boolean done = false;
for (int i = 0; i < options.length && !done; ++i) {
try {
if (options[i].getValueType() == IOption.STRING) {
String value = (String) options[i].getValue();
String id = options[i].getId();
if (id.indexOf("builddir") > 0) { // $NON-NLS-1$
runPath = makefile.getProject().getLocation().append(value.trim());
}
<MASK>done = true;</MASK>
}
} catch (BuildException e) {
// do nothing
}
}
IProgressMonitor monitor = new NullProgressMonitor();
String errMsg = null;
String[] makeArgs = new String[3];
makeArgs[0] = "-n"; // $NON-NLS-1$
makeArgs[1] = "all"; // $NON-NLS-1$
makeArgs[2] = "MAKE=make -W " + relFilePath.toOSString(); //$NON-NLS-1$
try {
Process proc = launcher.execute(makeCommandPath, makeArgs, env,
runPath, new NullProgressMonitor());
if (proc != null) {
try {
// Close the input of the process since we will never write to
// it
proc.getOutputStream().close();
} catch (IOException e) {
}
if (launcher.waitAndRead(stdout, stderr, new SubProgressMonitor(
monitor, IProgressMonitor.UNKNOWN)) != CommandLauncher.OK) {
errMsg = launcher.getErrorMessage();
}
outString = stdout.toString();
} else {
errMsg = launcher.getErrorMessage();
}
} catch (CoreException e) {
errMsg = e.getLocalizedMessage();
AutotoolsPlugin.logErrorMessage(errMsg);
}
return outString;
}" |
Inversion-Mutation | megadiff | "public Object getConnectionHandle(boolean recycle) throws Exception {
if (isFailed()) {
synchronized (this) {
try {
if (isFailed()) {
if (log.isDebugEnabled()) { log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition"); }
close();
init();
IncrementalRecoverer.recover(xaResourceProducer);
}
}
catch (RecoveryException ex) {
throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
catch (Exception ex) {
throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
}
}
long remainingTimeMs = bean.getAcquisitionTimeout() * 1000L;
while (true) {
long before = MonotonicClock.currentTimeMillis();
XAStatefulHolder xaStatefulHolder = null;
if (recycle) {
if (bean.getShareTransactionConnections()) {
xaStatefulHolder = getSharedXAStatefulHolder();
}
else {
xaStatefulHolder = getNotAccessible();
}
}
if (xaStatefulHolder == null) {
xaStatefulHolder = getInPool(remainingTimeMs);
}
if (log.isDebugEnabled()) { log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this); }
try {
// getConnectionHandle() here could throw an exception, if it doesn't the connection is
// still alive and we can share it (if sharing is enabled)
Object connectionHandle = xaStatefulHolder.getConnectionHandle();
if (bean.getShareTransactionConnections()) {
putSharedXAStatefulHolder(xaStatefulHolder);
}
growUntilMinPoolSize();
return connectionHandle;
} catch (Exception ex) {
try {
if (log.isDebugEnabled()) { log.debug("connection is invalid, trying to close it", ex); }
xaStatefulHolder.close();
} catch (Exception ex2) {
if (log.isDebugEnabled()) { log.debug("exception while trying to close invalid connection, ignoring it", ex2); }
}
finally {
if (xaStatefulHolder.getState() != XAStatefulHolder.STATE_CLOSED) {
stateChanged(xaStatefulHolder, xaStatefulHolder.getState(), XAStatefulHolder.STATE_CLOSED);
}
if (log.isDebugEnabled()) { log.debug("removed invalid connection " + xaStatefulHolder + " from " + this); }
if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this);
long waitTime = bean.getAcquisitionInterval() * 1000L;
if (waitTime > 0) {
try {
wait(waitTime);
} catch (InterruptedException ex2) {
// ignore
}
}
}
// check for timeout
long now = MonotonicClock.currentTimeMillis();
remainingTimeMs -= (now - before);
before = now;
if (remainingTimeMs <= 0) {
throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex);
}
Thread.sleep(bean.getAcquisitionInterval() * 1000L);
}
} // while true
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getConnectionHandle" | "public Object getConnectionHandle(boolean recycle) throws Exception {
if (isFailed()) {
synchronized (this) {
try {
if (isFailed()) {
if (log.isDebugEnabled()) { log.debug("resource '" + bean.getUniqueName() + "' is marked as failed, resetting and recovering it before trying connection acquisition"); }
close();
init();
IncrementalRecoverer.recover(xaResourceProducer);
}
}
catch (RecoveryException ex) {
throw new BitronixRuntimeException("incremental recovery failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
catch (Exception ex) {
throw new BitronixRuntimeException("pool reset failed when trying to acquire a connection from failed resource '" + bean.getUniqueName() + "'", ex);
}
}
}
<MASK>long before = MonotonicClock.currentTimeMillis();</MASK>
long remainingTimeMs = bean.getAcquisitionTimeout() * 1000L;
while (true) {
XAStatefulHolder xaStatefulHolder = null;
if (recycle) {
if (bean.getShareTransactionConnections()) {
xaStatefulHolder = getSharedXAStatefulHolder();
}
else {
xaStatefulHolder = getNotAccessible();
}
}
if (xaStatefulHolder == null) {
xaStatefulHolder = getInPool(remainingTimeMs);
}
if (log.isDebugEnabled()) { log.debug("found " + Decoder.decodeXAStatefulHolderState(xaStatefulHolder.getState()) + " connection " + xaStatefulHolder + " from " + this); }
try {
// getConnectionHandle() here could throw an exception, if it doesn't the connection is
// still alive and we can share it (if sharing is enabled)
Object connectionHandle = xaStatefulHolder.getConnectionHandle();
if (bean.getShareTransactionConnections()) {
putSharedXAStatefulHolder(xaStatefulHolder);
}
growUntilMinPoolSize();
return connectionHandle;
} catch (Exception ex) {
try {
if (log.isDebugEnabled()) { log.debug("connection is invalid, trying to close it", ex); }
xaStatefulHolder.close();
} catch (Exception ex2) {
if (log.isDebugEnabled()) { log.debug("exception while trying to close invalid connection, ignoring it", ex2); }
}
finally {
if (xaStatefulHolder.getState() != XAStatefulHolder.STATE_CLOSED) {
stateChanged(xaStatefulHolder, xaStatefulHolder.getState(), XAStatefulHolder.STATE_CLOSED);
}
if (log.isDebugEnabled()) { log.debug("removed invalid connection " + xaStatefulHolder + " from " + this); }
if (log.isDebugEnabled()) log.debug("waiting " + bean.getAcquisitionInterval() + "s before trying to acquire a connection again from " + this);
long waitTime = bean.getAcquisitionInterval() * 1000L;
if (waitTime > 0) {
try {
wait(waitTime);
} catch (InterruptedException ex2) {
// ignore
}
}
}
// check for timeout
long now = MonotonicClock.currentTimeMillis();
remainingTimeMs -= (now - before);
before = now;
if (remainingTimeMs <= 0) {
throw new BitronixRuntimeException("cannot get valid connection from " + this + " after trying for " + bean.getAcquisitionTimeout() + "s", ex);
}
Thread.sleep(bean.getAcquisitionInterval() * 1000L);
}
} // while true
}" |
Inversion-Mutation | megadiff | "@Test
public void testBuildNavigation() {
Collection<PageConfiguration> confs = new ArrayList<PageConfiguration>();
PageConfiguration conf = new PageConfiguration();
conf.setPageClass(LoginPage.class);
confs.add(conf);
moduleServiceMock.rebuildModuleLinks();
expect(pageLocatorMock.getPageConfigurations()).andReturn(confs);
List<ModuleLink> links = new ArrayList<ModuleLink>();
ModuleLink link = new ModuleLink();
link.setPageName(LoginPage.class.getSimpleName());
links.add(link);
expect(moduleServiceMock.findAllVisibleMainNavigationLinks()).andReturn(links);
replay(pageLocatorMock, moduleServiceMock);
impl.buildNavigation();
verify(pageLocatorMock, moduleServiceMock);
assertEquals(LoginPage.class, impl.getRegisteredPages().get(0));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testBuildNavigation" | "@Test
public void testBuildNavigation() {
Collection<PageConfiguration> confs = new ArrayList<PageConfiguration>();
PageConfiguration conf = new PageConfiguration();
conf.setPageClass(LoginPage.class);
confs.add(conf);
expect(pageLocatorMock.getPageConfigurations()).andReturn(confs);
List<ModuleLink> links = new ArrayList<ModuleLink>();
ModuleLink link = new ModuleLink();
link.setPageName(LoginPage.class.getSimpleName());
links.add(link);
expect(moduleServiceMock.findAllVisibleMainNavigationLinks()).andReturn(links);
<MASK>moduleServiceMock.rebuildModuleLinks();</MASK>
replay(pageLocatorMock, moduleServiceMock);
impl.buildNavigation();
verify(pageLocatorMock, moduleServiceMock);
assertEquals(LoginPage.class, impl.getRegisteredPages().get(0));
}" |
Inversion-Mutation | megadiff | "public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
//$JUnit-BEGIN$
// NOTE: the order of these tests matters
// TODO: make tests clear workbench state on completion
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllJavaTests.suite());
suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(MiscTests.suite());
//$JUnit-END$
return suite;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "suite" | "public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
//$JUnit-BEGIN$
// NOTE: the order of these tests matters
// TODO: make tests clear workbench state on completion
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
<MASK>suite.addTest(AllCoreTests.suite());</MASK>
suite.addTest(AllJavaTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(MiscTests.suite());
//$JUnit-END$
return suite;
}" |
Inversion-Mutation | megadiff | "private void saveToRecorder(ProcessorURI curi,
Socket socket, Recorder recorder)
throws IOException, InterruptedException {
recorder.inputWrap(socket.getInputStream());
recorder.outputWrap(socket.getOutputStream());
recorder.markContentBegin();
// Read the remote file/dir listing in its entirety.
long softMax = 0;
long hardMax = getMaxLengthBytes();
long timeout = (long)getTimeoutSeconds() * 1000L;
int maxRate = getMaxFetchKBSec();
RecordingInputStream input = recorder.getRecordedInput();
input.setLimits(hardMax, timeout, maxRate);
input.readFullyOrUntil(softMax);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveToRecorder" | "private void saveToRecorder(ProcessorURI curi,
Socket socket, Recorder recorder)
throws IOException, InterruptedException {
<MASK>recorder.markContentBegin();</MASK>
recorder.inputWrap(socket.getInputStream());
recorder.outputWrap(socket.getOutputStream());
// Read the remote file/dir listing in its entirety.
long softMax = 0;
long hardMax = getMaxLengthBytes();
long timeout = (long)getTimeoutSeconds() * 1000L;
int maxRate = getMaxFetchKBSec();
RecordingInputStream input = recorder.getRecordedInput();
input.setLimits(hardMax, timeout, maxRate);
input.readFullyOrUntil(softMax);
}" |
Inversion-Mutation | megadiff | "public void destroy()
{
mCache.destroy();
// close all listeners
final Iterator it = mListeners.iterator();
while (it.hasNext()) {
final AuditListener listener = (AuditListener) it.next();
final OutputStream os = listener.getOutputStream();
// close only those that can be closed...
if ((os != System.out) && (os != System.err) && (os != null)) {
try {
os.flush();
os.close();
}
catch (IOException ignored) {
}
}
it.remove();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "destroy" | "public void destroy()
{
mCache.destroy();
// close all listeners
final Iterator it = mListeners.iterator();
while (it.hasNext()) {
final AuditListener listener = (AuditListener) it.next();
final OutputStream os = listener.getOutputStream();
// close only those that can be closed...
if ((os != System.out) && (os != System.err) && (os != null)) {
try {
os.flush();
os.close();
}
catch (IOException ignored) {
}
}
}
<MASK>it.remove();</MASK>
}" |
Inversion-Mutation | megadiff | "public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
EvaluationContextManager.startup();
Protocol.invokeLater(new Runnable() {
public void run() {
if (bp_status_listener == null) bp_status_listener = new TCFBreakpointStatusListener();
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start" | "public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
Protocol.invokeLater(new Runnable() {
public void run() {
if (bp_status_listener == null) bp_status_listener = new TCFBreakpointStatusListener();
}
});
<MASK>EvaluationContextManager.startup();</MASK>
}" |
Inversion-Mutation | megadiff | "public PAP deleteTrustedPAP(String papAlias) throws NotFoundException {
PAP pap = getPAP(papAlias);
distributionConfiguration.removePAP(papAlias);
papDAO.delete(papAlias);
papList.remove(pap);
return pap;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deleteTrustedPAP" | "public PAP deleteTrustedPAP(String papAlias) throws NotFoundException {
PAP pap = getPAP(papAlias);
<MASK>papList.remove(pap);</MASK>
distributionConfiguration.removePAP(papAlias);
papDAO.delete(papAlias);
return pap;
}" |
Inversion-Mutation | megadiff | "public synchronized void prune ( int numToKeep )
{
if (maxSize < 0)
return;
ArrayList<E> list = this.list;
int numToDelete = list.size() - numToKeep;
if (numToDelete <= 0)
return;
debug("prune() -> "+numToKeep);
sortIfWeShould();
List<E> deletionList = list.subList(0, numToDelete);
clearAndRecycle(deletionList);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "prune" | "public synchronized void prune ( int numToKeep )
{
if (maxSize < 0)
return;
<MASK>debug("prune() -> "+numToKeep);</MASK>
ArrayList<E> list = this.list;
int numToDelete = list.size() - numToKeep;
if (numToDelete <= 0)
return;
sortIfWeShould();
List<E> deletionList = list.subList(0, numToDelete);
clearAndRecycle(deletionList);
}" |
Inversion-Mutation | megadiff | "private void addNodeInformation(Netlist netList, HashMap<Network,SpiceNet> spiceNets, NodeInst ni)
{
// cells have no area or capacitance (for now)
if (ni.isCellInstance()) return; // No area for complex nodes
PrimitiveNode.Function function = ni.getFunction();
// initialize to examine the polygons on this node
Technology tech = ni.getProto().getTechnology();
AffineTransform trans = ni.rotateOut();
// make linked list of polygons
Poly [] polyList = tech.getShapeOfNode(ni, true, true, null);
int tot = polyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = polyList[i];
// make sure this layer connects electrically to the desired port
PortProto pp = poly.getPort();
if (pp == null) continue;
Network net = netList.getNetwork(ni, pp, 0);
// don't bother with layers without capacity
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
// if (layer.isPseudoLayer()) continue;
if (layer.getTechnology() != Technology.getCurrent()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() == 0.0) continue;
// leave out the gate capacitance of transistors
if (layer.getFunction() == Layer.Function.GATE) continue;
SpiceNet spNet = spiceNets.get(net);
if (spNet == null) continue;
// get the area of this polygon
poly.transform(trans);
spNet.merge.addPolygon(layer, poly);
// count the number of transistors on this net
if (layer.isDiffusionLayer() && function.isTransistor()) spNet.transistorCount++;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addNodeInformation" | "private void addNodeInformation(Netlist netList, HashMap<Network,SpiceNet> spiceNets, NodeInst ni)
{
// cells have no area or capacitance (for now)
if (ni.isCellInstance()) return; // No area for complex nodes
PrimitiveNode.Function function = ni.getFunction();
// initialize to examine the polygons on this node
Technology tech = ni.getProto().getTechnology();
AffineTransform trans = ni.rotateOut();
// make linked list of polygons
Poly [] polyList = tech.getShapeOfNode(ni, true, true, null);
int tot = polyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = polyList[i];
// make sure this layer connects electrically to the desired port
PortProto pp = poly.getPort();
if (pp == null) continue;
Network net = netList.getNetwork(ni, pp, 0);
// don't bother with layers without capacity
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
// if (layer.isPseudoLayer()) continue;
<MASK>if (!layer.isDiffusionLayer() && layer.getCapacitance() == 0.0) continue;</MASK>
if (layer.getTechnology() != Technology.getCurrent()) continue;
// leave out the gate capacitance of transistors
if (layer.getFunction() == Layer.Function.GATE) continue;
SpiceNet spNet = spiceNets.get(net);
if (spNet == null) continue;
// get the area of this polygon
poly.transform(trans);
spNet.merge.addPolygon(layer, poly);
// count the number of transistors on this net
if (layer.isDiffusionLayer() && function.isTransistor()) spNet.transistorCount++;
}
}" |
Inversion-Mutation | megadiff | "public void mouseMoved(MouseEvent me) {
// Don't rotate unless they're actively looking at the window.
if(!gui.getImageWin().isFocused())
return;
if(me.isAltDown()) {
if(mouseStartX < 0) {
try {
stageStart[0] = mmc.getXPosition(xyStageLabel);
stageStart[1] = mmc.getYPosition(xyStageLabel);
stageStart[2] = mmc.getPosition(zStageLabel);
stageStart[3] = mmc.getPosition(twisterLabel);
} catch(Exception e) {
ReportingUtils.logError(e);
}
mouseStartX = me.getX();
return;
}
int delta = me.getX() - mouseStartX;
// For now, at least, one pixel is going to be about
// .1 steps.
try {
// Note: If the system isn't calibrated, the method below
// returns what we pass it -- for XYZ, the current position
// of the motors. That is, for an uncalibrated system, the
// setXYPosition and first setPosition lines below are noops.
Vector3D xyz = applyCalibratedRotation(new Vector3D(
stageStart[0], stageStart[1], stageStart[2]),
delta * 0.1);
mmc.setXYPosition(xyStageLabel, xyz.getX(), xyz.getY());
mmc.setPosition(zStageLabel, xyz.getZ());
mmc.setPosition(twisterLabel, stageStart[3] + delta * 0.1);
} catch (Exception e) {
ReportingUtils.logException("Couldn't move stage: ", e);
}
} else if(mouseStartX >= 0) {
mouseStartX = -1;
};
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "mouseMoved" | "public void mouseMoved(MouseEvent me) {
// Don't rotate unless they're actively looking at the window.
if(!gui.getImageWin().isFocused())
return;
if(me.isAltDown()) {
if(mouseStartX < 0) {
<MASK>mouseStartX = me.getX();</MASK>
try {
stageStart[0] = mmc.getXPosition(xyStageLabel);
stageStart[1] = mmc.getYPosition(xyStageLabel);
stageStart[2] = mmc.getPosition(zStageLabel);
stageStart[3] = mmc.getPosition(twisterLabel);
} catch(Exception e) {
ReportingUtils.logError(e);
}
return;
}
int delta = me.getX() - mouseStartX;
// For now, at least, one pixel is going to be about
// .1 steps.
try {
// Note: If the system isn't calibrated, the method below
// returns what we pass it -- for XYZ, the current position
// of the motors. That is, for an uncalibrated system, the
// setXYPosition and first setPosition lines below are noops.
Vector3D xyz = applyCalibratedRotation(new Vector3D(
stageStart[0], stageStart[1], stageStart[2]),
delta * 0.1);
mmc.setXYPosition(xyStageLabel, xyz.getX(), xyz.getY());
mmc.setPosition(zStageLabel, xyz.getZ());
mmc.setPosition(twisterLabel, stageStart[3] + delta * 0.1);
} catch (Exception e) {
ReportingUtils.logException("Couldn't move stage: ", e);
}
} else if(mouseStartX >= 0) {
mouseStartX = -1;
};
}" |
Inversion-Mutation | megadiff | "@Override public void run() {
try {
Events events = Events.open(30000);
final Session session = new Session(getHeartBtIntValue(), getConfig(), getSessionStore(), getMessageFactory());
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress("localhost", port));
channel.configureBlocking(false);
try {
channel.socket().setTcpNoDelay(true);
} catch (SocketException e) {
throw new RuntimeException(e);
}
Connection conn = new Connection<Message>(channel, new FixMessageParser(),
new Connection.Callback<Message>() {
@Override public void messages(Connection<Message> conn, Iterator<Message> messages) {
while (messages.hasNext())
session.receive(conn, messages.next(), new DefaultMessageVisitor());
}
@Override public void idle(Connection<Message> conn) {
session.keepAlive(conn);
}
@Override public void closed(Connection<Message> conn) {
}
@Override public void garbledMessage(String message, byte[] data) {
}
});
int txCount = 0;
tx[txCount++] = System.nanoTime();
events.register(conn);
session.logon(conn);
while (txCount < NUM_MESSAGES) {
tx[txCount++] = System.nanoTime();
MessageHeader header = new MessageHeader(MsgTypeValue.NEW_ORDER_SINGLE);
NewOrderSingleMessage message = new NewOrderSingleMessage(header);
session.send(conn, message);
}
events.dispatch();
} catch (IOException e) {
throw new RuntimeException(e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override public void run() {
try {
Events events = Events.open(30000);
final Session session = new Session(getHeartBtIntValue(), getConfig(), getSessionStore(), getMessageFactory());
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress("localhost", port));
channel.configureBlocking(false);
try {
channel.socket().setTcpNoDelay(true);
} catch (SocketException e) {
throw new RuntimeException(e);
}
Connection conn = new Connection<Message>(channel, new FixMessageParser(),
new Connection.Callback<Message>() {
@Override public void messages(Connection<Message> conn, Iterator<Message> messages) {
while (messages.hasNext())
session.receive(conn, messages.next(), new DefaultMessageVisitor());
}
@Override public void idle(Connection<Message> conn) {
session.keepAlive(conn);
}
@Override public void closed(Connection<Message> conn) {
}
@Override public void garbledMessage(String message, byte[] data) {
}
});
int txCount = 0;
tx[txCount++] = System.nanoTime();
session.logon(conn);
while (txCount < NUM_MESSAGES) {
tx[txCount++] = System.nanoTime();
MessageHeader header = new MessageHeader(MsgTypeValue.NEW_ORDER_SINGLE);
NewOrderSingleMessage message = new NewOrderSingleMessage(header);
session.send(conn, message);
}
<MASK>events.register(conn);</MASK>
events.dispatch();
} catch (IOException e) {
throw new RuntimeException(e);
}
}" |
Inversion-Mutation | megadiff | "private final TitanType makeTitanType(TitanTypeClass typeClass, String name, TypeAttribute.Map definition) {
verifyOpen();
Preconditions.checkArgument(StringUtils.isNotBlank(name));
TitanTypeVertex type;
if (typeClass==TitanTypeClass.KEY) {
TypeAttribute.isValidKeyDefinition(definition);
type = new TitanKeyVertex(this, temporaryID.decrementAndGet(), ElementLifeCycle.New);
} else {
Preconditions.checkArgument(typeClass==TitanTypeClass.LABEL);
TypeAttribute.isValidLabelDefinition(definition);
type = new TitanLabelVertex(this, temporaryID.decrementAndGet(), ElementLifeCycle.New);
}
addProperty(type, SystemKey.TypeName, name);
addProperty(type, SystemKey.TypeClass, typeClass);
for (TypeAttribute attribute : definition.getAttributes()) {
addProperty(type,SystemKey.TypeDefinition,attribute);
}
graph.assignID(type);
Preconditions.checkArgument(type.getID()>0);
vertexCache.add(type,type.getID());
typeCache.put(name,type);
return type;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeTitanType" | "private final TitanType makeTitanType(TitanTypeClass typeClass, String name, TypeAttribute.Map definition) {
verifyOpen();
Preconditions.checkArgument(StringUtils.isNotBlank(name));
TitanTypeVertex type;
if (typeClass==TitanTypeClass.KEY) {
TypeAttribute.isValidKeyDefinition(definition);
type = new TitanKeyVertex(this, temporaryID.decrementAndGet(), ElementLifeCycle.New);
} else {
Preconditions.checkArgument(typeClass==TitanTypeClass.LABEL);
TypeAttribute.isValidLabelDefinition(definition);
type = new TitanLabelVertex(this, temporaryID.decrementAndGet(), ElementLifeCycle.New);
}
<MASK>addProperty(type, SystemKey.TypeClass, typeClass);</MASK>
addProperty(type, SystemKey.TypeName, name);
for (TypeAttribute attribute : definition.getAttributes()) {
addProperty(type,SystemKey.TypeDefinition,attribute);
}
graph.assignID(type);
Preconditions.checkArgument(type.getID()>0);
vertexCache.add(type,type.getID());
typeCache.put(name,type);
return type;
}" |
Inversion-Mutation | megadiff | "public void invokeServlet(SipRequest request) throws SipException
{
try
{
_invokingServlet = true;
_appSession.getContext().handle(request);
//getServer().handle(request);
}
catch (TooManyHopsException e)
{
throw new SipException(SipServletResponse.SC_TOO_MANY_HOPS, e);
}
catch (Throwable t)
{
throw new SipException(SipServletResponse.SC_SERVER_INTERNAL_ERROR, t);
}
finally
{
_invokingServlet = false;
checkReadyToInvalidate();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "invokeServlet" | "public void invokeServlet(SipRequest request) throws SipException
{
try
{
<MASK>_appSession.getContext().handle(request);</MASK>
_invokingServlet = true;
//getServer().handle(request);
}
catch (TooManyHopsException e)
{
throw new SipException(SipServletResponse.SC_TOO_MANY_HOPS, e);
}
catch (Throwable t)
{
throw new SipException(SipServletResponse.SC_SERVER_INTERNAL_ERROR, t);
}
finally
{
_invokingServlet = false;
checkReadyToInvalidate();
}
}" |
Inversion-Mutation | megadiff | "public void doWrite(Query query) throws Exception {
Writer writer = connect();
try {
for (Result r : query.getResults()) {
if (isDebugEnabled()) {
log.debug(r.toString());
}
Map<String, Object> resultValues = r.getValues();
if (resultValues != null) {
for (Entry<String, Object> values : resultValues.entrySet()) {
if (JmxUtils.isNumeric(values.getValue())) {
String keyStr = null;
if (values.getKey().startsWith(r.getAttributeName())) {
keyStr = values.getKey();
} else {
keyStr = r.getAttributeName() + "." + values.getKey();
}
String alias = null;
if (query.getServer().getAlias() != null) {
alias = query.getServer().getAlias();
} else {
alias = query.getServer().getHost() + "_" + query.getServer().getPort();
alias = cleanupStr(alias);
}
StringBuilder sb = new StringBuilder();
sb.append("servers.");
sb.append(alias);
sb.append(".");
sb.append(cleanupStr(r.getClassName()));
sb.append(".");
String typeName = cleanupStr(getConcatedTypeNameValues(r.getTypeName()));
if (typeName != null) {
sb.append(typeName);
sb.append(".");
}
sb.append(cleanupStr(keyStr));
sb.append(" ");
sb.append(values.getValue());
sb.append(" ");
sb.append(r.getEpoch() / 1000);
sb.append("\n");
String line = sb.toString();
if (isDebugEnabled()) {
log.debug("Graphite Message: " + line.trim());
}
writer.write(line);
}
}
}
}
writer.flush();
} finally {
IOUtils.closeQuietly(writer);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doWrite" | "public void doWrite(Query query) throws Exception {
Writer writer = connect();
try {
for (Result r : query.getResults()) {
if (isDebugEnabled()) {
log.debug(r.toString());
}
Map<String, Object> resultValues = r.getValues();
if (resultValues != null) {
for (Entry<String, Object> values : resultValues.entrySet()) {
if (JmxUtils.isNumeric(values.getValue())) {
String keyStr = null;
if (values.getKey().startsWith(r.getAttributeName())) {
keyStr = values.getKey();
} else {
keyStr = r.getAttributeName() + "." + values.getKey();
}
String alias = null;
if (query.getServer().getAlias() != null) {
alias = query.getServer().getAlias();
} else {
alias = query.getServer().getHost() + "_" + query.getServer().getPort();
}
<MASK>alias = cleanupStr(alias);</MASK>
StringBuilder sb = new StringBuilder();
sb.append("servers.");
sb.append(alias);
sb.append(".");
sb.append(cleanupStr(r.getClassName()));
sb.append(".");
String typeName = cleanupStr(getConcatedTypeNameValues(r.getTypeName()));
if (typeName != null) {
sb.append(typeName);
sb.append(".");
}
sb.append(cleanupStr(keyStr));
sb.append(" ");
sb.append(values.getValue());
sb.append(" ");
sb.append(r.getEpoch() / 1000);
sb.append("\n");
String line = sb.toString();
if (isDebugEnabled()) {
log.debug("Graphite Message: " + line.trim());
}
writer.write(line);
}
}
}
}
writer.flush();
} finally {
IOUtils.closeQuietly(writer);
}
}" |
Inversion-Mutation | megadiff | "public void addComponentAtStart(QName component) {
if(pos == components.length) {
QName[] t = new QName[pos + 1];
System.arraycopy(components, 0, t, 1, pos);
components = t;
components[0] = component;
} else {
System.arraycopy(components, 0, components, 1, pos);
components[0] = component;
}
pos++;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addComponentAtStart" | "public void addComponentAtStart(QName component) {
if(pos == components.length) {
QName[] t = new QName[pos + 1];
System.arraycopy(components, 0, t, 1, pos);
components = t;
components[0] = component;
} else {
System.arraycopy(components, 0, components, 1, pos);
components[0] = component;
<MASK>pos++;</MASK>
}
}" |
Inversion-Mutation | megadiff | "@Override
public void dispose() {
owner.getLoggerGUI().info("sto chiudendo l'interfaccia.");
owner.stopClient();
super.dispose();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispose" | "@Override
public void dispose() {
owner.getLoggerGUI().info("sto chiudendo l'interfaccia.");
<MASK>super.dispose();</MASK>
owner.stopClient();
}" |
Inversion-Mutation | megadiff | "public AnyViewParameters handle() {
try {
final String actionmethod = PostDecoder.decodeAction(normalizedmap);
// Do this FIRST in case it discovers any scopelocks required
presmanager.scopeRestore();
// invoke all state-altering operations within the runnable wrapper.
postwrapper.invokeRunnable(new Runnable() {
public void run() {
if (viewparams.flowtoken != null) {
presmanager.restore(viewparams.flowtoken,
viewparams.endflow != null);
}
Exception exception = null;
try {
rsvcapplier.applyValues(requestrsvc); // many errors possible here.
}
catch (Exception e) {
exception = e;
}
Object newcode = handleError(actionresult, exception);
exception = null;
if ((newcode == null && !messages.isError())
|| newcode instanceof String) {
// only proceed to actually invoke action if no ARIResult already
// note all this odd two-step procedure is only required to be able
// to pass AES error returns and make them "appear" to be the
// returns of the first action method in a Flow.
try {
if (actionmethod != null) {
actionresult = rsvcapplier.invokeAction(actionmethod,
(String) newcode);
}
}
catch (Exception e) {
exception = e;
}
newcode = handleError(actionresult, exception);
}
if (newcode != null)
actionresult = newcode;
// must interpret ARI INSIDE the wrapper, since it may need it
// on closure.
if (actionresult instanceof ARIResult) {
ariresult = (ARIResult) actionresult;
}
else {
ActionResultInterpreter ari = ariresolver
.getActionResultInterpreter();
ariresult = ari.interpretActionResult(viewparams, actionresult);
}
arinterceptor.interceptActionResult(ariresult, viewparams, actionresult);
}
});
presmanager.scopePreserve();
flowstatemanager.inferFlowState(viewparams, ariresult);
// moved inside since this may itself cause an error!
String submitting = PostDecoder.decodeSubmittingControl(normalizedmap);
errorstatemanager.globaltargetid = submitting;
}
catch (Throwable e) { // avoid masking errors from the finally block
Logger.log.error("Error invoking action", e);
// ThreadErrorState.addError(new TargettedMessage(
// CoreMessages.GENERAL_ACTION_ERROR));
// Detect failure to fill out arires properly.
if (ariresult == null || ariresult.resultingView == null
|| e instanceof IllegalStateException) {
ariresult = new ARIResult();
ariresult.propagateBeans = ARIResult.FLOW_END;
ViewParameters defaultparameters = viewparams.copyBase();
ariresult.resultingView = defaultparameters;
}
}
finally {
String errortoken = errorstatemanager.requestComplete();
if (ariresult.resultingView instanceof ViewParameters) {
((ViewParameters) ariresult.resultingView).errortoken = errortoken;
}
}
return ariresult.resultingView;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handle" | "public AnyViewParameters handle() {
<MASK>final String actionmethod = PostDecoder.decodeAction(normalizedmap);</MASK>
try {
// Do this FIRST in case it discovers any scopelocks required
presmanager.scopeRestore();
// invoke all state-altering operations within the runnable wrapper.
postwrapper.invokeRunnable(new Runnable() {
public void run() {
if (viewparams.flowtoken != null) {
presmanager.restore(viewparams.flowtoken,
viewparams.endflow != null);
}
Exception exception = null;
try {
rsvcapplier.applyValues(requestrsvc); // many errors possible here.
}
catch (Exception e) {
exception = e;
}
Object newcode = handleError(actionresult, exception);
exception = null;
if ((newcode == null && !messages.isError())
|| newcode instanceof String) {
// only proceed to actually invoke action if no ARIResult already
// note all this odd two-step procedure is only required to be able
// to pass AES error returns and make them "appear" to be the
// returns of the first action method in a Flow.
try {
if (actionmethod != null) {
actionresult = rsvcapplier.invokeAction(actionmethod,
(String) newcode);
}
}
catch (Exception e) {
exception = e;
}
newcode = handleError(actionresult, exception);
}
if (newcode != null)
actionresult = newcode;
// must interpret ARI INSIDE the wrapper, since it may need it
// on closure.
if (actionresult instanceof ARIResult) {
ariresult = (ARIResult) actionresult;
}
else {
ActionResultInterpreter ari = ariresolver
.getActionResultInterpreter();
ariresult = ari.interpretActionResult(viewparams, actionresult);
}
arinterceptor.interceptActionResult(ariresult, viewparams, actionresult);
}
});
presmanager.scopePreserve();
flowstatemanager.inferFlowState(viewparams, ariresult);
// moved inside since this may itself cause an error!
String submitting = PostDecoder.decodeSubmittingControl(normalizedmap);
errorstatemanager.globaltargetid = submitting;
}
catch (Throwable e) { // avoid masking errors from the finally block
Logger.log.error("Error invoking action", e);
// ThreadErrorState.addError(new TargettedMessage(
// CoreMessages.GENERAL_ACTION_ERROR));
// Detect failure to fill out arires properly.
if (ariresult == null || ariresult.resultingView == null
|| e instanceof IllegalStateException) {
ariresult = new ARIResult();
ariresult.propagateBeans = ARIResult.FLOW_END;
ViewParameters defaultparameters = viewparams.copyBase();
ariresult.resultingView = defaultparameters;
}
}
finally {
String errortoken = errorstatemanager.requestComplete();
if (ariresult.resultingView instanceof ViewParameters) {
((ViewParameters) ariresult.resultingView).errortoken = errortoken;
}
}
return ariresult.resultingView;
}" |
Inversion-Mutation | megadiff | "private int createAndRunCluster(String clustername) throws Throwable {
//load the cluster description from the cd argument
String hoyaClusterDir = serviceArgs.hoyaClusterURI;
URI hoyaClusterURI = new URI(hoyaClusterDir);
Path clusterDirPath = new Path(hoyaClusterURI);
Path clusterSpecPath =
new Path(clusterDirPath, HoyaKeys.CLUSTER_SPECIFICATION_FILE);
FileSystem fs = getClusterFS();
ClusterDescription.verifyClusterSpecExists(clustername,
fs,
clusterSpecPath);
ClusterDescription clusterSpec = ClusterDescription.load(fs, clusterSpecPath);
File confDir = getLocalConfDir();
if (!confDir.exists() || !confDir.isDirectory()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't exist", confDir);
}
YarnConfiguration conf = new YarnConfiguration(getConfig());
//get our provider
String providerType = clusterSpec.type;
log.info("Cluster provider type is {}", providerType);
HoyaProviderFactory factory =
HoyaProviderFactory.createHoyaProviderFactory(
providerType);
providerService = factory.createServerProvider();
runChildService(providerService);
//verify that the cluster specification is now valid
providerService.validateClusterSpec(clusterSpec);
HoyaAMClientProvider clientProvider = new HoyaAMClientProvider(conf);
InetSocketAddress address = HoyaUtils.getRmSchedulerAddress(conf);
log.info("RM is at {}", address);
yarmRPC = YarnRPC.create(conf);
appMasterContainerID = ConverterUtils.toContainerId(
HoyaUtils.mandatoryEnvVariable(
ApplicationConstants.Environment.CONTAINER_ID.name()));
appAttemptID = appMasterContainerID.getApplicationAttemptId();
ApplicationId appid = appAttemptID.getApplicationId();
log.info("Hoya AM for ID {}", appid.getId());
Credentials credentials =
UserGroupInformation.getCurrentUser().getCredentials();
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
dob.close();
// Now remove the AM->RM token so that containers cannot access it.
Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
while (iter.hasNext()) {
Token<?> token = iter.next();
log.info("Token {}", token.getKind());
if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
iter.remove();
}
}
allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
// set up secret manager
secretManager = new ClientToAMTokenSecretManager(appAttemptID, null);
int heartbeatInterval = HEARTBEAT_INTERVAL;
//add the RM client -this brings the callbacks in
asyncRMClient = AMRMClientAsync.createAMRMClientAsync(HEARTBEAT_INTERVAL,
this);
addService(asyncRMClient);
//wrap it for the app state model
rmOperationHandler = new AsyncRMOperationHandler(asyncRMClient);
//now bring it up
runChildService(asyncRMClient);
//nmclient relays callbacks back to this class
nmClientAsync = new NMClientAsyncImpl("hoya", this);
runChildService(nmClientAsync);
//bring up the Hoya RPC service
startHoyaRPCServer();
InetSocketAddress rpcServiceAddr = rpcService.getConnectAddress();
appMasterHostname = rpcServiceAddr.getHostName();
appMasterRpcPort = rpcServiceAddr.getPort();
appMasterTrackingUrl = null;
log.info("HoyaAM Server is listening at {}:{}", appMasterHostname,
appMasterRpcPort);
//build the role map
List<ProviderRole> providerRoles =
new ArrayList<ProviderRole>(providerService.getRoles());
providerRoles.addAll(clientProvider.getRoles());
// work out a port for the AM
int infoport = clusterSpec.getRoleOptInt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
0);
if (0 == infoport) {
infoport =
HoyaUtils.findFreePort(providerService.getDefaultMasterInfoPort(), 128);
//need to get this to the app
clusterSpec.setRoleOpt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
infoport);
}
appMasterTrackingUrl =
"http://" + appMasterHostname + ":" + infoport;
// Register self with ResourceManager
// This will start heartbeating to the RM
address = HoyaUtils.getRmSchedulerAddress(asyncRMClient.getConfig());
log.info("Connecting to RM at {},address tracking URL={}",
appMasterRpcPort, appMasterTrackingUrl);
RegisterApplicationMasterResponse response = asyncRMClient
.registerApplicationMaster(appMasterHostname,
appMasterRpcPort,
appMasterTrackingUrl);
Resource maxResources =
response.getMaximumResourceCapability();
containerMaxMemory = maxResources.getMemory();
containerMaxCores = maxResources.getVirtualCores();
appState.setContainerLimits(maxResources.getMemory(),
maxResources.getVirtualCores());
boolean securityEnabled = UserGroupInformation.isSecurityEnabled();
if (securityEnabled) {
secretManager.setMasterKey(
response.getClientToAMTokenMasterKey().array());
applicationACLs = response.getApplicationACLs();
//tell the server what the ACLs are
rpcService.getServer().refreshServiceAcl(conf, new HoyaAMPolicyProvider());
}
//now validate the dir by loading in a hadoop-site.xml file from it
String siteXMLFilename = providerService.getSiteXMLFilename();
File siteXML = new File(confDir, siteXMLFilename);
if (!siteXML.exists()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't contain %s - listing is %s",
confDir, siteXMLFilename, HoyaUtils.listDir(confDir));
}
//now read it in
Configuration siteConf = ConfigHelper.loadConfFromFile(siteXML);
providerService.validateApplicationConfiguration(clusterSpec, confDir, securityEnabled);
//determine the location for the role history data
Path historyDir = new Path(clusterDirPath, HISTORY_DIR_NAME);
//build the instance
appState.buildInstance(clusterSpec, siteConf, providerRoles, fs, historyDir);
//before bothering to start the containers, bring up the master.
//This ensures that if the master doesn't come up, less
//cluster resources get wasted
appState.buildAppMasterNode(appMasterContainerID);
//launcher service
launchService = new RoleLaunchService(this,
providerService, getClusterFS(),
new Path(getDFSConfDir()));
runChildService(launchService);
boolean noLocalProcess = clusterSpec.getDesiredInstanceCount(ROLE_HOYA_AM, 1) <= 0;
if (noLocalProcess) {
log.info("skipping AM process launch");
eventCallbackEvent();
} else {
appState.noteAMLaunched();
//launch the provider; this is expected to trigger a callback that
//brings up the service
launchProviderService(clusterSpec, confDir);
}
try {
//now block waiting to be told to exit the process
waitForAMCompletionSignal();
//shutdown time
} finally {
finish();
}
return buildExitCode();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createAndRunCluster" | "private int createAndRunCluster(String clustername) throws Throwable {
//load the cluster description from the cd argument
String hoyaClusterDir = serviceArgs.hoyaClusterURI;
URI hoyaClusterURI = new URI(hoyaClusterDir);
Path clusterDirPath = new Path(hoyaClusterURI);
Path clusterSpecPath =
new Path(clusterDirPath, HoyaKeys.CLUSTER_SPECIFICATION_FILE);
FileSystem fs = getClusterFS();
ClusterDescription.verifyClusterSpecExists(clustername,
fs,
clusterSpecPath);
ClusterDescription clusterSpec = ClusterDescription.load(fs, clusterSpecPath);
File confDir = getLocalConfDir();
if (!confDir.exists() || !confDir.isDirectory()) {
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't exist", confDir);
}
YarnConfiguration conf = new YarnConfiguration(getConfig());
//get our provider
String providerType = clusterSpec.type;
log.info("Cluster provider type is {}", providerType);
HoyaProviderFactory factory =
HoyaProviderFactory.createHoyaProviderFactory(
providerType);
providerService = factory.createServerProvider();
runChildService(providerService);
//verify that the cluster specification is now valid
providerService.validateClusterSpec(clusterSpec);
HoyaAMClientProvider clientProvider = new HoyaAMClientProvider(conf);
InetSocketAddress address = HoyaUtils.getRmSchedulerAddress(conf);
log.info("RM is at {}", address);
yarmRPC = YarnRPC.create(conf);
appMasterContainerID = ConverterUtils.toContainerId(
HoyaUtils.mandatoryEnvVariable(
ApplicationConstants.Environment.CONTAINER_ID.name()));
appAttemptID = appMasterContainerID.getApplicationAttemptId();
ApplicationId appid = appAttemptID.getApplicationId();
log.info("Hoya AM for ID {}", appid.getId());
Credentials credentials =
UserGroupInformation.getCurrentUser().getCredentials();
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
// Now remove the AM->RM token so that containers cannot access it.
Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
while (iter.hasNext()) {
Token<?> token = iter.next();
log.info("Token {}", token.getKind());
if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) {
iter.remove();
}
}
allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
// set up secret manager
secretManager = new ClientToAMTokenSecretManager(appAttemptID, null);
int heartbeatInterval = HEARTBEAT_INTERVAL;
//add the RM client -this brings the callbacks in
asyncRMClient = AMRMClientAsync.createAMRMClientAsync(HEARTBEAT_INTERVAL,
this);
addService(asyncRMClient);
//wrap it for the app state model
rmOperationHandler = new AsyncRMOperationHandler(asyncRMClient);
//now bring it up
runChildService(asyncRMClient);
//nmclient relays callbacks back to this class
nmClientAsync = new NMClientAsyncImpl("hoya", this);
runChildService(nmClientAsync);
//bring up the Hoya RPC service
startHoyaRPCServer();
InetSocketAddress rpcServiceAddr = rpcService.getConnectAddress();
appMasterHostname = rpcServiceAddr.getHostName();
appMasterRpcPort = rpcServiceAddr.getPort();
appMasterTrackingUrl = null;
log.info("HoyaAM Server is listening at {}:{}", appMasterHostname,
appMasterRpcPort);
//build the role map
List<ProviderRole> providerRoles =
new ArrayList<ProviderRole>(providerService.getRoles());
providerRoles.addAll(clientProvider.getRoles());
// work out a port for the AM
int infoport = clusterSpec.getRoleOptInt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
0);
if (0 == infoport) {
infoport =
HoyaUtils.findFreePort(providerService.getDefaultMasterInfoPort(), 128);
//need to get this to the app
clusterSpec.setRoleOpt(ROLE_HOYA_AM,
RoleKeys.APP_INFOPORT,
infoport);
}
appMasterTrackingUrl =
"http://" + appMasterHostname + ":" + infoport;
// Register self with ResourceManager
// This will start heartbeating to the RM
address = HoyaUtils.getRmSchedulerAddress(asyncRMClient.getConfig());
log.info("Connecting to RM at {},address tracking URL={}",
appMasterRpcPort, appMasterTrackingUrl);
RegisterApplicationMasterResponse response = asyncRMClient
.registerApplicationMaster(appMasterHostname,
appMasterRpcPort,
appMasterTrackingUrl);
Resource maxResources =
response.getMaximumResourceCapability();
containerMaxMemory = maxResources.getMemory();
containerMaxCores = maxResources.getVirtualCores();
appState.setContainerLimits(maxResources.getMemory(),
maxResources.getVirtualCores());
boolean securityEnabled = UserGroupInformation.isSecurityEnabled();
if (securityEnabled) {
secretManager.setMasterKey(
response.getClientToAMTokenMasterKey().array());
applicationACLs = response.getApplicationACLs();
//tell the server what the ACLs are
rpcService.getServer().refreshServiceAcl(conf, new HoyaAMPolicyProvider());
}
//now validate the dir by loading in a hadoop-site.xml file from it
String siteXMLFilename = providerService.getSiteXMLFilename();
File siteXML = new File(confDir, siteXMLFilename);
if (!siteXML.exists()) {
<MASK>dob.close();</MASK>
throw new BadCommandArgumentsException(
"Configuration directory %s doesn't contain %s - listing is %s",
confDir, siteXMLFilename, HoyaUtils.listDir(confDir));
}
//now read it in
Configuration siteConf = ConfigHelper.loadConfFromFile(siteXML);
providerService.validateApplicationConfiguration(clusterSpec, confDir, securityEnabled);
//determine the location for the role history data
Path historyDir = new Path(clusterDirPath, HISTORY_DIR_NAME);
//build the instance
appState.buildInstance(clusterSpec, siteConf, providerRoles, fs, historyDir);
//before bothering to start the containers, bring up the master.
//This ensures that if the master doesn't come up, less
//cluster resources get wasted
appState.buildAppMasterNode(appMasterContainerID);
//launcher service
launchService = new RoleLaunchService(this,
providerService, getClusterFS(),
new Path(getDFSConfDir()));
runChildService(launchService);
boolean noLocalProcess = clusterSpec.getDesiredInstanceCount(ROLE_HOYA_AM, 1) <= 0;
if (noLocalProcess) {
log.info("skipping AM process launch");
eventCallbackEvent();
} else {
appState.noteAMLaunched();
//launch the provider; this is expected to trigger a callback that
//brings up the service
launchProviderService(clusterSpec, confDir);
}
try {
//now block waiting to be told to exit the process
waitForAMCompletionSignal();
//shutdown time
} finally {
finish();
}
return buildExitCode();
}" |
Inversion-Mutation | megadiff | "private void editCellAction(boolean newWindow)
{
Cell cell = null;
int pageNo = 1;
if (getCurrentlySelectedObject(0) instanceof Cell)
{
cell = (Cell)getCurrentlySelectedObject(0);
} else if (getCurrentlySelectedObject(0) instanceof ExplorerTreeModel.MultiPageCell)
{
ExplorerTreeModel.MultiPageCell mpc = (ExplorerTreeModel.MultiPageCell)getCurrentlySelectedObject(0);
cell = mpc.getCell();
pageNo = mpc.getPageNo();
}
WindowFrame wf = null;
if (newWindow)
{
wf = WindowFrame.createEditWindow(cell);
} else
{
wf = WindowFrame.getCurrentWindowFrame();
}
wf.setCellWindow(cell, null);
if (cell.isMultiPage() && wf.getContent() instanceof EditWindow)
{
EditWindow wnd = (EditWindow)wf.getContent();
wnd.setMultiPageNumber(pageNo);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "editCellAction" | "private void editCellAction(boolean newWindow)
{
Cell cell = null;
int pageNo = 1;
if (getCurrentlySelectedObject(0) instanceof Cell)
{
cell = (Cell)getCurrentlySelectedObject(0);
} else if (getCurrentlySelectedObject(0) instanceof ExplorerTreeModel.MultiPageCell)
{
ExplorerTreeModel.MultiPageCell mpc = (ExplorerTreeModel.MultiPageCell)getCurrentlySelectedObject(0);
cell = mpc.getCell();
pageNo = mpc.getPageNo();
}
WindowFrame wf = null;
if (newWindow)
{
wf = WindowFrame.createEditWindow(cell);
} else
{
wf = WindowFrame.getCurrentWindowFrame();
<MASK>wf.setCellWindow(cell, null);</MASK>
}
if (cell.isMultiPage() && wf.getContent() instanceof EditWindow)
{
EditWindow wnd = (EditWindow)wf.getContent();
wnd.setMultiPageNumber(pageNo);
}
}" |
Inversion-Mutation | megadiff | "@Override
public void stop() {
long stopTime = System.nanoTime();
long current = 0;
while (!stopNanos.compareAndSet(current, stopTime)) {
current = stopNanos.get();
stopTime = Math.max(stopTime, current);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stop" | "@Override
public void stop() {
<MASK>long current = 0;</MASK>
long stopTime = System.nanoTime();
while (!stopNanos.compareAndSet(current, stopTime)) {
current = stopNanos.get();
stopTime = Math.max(stopTime, current);
}
}" |
Inversion-Mutation | megadiff | "@Test
public void rootTest5() {
l.setValues(Levels.INFO);
r.setLevel(l);
r.addAppenderRef("A1");
r.generateProperties(p);
testExpected("INFO, A1");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "rootTest5" | "@Test
public void rootTest5() {
l.setValues(Levels.INFO);
r.setLevel(l);
<MASK>r.generateProperties(p);</MASK>
r.addAppenderRef("A1");
testExpected("INFO, A1");
}" |
Inversion-Mutation | megadiff | "@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
ft.replace(R.id.main_root, mFragments[tab.getPosition()]);
ft.commit();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onTabSelected" | "@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft = getSupportFragmentManager().beginTransaction();
<MASK>ft.replace(R.id.main_root, mFragments[tab.getPosition()]);</MASK>
ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
ft.commit();
}" |
Inversion-Mutation | megadiff | "synchronized static void stop() {
if (server != null) {
server.stop();
}
initialized = false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stop" | "synchronized static void stop() {
if (server != null) {
server.stop();
<MASK>initialized = false;</MASK>
}
}" |
Inversion-Mutation | megadiff | "@SuppressWarnings("fallthrough")
public TaskState doBuild() throws GameActionException {
// Build Chassis
if (builder.isActive()) return TaskState.ACTIVE;
switch(p) {
case -2:
// I shouldn't be able to build after a fail without initializing.
return TaskState.FAIL;
case -1:
if (chassis == null) {
p = -2;
return TaskState.FAIL;
}
if (myRC.getTeamResources() < res_mult*this.cost)
return TaskState.WAITING;
try {
if (builder.canBuild(chassis, location)) {
builder.build(chassis, location);
p++;
return TaskState.ACTIVE;
} else {
p = -2;
return TaskState.FAIL;
}
} catch (Exception e) {
System.out.println("caught exception:");
e.printStackTrace();
p = -2;
return TaskState.FAIL;
}
case 0:
if (components.length == 0) break;
default:
// I don't check if I can still build because the exception doesn't really cost that much and checking this is a PAIN.
if (myRC.getTeamResources() < res_mult*components[p].cost)
return TaskState.ACTIVE;
else {
try {
builder.build(components[p], location, level);
p++;
} catch (Exception e) {
// Thrown often, not worth checking.
//System.out.println("caught exception:");
//e.printStackTrace();
p = -2;
return TaskState.FAIL;
}
}
}
// Complete build or return in progress.
if (p == components.length) {
try {
if (turn_on)
myRC.turnOn(location, level);
p = -2;
} catch (Exception e) {
System.out.println("caught exception:");
e.printStackTrace();
p = -2;
return TaskState.FAIL;
}
return TaskState.DONE;
} else {
return TaskState.ACTIVE;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doBuild" | "@SuppressWarnings("fallthrough")
public TaskState doBuild() throws GameActionException {
// Build Chassis
if (builder.isActive()) return TaskState.ACTIVE;
switch(p) {
case -2:
// I shouldn't be able to build after a fail without initializing.
<MASK>return TaskState.FAIL;</MASK>
case -1:
if (chassis == null) {
p = -2;
<MASK>return TaskState.FAIL;</MASK>
}
if (myRC.getTeamResources() < res_mult*this.cost)
return TaskState.WAITING;
try {
if (builder.canBuild(chassis, location)) {
builder.build(chassis, location);
p++;
return TaskState.ACTIVE;
} else {
p = -2;
<MASK>return TaskState.FAIL;</MASK>
}
} catch (Exception e) {
System.out.println("caught exception:");
e.printStackTrace();
p = -2;
<MASK>return TaskState.FAIL;</MASK>
}
case 0:
if (components.length == 0) break;
default:
// I don't check if I can still build because the exception doesn't really cost that much and checking this is a PAIN.
if (myRC.getTeamResources() < res_mult*components[p].cost)
return TaskState.ACTIVE;
else {
try {
builder.build(components[p], location, level);
p++;
} catch (Exception e) {
// Thrown often, not worth checking.
//System.out.println("caught exception:");
//e.printStackTrace();
p = -2;
<MASK>return TaskState.FAIL;</MASK>
}
}
}
// Complete build or return in progress.
if (p == components.length) {
try {
if (turn_on)
myRC.turnOn(location, level);
p = -2;
} catch (Exception e) {
System.out.println("caught exception:");
e.printStackTrace();
<MASK>return TaskState.FAIL;</MASK>
p = -2;
}
return TaskState.DONE;
} else {
return TaskState.ACTIVE;
}
}" |
Inversion-Mutation | megadiff | "public WorkflowApp(AbstractWorkflowDataModel wfdm, String dir, boolean useSge, File seqwareJar,
String slotsSgeParamFormat, String maxMemorySgeParamFormat) {
this.wfdm = wfdm;
this.unqiueWorkingDir = dir;
this.jobs = new ArrayList<OozieJob>();
this.fileJobMap = new HashMap<SqwFile, OozieJob>();
this.useSge = useSge;
this.seqwareJar = seqwareJar;
this.slotsSgeParamFormat = slotsSgeParamFormat;
this.maxMemorySgeParamFormat = maxMemorySgeParamFormat;
this.parseDataModel(wfdm);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "WorkflowApp" | "public WorkflowApp(AbstractWorkflowDataModel wfdm, String dir, boolean useSge, File seqwareJar,
String slotsSgeParamFormat, String maxMemorySgeParamFormat) {
this.wfdm = wfdm;
this.unqiueWorkingDir = dir;
this.jobs = new ArrayList<OozieJob>();
this.fileJobMap = new HashMap<SqwFile, OozieJob>();
this.useSge = useSge;
this.seqwareJar = seqwareJar;
<MASK>this.parseDataModel(wfdm);</MASK>
this.slotsSgeParamFormat = slotsSgeParamFormat;
this.maxMemorySgeParamFormat = maxMemorySgeParamFormat;
}" |
Inversion-Mutation | megadiff | "protected final Watchers getWatches(NotifyType type) throws OrmException {
Watchers matching = new Watchers();
Set<Account.Id> projectWatchers = new HashSet<Account.Id>();
for (AccountProjectWatch w : args.db.get().accountProjectWatches()
.byProject(change.getProject())) {
if (w.isNotify(type)) {
projectWatchers.add(w.getAccountId());
add(matching, w);
}
}
for (AccountProjectWatch w : args.db.get().accountProjectWatches()
.byProject(args.allProjectsName)) {
if (!projectWatchers.contains(w.getAccountId()) && w.isNotify(type)) {
add(matching, w);
}
}
ProjectState state = projectState;
while (state != null) {
for (NotifyConfig nc : state.getConfig().getNotifyConfigs()) {
if (nc.isNotify(type)) {
try {
add(matching, nc, state.getProject().getNameKey());
} catch (QueryParseException e) {
log.warn(String.format(
"Project %s has invalid notify %s filter \"%s\": %s",
state.getProject().getName(), nc.getName(),
nc.getFilter(), e.getMessage()));
}
}
}
state = state.getParentState();
}
return matching;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getWatches" | "protected final Watchers getWatches(NotifyType type) throws OrmException {
Watchers matching = new Watchers();
Set<Account.Id> projectWatchers = new HashSet<Account.Id>();
for (AccountProjectWatch w : args.db.get().accountProjectWatches()
.byProject(change.getProject())) {
<MASK>projectWatchers.add(w.getAccountId());</MASK>
if (w.isNotify(type)) {
add(matching, w);
}
}
for (AccountProjectWatch w : args.db.get().accountProjectWatches()
.byProject(args.allProjectsName)) {
if (!projectWatchers.contains(w.getAccountId()) && w.isNotify(type)) {
add(matching, w);
}
}
ProjectState state = projectState;
while (state != null) {
for (NotifyConfig nc : state.getConfig().getNotifyConfigs()) {
if (nc.isNotify(type)) {
try {
add(matching, nc, state.getProject().getNameKey());
} catch (QueryParseException e) {
log.warn(String.format(
"Project %s has invalid notify %s filter \"%s\": %s",
state.getProject().getName(), nc.getName(),
nc.getFilter(), e.getMessage()));
}
}
}
state = state.getParentState();
}
return matching;
}" |
Inversion-Mutation | megadiff | "public void testTimeout() throws Exception {
DataSourceBean bean1 = new DataSourceBean();
bean1.setClassName(MockXADataSource.class.getName());
bean1.setUniqueName("pds1");
bean1.setPoolSize(5);
bean1.setAutomaticEnlistingEnabled(true);
DataSourceBean bean2 = new DataSourceBean();
bean2.setClassName(MockXADataSource.class.getName());
bean2.setUniqueName("pds2");
bean2.setPoolSize(5);
bean2.setAutomaticEnlistingEnabled(true);
PoolingDataSource poolingDataSource1 = (PoolingDataSource) bean1.createResource();
PoolingDataSource poolingDataSource2 = (PoolingDataSource) bean2.createResource();
BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
tm.setTransactionTimeout(1); // TX must timeout
tm.begin();
Connection connection1 = poolingDataSource1.getConnection();
MockXAConnection mockXAConnection1 = (MockXAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(((JdbcConnectionHandle) connection1).getPooledConnection());
connection1.createStatement();
Connection connection2 = poolingDataSource2.getConnection();
MockXAConnection mockXAConnection2 = (MockXAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(((JdbcConnectionHandle) connection2).getPooledConnection());
connection2.createStatement();
final MockXAResource mockXAResource1 = (MockXAResource) mockXAConnection1.getXAResource();
mockXAResource1.setRollbackException(createXAException("resource 1 rollback failed", XAException.XAER_INVAL));
MockXAResource mockXAResource2 = (MockXAResource) mockXAConnection2.getXAResource();
mockXAResource2.setPrepareException(createXAException("resource 2 prepare failed", XAException.XAER_RMERR));
try {
tm.commit();
fail("TM should have thrown an exception");
} catch (RollbackException ex) {
assertEquals("transaction failed during prepare, error=XAER_RMERR", ex.getMessage());
ex.printStackTrace(System.out);
assertEquals("resource 2 prepare failed", ex.getCause().getMessage());
} finally {
System.out.println(EventRecorder.dumpToString());
}
// we should find a ROLLINGBACK but not ROLLEDBACK status in the journal log
// and 4 rollback tries (1 successful for resource 2, 2 failed for resource 1 and 1 successful for resource 1)
int journalRollbackEventCount = 0;
int rollbackEventCount = 0;
List events = EventRecorder.getOrderedEvents();
for (int i = 0; i < events.size(); i++) {
Event event = (Event) events.get(i);
if (event instanceof XAResourceRollbackEvent)
rollbackEventCount++;
if (event instanceof JournalLogEvent) {
if (((JournalLogEvent) event).getStatus() == Status.STATUS_ROLLEDBACK)
journalRollbackEventCount++;
}
}
assertEquals("TM should not have logged a ROLLEDBACK status", 0, journalRollbackEventCount);
assertTrue("TM haven't properly tried to rollback", rollbackEventCount > 1);
poolingDataSource1.close();
poolingDataSource2.close();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testTimeout" | "public void testTimeout() throws Exception {
DataSourceBean bean1 = new DataSourceBean();
bean1.setClassName(MockXADataSource.class.getName());
bean1.setUniqueName("pds1");
bean1.setPoolSize(5);
bean1.setAutomaticEnlistingEnabled(true);
DataSourceBean bean2 = new DataSourceBean();
bean2.setClassName(MockXADataSource.class.getName());
bean2.setUniqueName("pds2");
bean2.setPoolSize(5);
bean2.setAutomaticEnlistingEnabled(true);
PoolingDataSource poolingDataSource1 = (PoolingDataSource) bean1.createResource();
PoolingDataSource poolingDataSource2 = (PoolingDataSource) bean2.createResource();
BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
<MASK>tm.begin();</MASK>
tm.setTransactionTimeout(1); // TX must timeout
Connection connection1 = poolingDataSource1.getConnection();
MockXAConnection mockXAConnection1 = (MockXAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(((JdbcConnectionHandle) connection1).getPooledConnection());
connection1.createStatement();
Connection connection2 = poolingDataSource2.getConnection();
MockXAConnection mockXAConnection2 = (MockXAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(((JdbcConnectionHandle) connection2).getPooledConnection());
connection2.createStatement();
final MockXAResource mockXAResource1 = (MockXAResource) mockXAConnection1.getXAResource();
mockXAResource1.setRollbackException(createXAException("resource 1 rollback failed", XAException.XAER_INVAL));
MockXAResource mockXAResource2 = (MockXAResource) mockXAConnection2.getXAResource();
mockXAResource2.setPrepareException(createXAException("resource 2 prepare failed", XAException.XAER_RMERR));
try {
tm.commit();
fail("TM should have thrown an exception");
} catch (RollbackException ex) {
assertEquals("transaction failed during prepare, error=XAER_RMERR", ex.getMessage());
ex.printStackTrace(System.out);
assertEquals("resource 2 prepare failed", ex.getCause().getMessage());
} finally {
System.out.println(EventRecorder.dumpToString());
}
// we should find a ROLLINGBACK but not ROLLEDBACK status in the journal log
// and 4 rollback tries (1 successful for resource 2, 2 failed for resource 1 and 1 successful for resource 1)
int journalRollbackEventCount = 0;
int rollbackEventCount = 0;
List events = EventRecorder.getOrderedEvents();
for (int i = 0; i < events.size(); i++) {
Event event = (Event) events.get(i);
if (event instanceof XAResourceRollbackEvent)
rollbackEventCount++;
if (event instanceof JournalLogEvent) {
if (((JournalLogEvent) event).getStatus() == Status.STATUS_ROLLEDBACK)
journalRollbackEventCount++;
}
}
assertEquals("TM should not have logged a ROLLEDBACK status", 0, journalRollbackEventCount);
assertTrue("TM haven't properly tried to rollback", rollbackEventCount > 1);
poolingDataSource1.close();
poolingDataSource2.close();
}" |
Inversion-Mutation | megadiff | "public void free() {
parentPool.reclaim(this);
isFreed = true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "free" | "public void free() {
<MASK>isFreed = true;</MASK>
parentPool.reclaim(this);
}" |
Inversion-Mutation | megadiff | "private void genJavaAction(SourceGenerator sourceGenerator, Class<?> clazz, String actionContext, FileWriter fileWriter, File javaMainSrcPath) {
String doPackage = clazz.getPackage().getName();
String baseBizPackage = StringUtil.getLastBefore(doPackage, ".biz.");
String baseActionPackage = baseBizPackage + ".web.action";
String targetActionPackage;
String actionContextPackage;
actionContext = normalizeContext(actionContext);
if (!StringUtil.isEmpty(actionContext)) {
actionContextPackage = actionContext.replace('/', '.');
targetActionPackage = baseActionPackage + "." + actionContextPackage;
} else {
targetActionPackage = baseActionPackage;
actionContextPackage = "";
}
String actionClassName = StringUtil.uppercaseFirstLetter(DaoGenUtil.getDoAlias(clazz));
String fullActionName = targetActionPackage + "." + actionClassName;
StringWriter stringWriter = new StringWriter();
sourceGenerator.genJavaAction(fullActionName, clazz, stringWriter, actionContextPackage);
String content = stringWriter.toString();
this.genJavaSrc(fullActionName, content, javaMainSrcPath, fileWriter);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "genJavaAction" | "private void genJavaAction(SourceGenerator sourceGenerator, Class<?> clazz, String actionContext, FileWriter fileWriter, File javaMainSrcPath) {
String doPackage = clazz.getPackage().getName();
String baseBizPackage = StringUtil.getLastBefore(doPackage, ".biz.");
String baseActionPackage = baseBizPackage + ".web.action";
String targetActionPackage;
String actionContextPackage;
if (!StringUtil.isEmpty(actionContext)) {
<MASK>actionContext = normalizeContext(actionContext);</MASK>
actionContextPackage = actionContext.replace('/', '.');
targetActionPackage = baseActionPackage + "." + actionContextPackage;
} else {
targetActionPackage = baseActionPackage;
actionContextPackage = "";
}
String actionClassName = StringUtil.uppercaseFirstLetter(DaoGenUtil.getDoAlias(clazz));
String fullActionName = targetActionPackage + "." + actionClassName;
StringWriter stringWriter = new StringWriter();
sourceGenerator.genJavaAction(fullActionName, clazz, stringWriter, actionContextPackage);
String content = stringWriter.toString();
this.genJavaSrc(fullActionName, content, javaMainSrcPath, fileWriter);
}" |
Inversion-Mutation | megadiff | "@Override
protected void pointDone(Point point, MapContext vc, ToolManager tm)
throws TransitionException {
try {
final ILayer layer = vc.getSelectedLayers()[0];
final GeoRaster geoRaster = layer.getRaster();
final Coordinate realWorldCoordinate = point.getCoordinate();
final Point2D gridContextCoordinate = geoRaster
.fromRealWorldToPixel(realWorldCoordinate.x,
realWorldCoordinate.y);
final int pixelX = (int) gridContextCoordinate.getX();
final int pixelY = (int) gridContextCoordinate.getY();
final float halfPixelSize_X = geoRaster.getMetadata()
.getPixelSize_X() / 2;
final float halfPixelSize_Y = geoRaster.getMetadata()
.getPixelSize_Y() / 2;
final Wand w = new Wand(geoRaster.getImagePlus().getProcessor());
w.autoOutline(pixelX, pixelY);
final Coordinate[] jtsCoords = new Coordinate[w.npoints + 1];
for (int i = 0; i < w.npoints; i++) {
final Point2D worldXY = geoRaster
.fromPixelToRealWorld(w.xpoints[i],
w.ypoints[i]);
jtsCoords[i] = new Coordinate(worldXY.getX() - halfPixelSize_X,
worldXY.getY() - halfPixelSize_Y);
}
jtsCoords[w.npoints] = jtsCoords[0];
final LinearRing shell = geometryFactory
.createLinearRing(jtsCoords);
final Polygon polygon = geometryFactory.createPolygon(shell, null);
if (dsf.getSourceManager().exists(wandLayername)) {
dsf.remove(wandLayername);
vc.getLayerModel().remove(wandLayername);
}
DataManager dataManager = (DataManager) Services
.getService("org.orbisgis.DataManager");
final ILayer wandLayer = dataManager
.createLayer(buildWandDatasource(polygon));
final UniqueSymbolLegend uniqueSymbolLegend = LegendFactory
.createUniqueSymbolLegend();
final Symbol polygonSymbol = SymbolFactory.createPolygonSymbol(
null, Color.ORANGE);
uniqueSymbolLegend.setSymbol(polygonSymbol);
vc.getLayerModel().insertLayer(wandLayer, 0);
wandLayer.setLegend(uniqueSymbolLegend);
} catch (LayerException e) {
Services.getErrorManager().error(
"Cannot use wand tool: " + e.getMessage(), e);
} catch (DriverException e) {
Services.getErrorManager().error(
"Cannot apply the legend : " + e.getMessage(), e);
} catch (IOException e) {
Services.getErrorManager().error(
"Error accessing the GeoRaster : " + e.getMessage(), e);
} catch (DriverLoadException e) {
Services.getErrorManager().error(
"Error accessing the wand layer datasource : "
+ e.getMessage(), e);
} catch (NoSuchTableException e) {
Services.getErrorManager().error(
"Error accessing the wand layer datasource : "
+ e.getMessage(), e);
} catch (DataSourceCreationException e) {
Services.getErrorManager().error(
"Error accessing the wand layer datasource : "
+ e.getMessage(), e);
} catch (NonEditableDataSourceException e) {
Services.getErrorManager().error(
"Error committing the wand layer datasource : "
+ e.getMessage(), e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "pointDone" | "@Override
protected void pointDone(Point point, MapContext vc, ToolManager tm)
throws TransitionException {
try {
final ILayer layer = vc.getSelectedLayers()[0];
final GeoRaster geoRaster = layer.getRaster();
final Coordinate realWorldCoordinate = point.getCoordinate();
final Point2D gridContextCoordinate = geoRaster
.fromRealWorldToPixel(realWorldCoordinate.x,
realWorldCoordinate.y);
final int pixelX = (int) gridContextCoordinate.getX();
final int pixelY = (int) gridContextCoordinate.getY();
final float halfPixelSize_X = geoRaster.getMetadata()
.getPixelSize_X() / 2;
final float halfPixelSize_Y = geoRaster.getMetadata()
.getPixelSize_Y() / 2;
final Wand w = new Wand(geoRaster.getImagePlus().getProcessor());
w.autoOutline(pixelX, pixelY);
final Coordinate[] jtsCoords = new Coordinate[w.npoints + 1];
for (int i = 0; i < w.npoints; i++) {
final Point2D worldXY = geoRaster
.fromPixelToRealWorld(w.xpoints[i],
w.ypoints[i]);
jtsCoords[i] = new Coordinate(worldXY.getX() - halfPixelSize_X,
worldXY.getY() - halfPixelSize_Y);
}
jtsCoords[w.npoints] = jtsCoords[0];
final LinearRing shell = geometryFactory
.createLinearRing(jtsCoords);
final Polygon polygon = geometryFactory.createPolygon(shell, null);
if (dsf.getSourceManager().exists(wandLayername)) {
dsf.remove(wandLayername);
vc.getLayerModel().remove(wandLayername);
}
DataManager dataManager = (DataManager) Services
.getService("org.orbisgis.DataManager");
final ILayer wandLayer = dataManager
.createLayer(buildWandDatasource(polygon));
final UniqueSymbolLegend uniqueSymbolLegend = LegendFactory
.createUniqueSymbolLegend();
final Symbol polygonSymbol = SymbolFactory.createPolygonSymbol(
null, Color.ORANGE);
uniqueSymbolLegend.setSymbol(polygonSymbol);
<MASK>wandLayer.setLegend(uniqueSymbolLegend);</MASK>
vc.getLayerModel().insertLayer(wandLayer, 0);
} catch (LayerException e) {
Services.getErrorManager().error(
"Cannot use wand tool: " + e.getMessage(), e);
} catch (DriverException e) {
Services.getErrorManager().error(
"Cannot apply the legend : " + e.getMessage(), e);
} catch (IOException e) {
Services.getErrorManager().error(
"Error accessing the GeoRaster : " + e.getMessage(), e);
} catch (DriverLoadException e) {
Services.getErrorManager().error(
"Error accessing the wand layer datasource : "
+ e.getMessage(), e);
} catch (NoSuchTableException e) {
Services.getErrorManager().error(
"Error accessing the wand layer datasource : "
+ e.getMessage(), e);
} catch (DataSourceCreationException e) {
Services.getErrorManager().error(
"Error accessing the wand layer datasource : "
+ e.getMessage(), e);
} catch (NonEditableDataSourceException e) {
Services.getErrorManager().error(
"Error committing the wand layer datasource : "
+ e.getMessage(), e);
}
}" |
Inversion-Mutation | megadiff | "public String compileString(String code) throws IOException {
compiler = new Compiler(types, packages);
loadTranslation();
return javaCode = compiler.compile(code);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "compileString" | "public String compileString(String code) throws IOException {
<MASK>loadTranslation();</MASK>
compiler = new Compiler(types, packages);
return javaCode = compiler.compile(code);
}" |
Inversion-Mutation | megadiff | "@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Subtitle subtitle = null;
if (firstSelection) {
boolean automaticallySelectSubtitle = preferences.getBoolean(
"automatic_subtitle_selection", false);
if (automaticallySelectSubtitle) {
String languageCode = preferences.getString(
"preferred_subtitle_language", "");
if (languageCode != "") {
for (int i = 0; i < parent.getAdapter().getCount(); i++) {
subtitle = (Subtitle) parent.getItemAtPosition(i);
if (languageCode.equals(subtitle.getLanguageCode())) {
parent.setSelection(i);
continue;
}
}
}
}
firstSelection = false;
} else {
subtitle = (Subtitle) parent.getItemAtPosition(position);
}
video.setSubtitle(subtitle);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onItemSelected" | "@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Subtitle subtitle = null;
if (firstSelection) {
boolean automaticallySelectSubtitle = preferences.getBoolean(
"automatic_subtitle_selection", false);
if (automaticallySelectSubtitle) {
String languageCode = preferences.getString(
"preferred_subtitle_language", "");
if (languageCode != "") {
for (int i = 0; i < parent.getAdapter().getCount(); i++) {
subtitle = (Subtitle) parent.getItemAtPosition(i);
if (languageCode.equals(subtitle.getLanguageCode())) {
parent.setSelection(i);
continue;
}
}
<MASK>firstSelection = false;</MASK>
}
}
} else {
subtitle = (Subtitle) parent.getItemAtPosition(position);
}
video.setSubtitle(subtitle);
}" |
Inversion-Mutation | megadiff | "@Override
protected void
processUnsolicited (Parcel p) {
Object ret;
int dataPosition = p.dataPosition(); // save off position within the Parcel
int response = p.readInt();
switch(response) {
case RIL_UNSOL_RIL_CONNECTED: // Fix for NV/RUIM setting on CDMA SIM devices
// skip getcdmascriptionsource as if qualcomm handles it in the ril binary
ret = responseInts(p);
setRadioPower(false, null);
setPreferredNetworkType(mPreferredNetworkType, null);
notifyRegistrantsRilConnectionChanged(((int[])ret)[0]);
isGSM = (mPhoneType != RILConstants.CDMA_PHONE);
samsungDriverCall = (needsOldRilFeature("newDriverCall") && !isGSM) || mRilVersion < 7 ? false : true;
break;
case RIL_UNSOL_NITZ_TIME_RECEIVED:
handleNitzTimeReceived(p);
break;
default:
// Rewind the Parcel
p.setDataPosition(dataPosition);
// Forward responses that we are not overriding to the super class
super.processUnsolicited(p);
return;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processUnsolicited" | "@Override
protected void
processUnsolicited (Parcel p) {
Object ret;
int dataPosition = p.dataPosition(); // save off position within the Parcel
int response = p.readInt();
switch(response) {
case RIL_UNSOL_RIL_CONNECTED: // Fix for NV/RUIM setting on CDMA SIM devices
// skip getcdmascriptionsource as if qualcomm handles it in the ril binary
ret = responseInts(p);
setRadioPower(false, null);
setPreferredNetworkType(mPreferredNetworkType, null);
notifyRegistrantsRilConnectionChanged(((int[])ret)[0]);
<MASK>samsungDriverCall = (needsOldRilFeature("newDriverCall") && !isGSM) || mRilVersion < 7 ? false : true;</MASK>
isGSM = (mPhoneType != RILConstants.CDMA_PHONE);
break;
case RIL_UNSOL_NITZ_TIME_RECEIVED:
handleNitzTimeReceived(p);
break;
default:
// Rewind the Parcel
p.setDataPosition(dataPosition);
// Forward responses that we are not overriding to the super class
super.processUnsolicited(p);
return;
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void buildUnmanagedDevices() {
Map<String, String> customMap = new HashMap<String, String>();
List<VmDevice> vmDevices =
DbFacade.getInstance()
.getVmDeviceDAO()
.getUnmanagedDevicesByVmId(vm.getId());
if (vmDevices.size() > 0) {
StringBuilder id = new StringBuilder();
for (VmDevice vmDevice : vmDevices) {
XmlRpcStruct struct = new XmlRpcStruct();
id.append(VdsProperties.Device);
id.append("_");
id.append(vmDevice.getDeviceId());
if (VmDeviceCommonUtils.isInWhiteList(vmDevice.getType(), vmDevice.getDevice())) {
struct.add(VdsProperties.Type, vmDevice.getType());
struct.add(VdsProperties.Device, vmDevice.getDevice());
addAddress(vmDevice, struct);
struct.add(VdsProperties.SpecParams, StringUtils.string2Map(vmDevice.getSpecParams()));
devices.add(struct);
} else {
customMap.put(id.toString(), vmDevice.toString());
}
}
}
createInfo.add(VdsProperties.Custom, customMap);
XmlRpcStruct[] devArray = new XmlRpcStruct[devices.size()];
createInfo.add(DEVICES, devices.toArray(devArray));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildUnmanagedDevices" | "@Override
protected void buildUnmanagedDevices() {
Map<String, String> customMap = new HashMap<String, String>();
List<VmDevice> vmDevices =
DbFacade.getInstance()
.getVmDeviceDAO()
.getUnmanagedDevicesByVmId(vm.getId());
if (vmDevices.size() > 0) {
<MASK>XmlRpcStruct struct = new XmlRpcStruct();</MASK>
StringBuilder id = new StringBuilder();
for (VmDevice vmDevice : vmDevices) {
id.append(VdsProperties.Device);
id.append("_");
id.append(vmDevice.getDeviceId());
if (VmDeviceCommonUtils.isInWhiteList(vmDevice.getType(), vmDevice.getDevice())) {
struct.add(VdsProperties.Type, vmDevice.getType());
struct.add(VdsProperties.Device, vmDevice.getDevice());
addAddress(vmDevice, struct);
struct.add(VdsProperties.SpecParams, StringUtils.string2Map(vmDevice.getSpecParams()));
devices.add(struct);
} else {
customMap.put(id.toString(), vmDevice.toString());
}
}
}
createInfo.add(VdsProperties.Custom, customMap);
XmlRpcStruct[] devArray = new XmlRpcStruct[devices.size()];
createInfo.add(DEVICES, devices.toArray(devArray));
}" |
Inversion-Mutation | megadiff | "public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
PropertyMediator property = (PropertyMediator) object;
if (itemPropertyDescriptors != null) {
itemPropertyDescriptors.clear();
}
super.getPropertyDescriptors(object);
addPropertyNamePropertyDescriptor(object);
addPropertyActionPropertyDescriptor(object);
if (property.getPropertyAction().equals(PropertyAction.SET)) {
addValueTypePropertyDescriptor(object);
addPropertyDataTypePropertyDescriptor(object);
if (property.getValueType().equals(PropertyValueType.LITERAL)) {
switch (property.getPropertyDataType()) {
case OM: {
addValueOMPropertyDescriptor(object);
break;
}
case STRING: {
addValueLiteralPropertyDescriptor(object);
addValueStringPatternPropertyDescriptor(object);
addValueStringCapturingGroupPropertyDescriptor(object);
break;
}
default: {
addValueLiteralPropertyDescriptor(object);
}
}
} else {
addValueExpressionPropertyDescriptor(object);
}
}
addPropertyScopePropertyDescriptor(object);
addDescriptionPropertyDescriptor(object);
/*if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addPropertyNamePropertyDescriptor(object);
addPropertyDataTypePropertyDescriptor(object);
addPropertyActionPropertyDescriptor(object);
addPropertyScopePropertyDescriptor(object);
addValueTypePropertyDescriptor(object);
addValueLiteralPropertyDescriptor(object);
addExpressionPropertyDescriptor(object);
addNamespacePrefixPropertyDescriptor(object);
addNamespacePropertyDescriptor(object);
addValueOMPropertyDescriptor(object);
addValueStringPatternPropertyDescriptor(object);
addValueStringCapturingGroupPropertyDescriptor(object);
}*/
return itemPropertyDescriptors;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getPropertyDescriptors" | "public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
PropertyMediator property = (PropertyMediator) object;
if (itemPropertyDescriptors != null) {
itemPropertyDescriptors.clear();
}
super.getPropertyDescriptors(object);
addPropertyNamePropertyDescriptor(object);
addPropertyActionPropertyDescriptor(object);
if (property.getPropertyAction().equals(PropertyAction.SET)) {
<MASK>addPropertyDataTypePropertyDescriptor(object);</MASK>
addValueTypePropertyDescriptor(object);
if (property.getValueType().equals(PropertyValueType.LITERAL)) {
switch (property.getPropertyDataType()) {
case OM: {
addValueOMPropertyDescriptor(object);
break;
}
case STRING: {
addValueLiteralPropertyDescriptor(object);
addValueStringPatternPropertyDescriptor(object);
addValueStringCapturingGroupPropertyDescriptor(object);
break;
}
default: {
addValueLiteralPropertyDescriptor(object);
}
}
} else {
addValueExpressionPropertyDescriptor(object);
}
}
addPropertyScopePropertyDescriptor(object);
addDescriptionPropertyDescriptor(object);
/*if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addPropertyNamePropertyDescriptor(object);
<MASK>addPropertyDataTypePropertyDescriptor(object);</MASK>
addPropertyActionPropertyDescriptor(object);
addPropertyScopePropertyDescriptor(object);
addValueTypePropertyDescriptor(object);
addValueLiteralPropertyDescriptor(object);
addExpressionPropertyDescriptor(object);
addNamespacePrefixPropertyDescriptor(object);
addNamespacePropertyDescriptor(object);
addValueOMPropertyDescriptor(object);
addValueStringPatternPropertyDescriptor(object);
addValueStringCapturingGroupPropertyDescriptor(object);
}*/
return itemPropertyDescriptors;
}" |
Inversion-Mutation | megadiff | "protected XSAttributeUseImpl traverseLocal(Element attrDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
XSComplexTypeDecl enclosingCT) {
// General Attribute Checking
Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, false, schemaDoc);
String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT];
String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED];
String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME];
QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF];
XInt useAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_USE];
// get 'attribute declaration'
XSAttributeDecl attribute = null;
if (attrDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) {
if (refAtt != null) {
attribute = (XSAttributeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ATTRIBUTE_TYPE, refAtt, attrDecl);
Element child = DOMUtil.getFirstChildElement(attrDecl);
if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) {
// REVISIT: put this somewhere
traverseAnnotationDecl(child, attrValues, false, schemaDoc);
child = DOMUtil.getNextSiblingElement(child);
}
if (child != null) {
reportSchemaError("src-attribute.3.2", new Object[]{refAtt.rawname}, child);
}
// for error reporting
nameAtt = refAtt.localpart;
} else {
attribute = null;
}
} else {
attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, false, enclosingCT);
}
// get 'value constraint'
short consType = XSConstants.VC_NONE;
if (defaultAtt != null) {
consType = XSConstants.VC_DEFAULT;
} else if (fixedAtt != null) {
consType = XSConstants.VC_FIXED;
defaultAtt = fixedAtt;
fixedAtt = null;
}
XSAttributeUseImpl attrUse = null;
if (attribute != null) {
if (fSchemaHandler.fDeclPool !=null) {
attrUse = fSchemaHandler.fDeclPool.getAttributeUse();
} else {
attrUse = new XSAttributeUseImpl();
}
attrUse.fAttrDecl = attribute;
attrUse.fUse = useAtt.shortValue();
attrUse.fConstraintType = consType;
if (defaultAtt != null) {
attrUse.fDefault = new ValidatedInfo();
attrUse.fDefault.normalizedValue = defaultAtt;
}
}
//src-attribute
// 1 default and fixed must not both be present.
if (defaultAtt != null && fixedAtt != null) {
reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl);
}
// 2 If default and use are both present, use must have the actual value optional.
if (consType == XSConstants.VC_DEFAULT &&
useAtt != null && useAtt.intValue() != SchemaSymbols.USE_OPTIONAL) {
reportSchemaError("src-attribute.2", new Object[]{nameAtt}, attrDecl);
}
// a-props-correct
if (defaultAtt != null && attrUse != null) {
// 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4).
fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport);
try {
checkDefaultValid(attrUse);
}
catch (InvalidDatatypeValueException ide) {
reportSchemaError (ide.getKey(), ide.getArgs(), attrDecl);
reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl);
}
// 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}.
if (((XSSimpleType)attribute.getTypeDefinition()).isIDType() ) {
reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl);
}
// check 3.5.6 constraint
// Attribute Use Correct
// 2 If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}.
if (attrUse.fAttrDecl.getConstraintType() == XSConstants.VC_FIXED &&
attrUse.fConstraintType != XSConstants.VC_NONE) {
if (attrUse.fConstraintType != XSConstants.VC_FIXED ||
!attrUse.fAttrDecl.getValInfo().actualValue.equals(attrUse.fDefault.actualValue)) {
reportSchemaError ("au-props-correct.2", new Object[]{nameAtt, attrUse.fAttrDecl.getValInfo().stringValue()}, attrDecl);
}
}
}
fAttrChecker.returnAttrArray(attrValues, schemaDoc);
return attrUse;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "traverseLocal" | "protected XSAttributeUseImpl traverseLocal(Element attrDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
XSComplexTypeDecl enclosingCT) {
// General Attribute Checking
Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, false, schemaDoc);
String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT];
String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED];
String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME];
QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF];
XInt useAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_USE];
// get 'attribute declaration'
XSAttributeDecl attribute = null;
if (attrDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) {
if (refAtt != null) {
attribute = (XSAttributeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ATTRIBUTE_TYPE, refAtt, attrDecl);
Element child = DOMUtil.getFirstChildElement(attrDecl);
if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) {
// REVISIT: put this somewhere
traverseAnnotationDecl(child, attrValues, false, schemaDoc);
child = DOMUtil.getNextSiblingElement(child);
}
if (child != null) {
reportSchemaError("src-attribute.3.2", new Object[]{refAtt.rawname}, child);
}
// for error reporting
nameAtt = refAtt.localpart;
} else {
attribute = null;
}
} else {
attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, false, enclosingCT);
}
// get 'value constraint'
short consType = XSConstants.VC_NONE;
if (defaultAtt != null) {
consType = XSConstants.VC_DEFAULT;
} else if (fixedAtt != null) {
consType = XSConstants.VC_FIXED;
defaultAtt = fixedAtt;
fixedAtt = null;
}
XSAttributeUseImpl attrUse = null;
if (attribute != null) {
if (fSchemaHandler.fDeclPool !=null) {
attrUse = fSchemaHandler.fDeclPool.getAttributeUse();
} else {
attrUse = new XSAttributeUseImpl();
}
attrUse.fAttrDecl = attribute;
attrUse.fUse = useAtt.shortValue();
attrUse.fConstraintType = consType;
if (defaultAtt != null) {
attrUse.fDefault = new ValidatedInfo();
attrUse.fDefault.normalizedValue = defaultAtt;
}
}
<MASK>fAttrChecker.returnAttrArray(attrValues, schemaDoc);</MASK>
//src-attribute
// 1 default and fixed must not both be present.
if (defaultAtt != null && fixedAtt != null) {
reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl);
}
// 2 If default and use are both present, use must have the actual value optional.
if (consType == XSConstants.VC_DEFAULT &&
useAtt != null && useAtt.intValue() != SchemaSymbols.USE_OPTIONAL) {
reportSchemaError("src-attribute.2", new Object[]{nameAtt}, attrDecl);
}
// a-props-correct
if (defaultAtt != null && attrUse != null) {
// 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4).
fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport);
try {
checkDefaultValid(attrUse);
}
catch (InvalidDatatypeValueException ide) {
reportSchemaError (ide.getKey(), ide.getArgs(), attrDecl);
reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl);
}
// 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}.
if (((XSSimpleType)attribute.getTypeDefinition()).isIDType() ) {
reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl);
}
// check 3.5.6 constraint
// Attribute Use Correct
// 2 If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}.
if (attrUse.fAttrDecl.getConstraintType() == XSConstants.VC_FIXED &&
attrUse.fConstraintType != XSConstants.VC_NONE) {
if (attrUse.fConstraintType != XSConstants.VC_FIXED ||
!attrUse.fAttrDecl.getValInfo().actualValue.equals(attrUse.fDefault.actualValue)) {
reportSchemaError ("au-props-correct.2", new Object[]{nameAtt, attrUse.fAttrDecl.getValInfo().stringValue()}, attrDecl);
}
}
}
return attrUse;
}" |
Inversion-Mutation | megadiff | "private static String pathNameToString(List name) {
if ( name == null ) {
throw new RuntimeException("PathName reference may not be null for "+
"conversion to String");
}
if ( name.size() == 0 ) {
throw new RuntimeException("PathName must contain at least one "+
"simple name for conversion to String");
}
if ( name.size() == 1 ) {
return (String) name.get(0);
} else if ( name.size() >= 2 ) {
StringBuffer sb = new StringBuffer(256);
Iterator it = name.iterator();
sb.append((String) it.next());
while ( it.hasNext() ) {
String elem = (String) it.next();
sb.append("::");
sb.append(elem);
}
return sb.toString();
} else {
throw new RuntimeException("Invalid length of PathName (length is " + name.size() );
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "pathNameToString" | "private static String pathNameToString(List name) {
if ( name == null ) {
throw new RuntimeException("PathName reference may not be null for "+
"conversion to String");
}
if ( name.size() == 0 ) {
throw new RuntimeException("PathName must contain at least one "+
"simple name for conversion to String");
}
if ( name.size() == 1 ) {
return (String) name.get(0);
} else if ( name.size() >= 2 ) {
StringBuffer sb = new StringBuffer(256);
Iterator it = name.iterator();
sb.append((String) it.next());
while ( it.hasNext() ) {
String elem = (String) it.next();
<MASK>sb.append(elem);</MASK>
sb.append("::");
}
return sb.toString();
} else {
throw new RuntimeException("Invalid length of PathName (length is " + name.size() );
}
}" |
Inversion-Mutation | megadiff | "@Override
public void tearDown() throws Exception {
HibernateUtil.closeSession();
TestDatabase.resetMySQLDatabase();
super.tearDown();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tearDown" | "@Override
public void tearDown() throws Exception {
<MASK>TestDatabase.resetMySQLDatabase();</MASK>
HibernateUtil.closeSession();
super.tearDown();
}" |
Inversion-Mutation | megadiff | "private boolean performNewSearch(boolean forground) {
SearchPatternData patternData= getPatternData();
if (patternData.fileNamePatterns == null || fExtensions.getText().length() <= 0) {
patternData.fileNamePatterns= new HashSet(1);
patternData.fileNamePatterns.add("*"); //$NON-NLS-1$
}
// Setup search scope
TextSearchScope scope= null;
switch (getContainer().getSelectedScope()) {
case ISearchPageContainer.WORKSPACE_SCOPE:
scope= TextSearchScope.newWorkspaceScope();
break;
case ISearchPageContainer.SELECTION_SCOPE:
scope= getSelectedResourcesScope(false);
break;
case ISearchPageContainer.SELECTED_PROJECTS_SCOPE:
scope= getSelectedResourcesScope(true);
break;
case ISearchPageContainer.WORKING_SET_SCOPE:
IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
String desc= SearchMessages.getFormattedString("WorkingSetScope", ScopePart.toString(workingSets)); //$NON-NLS-1$
scope= new TextSearchScope(desc, workingSets);
}
org.eclipse.search.ui.NewSearchUI.activateSearchResultView();
scope.addExtensions(patternData.fileNamePatterns);
FileSearchQuery wsJob= new FileSearchQuery(scope, getSearchOptions(), patternData.textPattern);
if (forground) {
IStatus status= NewSearchUI.runQueryInForeground(getRunnableContext(), wsJob);
return status.isOK();
} else
NewSearchUI.runQuery(wsJob);
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performNewSearch" | "private boolean performNewSearch(boolean forground) {
<MASK>org.eclipse.search.ui.NewSearchUI.activateSearchResultView();</MASK>
SearchPatternData patternData= getPatternData();
if (patternData.fileNamePatterns == null || fExtensions.getText().length() <= 0) {
patternData.fileNamePatterns= new HashSet(1);
patternData.fileNamePatterns.add("*"); //$NON-NLS-1$
}
// Setup search scope
TextSearchScope scope= null;
switch (getContainer().getSelectedScope()) {
case ISearchPageContainer.WORKSPACE_SCOPE:
scope= TextSearchScope.newWorkspaceScope();
break;
case ISearchPageContainer.SELECTION_SCOPE:
scope= getSelectedResourcesScope(false);
break;
case ISearchPageContainer.SELECTED_PROJECTS_SCOPE:
scope= getSelectedResourcesScope(true);
break;
case ISearchPageContainer.WORKING_SET_SCOPE:
IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
String desc= SearchMessages.getFormattedString("WorkingSetScope", ScopePart.toString(workingSets)); //$NON-NLS-1$
scope= new TextSearchScope(desc, workingSets);
}
scope.addExtensions(patternData.fileNamePatterns);
FileSearchQuery wsJob= new FileSearchQuery(scope, getSearchOptions(), patternData.textPattern);
if (forground) {
IStatus status= NewSearchUI.runQueryInForeground(getRunnableContext(), wsJob);
return status.isOK();
} else
NewSearchUI.runQuery(wsJob);
return true;
}" |
Inversion-Mutation | megadiff | "@Override
public void run() {
aggressiveUnload();
Coordinate c;
do {
if (isBeyondThreshold()) {
step = 0;
}
c = getCurrentPosition();
step++;
} while (!tryLoadChunk(c.getX(), c.getY()));
last = step;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run() {
aggressiveUnload();
Coordinate c;
do {
<MASK>step++;</MASK>
if (isBeyondThreshold()) {
step = 0;
}
c = getCurrentPosition();
} while (!tryLoadChunk(c.getX(), c.getY()));
last = step;
}" |
Inversion-Mutation | megadiff | "@Override
public void configure(JobConf jobConf) {
if (parameters == null) {
ParameteredGeneralizations.configureParameters(this, jobConf);
}
try {
if (weightsFile.get() != null) {
FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf);
Vector weights = (Vector) vectorClass.get().newInstance();
if (!fs.exists(weightsFile.get())) {
throw new FileNotFoundException(weightsFile.get().toString());
}
DataInputStream in = fs.open(weightsFile.get());
try {
weights.readFields(in);
} finally {
in.close();
}
this.weights = weights;
}
} catch (IOException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configure" | "@Override
public void configure(JobConf jobConf) {
if (parameters == null) {
ParameteredGeneralizations.configureParameters(this, jobConf);
}
try {
<MASK>FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf);</MASK>
if (weightsFile.get() != null) {
Vector weights = (Vector) vectorClass.get().newInstance();
if (!fs.exists(weightsFile.get())) {
throw new FileNotFoundException(weightsFile.get().toString());
}
DataInputStream in = fs.open(weightsFile.get());
try {
weights.readFields(in);
} finally {
in.close();
}
this.weights = weights;
}
} catch (IOException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}" |
Inversion-Mutation | megadiff | "public static Popup addScrollPaneIfNecessary(JPopupMenu popupMenu, int x, int y) {
SimpleScrollPane contents = new SimpleScrollPane(popupMenu, SimpleScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, SimpleScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
if (popupMenu instanceof JidePopupMenu && popupMenu.getPreferredSize().height != ((JidePopupMenu) popupMenu).getPreferredScrollableViewportSize().height) {
if (popupMenu.getLayout() instanceof DefaultMenuLayout) {
popupMenu.setLayout(new BoxLayout(popupMenu, ((DefaultMenuLayout) popupMenu.getLayout()).getAxis()));
}
PopupFactory popupFactory = PopupFactory.getSharedInstance();
contents.getScrollUpButton().setOpaque(true);
contents.getScrollDownButton().setOpaque(true);
contents.setBorder(BorderFactory.createEmptyBorder());
return popupFactory.getPopup(popupMenu.getInvoker(), contents, x, y);
}
else {
return null;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addScrollPaneIfNecessary" | "public static Popup addScrollPaneIfNecessary(JPopupMenu popupMenu, int x, int y) {
if (popupMenu instanceof JidePopupMenu && popupMenu.getPreferredSize().height != ((JidePopupMenu) popupMenu).getPreferredScrollableViewportSize().height) {
if (popupMenu.getLayout() instanceof DefaultMenuLayout) {
popupMenu.setLayout(new BoxLayout(popupMenu, ((DefaultMenuLayout) popupMenu.getLayout()).getAxis()));
}
PopupFactory popupFactory = PopupFactory.getSharedInstance();
<MASK>SimpleScrollPane contents = new SimpleScrollPane(popupMenu, SimpleScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, SimpleScrollPane.HORIZONTAL_SCROLLBAR_NEVER);</MASK>
contents.getScrollUpButton().setOpaque(true);
contents.getScrollDownButton().setOpaque(true);
contents.setBorder(BorderFactory.createEmptyBorder());
return popupFactory.getPopup(popupMenu.getInvoker(), contents, x, y);
}
else {
return null;
}
}" |
Inversion-Mutation | megadiff | "public UndoController(JTextArea textArea)
{
this.textArea = textArea;
lastUndoEdit = new CompoundEdit();
lastDisplayEdit = new CompoundEdit();
toUndo = lastUndoEdit;
view = new EditHistoryView(this);
view.addEdit(lastDisplayEdit);
undoAction = new UndoAction(this);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "UndoController" | "public UndoController(JTextArea textArea)
{
this.textArea = textArea;
<MASK>undoAction = new UndoAction(this);</MASK>
lastUndoEdit = new CompoundEdit();
lastDisplayEdit = new CompoundEdit();
toUndo = lastUndoEdit;
view = new EditHistoryView(this);
view.addEdit(lastDisplayEdit);
}" |
Inversion-Mutation | megadiff | "public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (contentType != null) {
response.setContentType(contentType);
}
ExtendedModelMap model = new ExtendedModelMap();
populateModel(model, request);
ModelAndView mv = new ModelAndView(viewName, model);
return mv;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleRequest" | "public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (contentType != null) {
response.setContentType(contentType);
}
ExtendedModelMap model = new ExtendedModelMap();
<MASK>ModelAndView mv = new ModelAndView(viewName, model);</MASK>
populateModel(model, request);
return mv;
}" |
Inversion-Mutation | megadiff | "public void writeStyleSheet() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
Iterator iter = getStyleMap().keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
String style = getStyle(name);
if ( !isDefaultStyle(name) && name.indexOf(".") == -1 ) {
name = "." + name;
}
String writeString = name + " {";
writer.write(writeString, 0, writeString.length());
writer.newLine();
if (style != null && style.length() > 0 ) {
StringTokenizer tokens = new StringTokenizer(style, ";");
while (tokens.hasMoreTokens()) {
writeString = "\t" + tokens.nextToken() + ";";
writer.write(writeString, 0, writeString.length());
writer.newLine();
}
}
writeString = "}";
writer.write(writeString, 0, writeString.length());
writer.newLine();
if (iter.hasNext()) {
writer.newLine();
}
}
writer.flush();
writer.close();
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "writeStyleSheet" | "public void writeStyleSheet() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
Iterator iter = getStyleMap().keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
if ( !isDefaultStyle(name) && name.indexOf(".") == -1 ) {
name = "." + name;
}
<MASK>String style = getStyle(name);</MASK>
String writeString = name + " {";
writer.write(writeString, 0, writeString.length());
writer.newLine();
if (style != null && style.length() > 0 ) {
StringTokenizer tokens = new StringTokenizer(style, ";");
while (tokens.hasMoreTokens()) {
writeString = "\t" + tokens.nextToken() + ";";
writer.write(writeString, 0, writeString.length());
writer.newLine();
}
}
writeString = "}";
writer.write(writeString, 0, writeString.length());
writer.newLine();
if (iter.hasNext()) {
writer.newLine();
}
}
writer.flush();
writer.close();
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}" |
Inversion-Mutation | megadiff | "public View() {
super();
this.setTitle("TSPArena");
this.getContentPane().setPreferredSize(new Dimension(640, 480));
this.setVisible(true);
this.pack(); //FORCE it to be 640 x 480, this has given me grief
this.setResizable(false);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "View" | "public View() {
super();
this.setTitle("TSPArena");
this.getContentPane().setPreferredSize(new Dimension(640, 480));
<MASK>this.pack(); //FORCE it to be 640 x 480, this has given me grief</MASK>
this.setVisible(true);
this.setResizable(false);
}" |
Inversion-Mutation | megadiff | "private void onDataConnectionAttached() {
if (DBG) log("onDataConnectionAttached");
mAttached.set(true);
if (getOverallState() == DctConstants.State.CONNECTED) {
if (DBG) log("onDataConnectionAttached: start polling notify attached");
startNetStatPoll();
startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
notifyDataConnection(Phone.REASON_DATA_ATTACHED);
} else {
// update APN availability so that APN can be enabled.
notifyOffApnsOfAvailability(Phone.REASON_DATA_ATTACHED);
}
mAutoAttachOnCreation = true;
setupDataOnConnectableApns(Phone.REASON_DATA_ATTACHED);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onDataConnectionAttached" | "private void onDataConnectionAttached() {
if (DBG) log("onDataConnectionAttached");
if (getOverallState() == DctConstants.State.CONNECTED) {
if (DBG) log("onDataConnectionAttached: start polling notify attached");
startNetStatPoll();
startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
notifyDataConnection(Phone.REASON_DATA_ATTACHED);
} else {
// update APN availability so that APN can be enabled.
notifyOffApnsOfAvailability(Phone.REASON_DATA_ATTACHED);
}
mAutoAttachOnCreation = true;
<MASK>mAttached.set(true);</MASK>
setupDataOnConnectableApns(Phone.REASON_DATA_ATTACHED);
}" |
Inversion-Mutation | megadiff | "public static <T> void copy(Collection<T> source, Collection<T> target) {
Assert.isTrue(source != null, "源集合不能为空。");
Assert.isTrue(source != null, "目标集合不能为空。");
target.clear();
if (!source.isEmpty()) {
for (T o : source) {
target.add(o);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "copy" | "public static <T> void copy(Collection<T> source, Collection<T> target) {
Assert.isTrue(source != null, "源集合不能为空。");
Assert.isTrue(source != null, "目标集合不能为空。");
if (!source.isEmpty()) {
<MASK>target.clear();</MASK>
for (T o : source) {
target.add(o);
}
}
}" |
Inversion-Mutation | megadiff | "public void flush(Connection connection) throws SQLException {
SessionImpl.LOG.debug("Flushing session {0}", this);
final ArrayList<ManagedInstance<?>> updates = Lists.newArrayList(this.newEntities);
final ArrayList<ManagedInstance<?>> removals = Lists.newArrayListWithCapacity(this.changedEntities.size());
for (final ManagedInstance<?> instance : this.changedEntities) {
if (instance.getStatus() == Status.NEW) {
// should be already in the list the instance is a new instance
continue;
}
else if (instance.getStatus() == Status.REMOVED) {
removals.add(instance);
}
else if (instance.hasSelfUpdate()) {
updates.add(instance);
}
}
if ((updates.size() == 0) && (removals.size() == 0)) {
return;
}
final ManagedInstance<?>[] sortedUpdates = new ManagedInstance[updates.size()];
final ManagedInstance<?>[] sortedRemovals = new ManagedInstance[removals.size()];
final CallbackAvailability callbackAvailability = new CallbackAvailability();
Prioritizer.sort(updates, removals, sortedUpdates, sortedRemovals, callbackAvailability);
SessionImpl.LOG.debug("Flushing session {0}: updates {1}, removals {2}", this, sortedUpdates.length, sortedRemovals.length);
// validations
final EntityManagerFactoryImpl entityManagerFactory = this.em.getEntityManagerFactory();
if (entityManagerFactory.hasValidators()) {
final Set<ConstraintViolation<?>> violations = Sets.newHashSet();
for (final ManagedInstance<?> instance : sortedUpdates) {
violations.addAll(instance.getType().runValidators(entityManagerFactory, instance));
}
for (final ManagedInstance<?> instance : sortedRemovals) {
violations.addAll(instance.getType().runValidators(entityManagerFactory, instance));
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Cannot flush due to validation errors.", violations);
}
}
// fire callbacks
this.firePreCallbacks(sortedUpdates, sortedRemovals, callbackAvailability);
this.doVersionUpgrades(connection, sortedUpdates);
for (final ManagedInstance<?> instance : sortedRemovals) {
instance.flushAssociations(connection, true, false);
}
for (final ManagedInstance<?> instance : sortedUpdates) {
instance.flushAssociations(connection, true, false);
}
this.doUpdates(connection, sortedUpdates);
this.doRemoves(connection, sortedRemovals);
for (final ManagedInstance<?> instance : sortedUpdates) {
instance.checkTransients();
}
for (final ManagedInstance<?> instance : sortedUpdates) {
instance.flushAssociations(connection, false, this.newEntities.contains(instance));
instance.sortLists();
instance.reset();
}
// fire callbacks
this.firePostCallbacks(sortedUpdates, sortedRemovals, callbackAvailability);
SessionImpl.LOG.debug("Flush successful for session {0}", this);
// move new entities to external entities
this.externalEntities.addAll(this.newEntities);
for (int i = 0; i < this.newEntities.size(); i++) {
final ManagedInstance<?> instance = this.newEntities.get(i);
if (!instance.hasInitialId()) {
this.repository.put(instance.getId(), instance);
}
}
this.changedEntities.clear();
this.newEntities.clear();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "flush" | "public void flush(Connection connection) throws SQLException {
SessionImpl.LOG.debug("Flushing session {0}", this);
final ArrayList<ManagedInstance<?>> updates = Lists.newArrayList(this.newEntities);
final ArrayList<ManagedInstance<?>> removals = Lists.newArrayListWithCapacity(this.changedEntities.size());
for (final ManagedInstance<?> instance : this.changedEntities) {
if (instance.getStatus() == Status.NEW) {
// should be already in the list the instance is a new instance
continue;
}
else if (instance.getStatus() == Status.REMOVED) {
removals.add(instance);
}
else if (instance.hasSelfUpdate()) {
updates.add(instance);
}
}
if ((updates.size() == 0) && (removals.size() == 0)) {
return;
}
final ManagedInstance<?>[] sortedUpdates = new ManagedInstance[updates.size()];
final ManagedInstance<?>[] sortedRemovals = new ManagedInstance[removals.size()];
final CallbackAvailability callbackAvailability = new CallbackAvailability();
Prioritizer.sort(updates, removals, sortedUpdates, sortedRemovals, callbackAvailability);
SessionImpl.LOG.debug("Flushing session {0}: updates {1}, removals {2}", this, sortedUpdates.length, sortedRemovals.length);
// validations
final EntityManagerFactoryImpl entityManagerFactory = this.em.getEntityManagerFactory();
if (entityManagerFactory.hasValidators()) {
final Set<ConstraintViolation<?>> violations = Sets.newHashSet();
for (final ManagedInstance<?> instance : sortedUpdates) {
violations.addAll(instance.getType().runValidators(entityManagerFactory, instance));
}
for (final ManagedInstance<?> instance : sortedRemovals) {
violations.addAll(instance.getType().runValidators(entityManagerFactory, instance));
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Cannot flush due to validation errors.", violations);
}
}
// fire callbacks
this.firePreCallbacks(sortedUpdates, sortedRemovals, callbackAvailability);
this.doVersionUpgrades(connection, sortedUpdates);
for (final ManagedInstance<?> instance : sortedRemovals) {
instance.flushAssociations(connection, true, false);
}
for (final ManagedInstance<?> instance : sortedUpdates) {
instance.flushAssociations(connection, true, false);
}
<MASK>this.doRemoves(connection, sortedRemovals);</MASK>
this.doUpdates(connection, sortedUpdates);
for (final ManagedInstance<?> instance : sortedUpdates) {
instance.checkTransients();
}
for (final ManagedInstance<?> instance : sortedUpdates) {
instance.flushAssociations(connection, false, this.newEntities.contains(instance));
instance.sortLists();
instance.reset();
}
// fire callbacks
this.firePostCallbacks(sortedUpdates, sortedRemovals, callbackAvailability);
SessionImpl.LOG.debug("Flush successful for session {0}", this);
// move new entities to external entities
this.externalEntities.addAll(this.newEntities);
for (int i = 0; i < this.newEntities.size(); i++) {
final ManagedInstance<?> instance = this.newEntities.get(i);
if (!instance.hasInitialId()) {
this.repository.put(instance.getId(), instance);
}
}
this.changedEntities.clear();
this.newEntities.clear();
}" |
Inversion-Mutation | megadiff | "GameEngine() {
keys = new HashSet<Integer>();
window = new JFrame();
window.setLayout(new BorderLayout());
window.setSize(800, 600);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
area = new JDrawingArea(this);
window.add(area, BorderLayout.CENTER);
window.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent keyEvent) {
}
@Override
public void keyPressed(KeyEvent keyEvent) {
keys.add(keyEvent.getKeyCode());
}
@Override
public void keyReleased(KeyEvent keyEvent) {
keys.remove(keyEvent.getKeyCode());
}
});
showMainMenu();
objList= new LinkedList<GameObject>();
window.setVisible(true);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "GameEngine" | "GameEngine() {
keys = new HashSet<Integer>();
window = new JFrame();
window.setLayout(new BorderLayout());
window.setSize(800, 600);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
<MASK>window.setVisible(true);</MASK>
area = new JDrawingArea(this);
window.add(area, BorderLayout.CENTER);
window.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent keyEvent) {
}
@Override
public void keyPressed(KeyEvent keyEvent) {
keys.add(keyEvent.getKeyCode());
}
@Override
public void keyReleased(KeyEvent keyEvent) {
keys.remove(keyEvent.getKeyCode());
}
});
showMainMenu();
objList= new LinkedList<GameObject>();
}" |
Inversion-Mutation | megadiff | "public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (exchangeHandler != null) {
logger.info("Filtering a EasySOA API request");
response = new HttpMessageResponseWrapper((HttpServletResponse) response);
}
// Let the request continue
chain.doFilter(request, response);
// Forward to the exchange handler
if (exchangeHandler != null) {
// Filtering HTTP requests only for registering exchanges
if (request instanceof HttpServletRequest) {
try {
exchangeHandler.handleExchange((HttpServletRequest) request, (HttpServletResponse) response);
} catch (Exception e) {
logger.error("An error occurred during the exchange handling", e);
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doFilter" | "public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
<MASK>logger.info("Filtering a EasySOA API request");</MASK>
if (exchangeHandler != null) {
response = new HttpMessageResponseWrapper((HttpServletResponse) response);
}
// Let the request continue
chain.doFilter(request, response);
// Forward to the exchange handler
if (exchangeHandler != null) {
// Filtering HTTP requests only for registering exchanges
if (request instanceof HttpServletRequest) {
try {
exchangeHandler.handleExchange((HttpServletRequest) request, (HttpServletResponse) response);
} catch (Exception e) {
logger.error("An error occurred during the exchange handling", e);
}
}
}
}" |
Inversion-Mutation | megadiff | "public void printStackTrace(PrintStream pStream) {
super.printStackTrace(pStream);
if (linkedException != null) {
pStream.println("Caused by:");
linkedException.printStackTrace(pStream);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "printStackTrace" | "public void printStackTrace(PrintStream pStream) {
super.printStackTrace(pStream);
if (linkedException != null) {
pStream.println("Caused by:");
}
<MASK>linkedException.printStackTrace(pStream);</MASK>
}" |
Inversion-Mutation | megadiff | "public void addImplicitConstraints(CADShapeEnum cse, boolean recursive)
{
for (Iterator it = discrete.iterator(); it.hasNext(); )
{
BDiscretization discr = (BDiscretization) it.next();
Iterator itc;
if (recursive)
itc = shapesExplorer(cse);
else
itc = shapesIterator();
while (itc.hasNext())
{
BCADGraphCell child = (BCADGraphCell) itc.next();
if (!recursive && child.getType() != cse)
continue;
boolean allIntersectionsEmpty = false;
BDiscretization discrChild = null;
for (Iterator itd = child.discrete.iterator(); itd.hasNext(); )
{
discrChild = (BDiscretization) itd.next();
if (!discr.emptyIntersection(discrChild))
break;
discrChild = null;
}
if (discrChild == null)
{
discrChild = new BDiscretization(child, null);
child.discrete.add(discrChild);
allIntersectionsEmpty = true;
}
discrChild.combineConstraint(discr);
discrChild.addAllSubMeshes(discr);
if (!allIntersectionsEmpty)
{
for (Iterator itd = child.discrete.iterator(); itd.hasNext(); )
{
BDiscretization otherDiscrChild = (BDiscretization) itd.next();
if ((otherDiscrChild != discrChild) &&
(!discrChild.emptyIntersection(otherDiscrChild)))
{
discrChild.combineConstraint(otherDiscrChild);
discrChild.addAllSubMeshes(otherDiscrChild);
itd.remove();
}
}
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addImplicitConstraints" | "public void addImplicitConstraints(CADShapeEnum cse, boolean recursive)
{
for (Iterator it = discrete.iterator(); it.hasNext(); )
{
BDiscretization discr = (BDiscretization) it.next();
Iterator itc;
if (recursive)
itc = shapesExplorer(cse);
else
itc = shapesIterator();
while (itc.hasNext())
{
BCADGraphCell child = (BCADGraphCell) itc.next();
if (!recursive && child.getType() != cse)
continue;
boolean allIntersectionsEmpty = false;
BDiscretization discrChild = null;
for (Iterator itd = child.discrete.iterator(); itd.hasNext(); )
{
discrChild = (BDiscretization) itd.next();
if (!discr.emptyIntersection(discrChild))
break;
discrChild = null;
<MASK>allIntersectionsEmpty = true;</MASK>
}
if (discrChild == null)
{
discrChild = new BDiscretization(child, null);
child.discrete.add(discrChild);
}
discrChild.combineConstraint(discr);
discrChild.addAllSubMeshes(discr);
if (!allIntersectionsEmpty)
{
for (Iterator itd = child.discrete.iterator(); itd.hasNext(); )
{
BDiscretization otherDiscrChild = (BDiscretization) itd.next();
if ((otherDiscrChild != discrChild) &&
(!discrChild.emptyIntersection(otherDiscrChild)))
{
discrChild.combineConstraint(otherDiscrChild);
discrChild.addAllSubMeshes(otherDiscrChild);
itd.remove();
}
}
}
}
}
}" |
Inversion-Mutation | megadiff | "private void runHand(GameIDGenerator gameIDGenerator, PublicGameInfo gameInfo, Level blindsLevel) {
gameInfo.setBlinds(blindsLevel.getSmallBlindAmount(), blindsLevel.getBigBlindAmount());
gameInfo.setGameID(gameIDGenerator.getNextGameID());
Dealer dealer = dealers.get(gameInfo);
dealer.playHand();
removeSittingOutPlayers(gameInfo);
dealer.moveButton();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runHand" | "private void runHand(GameIDGenerator gameIDGenerator, PublicGameInfo gameInfo, Level blindsLevel) {
gameInfo.setBlinds(blindsLevel.getSmallBlindAmount(), blindsLevel.getBigBlindAmount());
gameInfo.setGameID(gameIDGenerator.getNextGameID());
Dealer dealer = dealers.get(gameInfo);
dealer.playHand();
<MASK>dealer.moveButton();</MASK>
removeSittingOutPlayers(gameInfo);
}" |
Inversion-Mutation | megadiff | "@SuppressWarnings("nls")
public ScannerConfigPlugin() {
if (IS_MS_WINDOWS) {
System.loadLibrary("OpenThreadsWin32");
System.loadLibrary("opencv_core248");
System.loadLibrary("opencv_highgui248");
System.loadLibrary("opencv_imgproc248");
System.loadLibrary("dmscanlib");
} else if (IS_LINUX && IS_ARCH_64_BIT) {
System.loadLibrary("dmscanlib64");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ScannerConfigPlugin" | "@SuppressWarnings("nls")
public ScannerConfigPlugin() {
if (IS_MS_WINDOWS) {
System.loadLibrary("OpenThreadsWin32");
<MASK>System.loadLibrary("dmscanlib");</MASK>
System.loadLibrary("opencv_core248");
System.loadLibrary("opencv_highgui248");
System.loadLibrary("opencv_imgproc248");
} else if (IS_LINUX && IS_ARCH_64_BIT) {
System.loadLibrary("dmscanlib64");
}
}" |
Inversion-Mutation | megadiff | "public void beginRequest(HttpServletRequest request)
{
BeanMap beanMap = new SimpleBeanMap();
request.setAttribute(REQUEST_ATTRIBUTE_NAME, beanMap);
super.beginRequest(request.getRequestURI(), beanMap);
restoreSessionContext(request.getSession());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "beginRequest" | "public void beginRequest(HttpServletRequest request)
{
<MASK>restoreSessionContext(request.getSession());</MASK>
BeanMap beanMap = new SimpleBeanMap();
request.setAttribute(REQUEST_ATTRIBUTE_NAME, beanMap);
super.beginRequest(request.getRequestURI(), beanMap);
}" |
Inversion-Mutation | megadiff | "private void addTemporaryWallpaperTile(Uri uri) {
mTempWallpaperTiles.add(uri);
// Add a tile for the image picked from Gallery
FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_item, mWallpapersView, false);
setWallpaperItemPaddingToZero(pickedImageThumbnail);
// Load the thumbnail
ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image);
Point defaultSize = getDefaultThumbnailSize(this.getResources());
Bitmap thumb = createThumbnail(defaultSize, this, uri, null, null, 0, false);
if (thumb != null) {
image.setImageBitmap(thumb);
Drawable thumbDrawable = image.getDrawable();
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error loading thumbnail for uri=" + uri);
}
mWallpapersView.addView(pickedImageThumbnail, 0);
UriWallpaperInfo info = new UriWallpaperInfo(uri);
pickedImageThumbnail.setTag(info);
info.setView(pickedImageThumbnail);
updateTileIndices();
pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener);
mThumbnailOnClickListener.onClick(pickedImageThumbnail);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addTemporaryWallpaperTile" | "private void addTemporaryWallpaperTile(Uri uri) {
mTempWallpaperTiles.add(uri);
// Add a tile for the image picked from Gallery
FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_item, mWallpapersView, false);
setWallpaperItemPaddingToZero(pickedImageThumbnail);
// Load the thumbnail
ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image);
Point defaultSize = getDefaultThumbnailSize(this.getResources());
Bitmap thumb = createThumbnail(defaultSize, this, uri, null, null, 0, false);
if (thumb != null) {
image.setImageBitmap(thumb);
Drawable thumbDrawable = image.getDrawable();
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error loading thumbnail for uri=" + uri);
}
mWallpapersView.addView(pickedImageThumbnail, 0);
<MASK>updateTileIndices();</MASK>
UriWallpaperInfo info = new UriWallpaperInfo(uri);
pickedImageThumbnail.setTag(info);
info.setView(pickedImageThumbnail);
pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener);
mThumbnailOnClickListener.onClick(pickedImageThumbnail);
}" |
Inversion-Mutation | megadiff | "public void updateStations() {
if (eavdamMenu == null || eavdamMenu.getShowOnMapMenu() == null) {
return;
}
data = DBHandler.getData();
if (data != null) {
Options options = OptionsMenuItem.loadOptions();
//currentIcons = options.getIconsSize();
graphics.clear();
transmitCoverageLayer.getGraphicsList().clear();
receiveCoverageLayer.getGraphicsList().clear();
interferenceCoverageLayer.getGraphicsList().clear();
if (eavdamMenu.getShowOnMapMenu().getOwnOperativeStationsMenuItem().isSelected() || eavdamMenu.getShowOnMapMenu().getOwnPlannedStationsMenuItem().isSelected()) {
List<ActiveStation> activeStations = data.getActiveStations();
if (activeStations != null) {
for (ActiveStation as : activeStations) {
if (as.getStations() != null) {
for (AISFixedStationData stationData : as.getStations()) {
if (stationData.getStatus().getStatusID() == DerbyDBInterface.STATUS_ACTIVE &&
eavdamMenu.getShowOnMapMenu().getOwnOperativeStationsMenuItem().isSelected()) {
this.addBaseStation(null, stationData);
}
if (stationData.getStatus().getStatusID() == DerbyDBInterface.STATUS_PLANNED &&
eavdamMenu.getShowOnMapMenu().getOwnPlannedStationsMenuItem().isSelected()) {
this.addBaseStation(null, stationData);
}
}
}
}
}
}
if (eavdamMenu.getShowOnMapMenu().getSimulationMenuItems() != null) {
for (JCheckBoxMenuItem simulationMenuItem : eavdamMenu.getShowOnMapMenu().getSimulationMenuItems()) {
if (simulationMenuItem.isSelected()) {
String temp = StationInformationMenuItem.SIMULATION_LABEL + ": ";
String selectedSimulation = simulationMenuItem.getText().substring(temp.length());
if (data.getSimulatedStations() != null) {
for (Simulation s : data.getSimulatedStations()) {
if (s.getName().equals(selectedSimulation)) {
List<AISFixedStationData> stations = s.getStations();
for (AISFixedStationData stationData : stations) {
this.addBaseStation(s.getName(), stationData);
}
break;
}
}
}
}
}
}
if (eavdamMenu.getShowOnMapMenu().getOtherUsersStationsMenuItems() != null) {
for (JCheckBoxMenuItem otherUsersStationsMenuItem : eavdamMenu.getShowOnMapMenu().getOtherUsersStationsMenuItems()) {
if (otherUsersStationsMenuItem.isSelected()) {
String temp = StationInformationMenuItem.STATIONS_OF_ORGANIZATION_LABEL + " ";
String selectedOtherUser = otherUsersStationsMenuItem.getText().substring(temp.length());
if (data.getOtherUsersStations() != null) {
for (OtherUserStations ous : data.getOtherUsersStations()) {
EAVDAMUser user = ous.getUser();
if (user.getOrganizationName().equals(selectedOtherUser)) {
List<ActiveStation> activeStations = ous.getStations();
for (ActiveStation as : activeStations) {
List<AISFixedStationData> stations = as.getStations();
for (AISFixedStationData station : stations) {
if (station.getStatus().getStatusID() == DerbyDBInterface.STATUS_ACTIVE) {
this.addBaseStation(user, station);
}
}
}
break;
}
}
}
}
}
}
this.repaint();
this.validate();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateStations" | "public void updateStations() {
if (eavdamMenu == null || eavdamMenu.getShowOnMapMenu() == null) {
return;
}
data = DBHandler.getData();
if (data != null) {
Options options = OptionsMenuItem.loadOptions();
//currentIcons = options.getIconsSize();
graphics.clear();
transmitCoverageLayer.getGraphicsList().clear();
receiveCoverageLayer.getGraphicsList().clear();
interferenceCoverageLayer.getGraphicsList().clear();
if (eavdamMenu.getShowOnMapMenu().getOwnOperativeStationsMenuItem().isSelected() || eavdamMenu.getShowOnMapMenu().getOwnPlannedStationsMenuItem().isSelected()) {
List<ActiveStation> activeStations = data.getActiveStations();
if (activeStations != null) {
for (ActiveStation as : activeStations) {
if (as.getStations() != null) {
for (AISFixedStationData stationData : as.getStations()) {
if (stationData.getStatus().getStatusID() == DerbyDBInterface.STATUS_ACTIVE &&
eavdamMenu.getShowOnMapMenu().getOwnOperativeStationsMenuItem().isSelected()) {
this.addBaseStation(null, stationData);
}
if (stationData.getStatus().getStatusID() == DerbyDBInterface.STATUS_PLANNED &&
eavdamMenu.getShowOnMapMenu().getOwnPlannedStationsMenuItem().isSelected()) {
this.addBaseStation(null, stationData);
}
}
}
}
}
}
if (eavdamMenu.getShowOnMapMenu().getSimulationMenuItems() != null) {
for (JCheckBoxMenuItem simulationMenuItem : eavdamMenu.getShowOnMapMenu().getSimulationMenuItems()) {
if (simulationMenuItem.isSelected()) {
String temp = StationInformationMenuItem.SIMULATION_LABEL + ": ";
String selectedSimulation = simulationMenuItem.getText().substring(temp.length());
if (data.getSimulatedStations() != null) {
for (Simulation s : data.getSimulatedStations()) {
if (s.getName().equals(selectedSimulation)) {
List<AISFixedStationData> stations = s.getStations();
for (AISFixedStationData stationData : stations) {
this.addBaseStation(s.getName(), stationData);
}
<MASK>break;</MASK>
}
}
}
}
}
}
if (eavdamMenu.getShowOnMapMenu().getOtherUsersStationsMenuItems() != null) {
for (JCheckBoxMenuItem otherUsersStationsMenuItem : eavdamMenu.getShowOnMapMenu().getOtherUsersStationsMenuItems()) {
if (otherUsersStationsMenuItem.isSelected()) {
String temp = StationInformationMenuItem.STATIONS_OF_ORGANIZATION_LABEL + " ";
String selectedOtherUser = otherUsersStationsMenuItem.getText().substring(temp.length());
if (data.getOtherUsersStations() != null) {
for (OtherUserStations ous : data.getOtherUsersStations()) {
EAVDAMUser user = ous.getUser();
if (user.getOrganizationName().equals(selectedOtherUser)) {
List<ActiveStation> activeStations = ous.getStations();
for (ActiveStation as : activeStations) {
List<AISFixedStationData> stations = as.getStations();
for (AISFixedStationData station : stations) {
if (station.getStatus().getStatusID() == DerbyDBInterface.STATUS_ACTIVE) {
this.addBaseStation(user, station);
}
}
}
}
<MASK>break;</MASK>
}
}
}
}
}
this.repaint();
this.validate();
}
}" |
Inversion-Mutation | megadiff | "public boolean hasSideEffects()
{
switch (type) {
case Token.EXPR_VOID:
case Token.COMMA:
if (last != null)
return last.hasSideEffects();
else
return true;
case Token.HOOK:
if (first == null ||
first.next == null ||
first.next.next == null)
Kit.codeBug();
return first.next.hasSideEffects() &&
first.next.next.hasSideEffects();
case Token.ERROR: // Avoid cascaded error messages
case Token.EXPR_RESULT:
case Token.ASSIGN:
case Token.ASSIGN_ADD:
case Token.ASSIGN_SUB:
case Token.ASSIGN_MUL:
case Token.ASSIGN_DIV:
case Token.ASSIGN_MOD:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_LSH:
case Token.ASSIGN_RSH:
case Token.ASSIGN_URSH:
case Token.ENTERWITH:
case Token.LEAVEWITH:
case Token.RETURN:
case Token.GOTO:
case Token.IFEQ:
case Token.IFNE:
case Token.NEW:
case Token.DELPROP:
case Token.SETNAME:
case Token.SETPROP:
case Token.SETELEM:
case Token.CALL:
case Token.THROW:
case Token.RETHROW:
case Token.SETVAR:
case Token.CATCH_SCOPE:
case Token.RETURN_RESULT:
case Token.SET_REF:
case Token.DEL_REF:
case Token.REF_CALL:
case Token.TRY:
case Token.SEMI:
case Token.INC:
case Token.DEC:
case Token.EXPORT:
case Token.IMPORT:
case Token.IF:
case Token.ELSE:
case Token.SWITCH:
case Token.WHILE:
case Token.DO:
case Token.FOR:
case Token.BREAK:
case Token.CONTINUE:
case Token.VAR:
case Token.CONST:
case Token.WITH:
case Token.CATCH:
case Token.FINALLY:
case Token.BLOCK:
case Token.LABEL:
case Token.TARGET:
case Token.LOOP:
case Token.JSR:
case Token.SETPROP_OP:
case Token.SETELEM_OP:
case Token.LOCAL_BLOCK:
case Token.SET_REF_OP:
case Token.YIELD:
return true;
default:
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hasSideEffects" | "public boolean hasSideEffects()
{
switch (type) {
case Token.EXPR_VOID:
<MASK>case Token.EXPR_RESULT:</MASK>
case Token.COMMA:
if (last != null)
return last.hasSideEffects();
else
return true;
case Token.HOOK:
if (first == null ||
first.next == null ||
first.next.next == null)
Kit.codeBug();
return first.next.hasSideEffects() &&
first.next.next.hasSideEffects();
case Token.ERROR: // Avoid cascaded error messages
case Token.ASSIGN:
case Token.ASSIGN_ADD:
case Token.ASSIGN_SUB:
case Token.ASSIGN_MUL:
case Token.ASSIGN_DIV:
case Token.ASSIGN_MOD:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_LSH:
case Token.ASSIGN_RSH:
case Token.ASSIGN_URSH:
case Token.ENTERWITH:
case Token.LEAVEWITH:
case Token.RETURN:
case Token.GOTO:
case Token.IFEQ:
case Token.IFNE:
case Token.NEW:
case Token.DELPROP:
case Token.SETNAME:
case Token.SETPROP:
case Token.SETELEM:
case Token.CALL:
case Token.THROW:
case Token.RETHROW:
case Token.SETVAR:
case Token.CATCH_SCOPE:
case Token.RETURN_RESULT:
case Token.SET_REF:
case Token.DEL_REF:
case Token.REF_CALL:
case Token.TRY:
case Token.SEMI:
case Token.INC:
case Token.DEC:
case Token.EXPORT:
case Token.IMPORT:
case Token.IF:
case Token.ELSE:
case Token.SWITCH:
case Token.WHILE:
case Token.DO:
case Token.FOR:
case Token.BREAK:
case Token.CONTINUE:
case Token.VAR:
case Token.CONST:
case Token.WITH:
case Token.CATCH:
case Token.FINALLY:
case Token.BLOCK:
case Token.LABEL:
case Token.TARGET:
case Token.LOOP:
case Token.JSR:
case Token.SETPROP_OP:
case Token.SETELEM_OP:
case Token.LOCAL_BLOCK:
case Token.SET_REF_OP:
case Token.YIELD:
return true;
default:
return false;
}
}" |
Inversion-Mutation | megadiff | "@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
context.getSession().quit();
context.sendResponse("221 Bye");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute" | "@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
<MASK>context.sendResponse("221 Bye");</MASK>
context.getSession().quit();
}" |
Inversion-Mutation | megadiff | "public FitSphere(final Vector3D[] points) {
Vector3D mean = Vector3D.ZERO;
for(Vector3D point : points)
mean = mean.add(point.scalarMultiply(1D/(double)points.length));
ReportingUtils.logMessage("MEAN: " + mean.toString());
final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ());
double[] params = new double[PARAMLEN];
params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm();
Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS]));
params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ();
double[] steps = new double[PARAMLEN];
steps[XC] = steps[YC] = steps[ZC] = 0.001;
steps[RADIUS] = 0.00001;
ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps));
MultivariateRealFunction MRF = new MultivariateRealFunction() {
@Override
public double value(double[] params) {
Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]);
double err = 0;
for(Vector3D point : points)
err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D);
// ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err);
return err;
}
};
SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1);
NelderMeadSimplex nm = new NelderMeadSimplex(steps);
opt.setSimplex(nm);
double[] result = null;
try {
result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint();
error = Math.sqrt(MRF.value(result));
} catch(Throwable t) {
ReportingUtils.logError(t, "Optimization failed!");
}
ReportingUtils.logMessage("Fit: " + Arrays.toString(result));
center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean);
radius = result[RADIUS];
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "FitSphere" | "public FitSphere(final Vector3D[] points) {
Vector3D mean = Vector3D.ZERO;
for(Vector3D point : points)
mean = mean.add(point.scalarMultiply(1D/(double)points.length));
ReportingUtils.logMessage("MEAN: " + mean.toString());
final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ());
double[] params = new double[PARAMLEN];
params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm();
Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS]));
params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ();
double[] steps = new double[PARAMLEN];
steps[XC] = steps[YC] = steps[ZC] = 0.001;
steps[RADIUS] = 0.00001;
ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps));
MultivariateRealFunction MRF = new MultivariateRealFunction() {
@Override
public double value(double[] params) {
Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]);
double err = 0;
for(Vector3D point : points)
err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D);
// ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err);
return err;
}
};
SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1);
NelderMeadSimplex nm = new NelderMeadSimplex(steps);
opt.setSimplex(nm);
double[] result = null;
try {
result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint();
} catch(Throwable t) {
ReportingUtils.logError(t, "Optimization failed!");
}
ReportingUtils.logMessage("Fit: " + Arrays.toString(result));
center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean);
radius = result[RADIUS];
<MASK>error = Math.sqrt(MRF.value(result));</MASK>
}" |
Inversion-Mutation | megadiff | "@Test
public void testCanRemove() {
assertTrue(productGroup1.canRemove());
assertTrue(storageUnit1.canRemove());
productGroup1.add(productGroup2);
productGroup2.add(product1);
storageUnit1.add(productGroup1);
storageUnit1.add(item1);
assertFalse(productGroup1.canRemove());
assertFalse(storageUnit1.canRemove());
productGroup2.remove(item1, itemManager);
assertTrue(productGroup1.canRemove());
assertTrue(storageUnit1.canRemove());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testCanRemove" | "@Test
public void testCanRemove() {
assertTrue(productGroup1.canRemove());
assertTrue(storageUnit1.canRemove());
productGroup1.add(productGroup2);
productGroup2.add(product1);
<MASK>storageUnit1.add(item1);</MASK>
storageUnit1.add(productGroup1);
assertFalse(productGroup1.canRemove());
assertFalse(storageUnit1.canRemove());
productGroup2.remove(item1, itemManager);
assertTrue(productGroup1.canRemove());
assertTrue(storageUnit1.canRemove());
}" |
Inversion-Mutation | megadiff | "public ModelAndView populateContentModel(HttpServletRequest request) {
for (int i = 0; i < modelBuilders.length; i++) {
ModelBuilder modelBuilder = modelBuilders[i];
if (modelBuilder.isValid(request)) {
logger.info("Using " + modelBuilder.getClass().getName() + " to serve path: " + request.getPathInfo());
ModelAndView mv = modelBuilder.populateContentModel(request);
final String path = request.getPathInfo();
if (path.endsWith("/rss")) {
logger.info("Selecting rss view for path: " + path);
mv.setView(rssViewFactory.makeView());
return mv;
}
if (path.endsWith("/json")) {
logger.info("Selecting json view for path: " + path);
mv.setView(jsonViewFactory.makeView());
populateJsonCallback(request, mv);
return mv;
}
if (mv != null) {
modelBuilder.populateExtraModelConent(request, mv);
mv.setViewName(modelBuilder.getViewName(mv));
addCommonModelElements(mv);
return mv;
}
return null;
}
}
logger.warn("No matching model builders found for path: " + request.getPathInfo());
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "populateContentModel" | "public ModelAndView populateContentModel(HttpServletRequest request) {
for (int i = 0; i < modelBuilders.length; i++) {
ModelBuilder modelBuilder = modelBuilders[i];
if (modelBuilder.isValid(request)) {
logger.info("Using " + modelBuilder.getClass().getName() + " to serve path: " + request.getPathInfo());
ModelAndView mv = modelBuilder.populateContentModel(request);
final String path = request.getPathInfo();
if (path.endsWith("/rss")) {
logger.info("Selecting rss view for path: " + path);
mv.setView(rssViewFactory.makeView());
return mv;
}
if (path.endsWith("/json")) {
logger.info("Selecting json view for path: " + path);
mv.setView(jsonViewFactory.makeView());
populateJsonCallback(request, mv);
return mv;
}
if (mv != null) {
<MASK>mv.setViewName(modelBuilder.getViewName(mv));</MASK>
modelBuilder.populateExtraModelConent(request, mv);
addCommonModelElements(mv);
return mv;
}
return null;
}
}
logger.warn("No matching model builders found for path: " + request.getPathInfo());
return null;
}" |
Inversion-Mutation | megadiff | "public void createSession() {
Configuration configuration = new Configuration();
configuration.configure();
Properties prop = new Properties();
try {
prop.load(new FileInputStream("trademarket.props"));
} catch (FileNotFoundException e) {
prop.put("hibernate.connection.username", "root");
prop.put("hibernate.connection.url", "jdbc:mysql://localhost/trademarket");
prop.put("hibernate.connection.password", "");
System.out.println("Config file not found - using defaults");
} catch (IOException e) {
e.printStackTrace();
}
configuration.addProperties(prop);
SessionFactory sessionFactory = configuration.buildSessionFactory();
session = sessionFactory.openSession();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createSession" | "public void createSession() {
Configuration configuration = new Configuration();
configuration.configure();
Properties prop = new Properties();
try {
prop.load(new FileInputStream("trademarket.props"));
} catch (FileNotFoundException e) {
prop.put("hibernate.connection.username", "root");
prop.put("hibernate.connection.url", "jdbc:mysql://localhost/trademarket");
prop.put("hibernate.connection.password", "");
System.out.println("Config file not found - using defaults");
<MASK>configuration.addProperties(prop);</MASK>
} catch (IOException e) {
e.printStackTrace();
}
SessionFactory sessionFactory = configuration.buildSessionFactory();
session = sessionFactory.openSession();
}" |
Inversion-Mutation | megadiff | "public void actionPerformed(ActionEvent e)
{
String command;
Debug.println("Got action: " + e.getActionCommand());
if(e.getSource() == lObjView){
if(e.getActionCommand().equals("Done")){
lObjView.close();
remove(lObjView);
add(me);
}
} else if(e.getSource() == viewMenu){
if(e.getActionCommand().equals("Paging View")){
dict.viewType = dict.PAGING_VIEW;
if(container != null){
container.reload(this);
}
}
} else if(e.getSource() == editMenu){
if(e.getActionCommand().equals("Rename...")){
TreeNode selObj = treeControl.getSelected();
String [] buttons = {"Cancel", "Ok"};
if(selObj != null){
if(selObj.toString().equals("..empty..")) return;
rnDialog = Dialog.showInputDialog(this, "Rename Object", "Old Name was " + selObj.toString(),
buttons,Dialog.EDIT_INP_DIALOG);
} else {
rnDialog = Dialog.showInputDialog(this, "Rename Parent", "Old Name was " + dict.name,
buttons,Dialog.EDIT_INP_DIALOG);
}
} else if(e.getActionCommand().equals("Toggle hidden")){
LObjDictionary.globalHide = !LObjDictionary.globalHide;
if(container != null) container.reload(this);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed" | "public void actionPerformed(ActionEvent e)
{
String command;
Debug.println("Got action: " + e.getActionCommand());
if(e.getSource() == lObjView){
if(e.getActionCommand().equals("Done")){
lObjView.close();
remove(lObjView);
add(me);
}
} else if(e.getSource() == viewMenu){
if(e.getActionCommand().equals("Paging View")){
dict.viewType = dict.PAGING_VIEW;
if(container != null){
container.reload(this);
}
}
} else if(e.getSource() == editMenu){
if(e.getActionCommand().equals("Rename...")){
TreeNode selObj = treeControl.getSelected();
<MASK>if(selObj.toString().equals("..empty..")) return;</MASK>
String [] buttons = {"Cancel", "Ok"};
if(selObj != null){
rnDialog = Dialog.showInputDialog(this, "Rename Object", "Old Name was " + selObj.toString(),
buttons,Dialog.EDIT_INP_DIALOG);
} else {
rnDialog = Dialog.showInputDialog(this, "Rename Parent", "Old Name was " + dict.name,
buttons,Dialog.EDIT_INP_DIALOG);
}
} else if(e.getActionCommand().equals("Toggle hidden")){
LObjDictionary.globalHide = !LObjDictionary.globalHide;
if(container != null) container.reload(this);
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public User createFromParcel(Parcel source) {
int id = source.readInt();
String name = source.readString();
String area = source.readString();
return new User(name, area, id);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createFromParcel" | "@Override
public User createFromParcel(Parcel source) {
int id = source.readInt();
<MASK>String area = source.readString();</MASK>
String name = source.readString();
return new User(name, area, id);
}" |
Inversion-Mutation | megadiff | "public static boolean saveUserData() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document userList = docBuilder.newDocument();
Element rootElement = userList.createElement("userList");
userList.appendChild(rootElement);
for (int i = 0; i < uList.size(); i++) {
Element user = userList.createElement("user");
rootElement.appendChild(user);
Element userName = userList.createElement("userName");
userName.appendChild(userList.createTextNode(uList.get(i).getUserName()));
user.appendChild(userName);
Element balance = userList.createElement("balance");
balance.appendChild(userList.createTextNode(Double.toString(uList.get(i).getBalance())));
user.appendChild(balance);
Element userStockList = userList.createElement("stockList");
user.appendChild(userStockList);
for (int j = 0; j < uList.get(i).getStockListofUser().size(); j++) {
Element stockExchange = userList.createElement("stockExchange");
userStockList.appendChild(stockExchange);
Element ticker_name = userList.createElement("ticker_name");
ticker_name.appendChild(userList.createTextNode(uList.get(i).getStockListofUser().get(j).getTickerName()));
stockExchange.appendChild(ticker_name);
Element price = userList.createElement("price");
price.appendChild(userList.createTextNode(Double.toString(uList.get(i).getStockListofUser().get(j).getPrice())));
stockExchange.appendChild(price);
Element share = userList.createElement("share");
share.appendChild(userList.createTextNode(Integer.toString(uList.get(i).getStockListofUser().get(j).getShare())));
stockExchange.appendChild(share);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(userList);
StreamResult result = new StreamResult(new File("src/com/data/userData111.xml"));
transformer.transform(source, result);
return true;
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
return false;
} catch (TransformerException tfe) {
tfe.printStackTrace();
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveUserData" | "public static boolean saveUserData() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document userList = docBuilder.newDocument();
Element rootElement = userList.createElement("userList");
userList.appendChild(rootElement);
for (int i = 0; i < uList.size(); i++) {
Element user = userList.createElement("user");
rootElement.appendChild(user);
Element userName = userList.createElement("userName");
userName.appendChild(userList.createTextNode(uList.get(i).getUserName()));
user.appendChild(userName);
Element balance = userList.createElement("balance");
balance.appendChild(userList.createTextNode(Double.toString(uList.get(i).getBalance())));
user.appendChild(balance);
Element userStockList = userList.createElement("stockList");
user.appendChild(userStockList);
<MASK>Element stockExchange = userList.createElement("stockExchange");</MASK>
for (int j = 0; j < uList.get(i).getStockListofUser().size(); j++) {
userStockList.appendChild(stockExchange);
Element ticker_name = userList.createElement("ticker_name");
ticker_name.appendChild(userList.createTextNode(uList.get(i).getStockListofUser().get(j).getTickerName()));
stockExchange.appendChild(ticker_name);
Element price = userList.createElement("price");
price.appendChild(userList.createTextNode(Double.toString(uList.get(i).getStockListofUser().get(j).getPrice())));
stockExchange.appendChild(price);
Element share = userList.createElement("share");
share.appendChild(userList.createTextNode(Integer.toString(uList.get(i).getStockListofUser().get(j).getShare())));
stockExchange.appendChild(share);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(userList);
StreamResult result = new StreamResult(new File("src/com/data/userData111.xml"));
transformer.transform(source, result);
return true;
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
return false;
} catch (TransformerException tfe) {
tfe.printStackTrace();
return false;
}
}" |
Inversion-Mutation | megadiff | "private void serializeEvent(DataOutput out) throws IOException {
if (event == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
out.writeInt(eventType.ordinal());
if (eventType.equals(EventType.TASK_STATUS_UPDATE_EVENT)) {
// TODO NEWTEZ convert to PB
TaskStatusUpdateEvent sEvt = (TaskStatusUpdateEvent) event;
sEvt.write(out);
} else {
byte[] eventBytes = null;
switch (eventType) {
case DATA_MOVEMENT_EVENT:
DataMovementEvent dmEvt = (DataMovementEvent) event;
eventBytes = DataMovementEventProto.newBuilder()
.setSourceIndex(dmEvt.getSourceIndex())
.setTargetIndex(dmEvt.getTargetIndex())
.setUserPayload(ByteString.copyFrom(dmEvt.getUserPayload()))
.build().toByteArray();
break;
case INPUT_READ_ERROR_EVENT:
InputReadErrorEvent ideEvt = (InputReadErrorEvent) event;
eventBytes = InputReadErrorEventProto.newBuilder()
.setIndex(ideEvt.getIndex())
.setDiagnostics(ideEvt.getDiagnostics())
.build().toByteArray();
break;
case TASK_ATTEMPT_FAILED_EVENT:
TaskAttemptFailedEvent tfEvt = (TaskAttemptFailedEvent) event;
eventBytes = TaskAttemptFailedEventProto.newBuilder()
.setDiagnostics(tfEvt.getDiagnostics())
.build().toByteArray();
break;
case TASK_ATTEMPT_COMPLETED_EVENT:
eventBytes = TaskAttemptCompletedEventProto.newBuilder()
.build().toByteArray();
break;
case INPUT_FAILED_EVENT:
InputFailedEvent ifEvt = (InputFailedEvent) event;
eventBytes = InputFailedEventProto.newBuilder()
.setSourceIndex(ifEvt.getSourceIndex())
.setTargetIndex(ifEvt.getTargetIndex())
.setVersion(ifEvt.getVersion()).build().toByteArray();
case INTPUT_INFORMATION_EVENT:
InputInformationEvent iEvt = (InputInformationEvent) event;
eventBytes = InputInformationEventProto.newBuilder()
.setUserPayload(ByteString.copyFrom(iEvt.getUserPayload()))
.build().toByteArray();
default:
throw new TezUncheckedException("Unknown TezEvent"
+ ", type=" + eventType);
}
out.writeInt(eventBytes.length);
out.write(eventBytes);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "serializeEvent" | "private void serializeEvent(DataOutput out) throws IOException {
if (event == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if (eventType.equals(EventType.TASK_STATUS_UPDATE_EVENT)) {
// TODO NEWTEZ convert to PB
TaskStatusUpdateEvent sEvt = (TaskStatusUpdateEvent) event;
sEvt.write(out);
} else {
byte[] eventBytes = null;
switch (eventType) {
case DATA_MOVEMENT_EVENT:
DataMovementEvent dmEvt = (DataMovementEvent) event;
eventBytes = DataMovementEventProto.newBuilder()
.setSourceIndex(dmEvt.getSourceIndex())
.setTargetIndex(dmEvt.getTargetIndex())
.setUserPayload(ByteString.copyFrom(dmEvt.getUserPayload()))
.build().toByteArray();
break;
case INPUT_READ_ERROR_EVENT:
InputReadErrorEvent ideEvt = (InputReadErrorEvent) event;
eventBytes = InputReadErrorEventProto.newBuilder()
.setIndex(ideEvt.getIndex())
.setDiagnostics(ideEvt.getDiagnostics())
.build().toByteArray();
break;
case TASK_ATTEMPT_FAILED_EVENT:
TaskAttemptFailedEvent tfEvt = (TaskAttemptFailedEvent) event;
eventBytes = TaskAttemptFailedEventProto.newBuilder()
.setDiagnostics(tfEvt.getDiagnostics())
.build().toByteArray();
break;
case TASK_ATTEMPT_COMPLETED_EVENT:
eventBytes = TaskAttemptCompletedEventProto.newBuilder()
.build().toByteArray();
break;
case INPUT_FAILED_EVENT:
InputFailedEvent ifEvt = (InputFailedEvent) event;
eventBytes = InputFailedEventProto.newBuilder()
.setSourceIndex(ifEvt.getSourceIndex())
.setTargetIndex(ifEvt.getTargetIndex())
.setVersion(ifEvt.getVersion()).build().toByteArray();
case INTPUT_INFORMATION_EVENT:
InputInformationEvent iEvt = (InputInformationEvent) event;
eventBytes = InputInformationEventProto.newBuilder()
.setUserPayload(ByteString.copyFrom(iEvt.getUserPayload()))
.build().toByteArray();
default:
throw new TezUncheckedException("Unknown TezEvent"
+ ", type=" + eventType);
}
<MASK>out.writeInt(eventType.ordinal());</MASK>
out.writeInt(eventBytes.length);
out.write(eventBytes);
}
}" |
Inversion-Mutation | megadiff | "public NettyConnectionsPool(int maxTotalConnections, int maxConnectionPerHost, long maxIdleTime, boolean sslConnectionPoolEnabled, int maxConnectionLifeTimeInMs, Timer idleConnectionDetector) {
this.maxTotalConnections = maxTotalConnections;
this.maxConnectionPerHost = maxConnectionPerHost;
this.sslConnectionPoolEnabled = sslConnectionPoolEnabled;
this.maxIdleTime = maxIdleTime;
this.maxConnectionLifeTimeInMs = maxConnectionLifeTimeInMs;
this.idleConnectionDetector = idleConnectionDetector;
this.idleConnectionDetector.schedule(new IdleChannelDetector(), maxIdleTime, maxIdleTime);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "NettyConnectionsPool" | "public NettyConnectionsPool(int maxTotalConnections, int maxConnectionPerHost, long maxIdleTime, boolean sslConnectionPoolEnabled, int maxConnectionLifeTimeInMs, Timer idleConnectionDetector) {
this.maxTotalConnections = maxTotalConnections;
this.maxConnectionPerHost = maxConnectionPerHost;
this.sslConnectionPoolEnabled = sslConnectionPoolEnabled;
this.maxIdleTime = maxIdleTime;
this.maxConnectionLifeTimeInMs = maxConnectionLifeTimeInMs;
<MASK>this.idleConnectionDetector.schedule(new IdleChannelDetector(), maxIdleTime, maxIdleTime);</MASK>
this.idleConnectionDetector = idleConnectionDetector;
}" |
Inversion-Mutation | megadiff | "@Override
protected void handleUpdate(Update u) {
super.handleUpdate(u);
changed.clear();
for (Entity next : u.getUpdatedEntities()) {
if (next instanceof Building) {
Building b = (Building)next;
if (b.isBrokennessDefined()) {
// Brokenness has changed. Add some blockedness to nearby roads
// System.out.println(b + " is broken. Updating nearby roads");
for (Road r : nearbyRoads.get(b.getID())) {
int width = r.getWidth();
int block = r.getBlock();
int increase = calculateBlock(b);
// System.out.println("Increasing block of " + r + " by " + increase);
block += increase;
if (block > width) {
block = width;
}
// System.out.println("New block: " + block);
r.setBlock(block);
changed.add(r);
}
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleUpdate" | "@Override
protected void handleUpdate(Update u) {
changed.clear();
for (Entity next : u.getUpdatedEntities()) {
if (next instanceof Building) {
Building b = (Building)next;
if (b.isBrokennessDefined()) {
// Brokenness has changed. Add some blockedness to nearby roads
// System.out.println(b + " is broken. Updating nearby roads");
for (Road r : nearbyRoads.get(b.getID())) {
int width = r.getWidth();
int block = r.getBlock();
int increase = calculateBlock(b);
// System.out.println("Increasing block of " + r + " by " + increase);
block += increase;
if (block > width) {
block = width;
}
// System.out.println("New block: " + block);
r.setBlock(block);
changed.add(r);
}
}
}
}
<MASK>super.handleUpdate(u);</MASK>
}" |
Inversion-Mutation | megadiff | "@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInterract(PlayerInteractEvent event) {
SpectatorManager manager = getAPI().getSpectatorManager();
Player player = event.getPlayer();
if (manager.getSpectators().contains(player.getName())) {
manager.cycleTarget(player);
event.setCancelled(true);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPlayerInterract" | "@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInterract(PlayerInteractEvent event) {
SpectatorManager manager = getAPI().getSpectatorManager();
Player player = event.getPlayer();
if (manager.getSpectators().contains(player.getName())) {
<MASK>event.setCancelled(true);</MASK>
manager.cycleTarget(player);
}
}" |
Inversion-Mutation | megadiff | "public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
sbQuery.append("\tFILTER (");
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getMatchingURIs" | "public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
<MASK>sbQuery.append("\tFILTER (");</MASK>
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}" |
Inversion-Mutation | megadiff | "@Override
public Image getImage() {
synchronized (this) {
if (image == null) {
image = AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/brick.png").createImage();
}
return image;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getImage" | "@Override
public Image getImage() {
synchronized (this) {
if (image == null) {
image = AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/brick.png").createImage();
}
}
<MASK>return image;</MASK>
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) {
ArrayList<String> jobConfArgs = new ArrayList<String>();
String inputPathStr = null;
String outputDir = null;
try {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-input")) {
inputPathStr = args[++i];
} else if (args[i].equals("-jobconf")) {
jobConfArgs.add(args[++i]);
} else if (args[i].equals("-outputDir")) {
outputDir = args[++i];
}
}
} catch (IndexOutOfBoundsException e) {
System.err.println("Missing argument to option");
printUsage();
}
if (inputPathStr == null || outputDir == null
|| outputDir.trim().equals("")) {
printUsage();
}
List<String> inputPaths = new ArrayList<String>();
String[] paths = inputPathStr.split(INPUT_SEPERATOR);
if (paths == null || paths.length == 0) {
printUsage();
}
FileSystem fs = null;
JobConf conf = new JobConf(BlockMergeTask.class);
for (String path : paths) {
try {
Path pathObj = new Path(path);
if (fs == null) {
fs = FileSystem.get(pathObj.toUri(), conf);
}
FileStatus fstatus = fs.getFileStatus(pathObj);
if (fstatus.isDir()) {
FileStatus[] fileStatus = fs.listStatus(pathObj);
for (FileStatus st : fileStatus) {
inputPaths.add(st.getPath().toString());
}
} else {
inputPaths.add(fstatus.getPath().toString());
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
StringBuilder sb = new StringBuilder("JobConf:\n");
for (String one : jobConfArgs) {
int eqIndex = one.indexOf('=');
if (eqIndex != -1) {
try {
String key = one.substring(0, eqIndex);
String value = URLDecoder.decode(one.substring(eqIndex + 1), "UTF-8");
conf.set(key, value);
sb.append(key).append("=").append(value).append("\n");
} catch (UnsupportedEncodingException e) {
System.err.println("Unexpected error " + e.getMessage()
+ " while encoding " + one.substring(eqIndex + 1));
System.exit(3);
}
}
}
HiveConf hiveConf = new HiveConf(conf, BlockMergeTask.class);
Log LOG = LogFactory.getLog(BlockMergeTask.class.getName());
boolean isSilent = HiveConf.getBoolVar(conf,
HiveConf.ConfVars.HIVESESSIONSILENT);
LogHelper console = new LogHelper(LOG, isSilent);
// print out the location of the log file for the user so
// that it's easy to find reason for local mode execution failures
for (Appender appender : Collections
.list((Enumeration<Appender>) LogManager.getRootLogger()
.getAllAppenders())) {
if (appender instanceof FileAppender) {
console.printInfo("Execution log at: "
+ ((FileAppender) appender).getFile());
}
}
// log the list of job conf parameters for reference
LOG.info(sb.toString());
MergeWork mergeWork = new MergeWork(inputPaths, outputDir);
DriverContext driverCxt = new DriverContext();
BlockMergeTask taskExec = new BlockMergeTask();
taskExec.initialize(hiveConf, null, driverCxt);
taskExec.setWork(mergeWork);
int ret = taskExec.execute(driverCxt);
if (ret != 0) {
System.exit(2);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main" | "public static void main(String[] args) {
ArrayList<String> jobConfArgs = new ArrayList<String>();
String inputPathStr = null;
String outputDir = null;
try {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-input")) {
inputPathStr = args[++i];
} else if (args[i].equals("-jobconf")) {
jobConfArgs.add(args[++i]);
} else if (args[i].equals("-outputDir")) {
outputDir = args[++i];
}
}
} catch (IndexOutOfBoundsException e) {
System.err.println("Missing argument to option");
printUsage();
}
if (inputPathStr == null || outputDir == null
|| outputDir.trim().equals("")) {
printUsage();
}
List<String> inputPaths = new ArrayList<String>();
String[] paths = inputPathStr.split(INPUT_SEPERATOR);
if (paths == null || paths.length == 0) {
printUsage();
}
FileSystem fs = null;
JobConf conf = new JobConf(BlockMergeTask.class);
<MASK>HiveConf hiveConf = new HiveConf(conf, BlockMergeTask.class);</MASK>
for (String path : paths) {
try {
Path pathObj = new Path(path);
if (fs == null) {
fs = FileSystem.get(pathObj.toUri(), conf);
}
FileStatus fstatus = fs.getFileStatus(pathObj);
if (fstatus.isDir()) {
FileStatus[] fileStatus = fs.listStatus(pathObj);
for (FileStatus st : fileStatus) {
inputPaths.add(st.getPath().toString());
}
} else {
inputPaths.add(fstatus.getPath().toString());
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
StringBuilder sb = new StringBuilder("JobConf:\n");
for (String one : jobConfArgs) {
int eqIndex = one.indexOf('=');
if (eqIndex != -1) {
try {
String key = one.substring(0, eqIndex);
String value = URLDecoder.decode(one.substring(eqIndex + 1), "UTF-8");
conf.set(key, value);
sb.append(key).append("=").append(value).append("\n");
} catch (UnsupportedEncodingException e) {
System.err.println("Unexpected error " + e.getMessage()
+ " while encoding " + one.substring(eqIndex + 1));
System.exit(3);
}
}
}
Log LOG = LogFactory.getLog(BlockMergeTask.class.getName());
boolean isSilent = HiveConf.getBoolVar(conf,
HiveConf.ConfVars.HIVESESSIONSILENT);
LogHelper console = new LogHelper(LOG, isSilent);
// print out the location of the log file for the user so
// that it's easy to find reason for local mode execution failures
for (Appender appender : Collections
.list((Enumeration<Appender>) LogManager.getRootLogger()
.getAllAppenders())) {
if (appender instanceof FileAppender) {
console.printInfo("Execution log at: "
+ ((FileAppender) appender).getFile());
}
}
// log the list of job conf parameters for reference
LOG.info(sb.toString());
MergeWork mergeWork = new MergeWork(inputPaths, outputDir);
DriverContext driverCxt = new DriverContext();
BlockMergeTask taskExec = new BlockMergeTask();
taskExec.initialize(hiveConf, null, driverCxt);
taskExec.setWork(mergeWork);
int ret = taskExec.execute(driverCxt);
if (ret != 0) {
System.exit(2);
}
}" |
Inversion-Mutation | megadiff | "@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setDither",
args = {boolean.class}
)
public void testSetDither() {
assertConstantStateNotSet();
assertNull(mDrawableContainer.getCurrent());
mDrawableContainer.setConstantState(mDrawableContainerState);
mDrawableContainer.setDither(false);
mDrawableContainer.setDither(true);
MockDrawable dr = new MockDrawable();
addAndSelectDrawable(dr);
// call current drawable's setDither if dither is changed.
dr.reset();
mDrawableContainer.setDither(false);
assertTrue(dr.hasSetDitherCalled());
// does not call it if dither is not changed.
dr.reset();
mDrawableContainer.setDither(true);
assertTrue(dr.hasSetDitherCalled());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testSetDither" | "@TestTargetNew(
level = TestLevel.COMPLETE,
method = "setDither",
args = {boolean.class}
)
public void testSetDither() {
assertConstantStateNotSet();
assertNull(mDrawableContainer.getCurrent());
mDrawableContainer.setDither(false);
mDrawableContainer.setDither(true);
<MASK>mDrawableContainer.setConstantState(mDrawableContainerState);</MASK>
MockDrawable dr = new MockDrawable();
addAndSelectDrawable(dr);
// call current drawable's setDither if dither is changed.
dr.reset();
mDrawableContainer.setDither(false);
assertTrue(dr.hasSetDitherCalled());
// does not call it if dither is not changed.
dr.reset();
mDrawableContainer.setDither(true);
assertTrue(dr.hasSetDitherCalled());
}" |
Inversion-Mutation | megadiff | "private void decode_corbaloc (String addr)
{
String host = "127.0.0.1"; //default to localhost
short port = 2809; // default IIOP port
int major = 1;
int minor = 2; // should this be 0? should it be configurable?
String errorstr =
"Illegal IIOP protocol format in object address format: " + addr;
int sep = addr.indexOf (':');
String protocol_identifier = "";
if( sep != 0)
protocol_identifier = addr.substring( 0,sep);
if( sep + 1 == addr.length())
throw new IllegalArgumentException(errorstr);
addr = addr.substring (sep + 1);
// decode optional version number
sep = addr.indexOf( '@' );
if( sep > -1)
{
String ver_str = addr.substring(0,sep);
addr = addr.substring(sep+1);
sep = ver_str.indexOf('.');
if( sep != -1 )
{
try
{
major = Integer.parseInt(ver_str.substring(0,sep));
minor = Integer.parseInt(ver_str.substring(sep+1));
}
catch( NumberFormatException nfe )
{
throw new IllegalArgumentException(errorstr);
}
}
}
version = new org.omg.GIOP.Version ((byte)major,(byte)minor);
sep = addr.indexOf (':');
if( sep != -1 )
{
try
{
port = (short)Integer.parseInt(addr.substring(sep+1));
host = addr.substring(0, sep);
}
catch( NumberFormatException ill )
{
throw new IllegalArgumentException(errorstr);
}
}
primaryAddress = new IIOPAddress (host,port);
decode_extensions (protocol_identifier.toLowerCase());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "decode_corbaloc" | "private void decode_corbaloc (String addr)
{
String host = "127.0.0.1"; //default to localhost
short port = 2809; // default IIOP port
int major = 1;
int minor = 2; // should this be 0? should it be configurable?
String errorstr =
"Illegal IIOP protocol format in object address format: " + addr;
int sep = addr.indexOf (':');
String protocol_identifier = "";
if( sep != 0)
protocol_identifier = addr.substring( 0,sep);
if( sep + 1 == addr.length())
throw new IllegalArgumentException(errorstr);
addr = addr.substring (sep + 1);
// decode optional version number
sep = addr.indexOf( '@' );
if( sep > -1)
{
String ver_str = addr.substring(0,sep);
sep = ver_str.indexOf('.');
if( sep != -1 )
{
try
{
major = Integer.parseInt(ver_str.substring(0,sep));
minor = Integer.parseInt(ver_str.substring(sep+1));
}
catch( NumberFormatException nfe )
{
throw new IllegalArgumentException(errorstr);
}
}
<MASK>addr = addr.substring(sep+1);</MASK>
}
version = new org.omg.GIOP.Version ((byte)major,(byte)minor);
sep = addr.indexOf (':');
if( sep != -1 )
{
try
{
port = (short)Integer.parseInt(addr.substring(sep+1));
host = addr.substring(0, sep);
}
catch( NumberFormatException ill )
{
throw new IllegalArgumentException(errorstr);
}
}
primaryAddress = new IIOPAddress (host,port);
decode_extensions (protocol_identifier.toLowerCase());
}" |
Inversion-Mutation | megadiff | "@Override
protected void hideFakeTitleBar() {
if (isFakeTitleBarShowing()) {
mFakeTitleBar.setEditMode(false);
mTabBar.onHideTitleBar();
mContentView.removeView(mFakeTitleBar);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hideFakeTitleBar" | "@Override
protected void hideFakeTitleBar() {
if (isFakeTitleBarShowing()) {
mFakeTitleBar.setEditMode(false);
<MASK>mContentView.removeView(mFakeTitleBar);</MASK>
mTabBar.onHideTitleBar();
}
}" |
Inversion-Mutation | megadiff | "public String getEndpoint(HttpServletRequest request) {
Map<String, Object> map = applicationContext.getEndpointTypes();
Collection<Method> methods = new HashSet<Method>();
for(Entry<String, Object> entry: map.entrySet()) {
Collection<Method> m = Reflections.getAllMethods(entry.getValue().getClass(),
Predicates.and(
ReflectionUtils.withAnnotation(Action.class),
SherpaPredicates.withActionMappingPattern(UrlUtil.getPath(request))
)
);
methods.addAll(m);
}
method = MethodUtil.validateHttpMethods(methods.toArray(new Method[] {}), request.getMethod());
if(method != null) {
Class<?> type = method.getDeclaringClass();
if(type.isAnnotationPresent(Endpoint.class)) {
if(StringUtils.isNotEmpty(type.getAnnotation(Endpoint.class).value())) {
return type.getAnnotation(Endpoint.class).value();
}
}
return type.getSimpleName();
}
throw new SherpaEndpointNotFoundException("no endpoint for url [" + UrlUtil.getPath(request) + "]");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getEndpoint" | "public String getEndpoint(HttpServletRequest request) {
Map<String, Object> map = applicationContext.getEndpointTypes();
Collection<Method> methods = new HashSet<Method>();
for(Entry<String, Object> entry: map.entrySet()) {
Collection<Method> m = Reflections.getAllMethods(entry.getValue().getClass(),
Predicates.and(
ReflectionUtils.withAnnotation(Action.class),
SherpaPredicates.withActionMappingPattern(UrlUtil.getPath(request))
)
);
methods.addAll(m);
}
method = MethodUtil.validateHttpMethods(methods.toArray(new Method[] {}), request.getMethod());
<MASK>Class<?> type = method.getDeclaringClass();</MASK>
if(method != null) {
if(type.isAnnotationPresent(Endpoint.class)) {
if(StringUtils.isNotEmpty(type.getAnnotation(Endpoint.class).value())) {
return type.getAnnotation(Endpoint.class).value();
}
}
return type.getSimpleName();
}
throw new SherpaEndpointNotFoundException("no endpoint for url [" + UrlUtil.getPath(request) + "]");
}" |
Inversion-Mutation | megadiff | "public ClientProxy getProxy(String service, String id) {
final ObjectNamespace ns = new DefaultObjectNamespace(service, id);
final ClientProxy proxy = proxies.get(ns);
if (proxy != null) {
return proxy;
}
final ClientProxyFactory factory = proxyFactories.get(service);
if (factory == null) {
throw new IllegalArgumentException("No factory registered for service: " + service);
}
final ClientProxy clientProxy = factory.create(id);
final ClientProxy current = proxies.putIfAbsent(ns, clientProxy);
if (current != null){
return current;
}
initialize(clientProxy);
return clientProxy;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getProxy" | "public ClientProxy getProxy(String service, String id) {
final ObjectNamespace ns = new DefaultObjectNamespace(service, id);
final ClientProxy proxy = proxies.get(ns);
if (proxy != null) {
return proxy;
}
final ClientProxyFactory factory = proxyFactories.get(service);
if (factory == null) {
throw new IllegalArgumentException("No factory registered for service: " + service);
}
final ClientProxy clientProxy = factory.create(id);
<MASK>initialize(clientProxy);</MASK>
final ClientProxy current = proxies.putIfAbsent(ns, clientProxy);
if (current != null){
return current;
}
return clientProxy;
}" |
Inversion-Mutation | megadiff | "private void suspendExpression(AbstractAST x) {
setCurrentAST(x);
if(suspendRequest) {
suspendRequest = false;
debugger.notifySuspend();
} else if (expressionStepModeEnabled()) {
if (debugger.isStepping() || debugger.hasEnabledBreakpoint(getCurrentAST().getLocation())) {
debugger.notifySuspend();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "suspendExpression" | "private void suspendExpression(AbstractAST x) {
setCurrentAST(x);
if(suspendRequest) {
<MASK>debugger.notifySuspend();</MASK>
suspendRequest = false;
} else if (expressionStepModeEnabled()) {
if (debugger.isStepping() || debugger.hasEnabledBreakpoint(getCurrentAST().getLocation())) {
<MASK>debugger.notifySuspend();</MASK>
}
}
}" |
Inversion-Mutation | megadiff | "public boolean AssertNot(String value, String src) {
boolean result = false;
String msg = "";
if (isRegex(value)) {
value = this.strToRegex(value);
if (src.matches(value)) {
this.FailedAsserts += 1;
msg = String.format("(!)Assert Failed, Found Unexpected text: '%s'.", value);
this._log(msg);
this.SavePage();
result = false;
} else {
this.PassedAsserts += 1;
msg = String.format("Assert Failed for find: '%s' as expected.", value);
this.Log(msg);
result = true;
}
} else {
if (src.contains(value)) {
this.FailedAsserts += 1;
msg = String.format("(!)Assert Passed, Found: '%s'.", value);
this._log(msg);
this.SavePage();
result = false;
} else {
this.PassedAsserts += 1;
msg = String.format("Assert Failed for find: '%s' as expected.", value);
this.Log(msg);
result = true;
}
}
return result;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "AssertNot" | "public boolean AssertNot(String value, String src) {
boolean result = false;
String msg = "";
if (isRegex(value)) {
value = this.strToRegex(value);
if (src.matches(value)) {
this.FailedAsserts += 1;
msg = String.format("(!)Assert Failed, Found Unexpected text: '%s'.", value);
this._log(msg);
<MASK>this.SavePage();</MASK>
result = false;
} else {
this.PassedAsserts += 1;
msg = String.format("Assert Failed for find: '%s' as expected.", value);
this.Log(msg);
result = true;
}
} else {
if (src.contains(value)) {
this.FailedAsserts += 1;
msg = String.format("(!)Assert Passed, Found: '%s'.", value);
this._log(msg);
result = false;
} else {
this.PassedAsserts += 1;
msg = String.format("Assert Failed for find: '%s' as expected.", value);
this.Log(msg);
<MASK>this.SavePage();</MASK>
result = true;
}
}
return result;
}" |
Inversion-Mutation | megadiff | "@Override
public ClassImportStatementInfo resolve(final TargetClassInfo usingClass,
final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager,
final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) {
// s³ÈÄÑoµÅÈ¢©ð`FbN
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == classInfoManager) {
throw new NullPointerException();
}
// ùÉðÏÝÅ éêÍCLbV
ðÔ·
if (this.alreadyResolved()) {
return this.getResolved();
}
final int fromLine = this.getFromLine();
final int fromColumn = this.getFromColumn();
final int toLine = this.getToLine();
final int toColumn = this.getToColumn();
final SortedSet<ClassInfo> accessibleClasses = new TreeSet<ClassInfo>();
if (this.isAll()) {
final String[] namespace = this.getNamespace();
final Collection<ClassInfo> specifiedClasses = classInfoManager
.getClassInfos(namespace);
accessibleClasses.addAll(specifiedClasses);
} else {
final String[] importName = this.getImportName();
ClassInfo specifiedClass = classInfoManager.getClassInfo(importName);
if (null == specifiedClass) {
specifiedClass = new ExternalClassInfo(importName);
classInfoManager.add(specifiedClass);
}
accessibleClasses.add(specifiedClass);
}
this.resolvedInfo = new ClassImportStatementInfo(accessibleClasses, fromLine, fromColumn,
toLine, toColumn);
return this.resolvedInfo;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "resolve" | "@Override
public ClassImportStatementInfo resolve(final TargetClassInfo usingClass,
final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager,
final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) {
// s³ÈÄÑoµÅÈ¢©ð`FbN
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == classInfoManager) {
throw new NullPointerException();
}
// ùÉðÏÝÅ éêÍCLbV
ðÔ·
if (this.alreadyResolved()) {
return this.getResolved();
}
final int fromLine = this.getFromLine();
final int fromColumn = this.getFromColumn();
final int toLine = this.getToLine();
final int toColumn = this.getToColumn();
final SortedSet<ClassInfo> accessibleClasses = new TreeSet<ClassInfo>();
if (this.isAll()) {
final String[] namespace = this.getNamespace();
final Collection<ClassInfo> specifiedClasses = classInfoManager
.getClassInfos(namespace);
accessibleClasses.addAll(specifiedClasses);
} else {
final String[] importName = this.getImportName();
ClassInfo specifiedClass = classInfoManager.getClassInfo(importName);
if (null == specifiedClass) {
specifiedClass = new ExternalClassInfo(importName);
classInfoManager.add(specifiedClass);
<MASK>accessibleClasses.add(specifiedClass);</MASK>
}
}
this.resolvedInfo = new ClassImportStatementInfo(accessibleClasses, fromLine, fromColumn,
toLine, toColumn);
return this.resolvedInfo;
}" |
Inversion-Mutation | megadiff | "@Override
public Representation getRepresentation(final Status status, final Request request, final Response response)
{
final Map<String, Object> dataModel = RestletUtils.getBaseDataModel(request);
dataModel.put("contentTemplate", "error.html.ftl");
dataModel.put("pageTitle", "An error occurred : HTTP " + status.getCode());
dataModel.put("error_code", Integer.toString(status.getCode()));
final StringBuilder message = new StringBuilder();
if(status.getDescription() != null)
{
message.append(status.getDescription());
}
if(status.getThrowable() != null && status.getThrowable().getMessage() != null)
{
message.append(" (");
message.append(status.getThrowable().getMessage());
message.append(")");
}
dataModel.put("message", message.toString());
// TODO: Support non-HTML error representations
return RestletUtils.getHtmlRepresentation("poddBase.html.ftl", dataModel, MediaType.TEXT_HTML,
this.freemarkerConfiguration);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getRepresentation" | "@Override
public Representation getRepresentation(final Status status, final Request request, final Response response)
{
final Map<String, Object> dataModel = RestletUtils.getBaseDataModel(request);
dataModel.put("contentTemplate", "error.html.ftl");
dataModel.put("pageTitle", "An error occurred : HTTP " + status.getCode());
dataModel.put("error_code", Integer.toString(status.getCode()));
final StringBuilder message = new StringBuilder();
if(status.getDescription() != null)
{
message.append(status.getDescription());
<MASK>message.append(" (");</MASK>
}
if(status.getThrowable() != null && status.getThrowable().getMessage() != null)
{
message.append(status.getThrowable().getMessage());
message.append(")");
}
dataModel.put("message", message.toString());
// TODO: Support non-HTML error representations
return RestletUtils.getHtmlRepresentation("poddBase.html.ftl", dataModel, MediaType.TEXT_HTML,
this.freemarkerConfiguration);
}" |
Inversion-Mutation | megadiff | "public void load( ComponentSystemEvent event )
throws AbortProcessingException, ConfigurationException {
LOG.debug( "Load form for goup with id " + grpId );
if ( form != null ) {
form.getChildren().clear();
if ( forms.containsKey( grpId ) ) {
form.getChildren().add( forms.get( grpId ) );
} else {
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession( false );
configuration = FormConfigurationFactory.getOrCreateFormConfiguration( session.getId() );
FormGroup fg = configuration.getFormGroup( grpId );
grpId = fg.getId();
if ( fg != null ) {
HtmlPanelGrid grid = new HtmlPanelGrid();
grid.setId( GuiUtils.getUniqueId() );
addFormGroup( grid, fg, true );
forms.put( grpId, grid );
form.getChildren().add( grid );
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "load" | "public void load( ComponentSystemEvent event )
throws AbortProcessingException, ConfigurationException {
LOG.debug( "Load form for goup with id " + grpId );
if ( form != null ) {
form.getChildren().clear();
if ( forms.containsKey( grpId ) ) {
form.getChildren().add( forms.get( grpId ) );
} else {
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession( false );
configuration = FormConfigurationFactory.getOrCreateFormConfiguration( session.getId() );
FormGroup fg = configuration.getFormGroup( grpId );
if ( fg != null ) {
HtmlPanelGrid grid = new HtmlPanelGrid();
grid.setId( GuiUtils.getUniqueId() );
addFormGroup( grid, fg, true );
forms.put( grpId, grid );
form.getChildren().add( grid );
}
<MASK>grpId = fg.getId();</MASK>
}
}
}" |
Inversion-Mutation | megadiff | "private void executeAsForked(List<String> dmlFiles, String classFullName, String domainModelClassName) throws BuildException {
CommandlineJava cmd;
try {
cmd = (CommandlineJava) (getCommandline().clone());
} catch (CloneNotSupportedException e) {
throw new BuildException("This shouldn't happen", e, getLocation());
}
cmd.setClassname(POST_PROCESSOR_CLASS);
if (classFullName != null) {
cmd.createArgument().setValue("-cfn");
cmd.createArgument().setValue(classFullName);
}
if (domainModelClassName != null) {
cmd.createArgument().setValue("-domainModelClass");
cmd.createArgument().setValue(domainModelClassName);
}
for (String file : dmlFiles) {
cmd.createArgument().setValue("-d");
cmd.createArgument().setValue(file);
}
Execute execute = new Execute();
execute.setCommandline(cmd.getCommandline());
execute.setAntRun(getProject());
if (dir != null) {
execute.setWorkingDirectory(dir);
}
String[] environment = env.getVariables();
execute.setNewenvironment(true);
execute.setEnvironment(environment);
try {
execute.execute();
} catch (IOException e) {
throw new BuildException("Process fork failed.", e, getLocation());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeAsForked" | "private void executeAsForked(List<String> dmlFiles, String classFullName, String domainModelClassName) throws BuildException {
CommandlineJava cmd;
try {
cmd = (CommandlineJava) (getCommandline().clone());
} catch (CloneNotSupportedException e) {
throw new BuildException("This shouldn't happen", e, getLocation());
}
cmd.setClassname(POST_PROCESSOR_CLASS);
if (classFullName != null) {
cmd.createArgument().setValue("-cfn");
cmd.createArgument().setValue(classFullName);
}
if (domainModelClassName != null) {
cmd.createArgument().setValue("-domainModelClass");
cmd.createArgument().setValue(domainModelClassName);
}
<MASK>cmd.createArgument().setValue("-d");</MASK>
for (String file : dmlFiles) {
cmd.createArgument().setValue(file);
}
Execute execute = new Execute();
execute.setCommandline(cmd.getCommandline());
execute.setAntRun(getProject());
if (dir != null) {
execute.setWorkingDirectory(dir);
}
String[] environment = env.getVariables();
execute.setNewenvironment(true);
execute.setEnvironment(environment);
try {
execute.execute();
} catch (IOException e) {
throw new BuildException("Process fork failed.", e, getLocation());
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle icicle) {
this.mTestPath = (String) icicle.get("path");
String timeout_str = (String) icicle.get("timeout");
if (timeout_str != null) {
try {
this.mTimeoutInMillis = Integer.parseInt(timeout_str);
} catch (Exception e) {
e.printStackTrace();
}
}
String r = (String)icicle.get("rebaseline");
this.mRebaseline = (r != null && r.toLowerCase().equals("true"));
super.onCreate(icicle);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle icicle) {
<MASK>super.onCreate(icicle);</MASK>
this.mTestPath = (String) icicle.get("path");
String timeout_str = (String) icicle.get("timeout");
if (timeout_str != null) {
try {
this.mTimeoutInMillis = Integer.parseInt(timeout_str);
} catch (Exception e) {
e.printStackTrace();
}
}
String r = (String)icicle.get("rebaseline");
this.mRebaseline = (r != null && r.toLowerCase().equals("true"));
}" |
Inversion-Mutation | megadiff | "@Override
public void testEnded(String host) {
if(workerThread == null) {
return;
}
started = false;
workerThread.interrupt();
shutdownConnectors();
//reset autoFileName for next test run
autoFileBaseName = null;
counter = 0;
super.testEnded(host);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testEnded" | "@Override
public void testEnded(String host) {
if(workerThread == null) {
return;
}
workerThread.interrupt();
shutdownConnectors();
//reset autoFileName for next test run
autoFileBaseName = null;
counter = 0;
<MASK>started = false;</MASK>
super.testEnded(host);
}" |
Inversion-Mutation | megadiff | "@Override
public Set<SquareMatrix> compute() {
if (nodes.size() <= 500) {
for (MagicTreeNode node: nodes) {
node.get_children();
result.addAll(node.build());
}
} else {
int half = nodes.size() / 2;
List<MagicTreeNode> upper_half = nodes.subList(0, half);
List<MagicTreeNode> lower_half = nodes.subList(half, nodes.size());
NodeBuilderTask worker1 = new NodeBuilderTask(upper_half);
NodeBuilderTask worker2 = new NodeBuilderTask(lower_half);
worker1.fork();
result.addAll(worker2.compute());
result.addAll(worker1.join());
}
return result;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "compute" | "@Override
public Set<SquareMatrix> compute() {
if (nodes.size() <= 500) {
for (MagicTreeNode node: nodes) {
node.get_children();
result.addAll(node.build());
}
} else {
int half = nodes.size() / 2;
List<MagicTreeNode> upper_half = nodes.subList(0, half);
List<MagicTreeNode> lower_half = nodes.subList(half, nodes.size());
NodeBuilderTask worker1 = new NodeBuilderTask(upper_half);
NodeBuilderTask worker2 = new NodeBuilderTask(lower_half);
worker1.fork();
<MASK>result.addAll(worker1.join());</MASK>
result.addAll(worker2.compute());
}
return result;
}" |
Inversion-Mutation | megadiff | "static boolean executeScript(final NodeModel node, String script, final MModeController pMindMapController,
final IErrorHandler pErrorHandler, final PrintStream pOutStream,
final HashMap pScriptCookies) {
if (!noUserPermissionRequired) {
final int showResult = OptionalDontShowMeAgainDialog.show(pMindMapController.getController(),
"really_execute_script", "confirmation", RESOURCES_EXECUTE_SCRIPTS_WITHOUT_ASKING,
OptionalDontShowMeAgainDialog.ONLY_OK_SELECTION_IS_STORED);
if (showResult != JOptionPane.OK_OPTION) {
return false;
}
}
noUserPermissionRequired = Boolean.TRUE;
final Binding binding = new Binding();
binding.setVariable("c", ProxyFactory.createController(pMindMapController));
binding.setVariable("node", ProxyFactory.createNode(node, pMindMapController));
binding.setVariable("cookies", ScriptingEngine.sScriptCookies);
boolean assignResult = false;
String assignTo = null;
if (script.startsWith("=")) {
script = script.substring(1);
assignResult = true;
}
else {
final int indexOfEquals = script.indexOf('=');
if (indexOfEquals > 0) {
final String start = script.substring(0, indexOfEquals);
if (start.matches("[a-zA-Z0-9_]+")) {
assignTo = start;
script = script.substring(indexOfEquals + 1);
assignResult = true;
}
}
}
/*
* get preferences (and store them again after the script execution,
* such that the scripts are not able to change them).
*/
final String executeWithoutAsking = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_ASKING);
final String executeWithoutFileRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_FILE_RESTRICTION);
final String executeWithoutNetworkRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_NETWORK_RESTRICTION);
final String executeWithoutExecRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_EXEC_RESTRICTION);
final String signedScriptsWithoutRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_SIGNED_SCRIPT_ARE_TRUSTED);
/* *************** */
/* Signature */
/* *************** */
final PrintStream oldOut = System.out;
Object value = null;
GroovyRuntimeException e1 = null;
Throwable e2 = null;
boolean filePerm = Boolean.parseBoolean(executeWithoutFileRestriction);
boolean networkPerm = Boolean.parseBoolean(executeWithoutNetworkRestriction);
boolean execPerm = Boolean.parseBoolean(executeWithoutExecRestriction);
if (Boolean.parseBoolean(signedScriptsWithoutRestriction)) {
final boolean isSigned = new SignedScriptHandler().isScriptSigned(script, pOutStream);
if (isSigned) {
filePerm = true;
networkPerm = true;
execPerm = true;
}
}
final ScriptingSecurityManager scriptingSecurityManager = new ScriptingSecurityManager(filePerm, networkPerm,
execPerm);
final FreeplaneSecurityManager securityManager = (FreeplaneSecurityManager) System.getSecurityManager();
try {
System.setOut(pOutStream);
final GroovyShell shell = new GroovyShell(binding) {
/**
* Evaluates some script against the current Binding and returns the result
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
@Override
public Object evaluate(final InputStream in, final String fileName) throws CompilationFailedException {
Script script = null;
try {
script = parse(in, fileName);
securityManager.setFinalSecurityManager(scriptingSecurityManager);
return script.run();
}
finally {
if (script != null) {
InvokerHelper.removeClass(script.getClass());
securityManager.setFinalSecurityManager(scriptingSecurityManager);
}
}
}
};
value = shell.evaluate(script);
}
catch (final GroovyRuntimeException e) {
e1 = e;
}
catch (final Throwable e) {
e2 = e;
}
finally {
System.setOut(oldOut);
/* restore preferences (and assure that the values are unchanged!). */
ResourceController.getResourceController().setProperty(RESOURCES_EXECUTE_SCRIPTS_WITHOUT_ASKING,
executeWithoutAsking);
ResourceController.getResourceController().setProperty(RESOURCES_EXECUTE_SCRIPTS_WITHOUT_FILE_RESTRICTION,
executeWithoutFileRestriction);
ResourceController.getResourceController().setProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_NETWORK_RESTRICTION, executeWithoutNetworkRestriction);
ResourceController.getResourceController().setProperty(RESOURCES_EXECUTE_SCRIPTS_WITHOUT_EXEC_RESTRICTION,
executeWithoutExecRestriction);
ResourceController.getResourceController().setProperty(RESOURCES_SIGNED_SCRIPT_ARE_TRUSTED,
signedScriptsWithoutRestriction);
}
/*
* Cover exceptions in normal security context (ie. no problem with
* (log) file writing etc.)
*/
if (e1 != null) {
final String resultString = e1.getMessage();
pOutStream.print("message: " + resultString);
final ModuleNode module = e1.getModule();
final ASTNode astNode = e1.getNode();
int lineNumber = -1;
if (module != null) {
lineNumber = module.getLineNumber();
}
else if (astNode != null) {
lineNumber = astNode.getLineNumber();
}
else {
lineNumber = ScriptingEngine.findLineNumberInString(resultString, lineNumber);
}
pOutStream.print("Line number: " + lineNumber);
pErrorHandler.gotoLine(lineNumber);
return false;
}
if (e2 != null) {
pMindMapController.getMapController().select(node);
LogTool.warn(e2);
pOutStream.print(e2.getMessage());
final String cause = ((e2.getCause() != null) ? e2.getCause().getMessage() : "");
final String message = ((e2.getMessage() != null) ? e2.getMessage() : "");
UITools.errorMessage(e2.getClass().getName() + ": " + cause
+ ((cause.length() != 0 && message.length() != 0) ? ", " : "") + message);
return false;
}
pOutStream.print(ResourceBundles.getText("plugins/ScriptEditor/window.Result") + value);
if (assignResult && value != null) {
if (assignTo == null) {
((MTextController) TextController.getController(pMindMapController))
.setNodeText(node, value.toString());
}
else {
((MAttributeController) AttributeController.getController(pMindMapController)).editAttribute(node,
assignTo, value.toString());
}
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeScript" | "static boolean executeScript(final NodeModel node, String script, final MModeController pMindMapController,
final IErrorHandler pErrorHandler, final PrintStream pOutStream,
final HashMap pScriptCookies) {
if (!noUserPermissionRequired) {
final int showResult = OptionalDontShowMeAgainDialog.show(pMindMapController.getController(),
"really_execute_script", "confirmation", RESOURCES_EXECUTE_SCRIPTS_WITHOUT_ASKING,
OptionalDontShowMeAgainDialog.ONLY_OK_SELECTION_IS_STORED);
if (showResult != JOptionPane.OK_OPTION) {
return false;
}
}
noUserPermissionRequired = Boolean.TRUE;
final Binding binding = new Binding();
binding.setVariable("c", ProxyFactory.createController(pMindMapController));
binding.setVariable("node", ProxyFactory.createNode(node, pMindMapController));
binding.setVariable("cookies", ScriptingEngine.sScriptCookies);
boolean assignResult = false;
String assignTo = null;
if (script.startsWith("=")) {
script = script.substring(1);
assignResult = true;
}
else {
final int indexOfEquals = script.indexOf('=');
if (indexOfEquals > 0) {
final String start = script.substring(0, indexOfEquals);
if (start.matches("[a-zA-Z0-9_]+")) {
assignTo = start;
script = script.substring(indexOfEquals + 1);
assignResult = true;
}
}
}
/*
* get preferences (and store them again after the script execution,
* such that the scripts are not able to change them).
*/
final String executeWithoutAsking = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_ASKING);
final String executeWithoutFileRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_FILE_RESTRICTION);
final String executeWithoutNetworkRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_NETWORK_RESTRICTION);
final String executeWithoutExecRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_EXEC_RESTRICTION);
final String signedScriptsWithoutRestriction = ResourceController.getResourceController().getProperty(
RESOURCES_SIGNED_SCRIPT_ARE_TRUSTED);
/* *************** */
/* Signature */
/* *************** */
final PrintStream oldOut = System.out;
Object value = null;
GroovyRuntimeException e1 = null;
Throwable e2 = null;
boolean filePerm = Boolean.parseBoolean(executeWithoutFileRestriction);
boolean networkPerm = Boolean.parseBoolean(executeWithoutNetworkRestriction);
boolean execPerm = Boolean.parseBoolean(executeWithoutExecRestriction);
if (Boolean.parseBoolean(signedScriptsWithoutRestriction)) {
final boolean isSigned = new SignedScriptHandler().isScriptSigned(script, pOutStream);
if (isSigned) {
filePerm = true;
networkPerm = true;
execPerm = true;
}
}
final ScriptingSecurityManager scriptingSecurityManager = new ScriptingSecurityManager(filePerm, networkPerm,
execPerm);
final FreeplaneSecurityManager securityManager = (FreeplaneSecurityManager) System.getSecurityManager();
try {
System.setOut(pOutStream);
final GroovyShell shell = new GroovyShell(binding) {
/**
* Evaluates some script against the current Binding and returns the result
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
@Override
public Object evaluate(final InputStream in, final String fileName) throws CompilationFailedException {
Script script = null;
try {
script = parse(in, fileName);
<MASK>securityManager.setFinalSecurityManager(scriptingSecurityManager);</MASK>
return script.run();
}
finally {
if (script != null) {
InvokerHelper.removeClass(script.getClass());
}
}
}
};
value = shell.evaluate(script);
}
catch (final GroovyRuntimeException e) {
e1 = e;
}
catch (final Throwable e) {
e2 = e;
}
finally {
<MASK>securityManager.setFinalSecurityManager(scriptingSecurityManager);</MASK>
System.setOut(oldOut);
/* restore preferences (and assure that the values are unchanged!). */
ResourceController.getResourceController().setProperty(RESOURCES_EXECUTE_SCRIPTS_WITHOUT_ASKING,
executeWithoutAsking);
ResourceController.getResourceController().setProperty(RESOURCES_EXECUTE_SCRIPTS_WITHOUT_FILE_RESTRICTION,
executeWithoutFileRestriction);
ResourceController.getResourceController().setProperty(
RESOURCES_EXECUTE_SCRIPTS_WITHOUT_NETWORK_RESTRICTION, executeWithoutNetworkRestriction);
ResourceController.getResourceController().setProperty(RESOURCES_EXECUTE_SCRIPTS_WITHOUT_EXEC_RESTRICTION,
executeWithoutExecRestriction);
ResourceController.getResourceController().setProperty(RESOURCES_SIGNED_SCRIPT_ARE_TRUSTED,
signedScriptsWithoutRestriction);
}
/*
* Cover exceptions in normal security context (ie. no problem with
* (log) file writing etc.)
*/
if (e1 != null) {
final String resultString = e1.getMessage();
pOutStream.print("message: " + resultString);
final ModuleNode module = e1.getModule();
final ASTNode astNode = e1.getNode();
int lineNumber = -1;
if (module != null) {
lineNumber = module.getLineNumber();
}
else if (astNode != null) {
lineNumber = astNode.getLineNumber();
}
else {
lineNumber = ScriptingEngine.findLineNumberInString(resultString, lineNumber);
}
pOutStream.print("Line number: " + lineNumber);
pErrorHandler.gotoLine(lineNumber);
return false;
}
if (e2 != null) {
pMindMapController.getMapController().select(node);
LogTool.warn(e2);
pOutStream.print(e2.getMessage());
final String cause = ((e2.getCause() != null) ? e2.getCause().getMessage() : "");
final String message = ((e2.getMessage() != null) ? e2.getMessage() : "");
UITools.errorMessage(e2.getClass().getName() + ": " + cause
+ ((cause.length() != 0 && message.length() != 0) ? ", " : "") + message);
return false;
}
pOutStream.print(ResourceBundles.getText("plugins/ScriptEditor/window.Result") + value);
if (assignResult && value != null) {
if (assignTo == null) {
((MTextController) TextController.getController(pMindMapController))
.setNodeText(node, value.toString());
}
else {
((MAttributeController) AttributeController.getController(pMindMapController)).editAttribute(node,
assignTo, value.toString());
}
}
return true;
}" |
Inversion-Mutation | megadiff | "private void tryCloseSocket(Socket socket) {
try {
cancelAllRequests("channel closed");
socket.close();
} catch (IOException e1) {
logger.log(Level.WARNING,
"Unable to close socket " + socket,
e1);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tryCloseSocket" | "private void tryCloseSocket(Socket socket) {
try {
<MASK>socket.close();</MASK>
cancelAllRequests("channel closed");
} catch (IOException e1) {
logger.log(Level.WARNING,
"Unable to close socket " + socket,
e1);
}
}" |
Inversion-Mutation | megadiff | "public SWTBotTreeItem doubleClick() {
assertEnabled();
asyncExec(new VoidResult() {
public void run() {
tree.setSelection(widget);
}
});
notifyTree(SWT.Selection);
notifyTree(SWT.MouseDown);
notifyTree(SWT.MouseUp);
notifyTree(SWT.MouseDown);
notifyTree(SWT.MouseDoubleClick);
notifyTree(SWT.DefaultSelection);
notifyTree(SWT.MouseUp);
return this;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doubleClick" | "public SWTBotTreeItem doubleClick() {
assertEnabled();
<MASK>notifyTree(SWT.MouseDown);</MASK>
asyncExec(new VoidResult() {
public void run() {
tree.setSelection(widget);
}
});
notifyTree(SWT.Selection);
notifyTree(SWT.MouseUp);
<MASK>notifyTree(SWT.MouseDown);</MASK>
notifyTree(SWT.MouseDoubleClick);
notifyTree(SWT.DefaultSelection);
notifyTree(SWT.MouseUp);
return this;
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("loadUrlTimeoutValue", 60000);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 60000);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 60000);
<MASK>super.setIntegerProperty("loadUrlTimeoutValue", 60000);</MASK>
}" |
Inversion-Mutation | megadiff | "public ClassLoaderManager(Object commMgrBean) {
classloaderMap = new HashMap<Long, ClassLoader>();
objectToBundle = new HashMap<Object, Long>();
thisBundleId = getBundleId(commMgrBean);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ClassLoaderManager" | "public ClassLoaderManager(Object commMgrBean) {
<MASK>thisBundleId = getBundleId(commMgrBean);</MASK>
classloaderMap = new HashMap<Long, ClassLoader>();
objectToBundle = new HashMap<Object, Long>();
}" |
Inversion-Mutation | megadiff | "private void addWherePredicate(
StringBuilder whereBuilder,
Predicate predicate,
Predicate parentPredicate,
boolean usesLeftJoin,
boolean deferMetricAndHavingPredicates) {
if (predicate instanceof CompoundPredicate) {
CompoundPredicate compoundPredicate = (CompoundPredicate) predicate;
String operator = compoundPredicate.getOperator();
boolean isNot = PredicateParser.NOT_OPERATOR.equals(operator);
// e.g. (child1) OR (child2) OR ... (child#)
if (isNot || PredicateParser.OR_OPERATOR.equals(operator)) {
StringBuilder compoundBuilder = new StringBuilder();
List<Predicate> children = compoundPredicate.getChildren();
boolean usesLeftJoinChildren;
if (children.size() > 1) {
usesLeftJoinChildren = true;
needsDistinct = true;
} else {
usesLeftJoinChildren = isNot;
}
for (Predicate child : children) {
StringBuilder childBuilder = new StringBuilder();
addWherePredicate(childBuilder, child, predicate, usesLeftJoinChildren, deferMetricAndHavingPredicates);
if (childBuilder.length() > 0) {
compoundBuilder.append('(');
compoundBuilder.append(childBuilder);
compoundBuilder.append(")\nOR ");
}
}
if (compoundBuilder.length() > 0) {
compoundBuilder.setLength(compoundBuilder.length() - 4);
// e.g. NOT ((child1) OR (child2) OR ... (child#))
if (isNot) {
whereBuilder.append("NOT (");
whereBuilder.append(compoundBuilder);
whereBuilder.append(')');
} else {
whereBuilder.append(compoundBuilder);
}
}
return;
// e.g. (child1) AND (child2) AND .... (child#)
} else if (PredicateParser.AND_OPERATOR.equals(operator)) {
StringBuilder compoundBuilder = new StringBuilder();
for (Predicate child : compoundPredicate.getChildren()) {
StringBuilder childBuilder = new StringBuilder();
addWherePredicate(childBuilder, child, predicate, usesLeftJoin, deferMetricAndHavingPredicates);
if (childBuilder.length() > 0) {
compoundBuilder.append('(');
compoundBuilder.append(childBuilder);
compoundBuilder.append(")\nAND ");
}
}
if (compoundBuilder.length() > 0) {
compoundBuilder.setLength(compoundBuilder.length() - 5);
whereBuilder.append(compoundBuilder);
}
return;
}
} else if (predicate instanceof ComparisonPredicate) {
ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate;
String queryKey = comparisonPredicate.getKey();
Query.MappedKey mappedKey = mappedKeys.get(queryKey);
boolean isFieldCollection = mappedKey.isInternalCollectionType();
Join join = null;
if (mappedKey.getField() != null &&
parentPredicate instanceof CompoundPredicate &&
PredicateParser.OR_OPERATOR.equals(((CompoundPredicate) parentPredicate).getOperator())) {
for (Join j : joins) {
if (j.parent == parentPredicate &&
j.sqlIndex.equals(SqlIndex.Static.getByType(mappedKeys.get(queryKey).getInternalType()))) {
join = j;
join.addIndexKey(queryKey);
needsDistinct = true;
break;
}
}
if (join == null) {
join = getJoin(queryKey);
join.parent = parentPredicate;
}
} else if (isFieldCollection) {
join = createJoin(queryKey);
} else {
join = getJoin(queryKey);
}
if (usesLeftJoin) {
join.type = JoinType.LEFT_OUTER;
}
if (isFieldCollection &&
(join.sqlIndexTable == null ||
join.sqlIndexTable.getVersion() < 2)) {
needsDistinct = true;
}
if (deferMetricAndHavingPredicates) {
if (mappedKey.getField() != null) {
if (mappedKey.getField().isMetric()) {
if (recordMetricField == null) {
recordMetricField = mappedKey.getField();
} else if (! recordMetricField.equals(mappedKey.getField())) {
throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName() + " AND " + mappedKey.getField().getInternalName());
}
if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
recordMetricDatePredicates.add(predicate);
recordMetricParentDatePredicates.add(parentPredicate);
} else if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
recordMetricDimensionPredicates.add(predicate);
recordMetricParentDimensionPredicates.add(parentPredicate);
} else {
recordMetricHavingPredicates.add(predicate);
recordMetricParentHavingPredicates.add(parentPredicate);
}
return;
}
}
if (join.isHaving) {
// pass for now; we'll get called again later.
havingPredicates.add(predicate);
parentHavingPredicates.add(parentPredicate);
return;
}
}
String joinValueField = join.getValueField(queryKey, comparisonPredicate);
if (reverseAliasSql.containsKey(joinValueField)) {
joinValueField = reverseAliasSql.get(joinValueField);
}
String operator = comparisonPredicate.getOperator();
StringBuilder comparisonBuilder = new StringBuilder();
boolean hasMissing = false;
int subClauseCount = 0;
boolean isNotEqualsAll = PredicateParser.NOT_EQUALS_ALL_OPERATOR.equals(operator);
if (isNotEqualsAll || PredicateParser.EQUALS_ANY_OPERATOR.equals(operator)) {
Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate);
// e.g. field IN (SELECT ...)
if (valueQuery != null) {
if (isNotEqualsAll || isFieldCollection) {
needsDistinct = true;
}
if (findSimilarComparison(mappedKey.getField(), query.getPredicate())) {
whereBuilder.append(joinValueField);
if (isNotEqualsAll) {
whereBuilder.append(" NOT");
}
whereBuilder.append(" IN (");
whereBuilder.append(new SqlQuery(database, valueQuery).subQueryStatement());
whereBuilder.append(')');
} else {
SqlQuery subSqlQuery = getOrCreateSubSqlQuery(valueQuery, join.type == JoinType.LEFT_OUTER);
subQueries.put(valueQuery, joinValueField + (isNotEqualsAll ? " != " : " = "));
whereBuilder.append(subSqlQuery.whereClause.substring(7));
}
return;
}
for (Object value : comparisonPredicate.resolveValues(database)) {
if (value == null) {
++ subClauseCount;
comparisonBuilder.append("0 = 1");
} else if (value == Query.MISSING_VALUE) {
++ subClauseCount;
hasMissing = true;
comparisonBuilder.append(joinValueField);
if (isNotEqualsAll) {
if (isFieldCollection) {
needsDistinct = true;
}
comparisonBuilder.append(" IS NOT NULL");
} else {
join.type = JoinType.LEFT_OUTER;
comparisonBuilder.append(" IS NULL");
}
} else if (value instanceof Region) {
List<Location> locations = ((Region) value).getLocations();
if (!locations.isEmpty()) {
++ subClauseCount;
if (isNotEqualsAll) {
comparisonBuilder.append("NOT ");
}
try {
vendor.appendWhereRegion(comparisonBuilder, (Region) value, joinValueField);
} catch (UnsupportedIndexException uie) {
throw new UnsupportedIndexException(vendor, queryKey);
}
}
} else {
++ subClauseCount;
if (isNotEqualsAll) {
join.type = JoinType.LEFT_OUTER;
needsDistinct = true;
hasMissing = true;
comparisonBuilder.append('(');
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(" IS NULL OR ");
comparisonBuilder.append(joinValueField);
if (join.likeValuePrefix != null) {
comparisonBuilder.append(" NOT LIKE ");
join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%");
} else {
comparisonBuilder.append(" != ");
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
comparisonBuilder.append(')');
} else {
comparisonBuilder.append(joinValueField);
if (join.likeValuePrefix != null) {
comparisonBuilder.append(" LIKE ");
join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%");
} else {
comparisonBuilder.append(" = ");
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
}
}
comparisonBuilder.append(isNotEqualsAll ? " AND " : " OR ");
}
if (comparisonBuilder.length() == 0) {
whereBuilder.append(isNotEqualsAll ? "1 = 1" : "0 = 1");
return;
}
} else {
boolean isStartsWith = PredicateParser.STARTS_WITH_OPERATOR.equals(operator);
boolean isContains = PredicateParser.CONTAINS_OPERATOR.equals(operator);
String sqlOperator =
isStartsWith ? "LIKE" :
isContains ? "LIKE" :
PredicateParser.LESS_THAN_OPERATOR.equals(operator) ? "<" :
PredicateParser.LESS_THAN_OR_EQUALS_OPERATOR.equals(operator) ? "<=" :
PredicateParser.GREATER_THAN_OPERATOR.equals(operator) ? ">" :
PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR.equals(operator) ? ">=" :
null;
// e.g. field OP value1 OR field OP value2 OR ... field OP value#
if (sqlOperator != null) {
for (Object value : comparisonPredicate.resolveValues(database)) {
++ subClauseCount;
if (value == null) {
comparisonBuilder.append("0 = 1");
} else if (value instanceof Location) {
++ subClauseCount;
if (isNotEqualsAll) {
comparisonBuilder.append("NOT ");
}
try {
vendor.appendWhereLocation(comparisonBuilder, (Location) value, joinValueField);
} catch (UnsupportedIndexException uie) {
throw new UnsupportedIndexException(vendor, queryKey);
}
} else if (value == Query.MISSING_VALUE) {
hasMissing = true;
join.type = JoinType.LEFT_OUTER;
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(" IS NULL");
} else {
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(' ');
comparisonBuilder.append(sqlOperator);
comparisonBuilder.append(' ');
if (isStartsWith) {
value = value.toString() + "%";
} else if (isContains) {
value = "%" + value.toString() + "%";
}
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
comparisonBuilder.append(" OR ");
}
if (comparisonBuilder.length() == 0) {
whereBuilder.append("0 = 1");
return;
}
}
}
if (comparisonBuilder.length() > 0) {
comparisonBuilder.setLength(comparisonBuilder.length() - 5);
if (!hasMissing) {
if (join.needsIndexTable) {
String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey));
if (indexKey != null) {
whereBuilder.append(join.keyField);
whereBuilder.append(" = ");
whereBuilder.append(join.quoteIndexKey(indexKey));
whereBuilder.append(" AND ");
}
}
if (join.needsIsNotNull) {
whereBuilder.append(joinValueField);
whereBuilder.append(" IS NOT NULL AND ");
}
if (subClauseCount > 1) {
needsDistinct = true;
whereBuilder.append('(');
comparisonBuilder.append(')');
}
}
whereBuilder.append(comparisonBuilder);
return;
}
}
throw new UnsupportedPredicateException(this, predicate);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addWherePredicate" | "private void addWherePredicate(
StringBuilder whereBuilder,
Predicate predicate,
Predicate parentPredicate,
boolean usesLeftJoin,
boolean deferMetricAndHavingPredicates) {
if (predicate instanceof CompoundPredicate) {
CompoundPredicate compoundPredicate = (CompoundPredicate) predicate;
String operator = compoundPredicate.getOperator();
boolean isNot = PredicateParser.NOT_OPERATOR.equals(operator);
// e.g. (child1) OR (child2) OR ... (child#)
if (isNot || PredicateParser.OR_OPERATOR.equals(operator)) {
StringBuilder compoundBuilder = new StringBuilder();
List<Predicate> children = compoundPredicate.getChildren();
boolean usesLeftJoinChildren;
if (children.size() > 1) {
usesLeftJoinChildren = true;
needsDistinct = true;
} else {
usesLeftJoinChildren = isNot;
}
for (Predicate child : children) {
StringBuilder childBuilder = new StringBuilder();
addWherePredicate(childBuilder, child, predicate, usesLeftJoinChildren, deferMetricAndHavingPredicates);
if (childBuilder.length() > 0) {
compoundBuilder.append('(');
compoundBuilder.append(childBuilder);
compoundBuilder.append(")\nOR ");
}
}
if (compoundBuilder.length() > 0) {
compoundBuilder.setLength(compoundBuilder.length() - 4);
// e.g. NOT ((child1) OR (child2) OR ... (child#))
if (isNot) {
whereBuilder.append("NOT (");
whereBuilder.append(compoundBuilder);
whereBuilder.append(')');
} else {
whereBuilder.append(compoundBuilder);
}
}
return;
// e.g. (child1) AND (child2) AND .... (child#)
} else if (PredicateParser.AND_OPERATOR.equals(operator)) {
StringBuilder compoundBuilder = new StringBuilder();
for (Predicate child : compoundPredicate.getChildren()) {
StringBuilder childBuilder = new StringBuilder();
addWherePredicate(childBuilder, child, predicate, usesLeftJoin, deferMetricAndHavingPredicates);
if (childBuilder.length() > 0) {
compoundBuilder.append('(');
compoundBuilder.append(childBuilder);
compoundBuilder.append(")\nAND ");
}
}
if (compoundBuilder.length() > 0) {
compoundBuilder.setLength(compoundBuilder.length() - 5);
whereBuilder.append(compoundBuilder);
}
return;
}
} else if (predicate instanceof ComparisonPredicate) {
ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate;
String queryKey = comparisonPredicate.getKey();
Query.MappedKey mappedKey = mappedKeys.get(queryKey);
boolean isFieldCollection = mappedKey.isInternalCollectionType();
Join join = null;
if (mappedKey.getField() != null &&
parentPredicate instanceof CompoundPredicate &&
PredicateParser.OR_OPERATOR.equals(((CompoundPredicate) parentPredicate).getOperator())) {
for (Join j : joins) {
if (j.parent == parentPredicate &&
j.sqlIndex.equals(SqlIndex.Static.getByType(mappedKeys.get(queryKey).getInternalType()))) {
join = j;
join.addIndexKey(queryKey);
needsDistinct = true;
break;
}
}
if (join == null) {
join = getJoin(queryKey);
join.parent = parentPredicate;
}
} else if (isFieldCollection) {
join = createJoin(queryKey);
} else {
join = getJoin(queryKey);
}
if (usesLeftJoin) {
<MASK>join.type = JoinType.LEFT_OUTER;</MASK>
}
if (isFieldCollection &&
(join.sqlIndexTable == null ||
join.sqlIndexTable.getVersion() < 2)) {
needsDistinct = true;
}
if (deferMetricAndHavingPredicates) {
if (mappedKey.getField() != null) {
if (mappedKey.getField().isMetric()) {
if (recordMetricField == null) {
recordMetricField = mappedKey.getField();
} else if (! recordMetricField.equals(mappedKey.getField())) {
throw new Query.NoFieldException(query.getGroup(), recordMetricField.getInternalName() + " AND " + mappedKey.getField().getInternalName());
}
if (Query.METRIC_DATE_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
recordMetricDatePredicates.add(predicate);
recordMetricParentDatePredicates.add(parentPredicate);
} else if (Query.METRIC_DIMENSION_ATTRIBUTE.equals(mappedKey.getHashAttribute())) {
recordMetricDimensionPredicates.add(predicate);
recordMetricParentDimensionPredicates.add(parentPredicate);
} else {
recordMetricHavingPredicates.add(predicate);
recordMetricParentHavingPredicates.add(parentPredicate);
}
return;
}
}
if (join.isHaving) {
// pass for now; we'll get called again later.
havingPredicates.add(predicate);
parentHavingPredicates.add(parentPredicate);
return;
}
}
String joinValueField = join.getValueField(queryKey, comparisonPredicate);
if (reverseAliasSql.containsKey(joinValueField)) {
joinValueField = reverseAliasSql.get(joinValueField);
}
String operator = comparisonPredicate.getOperator();
StringBuilder comparisonBuilder = new StringBuilder();
boolean hasMissing = false;
int subClauseCount = 0;
boolean isNotEqualsAll = PredicateParser.NOT_EQUALS_ALL_OPERATOR.equals(operator);
if (isNotEqualsAll || PredicateParser.EQUALS_ANY_OPERATOR.equals(operator)) {
Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate);
// e.g. field IN (SELECT ...)
if (valueQuery != null) {
if (isNotEqualsAll || isFieldCollection) {
needsDistinct = true;
}
if (findSimilarComparison(mappedKey.getField(), query.getPredicate())) {
whereBuilder.append(joinValueField);
if (isNotEqualsAll) {
whereBuilder.append(" NOT");
}
whereBuilder.append(" IN (");
whereBuilder.append(new SqlQuery(database, valueQuery).subQueryStatement());
whereBuilder.append(')');
} else {
SqlQuery subSqlQuery = getOrCreateSubSqlQuery(valueQuery, join.type == JoinType.LEFT_OUTER);
subQueries.put(valueQuery, joinValueField + (isNotEqualsAll ? " != " : " = "));
whereBuilder.append(subSqlQuery.whereClause.substring(7));
}
return;
}
for (Object value : comparisonPredicate.resolveValues(database)) {
if (value == null) {
++ subClauseCount;
comparisonBuilder.append("0 = 1");
} else if (value == Query.MISSING_VALUE) {
++ subClauseCount;
hasMissing = true;
<MASK>join.type = JoinType.LEFT_OUTER;</MASK>
comparisonBuilder.append(joinValueField);
if (isNotEqualsAll) {
if (isFieldCollection) {
needsDistinct = true;
}
comparisonBuilder.append(" IS NOT NULL");
} else {
comparisonBuilder.append(" IS NULL");
}
} else if (value instanceof Region) {
List<Location> locations = ((Region) value).getLocations();
if (!locations.isEmpty()) {
++ subClauseCount;
if (isNotEqualsAll) {
comparisonBuilder.append("NOT ");
}
try {
vendor.appendWhereRegion(comparisonBuilder, (Region) value, joinValueField);
} catch (UnsupportedIndexException uie) {
throw new UnsupportedIndexException(vendor, queryKey);
}
}
} else {
++ subClauseCount;
if (isNotEqualsAll) {
<MASK>join.type = JoinType.LEFT_OUTER;</MASK>
needsDistinct = true;
hasMissing = true;
comparisonBuilder.append('(');
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(" IS NULL OR ");
comparisonBuilder.append(joinValueField);
if (join.likeValuePrefix != null) {
comparisonBuilder.append(" NOT LIKE ");
join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%");
} else {
comparisonBuilder.append(" != ");
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
comparisonBuilder.append(')');
} else {
comparisonBuilder.append(joinValueField);
if (join.likeValuePrefix != null) {
comparisonBuilder.append(" LIKE ");
join.appendValue(comparisonBuilder, comparisonPredicate, join.likeValuePrefix + database.getSymbolId(value.toString()) + ";%");
} else {
comparisonBuilder.append(" = ");
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
}
}
comparisonBuilder.append(isNotEqualsAll ? " AND " : " OR ");
}
if (comparisonBuilder.length() == 0) {
whereBuilder.append(isNotEqualsAll ? "1 = 1" : "0 = 1");
return;
}
} else {
boolean isStartsWith = PredicateParser.STARTS_WITH_OPERATOR.equals(operator);
boolean isContains = PredicateParser.CONTAINS_OPERATOR.equals(operator);
String sqlOperator =
isStartsWith ? "LIKE" :
isContains ? "LIKE" :
PredicateParser.LESS_THAN_OPERATOR.equals(operator) ? "<" :
PredicateParser.LESS_THAN_OR_EQUALS_OPERATOR.equals(operator) ? "<=" :
PredicateParser.GREATER_THAN_OPERATOR.equals(operator) ? ">" :
PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR.equals(operator) ? ">=" :
null;
// e.g. field OP value1 OR field OP value2 OR ... field OP value#
if (sqlOperator != null) {
for (Object value : comparisonPredicate.resolveValues(database)) {
++ subClauseCount;
if (value == null) {
comparisonBuilder.append("0 = 1");
} else if (value instanceof Location) {
++ subClauseCount;
if (isNotEqualsAll) {
comparisonBuilder.append("NOT ");
}
try {
vendor.appendWhereLocation(comparisonBuilder, (Location) value, joinValueField);
} catch (UnsupportedIndexException uie) {
throw new UnsupportedIndexException(vendor, queryKey);
}
} else if (value == Query.MISSING_VALUE) {
hasMissing = true;
<MASK>join.type = JoinType.LEFT_OUTER;</MASK>
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(" IS NULL");
} else {
comparisonBuilder.append(joinValueField);
comparisonBuilder.append(' ');
comparisonBuilder.append(sqlOperator);
comparisonBuilder.append(' ');
if (isStartsWith) {
value = value.toString() + "%";
} else if (isContains) {
value = "%" + value.toString() + "%";
}
join.appendValue(comparisonBuilder, comparisonPredicate, value);
}
comparisonBuilder.append(" OR ");
}
if (comparisonBuilder.length() == 0) {
whereBuilder.append("0 = 1");
return;
}
}
}
if (comparisonBuilder.length() > 0) {
comparisonBuilder.setLength(comparisonBuilder.length() - 5);
if (!hasMissing) {
if (join.needsIndexTable) {
String indexKey = mappedKeys.get(queryKey).getIndexKey(selectedIndexes.get(queryKey));
if (indexKey != null) {
whereBuilder.append(join.keyField);
whereBuilder.append(" = ");
whereBuilder.append(join.quoteIndexKey(indexKey));
whereBuilder.append(" AND ");
}
}
if (join.needsIsNotNull) {
whereBuilder.append(joinValueField);
whereBuilder.append(" IS NOT NULL AND ");
}
if (subClauseCount > 1) {
needsDistinct = true;
whereBuilder.append('(');
comparisonBuilder.append(')');
}
}
whereBuilder.append(comparisonBuilder);
return;
}
}
throw new UnsupportedPredicateException(this, predicate);
}" |
Inversion-Mutation | megadiff | "public void deleteData() throws SQLException, IOException {
update("delete from role_rights where roleid not in(1);");
update("delete from role_assignments where userid not in (1);");
update("delete from roles where name not in ('Admin');");
update("delete from facility_approved_products;");
update("delete from program_product_price_history;");
update("delete from orders;");
update("DELETE FROM requisition_status_changes;");
update("delete from user_password_reset_tokens ;");
update("delete from comments;");
update("delete from distributions ;");
update("delete from users where userName not like('Admin%');");
update("DELETE FROM requisition_line_item_losses_adjustments;");
update("DELETE FROM requisition_line_items;");
update("DELETE FROM regimen_line_items;");
update("DELETE FROM requisitions;");
update("delete from program_product_isa;");
update("delete from facility_approved_products;");
update("delete from facility_program_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
update("delete from product_groups;");
update("delete from supply_lines;");
update("delete from programs_supported;");
update("delete from requisition_group_members;");
update("delete from program_rnr_columns;");
update("delete from requisition_group_program_schedules ;");
update("delete from requisition_groups;");
update("delete from requisition_group_members;");
update("delete from delivery_zone_program_schedules ;");
update("delete from delivery_zone_warehouses ;");
update("delete from delivery_zone_members;");
update("delete from role_assignments where deliveryzoneid in (select id from delivery_zones where code in('DZ1','DZ2'));");
update("delete from delivery_zones;");
update("delete from supervisory_nodes;");
update("delete from refrigerators;");
update("delete from facility_ftp_details;");
update("delete from facilities;");
update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro');");
update("delete from processing_periods;");
update("delete from processing_schedules;");
update("delete from atomfeed.event_records;");
update("delete from regimens;");
update("delete from program_regimen_columns;");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deleteData" | "public void deleteData() throws SQLException, IOException {
update("delete from role_rights where roleid not in(1);");
update("delete from role_assignments where userid not in (1);");
update("delete from roles where name not in ('Admin');");
update("delete from facility_approved_products;");
update("delete from program_product_price_history;");
update("delete from orders;");
update("DELETE FROM requisition_status_changes;");
update("delete from user_password_reset_tokens ;");
update("delete from comments;");
update("delete from distributions ;");
update("delete from users where userName not like('Admin%');");
update("DELETE FROM requisition_line_item_losses_adjustments;");
update("DELETE FROM requisition_line_items;");
update("DELETE FROM regimen_line_items;");
update("DELETE FROM requisitions;");
update("delete from program_product_isa;");
update("delete from facility_approved_products;");
update("delete from facility_program_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
update("delete from product_groups;");
update("delete from supply_lines;");
update("delete from programs_supported;");
update("delete from requisition_group_members;");
update("delete from program_rnr_columns;");
update("delete from requisition_group_program_schedules ;");
update("delete from requisition_groups;");
update("delete from requisition_group_members;");
update("delete from delivery_zone_program_schedules ;");
update("delete from delivery_zone_warehouses ;");
update("delete from delivery_zone_members;");
update("delete from role_assignments where deliveryzoneid in (select id from delivery_zones where code in('DZ1','DZ2'));");
update("delete from delivery_zones;");
update("delete from supervisory_nodes;");
update("delete from refrigerators;");
update("delete from facilities;");
update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro');");
update("delete from processing_periods;");
update("delete from processing_schedules;");
update("delete from atomfeed.event_records;");
update("delete from regimens;");
update("delete from program_regimen_columns;");
<MASK>update("delete from facility_ftp_details;");</MASK>
}" |
Inversion-Mutation | megadiff | "@Override
public void resultSet(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
int[] types = new int[cols];
String[] labels = new String[cols];
for (int i = 0; i < cols; i++) {
types[i] = rsmd.getColumnType(i + 1);
labels[i] = rsmd.getColumnLabel(i + 1);
}
int[] maxs = new int[cols];
List<String[]> valueList = new ArrayList<>();
int numRecords = 0;
while (rs.next()) {
numRecords++;
String[] values = new String[cols];
for (int i = 0; i < cols; i++) {
String value = rs.getString(i + 1);
if (value == null) {
value = "<null>";
}
values[i] = value;
if (value.length() > maxs[i]) {
maxs[i] = value.length();
}
}
valueList.add(values);
}
StringBuilder b = new StringBuilder();
if (numRecords == 0) {
for (String label : labels) {
if (b.length() > 0) {
b.append(" | ");
}
b.append(label);
}
b.append("\n0 Rows");
output(b.toString());
return;
}
addLine(b, maxs, labels);
addHorizLine(b, maxs);
for (String[] record : valueList) {
addLine(b, maxs, record);
}
String row = "row";
if (numRecords != 1) {
row += "s";
}
b.append(numRecords + " " + row + " returned");
output(b.toString());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "resultSet" | "@Override
public void resultSet(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
int[] types = new int[cols];
String[] labels = new String[cols];
for (int i = 0; i < cols; i++) {
types[i] = rsmd.getColumnType(i + 1);
labels[i] = rsmd.getColumnLabel(i + 1);
}
int[] maxs = new int[cols];
List<String[]> valueList = new ArrayList<>();
int numRecords = 0;
while (rs.next()) {
numRecords++;
String[] values = new String[cols];
for (int i = 0; i < cols; i++) {
String value = rs.getString(i + 1);
<MASK>values[i] = value;</MASK>
if (value == null) {
value = "<null>";
}
if (value.length() > maxs[i]) {
maxs[i] = value.length();
}
}
valueList.add(values);
}
StringBuilder b = new StringBuilder();
if (numRecords == 0) {
for (String label : labels) {
if (b.length() > 0) {
b.append(" | ");
}
b.append(label);
}
b.append("\n0 Rows");
output(b.toString());
return;
}
addLine(b, maxs, labels);
addHorizLine(b, maxs);
for (String[] record : valueList) {
addLine(b, maxs, record);
}
String row = "row";
if (numRecords != 1) {
row += "s";
}
b.append(numRecords + " " + row + " returned");
output(b.toString());
}" |
Inversion-Mutation | megadiff | "public static MenuBar createMenuBar()
{
// create the menu bar
MenuBar menuBar = new MenuBar();
MenuItem m;
int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/****************************** THE FILE MENU ******************************/
Menu fileMenu = new Menu("File", 'F');
menuBar.add(fileMenu);
fileMenu.addMenuItem("New Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newLibraryCommand(); } });
fileMenu.addMenuItem("Open Library", KeyStroke.getKeyStroke('O', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { openLibraryCommand(); } });
Menu importSubMenu = new Menu("Import");
fileMenu.add(importSubMenu);
importSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { importLibraryCommand(); } });
fileMenu.addMenuItem("I/O Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { IOOptions.ioOptionsCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Close Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { closeLibraryCommand(Library.getCurrent()); } });
fileMenu.addMenuItem("Save Library", KeyStroke.getKeyStroke('S', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.ELIB); } });
fileMenu.addMenuItem("Save Library as...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAsLibraryCommand(); } });
fileMenu.addMenuItem("Save All Libraries",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAllLibrariesCommand(); } });
Menu exportSubMenu = new Menu("Export");
fileMenu.add(exportSubMenu);
exportSubMenu.addMenuItem("CIF (Caltech Intermediate Format)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CIF, false); } });
exportSubMenu.addMenuItem("GDS II (Stream)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.GDS, false); } });
exportSubMenu.addMenuItem("PostScript", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.POSTSCRIPT, false); } });
exportSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.READABLEDUMP); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Change Current Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.changeCurrentLibraryCommand(); } });
fileMenu.addMenuItem("List Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.listLibrariesCommand(); } });
fileMenu.addMenuItem("Rename Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameLibraryCommand(); } });
fileMenu.addMenuItem("Mark All Libraries for Saving", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.markAllLibrariesForSavingCommand(); } });
fileMenu.addMenuItem("Repair Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.checkAndRepairCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Print...", KeyStroke.getKeyStroke('P', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { printCommand(); } });
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
fileMenu.addSeparator();
fileMenu.addMenuItem("Quit", KeyStroke.getKeyStroke('Q', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { quitCommand(); } });
}
/****************************** THE EDIT MENU ******************************/
Menu editMenu = new Menu("Edit", 'E');
menuBar.add(editMenu);
editMenu.addMenuItem("Cut", KeyStroke.getKeyStroke('X', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } });
editMenu.addMenuItem("Copy", KeyStroke.getKeyStroke('C', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } });
editMenu.addMenuItem("Paste", KeyStroke.getKeyStroke('V', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(); } });
editMenu.addMenuItem("Duplicate", KeyStroke.getKeyStroke('M', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } });
editMenu.addSeparator();
Menu arcSubMenu = new Menu("Arc", 'A');
editMenu.add(arcSubMenu);
arcSubMenu.addMenuItem("Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }});
arcSubMenu.addMenuItem("Not Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }});
arcSubMenu.addMenuItem("Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }});
arcSubMenu.addMenuItem("Not Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Toggle Directionality", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }});
arcSubMenu.addMenuItem("Toggle Ends Extension", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcEndsExtendCommand(); }});
arcSubMenu.addMenuItem("Reverse", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcReverseCommand(); }});
arcSubMenu.addMenuItem("Toggle Head-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipHeadCommand(); }});
arcSubMenu.addMenuItem("Toggle Tail-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipTailCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Rip Bus", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }});
editMenu.addSeparator();
editMenu.addMenuItem("Undo", KeyStroke.getKeyStroke('Z', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } });
editMenu.addMenuItem("Redo", KeyStroke.getKeyStroke('Y', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } });
editMenu.addSeparator();
Menu rotateSubMenu = new Menu("Rotate", 'R');
editMenu.add(rotateSubMenu);
rotateSubMenu.addMenuItem("90 Degrees Clockwise", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }});
rotateSubMenu.addMenuItem("90 Degrees Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }});
rotateSubMenu.addMenuItem("180 Degrees", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }});
rotateSubMenu.addMenuItem("Other...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }});
Menu mirrorSubMenu = new Menu("Mirror", 'M');
editMenu.add(mirrorSubMenu);
mirrorSubMenu.addMenuItem("Horizontally (flip over X-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }});
mirrorSubMenu.addMenuItem("Vertically (flip over Y-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }});
Menu sizeSubMenu = new Menu("Size", 'S');
editMenu.add(sizeSubMenu);
sizeSubMenu.addMenuItem("Interactively", KeyStroke.getKeyStroke('B', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } });
sizeSubMenu.addMenuItem("All Selected Nodes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }});
sizeSubMenu.addMenuItem("All Selected Arcs...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }});
Menu moveSubMenu = new Menu("Move", 'V');
editMenu.add(moveSubMenu);
moveSubMenu.addMenuItem("Spread...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }});
moveSubMenu.addMenuItem("Move Objects By...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }});
moveSubMenu.addMenuItem("Align to Grid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Horizontally to Left", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }});
moveSubMenu.addMenuItem("Align Horizontally to Right", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }});
moveSubMenu.addMenuItem("Align Horizontally to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Vertically to Top", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }});
moveSubMenu.addMenuItem("Align Vertically to Bottom", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }});
moveSubMenu.addMenuItem("Align Vertically to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }});
editMenu.addMenuItem("Toggle Port Negation", KeyStroke.getKeyStroke('T', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }});
editMenu.addSeparator();
m=editMenu.addMenuItem("Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null);
editMenu.addMenuItem("Erase Geometry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelectedGeometry(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Edit Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { EditOptions.editOptionsCommand(); } });
editMenu.addMenuItem("Key Bindings...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { keyBindingsCommand(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Get Info...", KeyStroke.getKeyStroke('I', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(); } });
Menu editInfoSubMenu = new Menu("Info", 'V');
editMenu.add(editInfoSubMenu);
editInfoSubMenu.addMenuItem("Attributes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } });
editInfoSubMenu.addMenuItem("See All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Hide All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Default Parameter Visibility", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } });
editInfoSubMenu.addSeparator();
editInfoSubMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(false); } });
editMenu.addSeparator();
Menu modeSubMenu = new Menu("Modes");
editMenu.add(modeSubMenu);
Menu modeSubMenuEdit = new Menu("Edit");
modeSubMenu.add(modeSubMenuEdit);
ButtonGroup editGroup = new ButtonGroup();
JMenuItem cursorClickZoomWire, cursorSelect, cursorWiring, cursorPan, cursorZoom, cursorOutline, cursorMeasure;
cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } });
ToolBar.CursorMode cm = ToolBar.getCursorMode();
if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true);
if (ToolBar.secondaryInputModes) {
cursorSelect = modeSubMenuEdit.addRadioButton(ToolBar.cursorSelectName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectCommand(); } });
cursorWiring = modeSubMenuEdit.addRadioButton(ToolBar.cursorWiringName, false, editGroup, KeyStroke.getKeyStroke('W', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.wiringCommand(); } });
if (cm == ToolBar.CursorMode.SELECT) cursorSelect.setSelected(true);
if (cm == ToolBar.CursorMode.WIRE) cursorWiring.setSelected(true);
}
cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } });
cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } });
cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } });
cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } });
if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true);
if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true);
if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true);
if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true);
Menu modeSubMenuMovement = new Menu("Movement");
modeSubMenu.add(modeSubMenuMovement);
ButtonGroup movementGroup = new ButtonGroup();
JMenuItem moveFull, moveHalf, moveQuarter;
moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.fullArrowDistanceCommand(); } });
moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.halfArrowDistanceCommand(); } });
moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.quarterArrowDistanceCommand(); } });
double ad = ToolBar.getArrowDistance();
if (ad == 1.0) moveFull.setSelected(true); else
if (ad == 0.5) moveHalf.setSelected(true); else
moveQuarter.setSelected(true);
Menu modeSubMenuSelect = new Menu("Select");
modeSubMenu.add(modeSubMenuSelect);
ButtonGroup selectGroup = new ButtonGroup();
JMenuItem selectArea, selectObjects;
selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } });
selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } });
ToolBar.SelectMode sm = ToolBar.getSelectMode();
if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else
selectObjects.setSelected(true);
modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } });
editMenu.addMenuItem("Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } });
editMenu.addMenuItem("Insert Jog In Arc", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } });
editMenu.addMenuItem("Change...", KeyStroke.getKeyStroke('C', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } });
Menu textSubMenu = new Menu("Text");
editMenu.add(textSubMenu);
textSubMenu.addMenuItem("Find Text...", KeyStroke.getKeyStroke('L', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }});
textSubMenu.addMenuItem("Change Text Size...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }});
textSubMenu.addMenuItem("Read Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.readTextCell(); }});
textSubMenu.addMenuItem("Save Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.writeTextCell(); }});
Menu cleanupSubMenu = new Menu("Cleanup Cell");
editMenu.add(cleanupSubMenu);
cleanupSubMenu.addMenuItem("Cleanup Pins", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }});
cleanupSubMenu.addMenuItem("Cleanup Pins Everywhere", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }});
cleanupSubMenu.addMenuItem("Show Nonmanhattan", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }});
cleanupSubMenu.addMenuItem("Shorten Selected Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }});
Menu specialSubMenu = new Menu("Special Function");
editMenu.add(specialSubMenu);
specialSubMenu.addMenuItem("Show Undo List", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } });
m = specialSubMenu.addMenuItem("Show Cursor Coordinates", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
m = specialSubMenu.addMenuItem("Artwork Appearance...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
Menu selListSubMenu = new Menu("Selection");
editMenu.add(selListSubMenu);
selListSubMenu.addMenuItem("Select All", KeyStroke.getKeyStroke('A', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }});
selListSubMenu.addMenuItem("Select All Like This", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }});
selListSubMenu.addMenuItem("Select Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }});
selListSubMenu.addMenuItem("Select Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }});
selListSubMenu.addMenuItem("Select Nothing", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Select Object...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }});
selListSubMenu.addMenuItem("Deselect All Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Make Selected Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
selListSubMenu.addMenuItem("Make Selected Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }});
selListSubMenu.addSeparator();
m = selListSubMenu.addMenuItem("Push Selection", KeyStroke.getKeyStroke('1', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
m = selListSubMenu.addMenuItem("Pop Selection", KeyStroke.getKeyStroke('3', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Enclosed Objects", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Show Next Error", KeyStroke.getKeyStroke('>'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }});
selListSubMenu.addMenuItem("Show Previous Error", KeyStroke.getKeyStroke('<'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }});
/****************************** THE CELL MENU ******************************/
Menu cellMenu = new Menu("Cell", 'C');
menuBar.add(cellMenu);
cellMenu.addMenuItem("Edit Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.editCell); }});
cellMenu.addMenuItem("Place Cell Instance...", KeyStroke.getKeyStroke('N', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.newInstance); }});
cellMenu.addMenuItem("New Cell...", KeyStroke.getKeyStroke('N', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellCommand(); } });
cellMenu.addMenuItem("Rename Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.renameCell); }});
cellMenu.addMenuItem("Duplicate Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.duplicateCell); }});
cellMenu.addMenuItem("Delete Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.deleteCell); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("Delete Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteCellCommand(); } });
cellMenu.addMenuItem("Cell Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellControlCommand(); }});
cellMenu.addMenuItem("Cross-Library Copy...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { crossLibraryCopyCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Down Hierarchy", KeyStroke.getKeyStroke('D', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m = cellMenu.addMenuItem("Down Hierarchy In Place", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m.setEnabled(false);
cellMenu.addMenuItem("Up Hierarchy", KeyStroke.getKeyStroke('U', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { upHierCommand(); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("New Version of Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellVersionCommand(); } });
cellMenu.addMenuItem("Duplicate Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { duplicateCellCommand(); } });
cellMenu.addMenuItem("Delete Unused Old Versions", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteOldCellVersionsCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Describe this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.describeThisCellCommand(); } });
cellMenu.addMenuItem("General Cell Lists...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.generalCellListsCommand(); } });
Menu specListSubMenu = new Menu("Special Cell Lists");
cellMenu.add(specListSubMenu);
specListSubMenu.addMenuItem("List Nodes in this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listNodesInCellCommand(); }});
specListSubMenu.addMenuItem("List Cell Instances", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellInstancesCommand(); }});
specListSubMenu.addMenuItem("List Cell Usage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellUsageCommand(); }});
cellMenu.addMenuItem("Cell Parameters...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellParametersCommand(); } });
cellMenu.addSeparator();
Menu expandListSubMenu = new Menu("Expand Cell Instances");
cellMenu.add(expandListSubMenu);
expandListSubMenu.addMenuItem("One Level Down", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandOneLevelDownCommand(); }});
expandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandFullCommand(); }});
expandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandSpecificCommand(); }});
Menu unExpandListSubMenu = new Menu("Unexpand Cell Instances");
cellMenu.add(unExpandListSubMenu);
unExpandListSubMenu.addMenuItem("One Level Up", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandOneLevelUpCommand(); }});
unExpandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandFullCommand(); }});
unExpandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m = cellMenu.addMenuItem("Look Inside Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m.setEnabled(false);
cellMenu.addSeparator();
cellMenu.addMenuItem("Package Into Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.packageIntoCell(); } });
cellMenu.addMenuItem("Extract Cell Instance", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.extractCells(); } });
/****************************** THE EXPORT MENU ******************************/
Menu exportMenu = new Menu("Export", 'X');
menuBar.add(exportMenu);
exportMenu.addMenuItem("Create Export...", KeyStroke.getKeyStroke('E', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.newExportCommand(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Re-Export Everything", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportAll(); } });
exportMenu.addMenuItem("Re-Export Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportHighlighted(); } });
exportMenu.addMenuItem("Re-Export Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportPowerAndGround(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Delete Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExport(); } });
exportMenu.addMenuItem("Delete All Exports on Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsOnHighlighted(); } });
exportMenu.addMenuItem("Delete Exports in Area", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsInArea(); } });
exportMenu.addMenuItem("Move Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.moveExport(); } });
exportMenu.addMenuItem("Rename Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.renameExport(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Summarize Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(true); } });
exportMenu.addMenuItem("List Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(false); } });
exportMenu.addMenuItem("Show Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showExports(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Show Ports on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showPorts(); } });
/****************************** THE VIEW MENU ******************************/
Menu viewMenu = new Menu("View", 'V');
menuBar.add(viewMenu);
viewMenu.addMenuItem("View Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { viewControlCommand(); } });
viewMenu.addMenuItem("Change Cell's View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { changeViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Edit Layout View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editLayoutViewCommand(); } });
viewMenu.addMenuItem("Edit Schematic View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editMultiPageSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editIconViewCommand(); } });
viewMenu.addMenuItem("Edit VHDL View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editVHDLViewCommand(); } });
viewMenu.addMenuItem("Edit Documentation View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editDocViewCommand(); } });
viewMenu.addMenuItem("Edit Skeleton View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSkeletonViewCommand(); } });
viewMenu.addMenuItem("Edit Other View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editOtherViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Make Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeIconViewCommand(); } });
viewMenu.addMenuItem("Make Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeMultiPageSchematicViewCommand(); } });
/****************************** THE WINDOW MENU ******************************/
Menu windowMenu = new Menu("Window", 'W');
menuBar.add(windowMenu);
m = windowMenu.addMenuItem("Fill Display", KeyStroke.getKeyStroke('9', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { fullDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, buckyBit), null);
m = windowMenu.addMenuItem("Redisplay Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.redrawDisplay(); } });
m = windowMenu.addMenuItem("Zoom Out", KeyStroke.getKeyStroke('0', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomOutDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, buckyBit), null);
m = windowMenu.addMenuItem("Zoom In", KeyStroke.getKeyStroke('7', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomInDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD7, buckyBit), null);
Menu specialZoomSubMenu = new Menu("Special Zoom");
windowMenu.add(specialZoomSubMenu);
m = specialZoomSubMenu.addMenuItem("Focus on Highlighted", KeyStroke.getKeyStroke('F', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { focusOnHighlighted(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD5, buckyBit), null);
m = specialZoomSubMenu.addMenuItem("Zoom Box", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomBoxCommand(); }});
specialZoomSubMenu.addMenuItem("Make Grid Just Visible", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeGridJustVisibleCommand(); }});
specialZoomSubMenu.addMenuItem("Match Other Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { matchOtherWindowCommand(); }});
windowMenu.addSeparator();
m = windowMenu.addMenuItem("Pan Left", KeyStroke.getKeyStroke('4', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD4, buckyBit), null);
m = windowMenu.addMenuItem("Pan Right", KeyStroke.getKeyStroke('6', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, buckyBit), null);
m = windowMenu.addMenuItem("Pan Up", KeyStroke.getKeyStroke('8', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD8, buckyBit), null);
m = windowMenu.addMenuItem("Pan Down", KeyStroke.getKeyStroke('2', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, buckyBit), null);
Menu panningDistanceSubMenu = new Menu("Panning Distance");
windowMenu.add(panningDistanceSubMenu);
ButtonGroup windowPanGroup = new ButtonGroup();
JMenuItem panSmall, panMedium, panLarge;
panSmall = panningDistanceSubMenu.addRadioButton("Small", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.15); } });
panMedium = panningDistanceSubMenu.addRadioButton("Medium", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.3); } });
panLarge = panningDistanceSubMenu.addRadioButton("Large", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.6); } });
panLarge.setSelected(true);
windowMenu.addSeparator();
windowMenu.addMenuItem("Toggle Grid", KeyStroke.getKeyStroke('G', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { toggleGridCommand(); } });
windowMenu.addSeparator();
Menu windowPartitionSubMenu = new Menu("Adjust Position");
windowMenu.add(windowPartitionSubMenu);
windowPartitionSubMenu.addMenuItem("Tile Horizontally", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { tileHorizontallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Tile Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { tileVerticallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Cascade", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cascadeWindowsCommand(); }});
windowMenu.addMenuItem("Close Window", KeyStroke.getKeyStroke(KeyEvent.VK_W, buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { WindowFrame curWF = WindowFrame.getCurrentWindowFrame();
curWF.finished(); }});
if (!TopLevel.isMDIMode()) {
windowMenu.addSeparator();
windowMenu.addMenuItem("Move to Other Display", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { moveToOtherDisplayCommand(); } });
}
windowMenu.addSeparator();
windowMenu.addMenuItem("Layer Visibility...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerVisibilityCommand(); } });
Menu colorSubMenu = new Menu("Color");
windowMenu.add(colorSubMenu);
colorSubMenu.addMenuItem("Restore Default Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultBackgroundCommand(); }});
colorSubMenu.addMenuItem("Black Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { blackBackgroundCommand(); }});
colorSubMenu.addMenuItem("White Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { whiteBackgroundCommand(); }});
Menu messagesSubMenu = new Menu("Messages Window");
windowMenu.add(messagesSubMenu);
messagesSubMenu.addMenuItem("Save Messages", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().save(); }});
messagesSubMenu.addMenuItem("Clear", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().clear(); }});
/****************************** THE TOOL MENU ******************************/
Menu toolMenu = new Menu("Tool", 'T');
menuBar.add(toolMenu);
//------------------- DRC
Menu drcSubMenu = new Menu("DRC", 'D');
toolMenu.add(drcSubMenu);
drcSubMenu.addMenuItem("Check Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkHierarchically(); }});
drcSubMenu.addMenuItem("Check Selection Area Hierarchically", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkAreaHierarchically(); }});
//------------------- Simulation (SPICE)
Menu spiceSimulationSubMenu = new Menu("Simulation (SPICE)", 'S');
toolMenu.add(spiceSimulationSubMenu);
spiceSimulationSubMenu.addMenuItem("Write SPICE Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.SPICE, true); }});
spiceSimulationSubMenu.addMenuItem("Write CDL Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CDL, true); }});
spiceSimulationSubMenu.addMenuItem("Plot Spice Listing...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotSpiceResults(); }});
m = spiceSimulationSubMenu.addMenuItem("Plot Spice for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
spiceSimulationSubMenu.addMenuItem("Set Spice Model...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setSpiceModel(); }});
spiceSimulationSubMenu.addMenuItem("Add Multiplier", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
spiceSimulationSubMenu.addSeparator();
spiceSimulationSubMenu.addMenuItem("Set Generic SPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 2 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 3 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set HSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set PSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set GnuCap Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SmartSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }});
//------------------- Simulation (Verilog)
Menu verilogSimulationSubMenu = new Menu("Simulation (Verilog)", 'V');
toolMenu.add(verilogSimulationSubMenu);
verilogSimulationSubMenu.addMenuItem("Write Verilog Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.VERILOG, true); } });
verilogSimulationSubMenu.addMenuItem("Plot Verilog VCD Dump...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotVerilogResults(); }});
m = verilogSimulationSubMenu.addMenuItem("Plot Verilog for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
verilogSimulationSubMenu.addSeparator();
verilogSimulationSubMenu.addMenuItem("Set Verilog Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }});
verilogSimulationSubMenu.addSeparator();
Menu verilogWireTypeSubMenu = new Menu("Set Verilog Wire", 'W');
verilogWireTypeSubMenu.addMenuItem("Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(0); }});
verilogWireTypeSubMenu.addMenuItem("Trireg", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(1); }});
verilogWireTypeSubMenu.addMenuItem("Default", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(2); }});
verilogSimulationSubMenu.add(verilogWireTypeSubMenu);
Menu transistorStrengthSubMenu = new Menu("Transistor Strength", 'T');
transistorStrengthSubMenu.addMenuItem("Weak", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(true); }});
transistorStrengthSubMenu.addMenuItem("Normal", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(false); }});
verilogSimulationSubMenu.add(transistorStrengthSubMenu);
//------------------- Simulation (others)
Menu netlisters = new Menu("Simulation (others)");
toolMenu.add(netlisters);
netlisters.addMenuItem("Write IRSIM Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { irsimNetlistCommand(); }});
netlisters.addMenuItem("Write Maxwell Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.MAXWELL, true); } });
//------------------- ERC
Menu ercSubMenu = new Menu("ERC", 'E');
toolMenu.add(ercSubMenu);
ercSubMenu.addMenuItem("Check Wells", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ERCWellCheck.analyzeCurCell(true); } });
ercSubMenu.addMenuItem("Antenna Check", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { new ERCAntenna(); } });
//------------------- Network
Menu networkSubMenu = new Menu("Network", 'N');
toolMenu.add(networkSubMenu);
networkSubMenu.addMenuItem("Show Network", KeyStroke.getKeyStroke('K', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNetworkCommand(); } });
networkSubMenu.addMenuItem("List Networks", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listNetworksCommand(); } });
networkSubMenu.addMenuItem("List Connections on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listConnectionsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports below Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsBelowNetworkCommand(); } });
networkSubMenu.addMenuItem("List Geometry on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listGeometryOnNetworkCommand(); } });
networkSubMenu.addSeparator();
networkSubMenu.addMenuItem("Show Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showPowerAndGround(); } });
networkSubMenu.addMenuItem("Validate Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { validatePowerAndGround(); } });
networkSubMenu.addMenuItem("Redo Network Numbering", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { redoNetworkNumberingCommand(); } });
//------------------- Logical Effort
Menu logEffortSubMenu = new Menu("Logical Effort", 'L');
logEffortSubMenu.addMenuItem("Optimize for Equal Gate Delays", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { optimizeEqualGateDelaysCommand(); }});
logEffortSubMenu.addMenuItem("Print Info for Selected Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { printLEInfoCommand(); }});
toolMenu.add(logEffortSubMenu);
//------------------- Routing
Menu routingSubMenu = new Menu("Routing", 'R');
toolMenu.add(routingSubMenu);
routingSubMenu.addCheckBox("Enable Auto-Stitching", Routing.isAutoStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableAutoStitching(e); } });
routingSubMenu.addMenuItem("Auto-Stitch Now", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(false, true); }});
routingSubMenu.addMenuItem("Auto-Stitch Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(true, true); }});
routingSubMenu.addSeparator();
routingSubMenu.addCheckBox("Enable Mimic-Stitching", Routing.isMimicStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableMimicStitching(e); }});
routingSubMenu.addMenuItem("Mimic-Stitch Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { MimicStitch.mimicStitch(true); }});
routingSubMenu.addMenuItem("Mimic Selected", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.tool.mimicSelected(); }});
routingSubMenu.addSeparator();
routingSubMenu.addMenuItem("Get Unrouted Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { getUnroutedArcCommand(); }});
m = routingSubMenu.addMenuItem("Copy Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
m = routingSubMenu.addMenuItem("Paste Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
//------------------- Generation
Menu generationSubMenu = new Menu("Generation", 'G');
toolMenu.add(generationSubMenu);
generationSubMenu.addMenuItem("Coverage Implants Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { implantGeneratorCommand(true, false); }});
generationSubMenu.addMenuItem("Pad Frame Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { padFrameGeneratorCommand(); }});
toolMenu.addSeparator();
toolMenu.addMenuItem("Tool Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolOptions.toolOptionsCommand(); } });
toolMenu.addMenuItem("List Tools",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listToolsCommand(); } });
Menu languagesSubMenu = new Menu("Languages");
languagesSubMenu.addMenuItem("Run Java Bean Shell Script", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { javaBshScriptCommand(); }});
toolMenu.add(languagesSubMenu);
/****************************** THE HELP MENU ******************************/
Menu helpMenu = new Menu("Help", 'H');
menuBar.add(helpMenu);
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
helpMenu.addMenuItem("About Electric...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { aboutCommand(); } });
}
helpMenu.addMenuItem("Help Index", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { toolTipsCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Describe this Technology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Make fake circuitry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeFakeCircuitryCommand(); } });
helpMenu.addMenuItem("Make fake simulation window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { WaveformWindow.makeFakeWaveformCommand(); }});
// helpMenu.addMenuItem("Whit Diffie's design...", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { whitDiffieCommand(); } });
/****************************** Russell's TEST MENU ******************************/
Menu russMenu = new Menu("Russell", 'R');
menuBar.add(russMenu);
russMenu.addMenuItem("Generate fill cells", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.FillLibGen();
}
});
russMenu.addMenuItem("Gate Generator Regression", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateRegression();
}
});
russMenu.addMenuItem("Generate gate layouts", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateLayoutGenerator();
}
});
russMenu.addMenuItem("create flat netlists for Ivan", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.IvanFlat();
}
});
russMenu.addMenuItem("layout flat", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.LayFlat();
}
});
russMenu.addMenuItem("Jemini", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.ncc.NccJob();
}
});
russMenu.addMenuItem("Random Test", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.Test();
}
});
/****************************** Jon's TEST MENU ******************************/
Menu jongMenu = new Menu("JonG", 'J');
menuBar.add(jongMenu);
jongMenu.addMenuItem("Describe Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(false); }});
jongMenu.addMenuItem("Describe Proto Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(true); }});
jongMenu.addMenuItem("Describe Current Library Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listLibVars(); }});
jongMenu.addMenuItem("Eval Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { evalVarsOnObject(); }});
jongMenu.addMenuItem("LE test1", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { LENetlister.test1(); }});
jongMenu.addMenuItem("Open Purple Lib", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { openP4libCommand(); }});
//jongMenu.addMenuItem("Check Exports", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { checkExports(); }});
/****************************** Gilda's TEST MENU ******************************/
Menu gildaMenu = new Menu("Gilda", 'G');
menuBar.add(gildaMenu);
gildaMenu.addMenuItem("Merge Polyons", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, true);}});
gildaMenu.addMenuItem("Covering Implants", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, false);}});
gildaMenu.addMenuItem("Covering Implants Old", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(false, false);}});
gildaMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(true); } });
/********************************* Hidden Menus *******************************/
Menu wiringShortcuts = new Menu("Circuit Editing");
menuBar.addHidden(wiringShortcuts);
wiringShortcuts.addMenuItem("Wire to Poly", KeyStroke.getKeyStroke(KeyEvent.VK_0, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(0); }});
wiringShortcuts.addMenuItem("Wire to M1", KeyStroke.getKeyStroke(KeyEvent.VK_1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(1); }});
wiringShortcuts.addMenuItem("Wire to M2", KeyStroke.getKeyStroke(KeyEvent.VK_2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(2); }});
wiringShortcuts.addMenuItem("Wire to M3", KeyStroke.getKeyStroke(KeyEvent.VK_3, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(3); }});
wiringShortcuts.addMenuItem("Wire to M4", KeyStroke.getKeyStroke(KeyEvent.VK_4, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(4); }});
wiringShortcuts.addMenuItem("Wire to M5", KeyStroke.getKeyStroke(KeyEvent.VK_5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(5); }});
wiringShortcuts.addMenuItem("Wire to M6", KeyStroke.getKeyStroke(KeyEvent.VK_6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(6); }});
wiringShortcuts.addMenuItem("Switch Wiring Target", KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.switchWiringTarget(); }});
// return the menu bar
return menuBar;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createMenuBar" | "public static MenuBar createMenuBar()
{
// create the menu bar
MenuBar menuBar = new MenuBar();
MenuItem m;
int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/****************************** THE FILE MENU ******************************/
Menu fileMenu = new Menu("File", 'F');
menuBar.add(fileMenu);
fileMenu.addMenuItem("New Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newLibraryCommand(); } });
fileMenu.addMenuItem("Open Library", KeyStroke.getKeyStroke('O', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { openLibraryCommand(); } });
Menu importSubMenu = new Menu("Import");
fileMenu.add(importSubMenu);
importSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { importLibraryCommand(); } });
fileMenu.addMenuItem("I/O Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { IOOptions.ioOptionsCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Close Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { closeLibraryCommand(Library.getCurrent()); } });
fileMenu.addMenuItem("Save Library", KeyStroke.getKeyStroke('S', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.ELIB); } });
fileMenu.addMenuItem("Save Library as...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAsLibraryCommand(); } });
fileMenu.addMenuItem("Save All Libraries",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAllLibrariesCommand(); } });
Menu exportSubMenu = new Menu("Export");
fileMenu.add(exportSubMenu);
exportSubMenu.addMenuItem("CIF (Caltech Intermediate Format)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CIF, false); } });
exportSubMenu.addMenuItem("GDS II (Stream)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.GDS, false); } });
exportSubMenu.addMenuItem("PostScript", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.POSTSCRIPT, false); } });
exportSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.READABLEDUMP); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Change Current Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.changeCurrentLibraryCommand(); } });
fileMenu.addMenuItem("List Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.listLibrariesCommand(); } });
fileMenu.addMenuItem("Rename Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameLibraryCommand(); } });
fileMenu.addMenuItem("Mark All Libraries for Saving", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.markAllLibrariesForSavingCommand(); } });
fileMenu.addMenuItem("Repair Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.checkAndRepairCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Print...", KeyStroke.getKeyStroke('P', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { printCommand(); } });
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
fileMenu.addSeparator();
fileMenu.addMenuItem("Quit", KeyStroke.getKeyStroke('Q', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { quitCommand(); } });
}
/****************************** THE EDIT MENU ******************************/
Menu editMenu = new Menu("Edit", 'E');
menuBar.add(editMenu);
editMenu.addMenuItem("Cut", KeyStroke.getKeyStroke('X', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } });
editMenu.addMenuItem("Copy", KeyStroke.getKeyStroke('C', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } });
editMenu.addMenuItem("Paste", KeyStroke.getKeyStroke('V', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(); } });
editMenu.addMenuItem("Duplicate", KeyStroke.getKeyStroke('M', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } });
editMenu.addSeparator();
Menu arcSubMenu = new Menu("Arc", 'A');
editMenu.add(arcSubMenu);
arcSubMenu.addMenuItem("Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }});
arcSubMenu.addMenuItem("Not Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }});
arcSubMenu.addMenuItem("Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }});
arcSubMenu.addMenuItem("Not Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Toggle Directionality", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }});
arcSubMenu.addMenuItem("Toggle Ends Extension", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcEndsExtendCommand(); }});
arcSubMenu.addMenuItem("Reverse", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcReverseCommand(); }});
arcSubMenu.addMenuItem("Toggle Head-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipHeadCommand(); }});
arcSubMenu.addMenuItem("Toggle Tail-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipTailCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Rip Bus", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }});
editMenu.addSeparator();
editMenu.addMenuItem("Undo", KeyStroke.getKeyStroke('Z', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } });
editMenu.addMenuItem("Redo", KeyStroke.getKeyStroke('Y', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } });
editMenu.addSeparator();
Menu rotateSubMenu = new Menu("Rotate", 'R');
editMenu.add(rotateSubMenu);
rotateSubMenu.addMenuItem("90 Degrees Clockwise", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }});
rotateSubMenu.addMenuItem("90 Degrees Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }});
rotateSubMenu.addMenuItem("180 Degrees", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }});
rotateSubMenu.addMenuItem("Other...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }});
Menu mirrorSubMenu = new Menu("Mirror", 'M');
editMenu.add(mirrorSubMenu);
mirrorSubMenu.addMenuItem("Horizontally (flip over X-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }});
mirrorSubMenu.addMenuItem("Vertically (flip over Y-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }});
Menu sizeSubMenu = new Menu("Size", 'S');
editMenu.add(sizeSubMenu);
sizeSubMenu.addMenuItem("Interactively", KeyStroke.getKeyStroke('B', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } });
sizeSubMenu.addMenuItem("All Selected Nodes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }});
sizeSubMenu.addMenuItem("All Selected Arcs...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }});
Menu moveSubMenu = new Menu("Move", 'V');
editMenu.add(moveSubMenu);
moveSubMenu.addMenuItem("Spread...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }});
moveSubMenu.addMenuItem("Move Objects By...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }});
moveSubMenu.addMenuItem("Align to Grid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Horizontally to Left", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }});
moveSubMenu.addMenuItem("Align Horizontally to Right", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }});
moveSubMenu.addMenuItem("Align Horizontally to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Vertically to Top", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }});
moveSubMenu.addMenuItem("Align Vertically to Bottom", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }});
moveSubMenu.addMenuItem("Align Vertically to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }});
editMenu.addMenuItem("Toggle Port Negation", KeyStroke.getKeyStroke('T', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }});
editMenu.addSeparator();
m=editMenu.addMenuItem("Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null);
editMenu.addMenuItem("Erase Geometry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelectedGeometry(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Edit Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { EditOptions.editOptionsCommand(); } });
editMenu.addMenuItem("Key Bindings...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { keyBindingsCommand(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Get Info...", KeyStroke.getKeyStroke('I', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(); } });
Menu editInfoSubMenu = new Menu("Info", 'V');
editMenu.add(editInfoSubMenu);
editInfoSubMenu.addMenuItem("Attributes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } });
editInfoSubMenu.addMenuItem("See All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Hide All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Default Parameter Visibility", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } });
editInfoSubMenu.addSeparator();
editInfoSubMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(false); } });
editMenu.addSeparator();
Menu modeSubMenu = new Menu("Modes");
editMenu.add(modeSubMenu);
Menu modeSubMenuEdit = new Menu("Edit");
modeSubMenu.add(modeSubMenuEdit);
ButtonGroup editGroup = new ButtonGroup();
JMenuItem cursorClickZoomWire, cursorSelect, cursorWiring, cursorPan, cursorZoom, cursorOutline, cursorMeasure;
cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } });
ToolBar.CursorMode cm = ToolBar.getCursorMode();
if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true);
if (ToolBar.secondaryInputModes) {
cursorSelect = modeSubMenuEdit.addRadioButton(ToolBar.cursorSelectName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectCommand(); } });
cursorWiring = modeSubMenuEdit.addRadioButton(ToolBar.cursorWiringName, false, editGroup, KeyStroke.getKeyStroke('W', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.wiringCommand(); } });
if (cm == ToolBar.CursorMode.SELECT) cursorSelect.setSelected(true);
if (cm == ToolBar.CursorMode.WIRE) cursorWiring.setSelected(true);
}
cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } });
cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } });
cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } });
cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } });
if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true);
if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true);
if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true);
if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true);
Menu modeSubMenuMovement = new Menu("Movement");
modeSubMenu.add(modeSubMenuMovement);
ButtonGroup movementGroup = new ButtonGroup();
JMenuItem moveFull, moveHalf, moveQuarter;
moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.fullArrowDistanceCommand(); } });
moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.halfArrowDistanceCommand(); } });
moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.quarterArrowDistanceCommand(); } });
double ad = ToolBar.getArrowDistance();
if (ad == 1.0) moveFull.setSelected(true); else
if (ad == 0.5) moveHalf.setSelected(true); else
moveQuarter.setSelected(true);
Menu modeSubMenuSelect = new Menu("Select");
modeSubMenu.add(modeSubMenuSelect);
ButtonGroup selectGroup = new ButtonGroup();
JMenuItem selectArea, selectObjects;
selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } });
selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } });
ToolBar.SelectMode sm = ToolBar.getSelectMode();
if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else
selectObjects.setSelected(true);
modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } });
editMenu.addMenuItem("Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } });
editMenu.addMenuItem("Insert Jog In Arc", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } });
editMenu.addMenuItem("Change...", KeyStroke.getKeyStroke('C', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } });
Menu textSubMenu = new Menu("Text");
editMenu.add(textSubMenu);
textSubMenu.addMenuItem("Find Text...", KeyStroke.getKeyStroke('L', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }});
textSubMenu.addMenuItem("Change Text Size...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }});
textSubMenu.addMenuItem("Read Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.readTextCell(); }});
textSubMenu.addMenuItem("Save Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.writeTextCell(); }});
Menu cleanupSubMenu = new Menu("Cleanup Cell");
editMenu.add(cleanupSubMenu);
cleanupSubMenu.addMenuItem("Cleanup Pins", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }});
cleanupSubMenu.addMenuItem("Cleanup Pins Everywhere", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }});
cleanupSubMenu.addMenuItem("Show Nonmanhattan", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }});
cleanupSubMenu.addMenuItem("Shorten Selected Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }});
Menu specialSubMenu = new Menu("Special Function");
editMenu.add(specialSubMenu);
specialSubMenu.addMenuItem("Show Undo List", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } });
m = specialSubMenu.addMenuItem("Show Cursor Coordinates", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
m = specialSubMenu.addMenuItem("Artwork Appearance...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
Menu selListSubMenu = new Menu("Selection");
editMenu.add(selListSubMenu);
selListSubMenu.addMenuItem("Select All", KeyStroke.getKeyStroke('A', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }});
selListSubMenu.addMenuItem("Select All Like This", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }});
selListSubMenu.addMenuItem("Select Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }});
selListSubMenu.addMenuItem("Select Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }});
selListSubMenu.addMenuItem("Select Nothing", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Select Object...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }});
selListSubMenu.addMenuItem("Deselect All Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Make Selected Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
selListSubMenu.addMenuItem("Make Selected Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }});
selListSubMenu.addSeparator();
m = selListSubMenu.addMenuItem("Push Selection", KeyStroke.getKeyStroke('1', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
m = selListSubMenu.addMenuItem("Pop Selection", KeyStroke.getKeyStroke('3', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Enclosed Objects", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Show Next Error", KeyStroke.getKeyStroke('>'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }});
selListSubMenu.addMenuItem("Show Previous Error", KeyStroke.getKeyStroke('<'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }});
/****************************** THE CELL MENU ******************************/
Menu cellMenu = new Menu("Cell", 'C');
menuBar.add(cellMenu);
cellMenu.addMenuItem("Edit Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.editCell); }});
cellMenu.addMenuItem("Place Cell Instance...", KeyStroke.getKeyStroke('N', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.newInstance); }});
cellMenu.addMenuItem("New Cell...", KeyStroke.getKeyStroke('N', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellCommand(); } });
cellMenu.addMenuItem("Rename Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.renameCell); }});
cellMenu.addMenuItem("Duplicate Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.duplicateCell); }});
cellMenu.addMenuItem("Delete Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.deleteCell); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("Delete Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteCellCommand(); } });
cellMenu.addMenuItem("Cell Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellControlCommand(); }});
cellMenu.addMenuItem("Cross-Library Copy...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { crossLibraryCopyCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Down Hierarchy", KeyStroke.getKeyStroke('D', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m = cellMenu.addMenuItem("Down Hierarchy In Place", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m.setEnabled(false);
cellMenu.addMenuItem("Up Hierarchy", KeyStroke.getKeyStroke('U', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { upHierCommand(); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("New Version of Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellVersionCommand(); } });
cellMenu.addMenuItem("Duplicate Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { duplicateCellCommand(); } });
cellMenu.addMenuItem("Delete Unused Old Versions", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteOldCellVersionsCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Describe this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.describeThisCellCommand(); } });
cellMenu.addMenuItem("General Cell Lists...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.generalCellListsCommand(); } });
Menu specListSubMenu = new Menu("Special Cell Lists");
cellMenu.add(specListSubMenu);
specListSubMenu.addMenuItem("List Nodes in this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listNodesInCellCommand(); }});
specListSubMenu.addMenuItem("List Cell Instances", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellInstancesCommand(); }});
specListSubMenu.addMenuItem("List Cell Usage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellUsageCommand(); }});
cellMenu.addMenuItem("Cell Parameters...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellParametersCommand(); } });
cellMenu.addSeparator();
Menu expandListSubMenu = new Menu("Expand Cell Instances");
cellMenu.add(expandListSubMenu);
expandListSubMenu.addMenuItem("One Level Down", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandOneLevelDownCommand(); }});
expandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandFullCommand(); }});
expandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandSpecificCommand(); }});
Menu unExpandListSubMenu = new Menu("Unexpand Cell Instances");
cellMenu.add(unExpandListSubMenu);
unExpandListSubMenu.addMenuItem("One Level Up", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandOneLevelUpCommand(); }});
unExpandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandFullCommand(); }});
unExpandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m = cellMenu.addMenuItem("Look Inside Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m.setEnabled(false);
cellMenu.addSeparator();
cellMenu.addMenuItem("Package Into Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.packageIntoCell(); } });
cellMenu.addMenuItem("Extract Cell Instance", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.extractCells(); } });
/****************************** THE EXPORT MENU ******************************/
Menu exportMenu = new Menu("Export", 'X');
menuBar.add(exportMenu);
exportMenu.addMenuItem("Create Export...", KeyStroke.getKeyStroke('E', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.newExportCommand(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Re-Export Everything", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportAll(); } });
exportMenu.addMenuItem("Re-Export Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportHighlighted(); } });
exportMenu.addMenuItem("Re-Export Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportPowerAndGround(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Delete Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExport(); } });
exportMenu.addMenuItem("Delete All Exports on Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsOnHighlighted(); } });
exportMenu.addMenuItem("Delete Exports in Area", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsInArea(); } });
exportMenu.addMenuItem("Move Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.moveExport(); } });
exportMenu.addMenuItem("Rename Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.renameExport(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Summarize Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(true); } });
exportMenu.addMenuItem("List Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(false); } });
exportMenu.addMenuItem("Show Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showExports(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Show Ports on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showPorts(); } });
/****************************** THE VIEW MENU ******************************/
Menu viewMenu = new Menu("View", 'V');
menuBar.add(viewMenu);
viewMenu.addMenuItem("View Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { viewControlCommand(); } });
viewMenu.addMenuItem("Change Cell's View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { changeViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Edit Layout View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editLayoutViewCommand(); } });
viewMenu.addMenuItem("Edit Schematic View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editMultiPageSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editIconViewCommand(); } });
viewMenu.addMenuItem("Edit VHDL View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editVHDLViewCommand(); } });
viewMenu.addMenuItem("Edit Documentation View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editDocViewCommand(); } });
viewMenu.addMenuItem("Edit Skeleton View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSkeletonViewCommand(); } });
viewMenu.addMenuItem("Edit Other View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editOtherViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Make Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeIconViewCommand(); } });
viewMenu.addMenuItem("Make Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeMultiPageSchematicViewCommand(); } });
/****************************** THE WINDOW MENU ******************************/
Menu windowMenu = new Menu("Window", 'W');
menuBar.add(windowMenu);
m = windowMenu.addMenuItem("Fill Display", KeyStroke.getKeyStroke('9', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { fullDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, buckyBit), null);
m = windowMenu.addMenuItem("Redisplay Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.redrawDisplay(); } });
m = windowMenu.addMenuItem("Zoom Out", KeyStroke.getKeyStroke('0', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomOutDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, buckyBit), null);
m = windowMenu.addMenuItem("Zoom In", KeyStroke.getKeyStroke('7', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomInDisplay(); } });
Menu specialZoomSubMenu = new Menu("Special Zoom");
windowMenu.add(specialZoomSubMenu);
m = specialZoomSubMenu.addMenuItem("Focus on Highlighted", KeyStroke.getKeyStroke('F', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { focusOnHighlighted(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD5, buckyBit), null);
m = specialZoomSubMenu.addMenuItem("Zoom Box", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomBoxCommand(); }});
<MASK>menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD7, buckyBit), null);</MASK>
specialZoomSubMenu.addMenuItem("Make Grid Just Visible", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeGridJustVisibleCommand(); }});
specialZoomSubMenu.addMenuItem("Match Other Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { matchOtherWindowCommand(); }});
windowMenu.addSeparator();
m = windowMenu.addMenuItem("Pan Left", KeyStroke.getKeyStroke('4', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD4, buckyBit), null);
m = windowMenu.addMenuItem("Pan Right", KeyStroke.getKeyStroke('6', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, buckyBit), null);
m = windowMenu.addMenuItem("Pan Up", KeyStroke.getKeyStroke('8', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD8, buckyBit), null);
m = windowMenu.addMenuItem("Pan Down", KeyStroke.getKeyStroke('2', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, buckyBit), null);
Menu panningDistanceSubMenu = new Menu("Panning Distance");
windowMenu.add(panningDistanceSubMenu);
ButtonGroup windowPanGroup = new ButtonGroup();
JMenuItem panSmall, panMedium, panLarge;
panSmall = panningDistanceSubMenu.addRadioButton("Small", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.15); } });
panMedium = panningDistanceSubMenu.addRadioButton("Medium", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.3); } });
panLarge = panningDistanceSubMenu.addRadioButton("Large", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.6); } });
panLarge.setSelected(true);
windowMenu.addSeparator();
windowMenu.addMenuItem("Toggle Grid", KeyStroke.getKeyStroke('G', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { toggleGridCommand(); } });
windowMenu.addSeparator();
Menu windowPartitionSubMenu = new Menu("Adjust Position");
windowMenu.add(windowPartitionSubMenu);
windowPartitionSubMenu.addMenuItem("Tile Horizontally", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { tileHorizontallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Tile Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { tileVerticallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Cascade", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cascadeWindowsCommand(); }});
windowMenu.addMenuItem("Close Window", KeyStroke.getKeyStroke(KeyEvent.VK_W, buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { WindowFrame curWF = WindowFrame.getCurrentWindowFrame();
curWF.finished(); }});
if (!TopLevel.isMDIMode()) {
windowMenu.addSeparator();
windowMenu.addMenuItem("Move to Other Display", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { moveToOtherDisplayCommand(); } });
}
windowMenu.addSeparator();
windowMenu.addMenuItem("Layer Visibility...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerVisibilityCommand(); } });
Menu colorSubMenu = new Menu("Color");
windowMenu.add(colorSubMenu);
colorSubMenu.addMenuItem("Restore Default Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultBackgroundCommand(); }});
colorSubMenu.addMenuItem("Black Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { blackBackgroundCommand(); }});
colorSubMenu.addMenuItem("White Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { whiteBackgroundCommand(); }});
Menu messagesSubMenu = new Menu("Messages Window");
windowMenu.add(messagesSubMenu);
messagesSubMenu.addMenuItem("Save Messages", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().save(); }});
messagesSubMenu.addMenuItem("Clear", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().clear(); }});
/****************************** THE TOOL MENU ******************************/
Menu toolMenu = new Menu("Tool", 'T');
menuBar.add(toolMenu);
//------------------- DRC
Menu drcSubMenu = new Menu("DRC", 'D');
toolMenu.add(drcSubMenu);
drcSubMenu.addMenuItem("Check Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkHierarchically(); }});
drcSubMenu.addMenuItem("Check Selection Area Hierarchically", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkAreaHierarchically(); }});
//------------------- Simulation (SPICE)
Menu spiceSimulationSubMenu = new Menu("Simulation (SPICE)", 'S');
toolMenu.add(spiceSimulationSubMenu);
spiceSimulationSubMenu.addMenuItem("Write SPICE Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.SPICE, true); }});
spiceSimulationSubMenu.addMenuItem("Write CDL Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CDL, true); }});
spiceSimulationSubMenu.addMenuItem("Plot Spice Listing...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotSpiceResults(); }});
m = spiceSimulationSubMenu.addMenuItem("Plot Spice for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
spiceSimulationSubMenu.addMenuItem("Set Spice Model...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setSpiceModel(); }});
spiceSimulationSubMenu.addMenuItem("Add Multiplier", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
spiceSimulationSubMenu.addSeparator();
spiceSimulationSubMenu.addMenuItem("Set Generic SPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 2 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 3 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set HSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set PSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set GnuCap Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SmartSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }});
//------------------- Simulation (Verilog)
Menu verilogSimulationSubMenu = new Menu("Simulation (Verilog)", 'V');
toolMenu.add(verilogSimulationSubMenu);
verilogSimulationSubMenu.addMenuItem("Write Verilog Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.VERILOG, true); } });
verilogSimulationSubMenu.addMenuItem("Plot Verilog VCD Dump...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotVerilogResults(); }});
m = verilogSimulationSubMenu.addMenuItem("Plot Verilog for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
verilogSimulationSubMenu.addSeparator();
verilogSimulationSubMenu.addMenuItem("Set Verilog Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }});
verilogSimulationSubMenu.addSeparator();
Menu verilogWireTypeSubMenu = new Menu("Set Verilog Wire", 'W');
verilogWireTypeSubMenu.addMenuItem("Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(0); }});
verilogWireTypeSubMenu.addMenuItem("Trireg", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(1); }});
verilogWireTypeSubMenu.addMenuItem("Default", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(2); }});
verilogSimulationSubMenu.add(verilogWireTypeSubMenu);
Menu transistorStrengthSubMenu = new Menu("Transistor Strength", 'T');
transistorStrengthSubMenu.addMenuItem("Weak", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(true); }});
transistorStrengthSubMenu.addMenuItem("Normal", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(false); }});
verilogSimulationSubMenu.add(transistorStrengthSubMenu);
//------------------- Simulation (others)
Menu netlisters = new Menu("Simulation (others)");
toolMenu.add(netlisters);
netlisters.addMenuItem("Write IRSIM Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { irsimNetlistCommand(); }});
netlisters.addMenuItem("Write Maxwell Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.MAXWELL, true); } });
//------------------- ERC
Menu ercSubMenu = new Menu("ERC", 'E');
toolMenu.add(ercSubMenu);
ercSubMenu.addMenuItem("Check Wells", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ERCWellCheck.analyzeCurCell(true); } });
ercSubMenu.addMenuItem("Antenna Check", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { new ERCAntenna(); } });
//------------------- Network
Menu networkSubMenu = new Menu("Network", 'N');
toolMenu.add(networkSubMenu);
networkSubMenu.addMenuItem("Show Network", KeyStroke.getKeyStroke('K', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNetworkCommand(); } });
networkSubMenu.addMenuItem("List Networks", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listNetworksCommand(); } });
networkSubMenu.addMenuItem("List Connections on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listConnectionsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports below Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsBelowNetworkCommand(); } });
networkSubMenu.addMenuItem("List Geometry on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listGeometryOnNetworkCommand(); } });
networkSubMenu.addSeparator();
networkSubMenu.addMenuItem("Show Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showPowerAndGround(); } });
networkSubMenu.addMenuItem("Validate Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { validatePowerAndGround(); } });
networkSubMenu.addMenuItem("Redo Network Numbering", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { redoNetworkNumberingCommand(); } });
//------------------- Logical Effort
Menu logEffortSubMenu = new Menu("Logical Effort", 'L');
logEffortSubMenu.addMenuItem("Optimize for Equal Gate Delays", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { optimizeEqualGateDelaysCommand(); }});
logEffortSubMenu.addMenuItem("Print Info for Selected Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { printLEInfoCommand(); }});
toolMenu.add(logEffortSubMenu);
//------------------- Routing
Menu routingSubMenu = new Menu("Routing", 'R');
toolMenu.add(routingSubMenu);
routingSubMenu.addCheckBox("Enable Auto-Stitching", Routing.isAutoStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableAutoStitching(e); } });
routingSubMenu.addMenuItem("Auto-Stitch Now", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(false, true); }});
routingSubMenu.addMenuItem("Auto-Stitch Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(true, true); }});
routingSubMenu.addSeparator();
routingSubMenu.addCheckBox("Enable Mimic-Stitching", Routing.isMimicStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableMimicStitching(e); }});
routingSubMenu.addMenuItem("Mimic-Stitch Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { MimicStitch.mimicStitch(true); }});
routingSubMenu.addMenuItem("Mimic Selected", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.tool.mimicSelected(); }});
routingSubMenu.addSeparator();
routingSubMenu.addMenuItem("Get Unrouted Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { getUnroutedArcCommand(); }});
m = routingSubMenu.addMenuItem("Copy Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
m = routingSubMenu.addMenuItem("Paste Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
//------------------- Generation
Menu generationSubMenu = new Menu("Generation", 'G');
toolMenu.add(generationSubMenu);
generationSubMenu.addMenuItem("Coverage Implants Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { implantGeneratorCommand(true, false); }});
generationSubMenu.addMenuItem("Pad Frame Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { padFrameGeneratorCommand(); }});
toolMenu.addSeparator();
toolMenu.addMenuItem("Tool Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolOptions.toolOptionsCommand(); } });
toolMenu.addMenuItem("List Tools",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listToolsCommand(); } });
Menu languagesSubMenu = new Menu("Languages");
languagesSubMenu.addMenuItem("Run Java Bean Shell Script", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { javaBshScriptCommand(); }});
toolMenu.add(languagesSubMenu);
/****************************** THE HELP MENU ******************************/
Menu helpMenu = new Menu("Help", 'H');
menuBar.add(helpMenu);
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
helpMenu.addMenuItem("About Electric...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { aboutCommand(); } });
}
helpMenu.addMenuItem("Help Index", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { toolTipsCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Describe this Technology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Make fake circuitry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeFakeCircuitryCommand(); } });
helpMenu.addMenuItem("Make fake simulation window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { WaveformWindow.makeFakeWaveformCommand(); }});
// helpMenu.addMenuItem("Whit Diffie's design...", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { whitDiffieCommand(); } });
/****************************** Russell's TEST MENU ******************************/
Menu russMenu = new Menu("Russell", 'R');
menuBar.add(russMenu);
russMenu.addMenuItem("Generate fill cells", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.FillLibGen();
}
});
russMenu.addMenuItem("Gate Generator Regression", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateRegression();
}
});
russMenu.addMenuItem("Generate gate layouts", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateLayoutGenerator();
}
});
russMenu.addMenuItem("create flat netlists for Ivan", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.IvanFlat();
}
});
russMenu.addMenuItem("layout flat", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.LayFlat();
}
});
russMenu.addMenuItem("Jemini", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.ncc.NccJob();
}
});
russMenu.addMenuItem("Random Test", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.Test();
}
});
/****************************** Jon's TEST MENU ******************************/
Menu jongMenu = new Menu("JonG", 'J');
menuBar.add(jongMenu);
jongMenu.addMenuItem("Describe Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(false); }});
jongMenu.addMenuItem("Describe Proto Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(true); }});
jongMenu.addMenuItem("Describe Current Library Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listLibVars(); }});
jongMenu.addMenuItem("Eval Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { evalVarsOnObject(); }});
jongMenu.addMenuItem("LE test1", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { LENetlister.test1(); }});
jongMenu.addMenuItem("Open Purple Lib", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { openP4libCommand(); }});
//jongMenu.addMenuItem("Check Exports", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { checkExports(); }});
/****************************** Gilda's TEST MENU ******************************/
Menu gildaMenu = new Menu("Gilda", 'G');
menuBar.add(gildaMenu);
gildaMenu.addMenuItem("Merge Polyons", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, true);}});
gildaMenu.addMenuItem("Covering Implants", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, false);}});
gildaMenu.addMenuItem("Covering Implants Old", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(false, false);}});
gildaMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(true); } });
/********************************* Hidden Menus *******************************/
Menu wiringShortcuts = new Menu("Circuit Editing");
menuBar.addHidden(wiringShortcuts);
wiringShortcuts.addMenuItem("Wire to Poly", KeyStroke.getKeyStroke(KeyEvent.VK_0, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(0); }});
wiringShortcuts.addMenuItem("Wire to M1", KeyStroke.getKeyStroke(KeyEvent.VK_1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(1); }});
wiringShortcuts.addMenuItem("Wire to M2", KeyStroke.getKeyStroke(KeyEvent.VK_2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(2); }});
wiringShortcuts.addMenuItem("Wire to M3", KeyStroke.getKeyStroke(KeyEvent.VK_3, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(3); }});
wiringShortcuts.addMenuItem("Wire to M4", KeyStroke.getKeyStroke(KeyEvent.VK_4, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(4); }});
wiringShortcuts.addMenuItem("Wire to M5", KeyStroke.getKeyStroke(KeyEvent.VK_5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(5); }});
wiringShortcuts.addMenuItem("Wire to M6", KeyStroke.getKeyStroke(KeyEvent.VK_6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(6); }});
wiringShortcuts.addMenuItem("Switch Wiring Target", KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.switchWiringTarget(); }});
// return the menu bar
return menuBar;
}" |
Inversion-Mutation | megadiff | "private Element createAttributeElement(Element tag, String name, PropertyBase attribute) {
Element attr = tag.addElement("attribute");
addDescription(attr, attribute);
attr.addElement("name").addText(name);
if (attribute.isRequired()) {
attr.addElement("required").addText("true");
}
attr.addElement("type").addText(attribute.getType().getName());
return attr;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createAttributeElement" | "private Element createAttributeElement(Element tag, String name, PropertyBase attribute) {
Element attr = tag.addElement("attribute");
addDescription(attr, attribute);
attr.addElement("name").addText(name);
<MASK>attr.addElement("type").addText(attribute.getType().getName());</MASK>
if (attribute.isRequired()) {
attr.addElement("required").addText("true");
}
return attr;
}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.