type
stringclasses 1
value | dataset
stringclasses 1
value | input
stringlengths 75
160k
| instruction
stringlengths 117
171
| output
stringlengths 88
168k
|
---|---|---|---|---|
Inversion-Mutation | megadiff | "public void actionPerformed(final ActionEvent e)
{
final CreateNewRepositoryFolderDialog newFolderDialog =
new CreateNewRepositoryFolderDialog(RepositoryPublishDialog.this);
if (!newFolderDialog.performEdit())
{
return;
}
final FileObject treeNode = getSelectedView();
if (treeNode == null)
{
return;
}
if (!StringUtils.isEmpty(newFolderDialog.getName()))
{
final Component glassPane = SwingUtilities.getRootPane(RepositoryPublishDialog.this).getGlassPane();
try
{
glassPane.setVisible(true);
glassPane.setCursor(new Cursor(Cursor.WAIT_CURSOR));
final FileObject child = treeNode.resolveFile(newFolderDialog.getFolderName());
child.createFolder();
if (child instanceof WebSolutionFileObject)
{
final WebSolutionFileObject webSolutionFileObject = (WebSolutionFileObject) child;
webSolutionFileObject.setDescription(newFolderDialog.getDescription());
}
getTable().refresh();
}
catch (Exception e1)
{
UncaughtExceptionsModel.getInstance().addException(e1);
}
finally
{
glassPane.setVisible(false);
glassPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed" | "public void actionPerformed(final ActionEvent e)
{
final CreateNewRepositoryFolderDialog newFolderDialog =
new CreateNewRepositoryFolderDialog(RepositoryPublishDialog.this);
if (!newFolderDialog.performEdit())
{
return;
}
final FileObject treeNode = getSelectedView();
if (treeNode == null)
{
return;
}
if (!StringUtils.isEmpty(newFolderDialog.getName()))
{
final Component glassPane = SwingUtilities.getRootPane(RepositoryPublishDialog.this).getGlassPane();
try
{
glassPane.setVisible(true);
glassPane.setCursor(new Cursor(Cursor.WAIT_CURSOR));
final FileObject child = treeNode.resolveFile(newFolderDialog.getFolderName());
if (child instanceof WebSolutionFileObject)
{
final WebSolutionFileObject webSolutionFileObject = (WebSolutionFileObject) child;
webSolutionFileObject.setDescription(newFolderDialog.getDescription());
}
<MASK>child.createFolder();</MASK>
getTable().refresh();
}
catch (Exception e1)
{
UncaughtExceptionsModel.getInstance().addException(e1);
}
finally
{
glassPane.setVisible(false);
glassPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}" |
Inversion-Mutation | megadiff | "public void submitJob(final Job job, boolean stageFiles,
DtoActionStatus status) throws JobSubmissionException {
final String debug_token = "SUBMIT_" + job.getJobname() + ": ";
try {
int noStageins = 0;
if (stageFiles) {
final List<Element> stageIns = JsdlHelpers
.getStageInElements(job.getJobDescription());
noStageins = stageIns.size();
}
status.setTotalElements(status.getTotalElements() + 4 + noStageins);
// myLogger.debug("Preparing job environment...");
job.addLogMessage("Preparing job environment.");
status.addElement("Preparing job environment...");
addLogMessageToPossibleMultiPartJobParent(job,
"Starting job submission for job: " + job.getJobname());
myLogger.debug(debug_token + "preparing job environment...");
prepareJobEnvironment(job);
myLogger.debug(debug_token + "preparing job environment finished.");
if (stageFiles) {
myLogger.debug(debug_token + "staging in files started...");
status.addLogMessage("Starting file stage-in.");
job.addLogMessage("Staging possible input files.");
// myLogger.debug("Staging possible input files...");
stageFiles(job, status);
job.addLogMessage("File staging finished.");
status.addLogMessage("File stage-in finished.");
myLogger.debug(debug_token + "staging in files finished.");
}
status.addElement("Job environment prepared...");
} catch (final Throwable e) {
myLogger.debug(debug_token + "error: " + e.getLocalizedMessage());
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
throw new JobSubmissionException(
"Could not access remote filesystem: "
+ e.getLocalizedMessage());
}
status.addElement("Setting credential...");
myLogger.debug(debug_token + "setting credential started...");
if (job.getFqan() != null) {
try {
job.setCredential(getUser().getCredential(job.getFqan()));
} catch (final Throwable e) {
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Could not create credential to use to submit the job: "
+ e.getLocalizedMessage());
}
} else {
job.addLogMessage("Setting non-vo credential: " + job.getFqan());
job.setCredential(getUser().getCredential());
}
myLogger.debug(debug_token + "setting credential finished.");
myLogger.debug(debug_token
+ "adding job properties as env variables to jsdl..");
Document oldJsdl = job.getJobDescription();
for (String key : job.getJobProperties().keySet()) {
String value = job.getJobProperty(key);
key = "GRISU_" + key.toUpperCase();
if (StringUtils.isNotBlank(value)) {
Element e = JsdlHelpers
.addOrRetrieveExistingApplicationEnvironmentElement(
oldJsdl, key);
e.setTextContent(value);
}
}
job.setJobDescription(oldJsdl);
String handle = null;
myLogger.debug(debug_token + "submitting job to endpoint...");
try {
status.addElement("Starting job submission using GT4...");
job.addLogMessage("Submitting job to endpoint...");
final String candidate = JsdlHelpers.getCandidateHosts(job
.getJobDescription())[0];
final GridResource resource = getUser().getInformationManager()
.getGridResource(candidate);
String version = resource.getGRAMVersion();
if (version == null) {
// TODO is that good enough?
version = "4.0.0";
}
String submissionType = null;
if (version.startsWith("5")) {
submissionType = "GT5";
} else {
submissionType = "GT4";
}
try {
myLogger.debug(debug_token + "submitting...");
handle = getUser().getJobManager().submit(
submissionType, job);
myLogger.debug(debug_token + "submittission finished...");
} catch (final ServerJobSubmissionException e) {
myLogger.debug(debug_token + "submittission failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Job submission failed on server.");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " failed: " + e.getLocalizedMessage());
throw new JobSubmissionException(
"Submission to endpoint failed: "
+ e.getLocalizedMessage());
}
job.addLogMessage("Submission finished.");
} catch (final Throwable e) {
myLogger.debug(debug_token + "something failed: "
+ e.getLocalizedMessage());
// e.printStackTrace();
status.addLogMessage("Job submission failed.");
status.setFailed(true);
status.setFinished(true);
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname() + " failed: "
+ e.getLocalizedMessage());
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Job submission to endpoint failed: "
+ e.getLocalizedMessage(), e);
}
if (handle == null) {
myLogger.debug(debug_token
+ "submission finished but no jobhandle.");
status.addLogMessage("Submission finished but no jobhandle...");
status.setFailed(true);
status.setErrorCause("No jobhandle");
status.setFinished(true);
job.addLogMessage("Submission finished but jobhandle is null...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but jobhandle is null...");
throw new JobSubmissionException(
"Job apparently submitted but jobhandle is null for job: "
+ job.getJobname());
}
try {
myLogger.debug(debug_token + "wrapping up started");
job.addJobProperty(Constants.SUBMISSION_TIME_KEY,
Long.toString(new Date().getTime()));
// we don't want the credential to be stored with the job in this
// case
// TODO or do we want it to be stored?
job.setCredential(null);
job.addLogMessage("Job submission finished successful.");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished successful.");
jobdao.saveOrUpdate(job);
myLogger.debug(debug_token + "wrapping up finished");
myLogger.info("Jobsubmission for job " + job.getJobname()
+ " and user " + getUser().getDn() + " successful.");
status.addElement("Job submission finished...");
status.setFinished(true);
} catch (final Throwable e) {
myLogger.debug(debug_token + "wrapping up failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Submission finished, error in wrap-up...");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission finished, error in wrap-up...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but error in wrap-up...");
throw new JobSubmissionException(
"Job apparently submitted but error in wrap-up for job: "
+ job.getJobname());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "submitJob" | "public void submitJob(final Job job, boolean stageFiles,
DtoActionStatus status) throws JobSubmissionException {
final String debug_token = "SUBMIT_" + job.getJobname() + ": ";
try {
int noStageins = 0;
if (stageFiles) {
final List<Element> stageIns = JsdlHelpers
.getStageInElements(job.getJobDescription());
noStageins = stageIns.size();
}
status.setTotalElements(status.getTotalElements() + 4 + noStageins);
// myLogger.debug("Preparing job environment...");
job.addLogMessage("Preparing job environment.");
status.addElement("Preparing job environment...");
addLogMessageToPossibleMultiPartJobParent(job,
"Starting job submission for job: " + job.getJobname());
myLogger.debug(debug_token + "preparing job environment...");
prepareJobEnvironment(job);
myLogger.debug(debug_token + "preparing job environment finished.");
if (stageFiles) {
myLogger.debug(debug_token + "staging in files started...");
status.addLogMessage("Starting file stage-in.");
job.addLogMessage("Staging possible input files.");
// myLogger.debug("Staging possible input files...");
stageFiles(job, status);
job.addLogMessage("File staging finished.");
status.addLogMessage("File stage-in finished.");
myLogger.debug(debug_token + "staging in files finished.");
}
status.addElement("Job environment prepared...");
} catch (final Throwable e) {
myLogger.debug(debug_token + "error: " + e.getLocalizedMessage());
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
throw new JobSubmissionException(
"Could not access remote filesystem: "
+ e.getLocalizedMessage());
}
status.addElement("Setting credential...");
myLogger.debug(debug_token + "setting credential started...");
if (job.getFqan() != null) {
try {
job.setCredential(getUser().getCredential(job.getFqan()));
} catch (final Throwable e) {
status.setFailed(true);
status.setErrorCause(e.getLocalizedMessage());
status.setFinished(true);
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Could not create credential to use to submit the job: "
+ e.getLocalizedMessage());
}
} else {
job.addLogMessage("Setting non-vo credential: " + job.getFqan());
job.setCredential(getUser().getCredential());
}
myLogger.debug(debug_token + "setting credential finished.");
myLogger.debug(debug_token
+ "adding job properties as env variables to jsdl..");
Document oldJsdl = job.getJobDescription();
for (String key : job.getJobProperties().keySet()) {
<MASK>key = "GRISU_" + key.toUpperCase();</MASK>
String value = job.getJobProperty(key);
if (StringUtils.isNotBlank(value)) {
Element e = JsdlHelpers
.addOrRetrieveExistingApplicationEnvironmentElement(
oldJsdl, key);
e.setTextContent(value);
}
}
job.setJobDescription(oldJsdl);
String handle = null;
myLogger.debug(debug_token + "submitting job to endpoint...");
try {
status.addElement("Starting job submission using GT4...");
job.addLogMessage("Submitting job to endpoint...");
final String candidate = JsdlHelpers.getCandidateHosts(job
.getJobDescription())[0];
final GridResource resource = getUser().getInformationManager()
.getGridResource(candidate);
String version = resource.getGRAMVersion();
if (version == null) {
// TODO is that good enough?
version = "4.0.0";
}
String submissionType = null;
if (version.startsWith("5")) {
submissionType = "GT5";
} else {
submissionType = "GT4";
}
try {
myLogger.debug(debug_token + "submitting...");
handle = getUser().getJobManager().submit(
submissionType, job);
myLogger.debug(debug_token + "submittission finished...");
} catch (final ServerJobSubmissionException e) {
myLogger.debug(debug_token + "submittission failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Job submission failed on server.");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " failed: " + e.getLocalizedMessage());
throw new JobSubmissionException(
"Submission to endpoint failed: "
+ e.getLocalizedMessage());
}
job.addLogMessage("Submission finished.");
} catch (final Throwable e) {
myLogger.debug(debug_token + "something failed: "
+ e.getLocalizedMessage());
// e.printStackTrace();
status.addLogMessage("Job submission failed.");
status.setFailed(true);
status.setFinished(true);
job.addLogMessage("Submission to endpoint failed: "
+ e.getLocalizedMessage());
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname() + " failed: "
+ e.getLocalizedMessage());
myLogger.error(e.getLocalizedMessage(), e);
throw new JobSubmissionException(
"Job submission to endpoint failed: "
+ e.getLocalizedMessage(), e);
}
if (handle == null) {
myLogger.debug(debug_token
+ "submission finished but no jobhandle.");
status.addLogMessage("Submission finished but no jobhandle...");
status.setFailed(true);
status.setErrorCause("No jobhandle");
status.setFinished(true);
job.addLogMessage("Submission finished but jobhandle is null...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but jobhandle is null...");
throw new JobSubmissionException(
"Job apparently submitted but jobhandle is null for job: "
+ job.getJobname());
}
try {
myLogger.debug(debug_token + "wrapping up started");
job.addJobProperty(Constants.SUBMISSION_TIME_KEY,
Long.toString(new Date().getTime()));
// we don't want the credential to be stored with the job in this
// case
// TODO or do we want it to be stored?
job.setCredential(null);
job.addLogMessage("Job submission finished successful.");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished successful.");
jobdao.saveOrUpdate(job);
myLogger.debug(debug_token + "wrapping up finished");
myLogger.info("Jobsubmission for job " + job.getJobname()
+ " and user " + getUser().getDn() + " successful.");
status.addElement("Job submission finished...");
status.setFinished(true);
} catch (final Throwable e) {
myLogger.debug(debug_token + "wrapping up failed: "
+ e.getLocalizedMessage());
status.addLogMessage("Submission finished, error in wrap-up...");
status.setFailed(true);
status.setFinished(true);
status.setErrorCause(e.getLocalizedMessage());
job.addLogMessage("Submission finished, error in wrap-up...");
addLogMessageToPossibleMultiPartJobParent(
job,
"Job submission for job: " + job.getJobname()
+ " finished but error in wrap-up...");
throw new JobSubmissionException(
"Job apparently submitted but error in wrap-up for job: "
+ job.getJobname());
}
}" |
Inversion-Mutation | megadiff | "private void storeDicomFiles(InputStream istream, String parentDir) throws IOException {
File dicomDirectory = new File(temporaryStorageDirectory, parentDir);
dicomDirectory.mkdir();
ZipInputStream zis = new ZipInputStream(istream);
ZipEntryInputStream zeis = null;
while (true) {
try {
zeis = new ZipEntryInputStream(zis);
} catch (EOFException e) {
break;
} catch (IOException e) {
break;
}
BufferedInputStream bis = new BufferedInputStream(zeis);
byte[] data = new byte[BUFFER_SIZE];
int bytesRead = 0;
File dicomFile = new File(dicomDirectory, zeis.getName());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dicomFile));
while ((bytesRead = (bis.read(data, 0, data.length))) > 0) {
bos.write(data, 0, bytesRead);
}
bos.flush();
bos.close();
}
zis.close();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "storeDicomFiles" | "private void storeDicomFiles(InputStream istream, String parentDir) throws IOException {
File dicomDirectory = new File(temporaryStorageDirectory, parentDir);
dicomDirectory.mkdir();
ZipInputStream zis = new ZipInputStream(istream);
ZipEntryInputStream zeis = null;
while (true) {
try {
zeis = new ZipEntryInputStream(zis);
} catch (EOFException e) {
break;
} catch (IOException e) {
break;
}
BufferedInputStream bis = new BufferedInputStream(zeis);
byte[] data = new byte[BUFFER_SIZE];
int bytesRead = 0;
File dicomFile = new File(dicomDirectory, zeis.getName());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dicomFile));
while ((bytesRead = (bis.read(data, 0, data.length))) > 0) {
bos.write(data, 0, bytesRead);
}
bos.flush();
bos.close();
<MASK>zis.close();</MASK>
}
}" |
Inversion-Mutation | megadiff | "public int getFarmedPotential(int goods, Tile tile) {
if (tile == null) {
throw new NullPointerException();
}
int base = tile.potential(goods);
if (getLocation() instanceof ColonyTile && !((ColonyTile) getLocation()).getWorkTile().isLand()
&& !((ColonyTile) getLocation()).getColony().getBuilding(Building.DOCK).isBuilt()) {
base = 0;
}
if (base == 0) {
return 0;
}
base = getProductionUsing(getType(), goods, base, tile);
if (goods == Goods.FURS && getOwner().hasFather(FoundingFather.HENRY_HUDSON)) {
base *= 2;
}
if (getColony() != null) {
base += getColony().getProductionBonus();
}
return Math.max(base, 1);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getFarmedPotential" | "public int getFarmedPotential(int goods, Tile tile) {
if (tile == null) {
throw new NullPointerException();
}
int base = tile.potential(goods);
<MASK>base = getProductionUsing(getType(), goods, base, tile);</MASK>
if (getLocation() instanceof ColonyTile && !((ColonyTile) getLocation()).getWorkTile().isLand()
&& !((ColonyTile) getLocation()).getColony().getBuilding(Building.DOCK).isBuilt()) {
base = 0;
}
if (base == 0) {
return 0;
}
if (goods == Goods.FURS && getOwner().hasFather(FoundingFather.HENRY_HUDSON)) {
base *= 2;
}
if (getColony() != null) {
base += getColony().getProductionBonus();
}
return Math.max(base, 1);
}" |
Inversion-Mutation | megadiff | "public synchronized int subscribeToSensorData(int sensorId, SensorDataListener listener) throws ESException
{
AbstractSensorTask task = sensorTaskMap.get(sensorId);
if (task != null)
{
if (!isSubscribedToBattery)
{
// register with battery sensor
isSubscribedToBattery = true;
batterySubscriptionId = subscribeToSensorData(SensorUtils.SENSOR_TYPE_BATTERY, this);
}
Log.d(TAG, "subscribeToSensorData() subscribing listener to sensorId " + sensorId);
Subscription subscription = new Subscription(task, listener);
int subscriptionId = subscriptionList.registerSubscription(subscription);
return subscriptionId;
}
else
{
throw new ESException(ESException.UNKNOWN_SENSOR_TYPE, "Invalid sensor type: " + sensorId);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "subscribeToSensorData" | "public synchronized int subscribeToSensorData(int sensorId, SensorDataListener listener) throws ESException
{
AbstractSensorTask task = sensorTaskMap.get(sensorId);
if (task != null)
{
if (!isSubscribedToBattery)
{
// register with battery sensor
<MASK>batterySubscriptionId = subscribeToSensorData(SensorUtils.SENSOR_TYPE_BATTERY, this);</MASK>
isSubscribedToBattery = true;
}
Log.d(TAG, "subscribeToSensorData() subscribing listener to sensorId " + sensorId);
Subscription subscription = new Subscription(task, listener);
int subscriptionId = subscriptionList.registerSubscription(subscription);
return subscriptionId;
}
else
{
throw new ESException(ESException.UNKNOWN_SENSOR_TYPE, "Invalid sensor type: " + sensorId);
}
}" |
Inversion-Mutation | megadiff | "@Override
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) {
TileEntitySecurityCore te = (TileEntitySecurityCore) par1World.getBlockTileEntity(par2, par3, par4);
switch (te.inputMode) {
case 1:
par5EntityPlayer.openGui(SecureMod.instance, GuiIdReference.GUI_SECURECOREPASS, par1World, par2, par3, par4);
return true;
case 2:
if (par5EntityPlayer.getHeldItem() != null && par5EntityPlayer.getHeldItem().itemID == SecureModItems.securityPass.itemID && par5EntityPlayer.getHeldItem().getTagCompound() != null) {
if (Integer.toString(par5EntityPlayer.getHeldItem().getTagCompound().getInteger("cardID")).equals(te.passcode)) {
te.setOutput();
return true;
}
}
break;
case 3:
if (par5EntityPlayer.username.equals(te.playerName)) {
te.setOutput();
return true;
}
break;
case 4:
break;
}
te.setRetaliate(par5EntityPlayer);
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBlockActivated" | "@Override
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) {
TileEntitySecurityCore te = (TileEntitySecurityCore) par1World.getBlockTileEntity(par2, par3, par4);
switch (te.inputMode) {
case 1:
par5EntityPlayer.openGui(SecureMod.instance, GuiIdReference.GUI_SECURECOREPASS, par1World, par2, par3, par4);
<MASK>return true;</MASK>
case 2:
if (par5EntityPlayer.getHeldItem() != null && par5EntityPlayer.getHeldItem().itemID == SecureModItems.securityPass.itemID && par5EntityPlayer.getHeldItem().getTagCompound() != null) {
if (Integer.toString(par5EntityPlayer.getHeldItem().getTagCompound().getInteger("cardID")).equals(te.passcode)) {
te.setOutput();
}
<MASK>return true;</MASK>
}
break;
case 3:
if (par5EntityPlayer.username.equals(te.playerName)) {
te.setOutput();
<MASK>return true;</MASK>
}
break;
case 4:
break;
}
te.setRetaliate(par5EntityPlayer);
return false;
}" |
Inversion-Mutation | megadiff | "public void combineWays(Collection<Way> ways) {
// prepare and clean the list of ways to combine
//
if (ways == null || ways.isEmpty())
return;
ways.remove(null); // just in case - remove all null ways from the collection
ways = new HashSet<Way>(ways); // remove duplicates
// try to build a new way which includes all the combined
// ways
//
NodeGraph graph = NodeGraph.createUndirectedGraphFromNodeWays(ways);
List<Node> path = graph.buildSpanningPath();
if (path == null) {
warnCombiningImpossible();
return;
}
// check whether any ways have been reversed in the process
// and build the collection of tags used by the ways to combine
//
TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
List<Way> reversedWays = new LinkedList<Way>();
List<Way> unreversedWays = new LinkedList<Way>();
for (Way w: ways) {
if ((path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
unreversedWays.add(w);
} else {
reversedWays.add(w);
}
}
// reverse path if all ways have been reversed
if (unreversedWays.isEmpty()) {
Collections.reverse(path);
unreversedWays = reversedWays;
reversedWays = null;
}
if ((reversedWays != null) && !reversedWays.isEmpty()) {
if (!confirmChangeDirectionOfWays()) return;
// filter out ways that have no direction-dependent tags
unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
// reverse path if there are more reversed than unreversed ways with direction-dependent tags
if (reversedWays.size() > unreversedWays.size()) {
Collections.reverse(path);
List<Way> tempWays = unreversedWays;
unreversedWays = reversedWays;
reversedWays = tempWays;
}
// if there are still reversed ways with direction-dependent tags, reverse their tags
if (!reversedWays.isEmpty() && Main.pref.getBoolean("tag-correction.reverse-way", true)) {
List<Way> unreversedTagWays = new ArrayList<Way>(ways);
unreversedTagWays.removeAll(reversedWays);
ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
List<Way> reversedTagWays = new ArrayList<Way>();
Collection<Command> changePropertyCommands = null;
for (Way w : reversedWays) {
Way wnew = new Way(w);
reversedTagWays.add(wnew);
try {
changePropertyCommands = reverseWayTagCorrector.execute(w, wnew);
}
catch(UserCancelException ex) {
return;
}
}
if ((changePropertyCommands != null) && !changePropertyCommands.isEmpty()) {
for (Command c : changePropertyCommands) {
c.executeCommand();
}
}
wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
}
}
// create the new way and apply the new node list
//
Way targetWay = getTargetWay(ways);
Way modifiedTargetWay = new Way(targetWay);
modifiedTargetWay.setNodes(path);
TagCollection completeWayTags = new TagCollection(wayTags);
combineTigerTags(completeWayTags);
normalizeTagCollectionBeforeEditing(completeWayTags, ways);
TagCollection tagsToEdit = new TagCollection(completeWayTags);
completeTagCollectionForEditing(tagsToEdit);
CombinePrimitiveResolverDialog dialog = CombinePrimitiveResolverDialog.getInstance();
dialog.getTagConflictResolverModel().populate(tagsToEdit, completeWayTags.getKeysWithMultipleValues());
dialog.setTargetPrimitive(targetWay);
Set<Relation> parentRelations = getParentRelations(ways);
dialog.getRelationMemberConflictResolverModel().populate(
parentRelations,
ways
);
dialog.prepareDefaultDecisions();
// resolve tag conflicts if necessary
//
if (!completeWayTags.isApplicableToPrimitive() || !parentRelations.isEmpty()) {
dialog.setVisible(true);
if (dialog.isCancelled())
return;
}
LinkedList<Command> cmds = new LinkedList<Command>();
LinkedList<Way> deletedWays = new LinkedList<Way>(ways);
deletedWays.remove(targetWay);
cmds.add(new ChangeCommand(targetWay, modifiedTargetWay));
cmds.addAll(dialog.buildResolutionCommands());
cmds.add(new DeleteCommand(deletedWays));
final SequenceCommand sequenceCommand = new SequenceCommand(tr("Combine {0} ways", ways.size()), cmds);
// update gui
final Way selectedWay = targetWay;
Runnable guiTask = new Runnable() {
public void run() {
Main.main.undoRedo.add(sequenceCommand);
getCurrentDataSet().setSelected(selectedWay);
}
};
if (SwingUtilities.isEventDispatchThread()) {
guiTask.run();
} else {
SwingUtilities.invokeLater(guiTask);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "combineWays" | "public void combineWays(Collection<Way> ways) {
// prepare and clean the list of ways to combine
//
if (ways == null || ways.isEmpty())
return;
ways.remove(null); // just in case - remove all null ways from the collection
ways = new HashSet<Way>(ways); // remove duplicates
// try to build a new way which includes all the combined
// ways
//
NodeGraph graph = NodeGraph.createUndirectedGraphFromNodeWays(ways);
List<Node> path = graph.buildSpanningPath();
if (path == null) {
warnCombiningImpossible();
return;
}
// check whether any ways have been reversed in the process
// and build the collection of tags used by the ways to combine
//
TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
List<Way> reversedWays = new LinkedList<Way>();
List<Way> unreversedWays = new LinkedList<Way>();
for (Way w: ways) {
if ((path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
unreversedWays.add(w);
} else {
reversedWays.add(w);
}
}
// reverse path if all ways have been reversed
if (unreversedWays.isEmpty()) {
Collections.reverse(path);
unreversedWays = reversedWays;
reversedWays = null;
}
if ((reversedWays != null) && !reversedWays.isEmpty()) {
if (!confirmChangeDirectionOfWays()) return;
// filter out ways that have no direction-dependent tags
unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
// reverse path if there are more reversed than unreversed ways with direction-dependent tags
if (reversedWays.size() > unreversedWays.size()) {
Collections.reverse(path);
List<Way> tempWays = unreversedWays;
unreversedWays = reversedWays;
reversedWays = tempWays;
}
// if there are still reversed ways with direction-dependent tags, reverse their tags
if (!reversedWays.isEmpty() && Main.pref.getBoolean("tag-correction.reverse-way", true)) {
List<Way> unreversedTagWays = new ArrayList<Way>(ways);
unreversedTagWays.removeAll(reversedWays);
ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
List<Way> reversedTagWays = new ArrayList<Way>();
Collection<Command> changePropertyCommands = null;
for (Way w : reversedWays) {
Way wnew = new Way(w);
reversedTagWays.add(wnew);
try {
changePropertyCommands = reverseWayTagCorrector.execute(w, wnew);
}
catch(UserCancelException ex) {
return;
}
}
if ((changePropertyCommands != null) && !changePropertyCommands.isEmpty()) {
for (Command c : changePropertyCommands) {
c.executeCommand();
}
}
wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
}
}
// create the new way and apply the new node list
//
Way targetWay = getTargetWay(ways);
Way modifiedTargetWay = new Way(targetWay);
modifiedTargetWay.setNodes(path);
TagCollection completeWayTags = new TagCollection(wayTags);
combineTigerTags(completeWayTags);
normalizeTagCollectionBeforeEditing(completeWayTags, ways);
TagCollection tagsToEdit = new TagCollection(completeWayTags);
completeTagCollectionForEditing(tagsToEdit);
CombinePrimitiveResolverDialog dialog = CombinePrimitiveResolverDialog.getInstance();
dialog.getTagConflictResolverModel().populate(tagsToEdit, completeWayTags.getKeysWithMultipleValues());
dialog.setTargetPrimitive(targetWay);
Set<Relation> parentRelations = getParentRelations(ways);
dialog.getRelationMemberConflictResolverModel().populate(
parentRelations,
ways
);
dialog.prepareDefaultDecisions();
// resolve tag conflicts if necessary
//
if (!completeWayTags.isApplicableToPrimitive() || !parentRelations.isEmpty()) {
dialog.setVisible(true);
if (dialog.isCancelled())
return;
}
LinkedList<Command> cmds = new LinkedList<Command>();
LinkedList<Way> deletedWays = new LinkedList<Way>(ways);
deletedWays.remove(targetWay);
<MASK>cmds.add(new DeleteCommand(deletedWays));</MASK>
cmds.add(new ChangeCommand(targetWay, modifiedTargetWay));
cmds.addAll(dialog.buildResolutionCommands());
final SequenceCommand sequenceCommand = new SequenceCommand(tr("Combine {0} ways", ways.size()), cmds);
// update gui
final Way selectedWay = targetWay;
Runnable guiTask = new Runnable() {
public void run() {
Main.main.undoRedo.add(sequenceCommand);
getCurrentDataSet().setSelected(selectedWay);
}
};
if (SwingUtilities.isEventDispatchThread()) {
guiTask.run();
} else {
SwingUtilities.invokeLater(guiTask);
}
}" |
Inversion-Mutation | megadiff | "private void connect() {
LOG.debug("Connecting to bookie: {}", addr);
// Set up the ClientBootStrap so we can create a new Channel connection
// to the bookie.
ClientBootstrap bootstrap = new ClientBootstrap(channelFactory);
bootstrap.setPipelineFactory(this);
bootstrap.setOption("tcpNoDelay", conf.getClientTcpNoDelay());
bootstrap.setOption("keepAlive", true);
ChannelFuture future = bootstrap.connect(addr);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
int rc;
Queue<GenericCallback<Void>> oldPendingOps;
synchronized (PerChannelBookieClient.this) {
if (future.isSuccess() && state == ConnectionState.CONNECTING) {
rc = BKException.Code.OK;
channel = future.getChannel();
state = ConnectionState.CONNECTED;
LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel);
} else if (future.isSuccess() && state == ConnectionState.CONNECTED) {
LOG.info("Already connected with another channel {}, so close the new channel {}", channel, future.getChannel());
rc = BKException.Code.OK;
future.getChannel().close();
assert (state == ConnectionState.CONNECTED);
} else if (future.isSuccess() && (state == ConnectionState.CLOSED
|| state == ConnectionState.DISCONNECTED)) {
LOG.error("Closed before connection completed state {}, clean up: {}", state, future.getChannel());
future.getChannel().close();
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
} else {
LOG.error("Could not connect to bookie: " + addr);
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
if (state != ConnectionState.CLOSED) {
state = ConnectionState.DISCONNECTED;
}
}
// trick to not do operations under the lock, take the list
// of pending ops and assign it to a new variable, while
// emptying the pending ops by just assigning it to a new
// list
oldPendingOps = pendingOps;
pendingOps = new ArrayDeque<GenericCallback<Void>>();
}
for (GenericCallback<Void> pendingOp : oldPendingOps) {
pendingOp.operationComplete(rc, null);
}
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "connect" | "private void connect() {
LOG.debug("Connecting to bookie: {}", addr);
// Set up the ClientBootStrap so we can create a new Channel connection
// to the bookie.
ClientBootstrap bootstrap = new ClientBootstrap(channelFactory);
bootstrap.setPipelineFactory(this);
bootstrap.setOption("tcpNoDelay", conf.getClientTcpNoDelay());
bootstrap.setOption("keepAlive", true);
ChannelFuture future = bootstrap.connect(addr);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
int rc;
Queue<GenericCallback<Void>> oldPendingOps;
synchronized (PerChannelBookieClient.this) {
if (future.isSuccess() && state == ConnectionState.CONNECTING) {
<MASK>LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel);</MASK>
rc = BKException.Code.OK;
channel = future.getChannel();
state = ConnectionState.CONNECTED;
} else if (future.isSuccess() && state == ConnectionState.CONNECTED) {
LOG.info("Already connected with another channel {}, so close the new channel {}", channel, future.getChannel());
rc = BKException.Code.OK;
future.getChannel().close();
assert (state == ConnectionState.CONNECTED);
} else if (future.isSuccess() && (state == ConnectionState.CLOSED
|| state == ConnectionState.DISCONNECTED)) {
LOG.error("Closed before connection completed state {}, clean up: {}", state, future.getChannel());
future.getChannel().close();
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
} else {
LOG.error("Could not connect to bookie: " + addr);
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
if (state != ConnectionState.CLOSED) {
state = ConnectionState.DISCONNECTED;
}
}
// trick to not do operations under the lock, take the list
// of pending ops and assign it to a new variable, while
// emptying the pending ops by just assigning it to a new
// list
oldPendingOps = pendingOps;
pendingOps = new ArrayDeque<GenericCallback<Void>>();
}
for (GenericCallback<Void> pendingOp : oldPendingOps) {
pendingOp.operationComplete(rc, null);
}
}
});
}" |
Inversion-Mutation | megadiff | "@Override
public void operationComplete(ChannelFuture future) throws Exception {
int rc;
Queue<GenericCallback<Void>> oldPendingOps;
synchronized (PerChannelBookieClient.this) {
if (future.isSuccess() && state == ConnectionState.CONNECTING) {
rc = BKException.Code.OK;
channel = future.getChannel();
state = ConnectionState.CONNECTED;
LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel);
} else if (future.isSuccess() && state == ConnectionState.CONNECTED) {
LOG.info("Already connected with another channel {}, so close the new channel {}", channel, future.getChannel());
rc = BKException.Code.OK;
future.getChannel().close();
assert (state == ConnectionState.CONNECTED);
} else if (future.isSuccess() && (state == ConnectionState.CLOSED
|| state == ConnectionState.DISCONNECTED)) {
LOG.error("Closed before connection completed state {}, clean up: {}", state, future.getChannel());
future.getChannel().close();
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
} else {
LOG.error("Could not connect to bookie: " + addr);
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
if (state != ConnectionState.CLOSED) {
state = ConnectionState.DISCONNECTED;
}
}
// trick to not do operations under the lock, take the list
// of pending ops and assign it to a new variable, while
// emptying the pending ops by just assigning it to a new
// list
oldPendingOps = pendingOps;
pendingOps = new ArrayDeque<GenericCallback<Void>>();
}
for (GenericCallback<Void> pendingOp : oldPendingOps) {
pendingOp.operationComplete(rc, null);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "operationComplete" | "@Override
public void operationComplete(ChannelFuture future) throws Exception {
int rc;
Queue<GenericCallback<Void>> oldPendingOps;
synchronized (PerChannelBookieClient.this) {
if (future.isSuccess() && state == ConnectionState.CONNECTING) {
<MASK>LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel);</MASK>
rc = BKException.Code.OK;
channel = future.getChannel();
state = ConnectionState.CONNECTED;
} else if (future.isSuccess() && state == ConnectionState.CONNECTED) {
LOG.info("Already connected with another channel {}, so close the new channel {}", channel, future.getChannel());
rc = BKException.Code.OK;
future.getChannel().close();
assert (state == ConnectionState.CONNECTED);
} else if (future.isSuccess() && (state == ConnectionState.CLOSED
|| state == ConnectionState.DISCONNECTED)) {
LOG.error("Closed before connection completed state {}, clean up: {}", state, future.getChannel());
future.getChannel().close();
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
} else {
LOG.error("Could not connect to bookie: " + addr);
rc = BKException.Code.BookieHandleNotAvailableException;
channel = null;
if (state != ConnectionState.CLOSED) {
state = ConnectionState.DISCONNECTED;
}
}
// trick to not do operations under the lock, take the list
// of pending ops and assign it to a new variable, while
// emptying the pending ops by just assigning it to a new
// list
oldPendingOps = pendingOps;
pendingOps = new ArrayDeque<GenericCallback<Void>>();
}
for (GenericCallback<Void> pendingOp : oldPendingOps) {
pendingOp.operationComplete(rc, null);
}
}" |
Inversion-Mutation | megadiff | "public void beginMinecraftLoading(Minecraft minecraft)
{
client = minecraft;
if (minecraft.func_71355_q())
{
FMLLog.severe("DEMO MODE DETECTED, FML will not work. Finishing now.");
haltGame("FML will not run in demo mode", new RuntimeException());
return;
}
loading = true;
// TextureFXManager.instance().setClient(client);
FMLCommonHandler.instance().beginLoading(this);
new ModLoaderClientHelper(client);
try
{
Class<?> optifineConfig = Class.forName("Config", false, Loader.instance().getModClassLoader());
String optifineVersion = (String) optifineConfig.getField("VERSION").get(null);
Map<String,Object> dummyOptifineMeta = ImmutableMap.<String,Object>builder().put("name", "Optifine").put("version", optifineVersion).build();
ModMetadata optifineMetadata = MetadataCollection.from(getClass().getResourceAsStream("optifinemod.info"),"optifine").getMetadataForId("optifine", dummyOptifineMeta);
optifineContainer = new DummyModContainer(optifineMetadata);
FMLLog.info("Forge Mod Loader has detected optifine %s, enabling compatibility features",optifineContainer.getVersion());
}
catch (Exception e)
{
optifineContainer = null;
}
try
{
Loader.instance().loadMods();
}
catch (WrongMinecraftVersionException wrong)
{
wrongMC = wrong;
}
catch (DuplicateModsFoundException dupes)
{
dupesFound = dupes;
}
catch (MissingModsException missing)
{
modsMissing = missing;
}
catch (CustomModLoadingErrorDisplayException custom)
{
FMLLog.log(Level.SEVERE, custom, "A custom exception was thrown by a mod, the game will now halt");
customError = custom;
}
catch (LoaderException le)
{
haltGame("There was a severe problem during mod loading that has caused the game to fail", le);
return;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "beginMinecraftLoading" | "public void beginMinecraftLoading(Minecraft minecraft)
{
if (minecraft.func_71355_q())
{
FMLLog.severe("DEMO MODE DETECTED, FML will not work. Finishing now.");
haltGame("FML will not run in demo mode", new RuntimeException());
return;
}
loading = true;
<MASK>client = minecraft;</MASK>
// TextureFXManager.instance().setClient(client);
FMLCommonHandler.instance().beginLoading(this);
new ModLoaderClientHelper(client);
try
{
Class<?> optifineConfig = Class.forName("Config", false, Loader.instance().getModClassLoader());
String optifineVersion = (String) optifineConfig.getField("VERSION").get(null);
Map<String,Object> dummyOptifineMeta = ImmutableMap.<String,Object>builder().put("name", "Optifine").put("version", optifineVersion).build();
ModMetadata optifineMetadata = MetadataCollection.from(getClass().getResourceAsStream("optifinemod.info"),"optifine").getMetadataForId("optifine", dummyOptifineMeta);
optifineContainer = new DummyModContainer(optifineMetadata);
FMLLog.info("Forge Mod Loader has detected optifine %s, enabling compatibility features",optifineContainer.getVersion());
}
catch (Exception e)
{
optifineContainer = null;
}
try
{
Loader.instance().loadMods();
}
catch (WrongMinecraftVersionException wrong)
{
wrongMC = wrong;
}
catch (DuplicateModsFoundException dupes)
{
dupesFound = dupes;
}
catch (MissingModsException missing)
{
modsMissing = missing;
}
catch (CustomModLoadingErrorDisplayException custom)
{
FMLLog.log(Level.SEVERE, custom, "A custom exception was thrown by a mod, the game will now halt");
customError = custom;
}
catch (LoaderException le)
{
haltGame("There was a severe problem during mod loading that has caused the game to fail", le);
return;
}
}" |
Inversion-Mutation | megadiff | "public PortfolioView()
throws IOException, ParserConfigurationException, SAXException, NamingException {
frame = new JFrame("Invest");
JLabel label = new JLabel("Starting...", JLabel.CENTER);
label.setPreferredSize(new Dimension(480, 300));
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(frame.getOwner());
frame.setVisible(true);
investments = new Investments(label);
frame.setVisible(false);
frame.remove(label);
mainCommandPanel = new MainCommandPanel(this);
frame.add(mainCommandPanel, BorderLayout.SOUTH);
portfolioMenu = new JMenu("Portfolios");
portfolioMenu.add(new JMenuItem(investments.getCurrentPortfolio().getName()));
JMenuBar menuBar = new JMenuBar();
menuBar.add(portfolioMenu);
mainPanel = new MainPanel(this);
frame.add(mainPanel);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setLocationRelativeTo(frame.getOwner());
frame.setVisible(true);
System.out.println("Done!");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "PortfolioView" | "public PortfolioView()
throws IOException, ParserConfigurationException, SAXException, NamingException {
frame = new JFrame("Invest");
JLabel label = new JLabel("Starting...", JLabel.CENTER);
label.setPreferredSize(new Dimension(480, 300));
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<MASK>frame.setLocationRelativeTo(frame.getOwner());</MASK>
frame.pack();
frame.setVisible(true);
investments = new Investments(label);
frame.setVisible(false);
frame.remove(label);
mainCommandPanel = new MainCommandPanel(this);
frame.add(mainCommandPanel, BorderLayout.SOUTH);
portfolioMenu = new JMenu("Portfolios");
portfolioMenu.add(new JMenuItem(investments.getCurrentPortfolio().getName()));
JMenuBar menuBar = new JMenuBar();
menuBar.add(portfolioMenu);
mainPanel = new MainPanel(this);
frame.add(mainPanel);
frame.setJMenuBar(menuBar);
frame.pack();
<MASK>frame.setLocationRelativeTo(frame.getOwner());</MASK>
frame.setVisible(true);
System.out.println("Done!");
}" |
Inversion-Mutation | megadiff | "public void save(String fileName, boolean onlyData) {
FileOperations.createDirectory(TEMP_PROJECT_FOLDER);
try {
if (!onlyData) {
saveWorkbenchData(TEMP_PROJECT_FOLDER);
}
savePluginData(TEMP_PROJECT_FOLDER);
saveData(TEMP_PROJECT_FOLDER);
}
catch (Exception savingException) {
String failureMessage = "Faild to save project to " + fileName + ".";
Logger.log(new Status(Status.ERROR, "org.caleydo.core", failureMessage, savingException));
if (PlatformUI.isWorkbenchRunning()) {
MessageBox messageBox =
new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OK);
messageBox.setText("Project Save");
messageBox.setMessage(failureMessage);
messageBox.open();
return;
}
}
ZipUtils zipUtils = new ZipUtils();
zipUtils.zipDirectory(TEMP_PROJECT_FOLDER, fileName);
FileOperations.deleteDirectory(TEMP_PROJECT_FOLDER);
String message = "Caleydo project successfully written to\n" + fileName;
Logger.log(new Status(IStatus.INFO, this.toString(), message));
if (PlatformUI.isWorkbenchRunning()) {
MessageBox messageBox =
new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OK);
messageBox.setText("Project Save");
messageBox.setMessage(message);
messageBox.open();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "save" | "public void save(String fileName, boolean onlyData) {
FileOperations.createDirectory(TEMP_PROJECT_FOLDER);
try {
if (!onlyData) {
<MASK>savePluginData(TEMP_PROJECT_FOLDER);</MASK>
saveWorkbenchData(TEMP_PROJECT_FOLDER);
}
saveData(TEMP_PROJECT_FOLDER);
}
catch (Exception savingException) {
String failureMessage = "Faild to save project to " + fileName + ".";
Logger.log(new Status(Status.ERROR, "org.caleydo.core", failureMessage, savingException));
if (PlatformUI.isWorkbenchRunning()) {
MessageBox messageBox =
new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OK);
messageBox.setText("Project Save");
messageBox.setMessage(failureMessage);
messageBox.open();
return;
}
}
ZipUtils zipUtils = new ZipUtils();
zipUtils.zipDirectory(TEMP_PROJECT_FOLDER, fileName);
FileOperations.deleteDirectory(TEMP_PROJECT_FOLDER);
String message = "Caleydo project successfully written to\n" + fileName;
Logger.log(new Status(IStatus.INFO, this.toString(), message));
if (PlatformUI.isWorkbenchRunning()) {
MessageBox messageBox =
new MessageBox(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OK);
messageBox.setText("Project Save");
messageBox.setMessage(message);
messageBox.open();
}
}" |
Inversion-Mutation | megadiff | "public static Resolution invokeEventHandler(ExecutionContext ctx) throws Exception {
final Configuration config = StripesFilter.getConfiguration();
final Method handler = ctx.getHandler();
final ActionBean bean = ctx.getActionBean();
// Finally execute the handler method!
ctx.setLifecycleStage(LifecycleStage.EventHandling);
ctx.setInterceptors(config.getInterceptors(LifecycleStage.EventHandling));
return ctx.wrap( new Interceptor() {
public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
fillInValidationErrors(ctx);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
return null;
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "invokeEventHandler" | "public static Resolution invokeEventHandler(ExecutionContext ctx) throws Exception {
final Configuration config = StripesFilter.getConfiguration();
final Method handler = ctx.getHandler();
final ActionBean bean = ctx.getActionBean();
// Finally execute the handler method!
ctx.setLifecycleStage(LifecycleStage.EventHandling);
ctx.setInterceptors(config.getInterceptors(LifecycleStage.EventHandling));
return ctx.wrap( new Interceptor() {
public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
<MASK>fillInValidationErrors(ctx);</MASK>
return null;
}
});
}" |
Inversion-Mutation | megadiff | "public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
fillInValidationErrors(ctx);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "intercept" | "public Resolution intercept(ExecutionContext ctx) throws Exception {
Object returnValue = handler.invoke(bean);
if (returnValue != null && returnValue instanceof Resolution) {
ctx.setResolutionFromHandler(true);
return (Resolution) returnValue;
}
else if (returnValue != null) {
log.warn("Expected handler method ", handler.getName(), " on class ",
bean.getClass().getSimpleName(), " to return a Resolution. Instead it ",
"returned: ", returnValue);
}
<MASK>fillInValidationErrors(ctx);</MASK>
return null;
}" |
Inversion-Mutation | megadiff | "private void evaluationFinished(IEvaluationResult result) {
fEngine.evaluationThreadFinished(this);
fListener.evaluationComplete(result);
fExpression= null;
fContext= null;
fThread= null;
fListener= null;
fException= null;
fEvaluating = false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "evaluationFinished" | "private void evaluationFinished(IEvaluationResult result) {
<MASK>fEvaluating = false;</MASK>
fEngine.evaluationThreadFinished(this);
fListener.evaluationComplete(result);
fExpression= null;
fContext= null;
fThread= null;
fListener= null;
fException= null;
}" |
Inversion-Mutation | megadiff | "public boolean upgradeTower(ITower tower){
if(playerCanAffordUpgrade(tower)){
player.removeMoney(tower.getUpgradeCost());
tower.upgrade();
return true;
} else {
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "upgradeTower" | "public boolean upgradeTower(ITower tower){
if(playerCanAffordUpgrade(tower)){
<MASK>tower.upgrade();</MASK>
player.removeMoney(tower.getUpgradeCost());
return true;
} else {
return false;
}
}" |
Inversion-Mutation | megadiff | "public void process(RelationContainer relationContainer) {
Relation relation;
EntityType[] entityTypes;
entityTypes = EntityType.values();
relation = relationContainer.getEntity();
relationWriter.writeField(relation.getId());
relationWriter.writeField(relation.getVersion());
relationWriter.writeField(relation.getUser().getId());
relationWriter.writeField(relation.getTimestamp());
relationWriter.writeField(ChangesetAction.ADD.getDatabaseValue());
relationWriter.endRecord();
for (Tag tag : relation.getTagList()) {
relationTagWriter.writeField(relation.getId());
relationTagWriter.writeField(tag.getKey());
relationTagWriter.writeField(tag.getValue());
relationTagWriter.endRecord();
}
for (RelationMember member : relation.getMemberList()) {
relationMemberWriter.writeField(relation.getId());
relationMemberWriter.writeField(member.getMemberId());
for (byte i = 0; i < entityTypes.length; i++) {
if (entityTypes[i].equals(member.getMemberType())) {
relationMemberWriter.writeField(i);
}
}
relationMemberWriter.writeField(member.getMemberRole());
relationMemberWriter.endRecord();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "process" | "public void process(RelationContainer relationContainer) {
Relation relation;
EntityType[] entityTypes;
entityTypes = EntityType.values();
relation = relationContainer.getEntity();
relationWriter.writeField(relation.getId());
relationWriter.writeField(relation.getVersion());
relationWriter.writeField(relation.getUser().getId());
relationWriter.writeField(relation.getTimestamp());
relationWriter.writeField(ChangesetAction.ADD.getDatabaseValue());
relationWriter.endRecord();
for (Tag tag : relation.getTagList()) {
relationTagWriter.writeField(relation.getId());
relationTagWriter.writeField(tag.getKey());
relationTagWriter.writeField(tag.getValue());
relationTagWriter.endRecord();
}
for (RelationMember member : relation.getMemberList()) {
relationMemberWriter.writeField(relation.getId());
relationMemberWriter.writeField(member.getMemberId());
<MASK>relationMemberWriter.writeField(member.getMemberRole());</MASK>
for (byte i = 0; i < entityTypes.length; i++) {
if (entityTypes[i].equals(member.getMemberType())) {
relationMemberWriter.writeField(i);
}
}
relationMemberWriter.endRecord();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onResume() {
super.onResume();
// We look for saved user keys
if(mSettings.contains(App.USER_TOKEN) && mSettings.contains(App.USER_SECRET)) {
mToken = mSettings.getString(App.USER_TOKEN, null);
mSecret = mSettings.getString(App.USER_SECRET, null);
// If we find some we update the consumer with them
if(!(mToken == null || mSecret == null)) {
mConsumer.setTokenWithSecret(mToken, mSecret);
(new GetCredentialsTask()).execute();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onResume" | "@Override
public void onResume() {
super.onResume();
// We look for saved user keys
if(mSettings.contains(App.USER_TOKEN) && mSettings.contains(App.USER_SECRET)) {
mToken = mSettings.getString(App.USER_TOKEN, null);
mSecret = mSettings.getString(App.USER_SECRET, null);
// If we find some we update the consumer with them
if(!(mToken == null || mSecret == null)) {
mConsumer.setTokenWithSecret(mToken, mSecret);
}
}
<MASK>(new GetCredentialsTask()).execute();</MASK>
}" |
Inversion-Mutation | megadiff | "private static Class makeClass(Class referent, Vector secondary,
String name, ByteArrayOutputStream bytes)
{
Vector referents = null;
if (secondary != null) {
if (referent != null) {
secondary.insertElementAt(referent,0);
}
referents = secondary;
} else {
if (referent != null) {
referents = new Vector();
referents.addElement(referent);
}
}
return BytecodeLoader.makeClass(name, referents, bytes.toByteArray());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeClass" | "private static Class makeClass(Class referent, Vector secondary,
String name, ByteArrayOutputStream bytes)
{
Vector referents = null;
if (secondary != null) {
if (referent != null) {
secondary.insertElementAt(referent,0);
<MASK>referents = secondary;</MASK>
}
} else {
if (referent != null) {
referents = new Vector();
referents.addElement(referent);
}
}
return BytecodeLoader.makeClass(name, referents, bytes.toByteArray());
}" |
Inversion-Mutation | megadiff | "private void call(String procUri, CallMeta resultMeta, Object... arguments) {
WampMessage.Call call = new WampMessage.Call(newId(), procUri, arguments.length);
for (int i = 0; i < arguments.length; ++i) {
call.mArgs[i] = arguments[i];
}
mCalls.put(call.mCallId, resultMeta);
mWriter.forward(call);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "call" | "private void call(String procUri, CallMeta resultMeta, Object... arguments) {
WampMessage.Call call = new WampMessage.Call(newId(), procUri, arguments.length);
for (int i = 0; i < arguments.length; ++i) {
call.mArgs[i] = arguments[i];
}
<MASK>mWriter.forward(call);</MASK>
mCalls.put(call.mCallId, resultMeta);
}" |
Inversion-Mutation | megadiff | "@Override
public void tearDown() throws Exception {
if (root.hasNode(ID_TEST)) {
root.getNode(ID_TEST).remove();
session.save();
}
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>super.tearDown();</MASK>
if (root.hasNode(ID_TEST)) {
root.getNode(ID_TEST).remove();
session.save();
}
}" |
Inversion-Mutation | megadiff | "Augmentations handleEndElement(QName element, Augmentations augs) {
if (DEBUG) {
System.out.println("==>handleEndElement:" +element);
}
// if we are skipping, return
if (fSkipValidationDepth >= 0) {
// but if this is the top element that we are skipping,
// restore the states.
if (fSkipValidationDepth == fElementDepth &&
fSkipValidationDepth > 0) {
// set the partial validation depth to the depth of parent
fNFullValidationDepth = fSkipValidationDepth-1;
fSkipValidationDepth = -1;
fElementDepth--;
fSubElement = fSubElementStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fNotation = fNotationStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fStrictAssess = fStrictAssessStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawText = fSawTextStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
fSawChildren = fSawChildrenStack[fElementDepth];
}
else {
fElementDepth--;
}
// PSVI: validation attempted:
// use default values in psvi item for
// validation attempted, validity, and error codes
// check extra schema constraints on root element
if (fElementDepth == -1 && fFullChecking) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter);
}
if (fAugPSVI)
augs = getEmptyAugs(augs);
return augs;
}
// now validate the content of the element
processElementContent(element);
// Element Locally Valid (Element)
// 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4).
// call matchers and de-activate context
int oldCount = fMatcherStack.getMatcherCount();
for (int i = oldCount - 1; i >= 0; i--) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.endElement(element, fCurrentElemDecl,
fDefaultValue == null ?
fValidatedInfo.normalizedValue :
fCurrentElemDecl.fDefault.normalizedValue);
}
if (fMatcherStack.size() > 0) {
fMatcherStack.popContext();
}
int newCount = fMatcherStack.getMatcherCount();
// handle everything *but* keyref's.
for (int i = oldCount - 1; i >= newCount; i--) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
if(matcher instanceof Selector.Matcher) {
Selector.Matcher selMatcher = (Selector.Matcher)matcher;
IdentityConstraint id;
if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) {
fValueStoreCache.transplant(id, selMatcher.getInitialDepth());
}
}
}
// now handle keyref's/...
for (int i = oldCount - 1; i >= newCount; i--) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
if(matcher instanceof Selector.Matcher) {
Selector.Matcher selMatcher = (Selector.Matcher)matcher;
IdentityConstraint id;
if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) {
ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth());
if (values != null) // nothing to do if nothing matched!
values.endDocumentFragment();
}
}
}
fValueStoreCache.endElement();
SchemaGrammar[] grammars = null;
// have we reached the end tag of the validation root?
if (fElementDepth == 0) {
// 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4).
String invIdRef = fValidationState.checkIDRefID();
fValidationState.resetIDTables();
if (invIdRef != null) {
reportSchemaError("cvc-id.1", new Object[]{invIdRef});
}
// check extra schema constraints
if (fFullChecking) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter);
}
grammars = fGrammarBucket.getGrammars();
// return the final set of grammars validator ended up with
if (fGrammarPool != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars);
}
augs = endElementPSVI(true, grammars, augs);
}
else {
augs = endElementPSVI(false, grammars, augs);
// decrease element depth and restore states
fElementDepth--;
// get the states for the parent element.
fSubElement = fSubElementStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fNotation = fNotationStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fStrictAssess = fStrictAssessStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawText = fSawTextStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
fSawChildren = fSawChildrenStack[fElementDepth];
// We should have a stack for whitespace value, and pop it up here.
// But when fWhiteSpace != -1, and we see a sub-element, it must be
// an error (at least for Schema 1.0). So for valid documents, the
// only value we are going to push/pop in the stack is -1.
// Here we just mimic the effect of popping -1. -SG
fWhiteSpace = -1;
// Same for append buffer. Simple types and elements with fixed
// value constraint don't allow sub-elements. -SG
fAppendBuffer = false;
// same here.
fUnionType = false;
}
return augs;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleEndElement" | "Augmentations handleEndElement(QName element, Augmentations augs) {
if (DEBUG) {
System.out.println("==>handleEndElement:" +element);
}
// if we are skipping, return
if (fSkipValidationDepth >= 0) {
// but if this is the top element that we are skipping,
// restore the states.
if (fSkipValidationDepth == fElementDepth &&
fSkipValidationDepth > 0) {
// set the partial validation depth to the depth of parent
fNFullValidationDepth = fSkipValidationDepth-1;
fSkipValidationDepth = -1;
fElementDepth--;
fSubElement = fSubElementStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fNotation = fNotationStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fStrictAssess = fStrictAssessStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawText = fSawTextStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
fSawChildren = fSawChildrenStack[fElementDepth];
}
else {
fElementDepth--;
}
// PSVI: validation attempted:
// use default values in psvi item for
// validation attempted, validity, and error codes
// check extra schema constraints on root element
if (fElementDepth == -1 && fFullChecking) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter);
}
if (fAugPSVI)
augs = getEmptyAugs(augs);
return augs;
}
// now validate the content of the element
processElementContent(element);
// Element Locally Valid (Element)
// 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4).
// call matchers and de-activate context
int oldCount = fMatcherStack.getMatcherCount();
for (int i = oldCount - 1; i >= 0; i--) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.endElement(element, fCurrentElemDecl,
fDefaultValue == null ?
fValidatedInfo.normalizedValue :
fCurrentElemDecl.fDefault.normalizedValue);
}
if (fMatcherStack.size() > 0) {
fMatcherStack.popContext();
}
int newCount = fMatcherStack.getMatcherCount();
// handle everything *but* keyref's.
for (int i = oldCount - 1; i >= newCount; i--) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
if(matcher instanceof Selector.Matcher) {
Selector.Matcher selMatcher = (Selector.Matcher)matcher;
IdentityConstraint id;
if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) {
fValueStoreCache.transplant(id, selMatcher.getInitialDepth());
}
}
}
// now handle keyref's/...
for (int i = oldCount - 1; i >= newCount; i--) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
if(matcher instanceof Selector.Matcher) {
Selector.Matcher selMatcher = (Selector.Matcher)matcher;
IdentityConstraint id;
if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) {
ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth());
if (values != null) // nothing to do if nothing matched!
values.endDocumentFragment();
}
}
}
fValueStoreCache.endElement();
SchemaGrammar[] grammars = null;
// have we reached the end tag of the validation root?
if (fElementDepth == 0) {
// 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4).
String invIdRef = fValidationState.checkIDRefID();
if (invIdRef != null) {
reportSchemaError("cvc-id.1", new Object[]{invIdRef});
}
// check extra schema constraints
if (fFullChecking) {
XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter);
}
<MASK>fValidationState.resetIDTables();</MASK>
grammars = fGrammarBucket.getGrammars();
// return the final set of grammars validator ended up with
if (fGrammarPool != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars);
}
augs = endElementPSVI(true, grammars, augs);
}
else {
augs = endElementPSVI(false, grammars, augs);
// decrease element depth and restore states
fElementDepth--;
// get the states for the parent element.
fSubElement = fSubElementStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fNotation = fNotationStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fStrictAssess = fStrictAssessStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawText = fSawTextStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
fSawChildren = fSawChildrenStack[fElementDepth];
// We should have a stack for whitespace value, and pop it up here.
// But when fWhiteSpace != -1, and we see a sub-element, it must be
// an error (at least for Schema 1.0). So for valid documents, the
// only value we are going to push/pop in the stack is -1.
// Here we just mimic the effect of popping -1. -SG
fWhiteSpace = -1;
// Same for append buffer. Simple types and elements with fixed
// value constraint don't allow sub-elements. -SG
fAppendBuffer = false;
// same here.
fUnionType = false;
}
return augs;
}" |
Inversion-Mutation | megadiff | "private void viewForm(IWContext iwc) throws RemoteException {
if (child != null) {
Form form = new Form();
form.maintainParameter(prmChildId);
Table table = new Table();
table.setWidth(getWidth());
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
form.add(table);
int row = 1;
table.add(getChildInfoTable(iwc), 1, row++);
table.setHeight(row++, 12);
table.add(getInputTable(iwc), 1, row++);
table.setHeight(row++, 12);
SubmitButton submit = (SubmitButton) getButton(new SubmitButton(localize(PARAM_FORM_SUBMIT, "Submit application"), PARAMETER_ACTION, String.valueOf(ACTION_SUBMIT)));
if (isAdmin) {
try {
User parent = getBusiness().getUserBusiness().getCustodianForChild(child);
if (parent == null)
submit.setDisabled(true);
}
catch (RemoteException re) {
submit.setDisabled(true);
}
}
table.add(submit, 1, row);
submit.setOnSubmitFunction("checkApplication", getSubmitCheckScript());
form.setToDisableOnSubmit(submit, true);
if (submit.getDisabled()) {
row++;
table.setHeight(row++, 6);
table.add(getSmallErrorText(localize("no_parent_found", "No parent found")), 1, row);
}
add(form);
}
else {
add(getErrorText(localize("no_child_selected", "No child selected.")));
add(new Break(2));
add(new UserHomeLink());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "viewForm" | "private void viewForm(IWContext iwc) throws RemoteException {
if (child != null) {
Form form = new Form();
form.maintainParameter(prmChildId);
Table table = new Table();
table.setWidth(getWidth());
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
form.add(table);
int row = 1;
table.add(getChildInfoTable(iwc), 1, row++);
table.setHeight(row++, 12);
table.add(getInputTable(iwc), 1, row++);
table.setHeight(row++, 12);
SubmitButton submit = (SubmitButton) getButton(new SubmitButton(localize(PARAM_FORM_SUBMIT, "Submit application"), PARAMETER_ACTION, String.valueOf(ACTION_SUBMIT)));
if (isAdmin) {
try {
User parent = getBusiness().getUserBusiness().getCustodianForChild(child);
if (parent == null)
submit.setDisabled(true);
}
catch (RemoteException re) {
submit.setDisabled(true);
}
}
submit.setOnSubmitFunction("checkApplication", getSubmitCheckScript());
form.setToDisableOnSubmit(submit, true);
<MASK>table.add(submit, 1, row);</MASK>
if (submit.getDisabled()) {
row++;
table.setHeight(row++, 6);
table.add(getSmallErrorText(localize("no_parent_found", "No parent found")), 1, row);
}
add(form);
}
else {
add(getErrorText(localize("no_child_selected", "No child selected.")));
add(new Break(2));
add(new UserHomeLink());
}
}" |
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 | "protected void renderName(EntityPlayer var1, double var2, double var4, double var6) {
if(Minecraft.isGuiEnabled() && (var1 != this.renderManager.livingPlayer || (Minecraft.theMinecraft.gameSettings.thirdPersonView != 0 && Minecraft.theMinecraft.currentScreen == null))) {
float var8 = 1.6F;
float var9 = 0.016666668F * var8;
double var10 = var1.getDistanceSqToEntity(this.renderManager.livingPlayer);
float var12 = var1.isSneaking() ? 32.0F : 64.0F;
if(var10 < (double)(var12 * var12)) {
//Spout Start
String title = var1.displayName;
//int color = EasterEggs.getEasterEggTitleColor();
float alpha = 0.25F;
//if a plugin hasn't set a title, use the easter egg title (if one exists)
//if (EasterEggs.getEasterEggTitle(var1.username) != null && color == -1) {
// title = EasterEggs.getEasterEggTitle(var1.username);
// alpha = 0.0F;
//}
if (!title.equals("[hide]")) {
String lines[] = title.split("\\n");
double y = var4;
for (int line = 0; line < lines.length; line++) {
title = lines[line];
var4 = y + (0.275D * (lines.length - line - 1));
if(!var1.isSneaking()) {
if(var1.isPlayerSleeping()) {
this.renderLivingLabel(var1, title, var2, var4 - 1.5D, var6, 64);
} else {
//if (color != -1) {
// this.renderLivingLabel(var1, title, var2, var4, var6, 64, color, color);
//}
//else {
this.renderLivingLabel(var1, title, var2, var4, var6, 64);
//}
}
} else {
title = ChatColor.stripColor(title); //strip colors when sneaking
FontRenderer var14 = this.getFontRendererFromRenderManager();
GL11.glPushMatrix();
GL11.glTranslatef((float) var2 + 0.0F, (float) var4 + 2.3F, (float) var6);
GL11.glNormal3f(0.0F, 1.0F, 0.0F);
GL11.glRotatef(-this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(this.renderManager.playerViewX, 1.0F, 0.0F, 0.0F);
GL11.glScalef(-var9, -var9, var9);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glTranslatef(0.0F, 0.25F / var9, 0.0F);
GL11.glDepthMask(false);
GL11.glDisable(GL11.GL_ALPHA_TEST); //Spout - ?
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
Tessellator var15 = Tessellator.instance;
GL11.glDisable(GL11.GL_TEXTURE_2D);
var15.startDrawingQuads();
int var16 = var14.getStringWidth(title) / 2;
var15.setColorRGBA_F(0.0F, 0.0F, 0.0F, 0.25F);
var15.addVertex((double) (-var16 - 1), -1.0D, 0.0D);
var15.addVertex((double) (-var16 - 1), 8.0D, 0.0D);
var15.addVertex((double) (var16 + 1), 8.0D, 0.0D);
var15.addVertex((double) (var16 + 1), -1.0D, 0.0D);
var15.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(true);
var14.drawString(title, -var14.getStringWidth(title) / 2, 0, 553648127);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_ALPHA_TEST); //Spout - ?
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glPopMatrix();
}
}
}
//Spout End
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "renderName" | "protected void renderName(EntityPlayer var1, double var2, double var4, double var6) {
if(Minecraft.isGuiEnabled() && (var1 != this.renderManager.livingPlayer || (Minecraft.theMinecraft.gameSettings.thirdPersonView != 0 && Minecraft.theMinecraft.currentScreen == null))) {
float var8 = 1.6F;
float var9 = 0.016666668F * var8;
double var10 = var1.getDistanceSqToEntity(this.renderManager.livingPlayer);
float var12 = var1.isSneaking() ? 32.0F : 64.0F;
if(var10 < (double)(var12 * var12)) {
//Spout Start
String title = var1.displayName;
//int color = EasterEggs.getEasterEggTitleColor();
float alpha = 0.25F;
//if a plugin hasn't set a title, use the easter egg title (if one exists)
//if (EasterEggs.getEasterEggTitle(var1.username) != null && color == -1) {
// title = EasterEggs.getEasterEggTitle(var1.username);
// alpha = 0.0F;
//}
if (!title.equals("[hide]")) {
String lines[] = title.split("\\n");
double y = var4;
for (int line = 0; line < lines.length; line++) {
title = lines[line];
var4 = y + (0.275D * (lines.length - line - 1));
if(!var1.isSneaking()) {
if(var1.isPlayerSleeping()) {
this.renderLivingLabel(var1, title, var2, var4 - 1.5D, var6, 64);
} else {
//if (color != -1) {
// this.renderLivingLabel(var1, title, var2, var4, var6, 64, color, color);
//}
//else {
this.renderLivingLabel(var1, title, var2, var4, var6, 64);
//}
}
} else {
title = ChatColor.stripColor(title); //strip colors when sneaking
FontRenderer var14 = this.getFontRendererFromRenderManager();
GL11.glPushMatrix();
GL11.glTranslatef((float) var2 + 0.0F, (float) var4 + 2.3F, (float) var6);
GL11.glNormal3f(0.0F, 1.0F, 0.0F);
GL11.glRotatef(-this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(this.renderManager.playerViewX, 1.0F, 0.0F, 0.0F);
GL11.glScalef(-var9, -var9, var9);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glTranslatef(0.0F, 0.25F / var9, 0.0F);
GL11.glDepthMask(false);
GL11.glDisable(GL11.GL_ALPHA_TEST); //Spout - ?
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
Tessellator var15 = Tessellator.instance;
GL11.glDisable(GL11.GL_TEXTURE_2D);
var15.startDrawingQuads();
int var16 = var14.getStringWidth(title) / 2;
var15.setColorRGBA_F(0.0F, 0.0F, 0.0F, 0.25F);
var15.addVertex((double) (-var16 - 1), -1.0D, 0.0D);
var15.addVertex((double) (-var16 - 1), 8.0D, 0.0D);
var15.addVertex((double) (var16 + 1), 8.0D, 0.0D);
var15.addVertex((double) (var16 + 1), -1.0D, 0.0D);
var15.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
<MASK>GL11.glEnable(GL11.GL_ALPHA_TEST); //Spout - ?</MASK>
GL11.glDepthMask(true);
var14.drawString(title, -var14.getStringWidth(title) / 2, 0, 553648127);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glPopMatrix();
}
}
}
//Spout End
}
}
}" |
Inversion-Mutation | megadiff | "public void update(long elapsedTime)
{
Vector2D vector = new Vector2D();
TeamBehaviorInterface teamBehavior = mTeam.getBehavior();
mBehavior.apply(vector, elapsedTime);
if (teamBehavior != null) {
teamBehavior.apply(vector, elapsedTime);
}
mSpeedVector = vector;
move(elapsedTime);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "update" | "public void update(long elapsedTime)
{
Vector2D vector = new Vector2D();
TeamBehaviorInterface teamBehavior = mTeam.getBehavior();
mBehavior.apply(vector, elapsedTime);
if (teamBehavior != null) {
teamBehavior.apply(vector, elapsedTime);
}
<MASK>move(elapsedTime);</MASK>
mSpeedVector = vector;
}" |
Inversion-Mutation | megadiff | "public void startElement(String uri, String localName, String qName,
Attributes a) throws SAXException {
// Initialize string buffer to hold content of the new element.
// This will start a fresh buffer for every element encountered.
m_elementContent=new StringBuffer();
if (uri.equals(F) && !m_inXMLMetadata) {
// WE ARE NOT INSIDE A BLOCK OF INLINE XML...
if (localName.equals("digitalObject")) {
m_rootElementFound=true;
//======================
// OBJECT IDENTIFIERS...
//======================
m_obj.setPid(grab(a, F, "PID"));
//=====================
// OBJECT PROPERTIES...
//=====================
} else if (localName.equals("property") || localName.equals("extproperty")) {
m_objPropertyName = grab(a, F, "NAME");
if (m_objPropertyName.equals(MODEL.STATE.uri)){
String stateString = grab(a, F, "VALUE");
String stateCode = null;
if (MODEL.DELETED.looselyMatches(stateString, true)) {
stateCode = "D";
} else if (MODEL.INACTIVE.looselyMatches(stateString, true)) {
stateCode = "I";
} else if (MODEL.ACTIVE.looselyMatches(stateString, true)) {
stateCode = "A";
}
m_obj.setState(stateCode);
} else if (m_objPropertyName.equals(MODEL.CONTENT_MODEL.uri)){
m_obj.setContentModelId(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.LABEL.uri)){
m_obj.setLabel(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.CREATED_DATE.uri)){
m_obj.setCreateDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(VIEW.LAST_MODIFIED_DATE.uri)){
m_obj.setLastModDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(RDF.TYPE.uri)) {
String oType = grab(a, F, "VALUE");
if (oType==null || oType.equals("")) { oType=MODEL.DATA_OBJECT.localName; }
if (MODEL.BDEF_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BDEF_OBJECT);
} else if (MODEL.BMECH_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
} else {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_OBJECT);
}
} else {
// add an extensible property in the property map
m_obj.setExtProperty(m_objPropertyName, grab(a, F, "VALUE"));
}
//===============
// DATASTREAMS...
//===============
} else if (localName.equals("datastream")) {
// get datastream container-level attributes...
// These are common for all versions of the datastream.
m_dsId=grab(a, F, "ID");
m_dsState=grab(a, F, "STATE");
m_dsControlGrp=grab(a, F, "CONTROL_GROUP");
String versionable =grab(a, F, "VERSIONABLE");
// If dsVersionable is null or missing, default to true.
if (versionable==null || versionable.equals("")) {
m_dsVersionable=true;
} else {
m_dsVersionable=new Boolean(versionable).booleanValue();
}
// Never allow the AUDIT datastream to be versioned
// since it naturally represents a system-controlled
// view of changes over time.
if (m_dsId.equals("AUDIT")) {
m_dsVersionable=false;
}
} else if (localName.equals("datastreamVersion")) {
// get datastream version-level attributes...
m_dsVersId=grab(a, F, "ID");
m_dsLabel=grab(a, F, "LABEL");
m_dsCreateDate=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
String altIDsString = grab(a, F, "ALT_IDS");
if (altIDsString.length() == 0) {
m_dsAltIds = new String[0];
} else {
m_dsAltIds = altIDsString.split(" ");
}
m_dsFormatURI=grab(a, F, "FORMAT_URI");
if (m_dsFormatURI.length() == 0) {
m_dsFormatURI = null;
}
checkMETSFormat(m_dsFormatURI);
m_dsMimeType=grab(a, F, "MIMETYPE");
String sizeString=grab(a, F, "SIZE");
if (sizeString!=null && !sizeString.equals("")) {
try {
m_dsSize=Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
throw new SAXException("If specified, a datastream's "
+ "SIZE attribute must be an xsd:long.");
}
} else {
m_dsSize=-1;
}
if (m_dsVersId.equals("AUDIT.0")) {
m_gotAudit=true;
}
//======================
// DATASTREAM CONTENT...
//======================
// inside a datastreamVersion element, it's either going to be
// xmlContent (inline xml), contentLocation (a reference) or binaryContent
} else if (localName.equals("xmlContent")) {
m_dsXMLBuffer=new StringBuffer();
m_xmlDataLevel=0;
m_inXMLMetadata=true;
} else if (localName.equals("contentLocation")) {
String dsLocation=grab(a,F,"REF");
if (dsLocation==null || dsLocation.equals("")) {
throw new SAXException("REF attribute must be specified in contentLocation element");
}
// check if datastream is ExternalReferenced
if (m_dsControlGrp.equalsIgnoreCase("E") ||
m_dsControlGrp.equalsIgnoreCase("R") ) {
// URL FORMAT VALIDATION for dsLocation:
// make sure we have a properly formed URL
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
// system will set dsLocationType for E and R datastreams...
m_dsLocationType="URL";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamReferencedContent());
// check if datastream is ManagedContent
} else if (m_dsControlGrp.equalsIgnoreCase("M")) {
// URL FORMAT VALIDATION for dsLocation:
// For Managed Content the URL is only checked when we are parsing a
// a NEW ingest file because the URL is replaced with an internal identifier
// once the repository has sucked in the content for storage.
if (m_obj.isNew()) {
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
}
m_dsLocationType="INTERNAL_ID";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamManagedContent());
}
} else if (localName.equals("binaryContent")) {
// FIXME: implement support for this in Fedora 1.2
if (m_dsControlGrp.equalsIgnoreCase("M"))
{
m_readingBinaryContent=true;
m_binaryContentTempFile = null;
try {
m_binaryContentTempFile = File.createTempFile("binary-datastream", null);
}
catch (IOException ioe)
{
throw new SAXException(new StreamIOException("Unable to create temporary file for binary content"));
}
}
//==================
// DISSEMINATORS...
//==================
} else if (localName.equals("disseminator")) {
m_dissID=grab(a, F,"ID");
m_bDefID=grab(a, F, "BDEF_CONTRACT_PID");
m_dissState=grab(a, F,"STATE");
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
} else if (localName.equals("disseminatorVersion")) {
m_diss = new Disseminator();
m_diss.dissID=m_dissID;
m_diss.bDefID=m_bDefID;
m_diss.dissState=m_dissState;
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
m_diss.dissVersionID=grab(a, F,"ID");
m_diss.dissLabel=grab(a, F, "LABEL");
m_diss.bMechID=grab(a, F, "BMECH_SERVICE_PID");
m_diss.dissCreateDT=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
} else if (localName.equals("serviceInputMap")) {
m_diss.dsBindMap=new DSBindingMap();
m_dsBindings = new ArrayList();
// Note that the dsBindMapID is not really necessary from the
// FOXML standpoint, but it was necessary in METS since the structMap
// was outside the disseminator. (Look at how it's used in the sql db.)
// Also, the rest of the attributes on the DSBindingMap are not
// really necessary since they are inherited from the disseminator.
// I just use the values picked up from disseminatorVersion.
m_diss.dsBindMapID=m_diss.dissVersionID + "b";
m_diss.dsBindMap.dsBindMapID=m_diss.dsBindMapID;
m_diss.dsBindMap.dsBindMechanismPID = m_diss.bMechID;
m_diss.dsBindMap.dsBindMapLabel = ""; // does not exist in FOXML
m_diss.dsBindMap.state = m_diss.dissState;
} else if (localName.equals("datastreamBinding")) {
DSBinding dsb = new DSBinding();
dsb.bindKeyName = grab(a, F,"KEY");
dsb.bindLabel = grab(a, F,"LABEL");
dsb.datastreamID = grab(a, F,"DATASTREAM_ID");
dsb.seqNo = grab(a, F,"ORDER");
m_dsBindings.add(dsb);
}
} else {
//===============
// INLINE XML...
//===============
if (m_inXMLMetadata) {
// we are inside an xmlContent element.
// just output it, remembering the number of foxml:xmlContent elements we see,
appendElementStart(uri, localName, qName, a, m_dsXMLBuffer);
// FOXML INSIDE FOXML! we have an inline XML datastream
// that is itself FOXML. We do not want to parse this!
if (uri.equals(F) && localName.equals("xmlContent")) {
m_xmlDataLevel++;
}
// if AUDIT datastream, initialize new audit record object
if (m_gotAudit) {
if (localName.equals("record")) {
m_auditRec=new AuditRecord();
m_auditRec.id=grab(a, uri, "ID");
} else if (localName.equals("process")) {
m_auditProcessType=grab(a, uri, "type");
}
}
} else {
// ignore all else
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startElement" | "public void startElement(String uri, String localName, String qName,
Attributes a) throws SAXException {
// Initialize string buffer to hold content of the new element.
// This will start a fresh buffer for every element encountered.
m_elementContent=new StringBuffer();
if (uri.equals(F) && !m_inXMLMetadata) {
// WE ARE NOT INSIDE A BLOCK OF INLINE XML...
if (localName.equals("digitalObject")) {
m_rootElementFound=true;
//======================
// OBJECT IDENTIFIERS...
//======================
m_obj.setPid(grab(a, F, "PID"));
//=====================
// OBJECT PROPERTIES...
//=====================
} else if (localName.equals("property") || localName.equals("extproperty")) {
m_objPropertyName = grab(a, F, "NAME");
if (m_objPropertyName.equals(MODEL.STATE.uri)){
String stateString = grab(a, F, "VALUE");
String stateCode = null;
if (MODEL.DELETED.looselyMatches(stateString, true)) {
stateCode = "D";
} else if (MODEL.INACTIVE.looselyMatches(stateString, true)) {
stateCode = "I";
} else if (MODEL.ACTIVE.looselyMatches(stateString, true)) {
stateCode = "A";
}
m_obj.setState(stateCode);
} else if (m_objPropertyName.equals(MODEL.CONTENT_MODEL.uri)){
m_obj.setContentModelId(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.LABEL.uri)){
m_obj.setLabel(grab(a, F, "VALUE"));
} else if (m_objPropertyName.equals(MODEL.CREATED_DATE.uri)){
m_obj.setCreateDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(VIEW.LAST_MODIFIED_DATE.uri)){
m_obj.setLastModDate(DateUtility.convertStringToDate(grab(a, F, "VALUE")));
} else if (m_objPropertyName.equals(RDF.TYPE.uri)) {
String oType = grab(a, F, "VALUE");
if (oType==null || oType.equals("")) { oType=MODEL.DATA_OBJECT.localName; }
if (MODEL.BDEF_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BDEF_OBJECT);
} else if (MODEL.BMECH_OBJECT.looselyMatches(oType, false)) {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
} else {
m_obj.setFedoraObjectType(DigitalObject.FEDORA_OBJECT);
}
} else {
// add an extensible property in the property map
m_obj.setExtProperty(m_objPropertyName, grab(a, F, "VALUE"));
}
//===============
// DATASTREAMS...
//===============
} else if (localName.equals("datastream")) {
// get datastream container-level attributes...
// These are common for all versions of the datastream.
m_dsId=grab(a, F, "ID");
m_dsState=grab(a, F, "STATE");
m_dsControlGrp=grab(a, F, "CONTROL_GROUP");
String versionable =grab(a, F, "VERSIONABLE");
// If dsVersionable is null or missing, default to true.
if (versionable==null || versionable.equals("")) {
m_dsVersionable=true;
} else {
m_dsVersionable=new Boolean(versionable).booleanValue();
}
// Never allow the AUDIT datastream to be versioned
// since it naturally represents a system-controlled
// view of changes over time.
<MASK>checkMETSFormat(m_dsFormatURI);</MASK>
if (m_dsId.equals("AUDIT")) {
m_dsVersionable=false;
}
} else if (localName.equals("datastreamVersion")) {
// get datastream version-level attributes...
m_dsVersId=grab(a, F, "ID");
m_dsLabel=grab(a, F, "LABEL");
m_dsCreateDate=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
String altIDsString = grab(a, F, "ALT_IDS");
if (altIDsString.length() == 0) {
m_dsAltIds = new String[0];
} else {
m_dsAltIds = altIDsString.split(" ");
}
m_dsFormatURI=grab(a, F, "FORMAT_URI");
if (m_dsFormatURI.length() == 0) {
m_dsFormatURI = null;
}
m_dsMimeType=grab(a, F, "MIMETYPE");
String sizeString=grab(a, F, "SIZE");
if (sizeString!=null && !sizeString.equals("")) {
try {
m_dsSize=Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
throw new SAXException("If specified, a datastream's "
+ "SIZE attribute must be an xsd:long.");
}
} else {
m_dsSize=-1;
}
if (m_dsVersId.equals("AUDIT.0")) {
m_gotAudit=true;
}
//======================
// DATASTREAM CONTENT...
//======================
// inside a datastreamVersion element, it's either going to be
// xmlContent (inline xml), contentLocation (a reference) or binaryContent
} else if (localName.equals("xmlContent")) {
m_dsXMLBuffer=new StringBuffer();
m_xmlDataLevel=0;
m_inXMLMetadata=true;
} else if (localName.equals("contentLocation")) {
String dsLocation=grab(a,F,"REF");
if (dsLocation==null || dsLocation.equals("")) {
throw new SAXException("REF attribute must be specified in contentLocation element");
}
// check if datastream is ExternalReferenced
if (m_dsControlGrp.equalsIgnoreCase("E") ||
m_dsControlGrp.equalsIgnoreCase("R") ) {
// URL FORMAT VALIDATION for dsLocation:
// make sure we have a properly formed URL
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
// system will set dsLocationType for E and R datastreams...
m_dsLocationType="URL";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamReferencedContent());
// check if datastream is ManagedContent
} else if (m_dsControlGrp.equalsIgnoreCase("M")) {
// URL FORMAT VALIDATION for dsLocation:
// For Managed Content the URL is only checked when we are parsing a
// a NEW ingest file because the URL is replaced with an internal identifier
// once the repository has sucked in the content for storage.
if (m_obj.isNew()) {
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
}
m_dsLocationType="INTERNAL_ID";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamManagedContent());
}
} else if (localName.equals("binaryContent")) {
// FIXME: implement support for this in Fedora 1.2
if (m_dsControlGrp.equalsIgnoreCase("M"))
{
m_readingBinaryContent=true;
m_binaryContentTempFile = null;
try {
m_binaryContentTempFile = File.createTempFile("binary-datastream", null);
}
catch (IOException ioe)
{
throw new SAXException(new StreamIOException("Unable to create temporary file for binary content"));
}
}
//==================
// DISSEMINATORS...
//==================
} else if (localName.equals("disseminator")) {
m_dissID=grab(a, F,"ID");
m_bDefID=grab(a, F, "BDEF_CONTRACT_PID");
m_dissState=grab(a, F,"STATE");
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
} else if (localName.equals("disseminatorVersion")) {
m_diss = new Disseminator();
m_diss.dissID=m_dissID;
m_diss.bDefID=m_bDefID;
m_diss.dissState=m_dissState;
String versionable =grab(a, F, "VERSIONABLE");
// disseminator versioning is defaulted to true
if (versionable==null || versionable.equals("")) {
m_dissVersionable=true;
} else {
m_dissVersionable=new Boolean(versionable).booleanValue();
}
m_diss.dissVersionID=grab(a, F,"ID");
m_diss.dissLabel=grab(a, F, "LABEL");
m_diss.bMechID=grab(a, F, "BMECH_SERVICE_PID");
m_diss.dissCreateDT=DateUtility.convertStringToDate(grab(a, F, "CREATED"));
} else if (localName.equals("serviceInputMap")) {
m_diss.dsBindMap=new DSBindingMap();
m_dsBindings = new ArrayList();
// Note that the dsBindMapID is not really necessary from the
// FOXML standpoint, but it was necessary in METS since the structMap
// was outside the disseminator. (Look at how it's used in the sql db.)
// Also, the rest of the attributes on the DSBindingMap are not
// really necessary since they are inherited from the disseminator.
// I just use the values picked up from disseminatorVersion.
m_diss.dsBindMapID=m_diss.dissVersionID + "b";
m_diss.dsBindMap.dsBindMapID=m_diss.dsBindMapID;
m_diss.dsBindMap.dsBindMechanismPID = m_diss.bMechID;
m_diss.dsBindMap.dsBindMapLabel = ""; // does not exist in FOXML
m_diss.dsBindMap.state = m_diss.dissState;
} else if (localName.equals("datastreamBinding")) {
DSBinding dsb = new DSBinding();
dsb.bindKeyName = grab(a, F,"KEY");
dsb.bindLabel = grab(a, F,"LABEL");
dsb.datastreamID = grab(a, F,"DATASTREAM_ID");
dsb.seqNo = grab(a, F,"ORDER");
m_dsBindings.add(dsb);
}
} else {
//===============
// INLINE XML...
//===============
if (m_inXMLMetadata) {
// we are inside an xmlContent element.
// just output it, remembering the number of foxml:xmlContent elements we see,
appendElementStart(uri, localName, qName, a, m_dsXMLBuffer);
// FOXML INSIDE FOXML! we have an inline XML datastream
// that is itself FOXML. We do not want to parse this!
if (uri.equals(F) && localName.equals("xmlContent")) {
m_xmlDataLevel++;
}
// if AUDIT datastream, initialize new audit record object
if (m_gotAudit) {
if (localName.equals("record")) {
m_auditRec=new AuditRecord();
m_auditRec.id=grab(a, uri, "ID");
} else if (localName.equals("process")) {
m_auditProcessType=grab(a, uri, "type");
}
}
} else {
// ignore all else
}
}
}" |
Inversion-Mutation | megadiff | "ToolbarPanel() {
setBackground(Color.white);
addMouseListener(this);
try {
drawButton = Toolbar.class.getDeclaredMethod("drawButton", Graphics.class, Integer.TYPE);
drawButton.setAccessible(true);
lineType = Toolbar.class.getDeclaredField("lineType");
lineType.setAccessible(true);
SIZE = Toolbar.class.getDeclaredField("SIZE");
SIZE.setAccessible(true);
OFFSET = Toolbar.class.getDeclaredField("OFFSET");
OFFSET.setAccessible(true);
size = ((Integer)SIZE.get(null)).intValue();
//offset = ((Integer)OFFSET.get(null)).intValue();
} catch (Exception e) {
IJError.print(e);
}
// Magic cocktail:
Dimension dim = new Dimension(250, size+size);
setMinimumSize(dim);
setPreferredSize(dim);
setMaximumSize(dim);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ToolbarPanel" | "ToolbarPanel() {
setBackground(Color.white);
addMouseListener(this);
try {
drawButton = Toolbar.class.getDeclaredMethod("drawButton", Graphics.class, Integer.TYPE);
drawButton.setAccessible(true);
lineType = Toolbar.class.getDeclaredField("lineType");
lineType.setAccessible(true);
SIZE = Toolbar.class.getDeclaredField("SIZE");
SIZE.setAccessible(true);
OFFSET = Toolbar.class.getDeclaredField("OFFSET");
OFFSET.setAccessible(true);
size = ((Integer)SIZE.get(null)).intValue();
//offset = ((Integer)OFFSET.get(null)).intValue();
} catch (Exception e) {
IJError.print(e);
}
// Magic cocktail:
Dimension dim = new Dimension(250, size+size);
<MASK>setPreferredSize(dim);</MASK>
setMinimumSize(dim);
setMaximumSize(dim);
}" |
Inversion-Mutation | megadiff | "private void setView() {
switch(mMode) {
case MODE_EDITOR:
setContentView(R.layout.activity_list);
EditText editText = (EditText) findViewById(R.id.editText1);
// Button mGoBtn = (Button) findViewById(R.id.button1);
// mGoBtn.setOnClickListener(this);
// Button mGoBtn2 = (Button) findViewById(R.id.button2);
// mGoBtn2.setOnClickListener(this);
// Button mGoBtn3 = (Button) findViewById(R.id.button3);
// mGoBtn3.setOnClickListener(this);
java.lang.reflect.Field[] fields = R.layout.class.getFields();
List<String> layoutNameList = new ArrayList<String>();
List<Integer> layoutIdList = new ArrayList<Integer>();
R.layout layoutInstance = new R.layout();
for (Field field : fields) {
layoutNameList.add(field.getName());
try {
layoutIdList.add(field.getInt(layoutInstance));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
layoutNameArray = layoutNameList.toArray(new String[0]);
layoutIdArray = layoutIdList.toArray(new Integer[0]);
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list, layoutNameArray);
listView.setAdapter(adapter);
// リストビューのアイテムがクリックされた時に呼び出されるコールバックリスナーを登録します
listView.setOnItemClickListener(this);
editText.setText(mXmlText);
break;
case MODE_FILER:
File currentPath = new File(mCurrentPath);
//System.out.println("selected is " + currentPath.getPath() + "," + currentPath.getName());
if(currentPath.isDirectory()){
File[] ffTemp = currentPath.listFiles();
File[] ff;
if(currentPath.getPath().equals("/")){
ff = ffTemp;
}
else {
if(ffTemp != null){
ff = new File[ffTemp.length+1];
System.arraycopy(ffTemp, 0, ff, 1, ffTemp.length);
}
else {
ff = new File[1];
}
ff[0] = currentPath.getParentFile();
}
if(ff != null) {
Arrays.sort(ff);
System.out.println("list is null");
ArrayAdapter<File> adapter_filelist = new ArrayAdapter<File>(this,
R.layout.list, ff);
setContentView(R.layout.activity_filer);
ListView listView_file = (ListView) findViewById(R.id.listView_file);
listView_file.setAdapter(adapter_filelist);
// リストビューのアイテムがクリックされた時に呼び出されるコールバックリスナーを登録します
listView_file.setOnItemClickListener(this);
}
}
else {
System.out.println("not directory");
mCurrentPath = currentPath.getParent();
if(!currentPath.getParentFile().getName().equals("layout")) {
// ダイアログの表示
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("Not opened.");
dlg.setMessage("Select XML file in layout folder.");
dlg.show();
}
else if(!currentPath.getName().endsWith("xml")) {
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("Can'T opened.");
dlg.setMessage("Select XML file.");
dlg.show();
}
else {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(currentPath.getPath());
byte[] readBytes = new byte[fileInputStream.available()];
fileInputStream.read(readBytes);
mXmlText = new String(readBytes);
mMode = MODE_EDITOR;
setView();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
break;
case MODE_VIEWER:
if (mXmlText.isEmpty()) {
// ダイアログの表示
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("String Empty");
dlg.setMessage("Select from list or input text.");
dlg.show();
mMode = MODE_EDITOR;
} else {
InputStream bais = null;
try {
bais = new ByteArrayInputStream(mXmlText.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(bais, "utf-8");
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(
metrics);
LayoutInflater orgLayInf = this.getLayoutInflater();
LayoutInflater2 layInf = new LayoutInflater2(orgLayInf,
this, metrics);
View view = layInf.inflate(parser, null);
setContentView(view);
} catch (Exception e) {
e.printStackTrace();
// ダイアログの表示
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("inflate error");
dlg.setMessage(e.getMessage());
dlg.show();
mMode = MODE_EDITOR;
setView();
}
} catch (XmlPullParserException e1) {
e1.printStackTrace();
}
}
break;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setView" | "private void setView() {
switch(mMode) {
case MODE_EDITOR:
setContentView(R.layout.activity_list);
EditText editText = (EditText) findViewById(R.id.editText1);
// Button mGoBtn = (Button) findViewById(R.id.button1);
// mGoBtn.setOnClickListener(this);
// Button mGoBtn2 = (Button) findViewById(R.id.button2);
// mGoBtn2.setOnClickListener(this);
// Button mGoBtn3 = (Button) findViewById(R.id.button3);
// mGoBtn3.setOnClickListener(this);
java.lang.reflect.Field[] fields = R.layout.class.getFields();
List<String> layoutNameList = new ArrayList<String>();
List<Integer> layoutIdList = new ArrayList<Integer>();
R.layout layoutInstance = new R.layout();
for (Field field : fields) {
layoutNameList.add(field.getName());
try {
layoutIdList.add(field.getInt(layoutInstance));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
layoutNameArray = layoutNameList.toArray(new String[0]);
layoutIdArray = layoutIdList.toArray(new Integer[0]);
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list, layoutNameArray);
listView.setAdapter(adapter);
// リストビューのアイテムがクリックされた時に呼び出されるコールバックリスナーを登録します
listView.setOnItemClickListener(this);
editText.setText(mXmlText);
break;
case MODE_FILER:
File currentPath = new File(mCurrentPath);
//System.out.println("selected is " + currentPath.getPath() + "," + currentPath.getName());
if(currentPath.isDirectory()){
File[] ffTemp = currentPath.listFiles();
File[] ff;
if(currentPath.getPath().equals("/")){
ff = ffTemp;
}
else {
if(ffTemp != null){
ff = new File[ffTemp.length+1];
System.arraycopy(ffTemp, 0, ff, 1, ffTemp.length);
}
else {
ff = new File[1];
}
ff[0] = currentPath.getParentFile();
<MASK>Arrays.sort(ff);</MASK>
}
if(ff != null) {
System.out.println("list is null");
ArrayAdapter<File> adapter_filelist = new ArrayAdapter<File>(this,
R.layout.list, ff);
setContentView(R.layout.activity_filer);
ListView listView_file = (ListView) findViewById(R.id.listView_file);
listView_file.setAdapter(adapter_filelist);
// リストビューのアイテムがクリックされた時に呼び出されるコールバックリスナーを登録します
listView_file.setOnItemClickListener(this);
}
}
else {
System.out.println("not directory");
mCurrentPath = currentPath.getParent();
if(!currentPath.getParentFile().getName().equals("layout")) {
// ダイアログの表示
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("Not opened.");
dlg.setMessage("Select XML file in layout folder.");
dlg.show();
}
else if(!currentPath.getName().endsWith("xml")) {
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("Can'T opened.");
dlg.setMessage("Select XML file.");
dlg.show();
}
else {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(currentPath.getPath());
byte[] readBytes = new byte[fileInputStream.available()];
fileInputStream.read(readBytes);
mXmlText = new String(readBytes);
mMode = MODE_EDITOR;
setView();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
break;
case MODE_VIEWER:
if (mXmlText.isEmpty()) {
// ダイアログの表示
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("String Empty");
dlg.setMessage("Select from list or input text.");
dlg.show();
mMode = MODE_EDITOR;
} else {
InputStream bais = null;
try {
bais = new ByteArrayInputStream(mXmlText.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(bais, "utf-8");
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(
metrics);
LayoutInflater orgLayInf = this.getLayoutInflater();
LayoutInflater2 layInf = new LayoutInflater2(orgLayInf,
this, metrics);
View view = layInf.inflate(parser, null);
setContentView(view);
} catch (Exception e) {
e.printStackTrace();
// ダイアログの表示
AlertDialog.Builder dlg;
dlg = new AlertDialog.Builder(this);
dlg.setTitle("inflate error");
dlg.setMessage(e.getMessage());
dlg.show();
mMode = MODE_EDITOR;
setView();
}
} catch (XmlPullParserException e1) {
e1.printStackTrace();
}
}
break;
}
}" |
Inversion-Mutation | megadiff | "public static MediaItem createMediaItemFromUri(Context context, Uri target, int mediaType) {
MediaItem item = null;
long id = ContentUris.parseId(target);
ContentResolver cr = context.getContentResolver();
String whereClause = Images.ImageColumns._ID + "=" + Long.toString(id);
try {
final Uri uri = (mediaType == MediaItem.MEDIA_TYPE_IMAGE)
? Images.Media.EXTERNAL_CONTENT_URI
: Video.Media.EXTERNAL_CONTENT_URI;
final String[] projection = (mediaType == MediaItem.MEDIA_TYPE_IMAGE)
? CacheService.PROJECTION_IMAGES
: CacheService.PROJECTION_VIDEOS;
Cursor cursor = cr.query(uri, projection, whereClause, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
item = new MediaItem();
CacheService.populateMediaItemFromCursor(item, cr, cursor, uri.toString() + "/");
item.mId = id;
}
cursor.close();
cursor = null;
}
} catch (Exception e) {
// If the database operation failed for any reason.
;
}
return item;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createMediaItemFromUri" | "public static MediaItem createMediaItemFromUri(Context context, Uri target, int mediaType) {
MediaItem item = null;
long id = ContentUris.parseId(target);
ContentResolver cr = context.getContentResolver();
String whereClause = Images.ImageColumns._ID + "=" + Long.toString(id);
try {
final Uri uri = (mediaType == MediaItem.MEDIA_TYPE_IMAGE)
? Images.Media.EXTERNAL_CONTENT_URI
: Video.Media.EXTERNAL_CONTENT_URI;
final String[] projection = (mediaType == MediaItem.MEDIA_TYPE_IMAGE)
? CacheService.PROJECTION_IMAGES
: CacheService.PROJECTION_VIDEOS;
Cursor cursor = cr.query(uri, projection, whereClause, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
item = new MediaItem();
CacheService.populateMediaItemFromCursor(item, cr, cursor, uri.toString() + "/");
}
cursor.close();
cursor = null;
}
} catch (Exception e) {
// If the database operation failed for any reason.
;
}
<MASK>item.mId = id;</MASK>
return item;
}" |
Inversion-Mutation | megadiff | "public static boolean parsePage(String htmlCode, SQLiteDatabase db, int cafeteriaid) throws ParseException
{
Integer cid = Integer.valueOf(cafeteriaid);
htmlCode = StringUtils.substringAfter(htmlCode, "<div class=\"\">");
htmlCode = StringUtils.substringBefore(htmlCode, "<table class");
htmlCode = htmlCode.replace("\n", " ");
SimpleDateFormat dateFormat = new SimpleDateFormat("d.M.y");
Pattern dayPattern = Pattern.compile("<div.*?>.*?, (.*?)</div>.*?<table.*?>(.*?)</table>");
Matcher dayMatcher = dayPattern.matcher(htmlCode);
Pattern menuRowPattern = Pattern.compile("<tr.*?</tr>");
Pattern menuTypePattern = Pattern.compile("<td.*?>(.*?)</td>");
Pattern menuMenuPattern = Pattern.compile("<td.*?>\\s*(.*?)\\s* ");
Pattern priceNormalPattern = Pattern.compile("<td.*?Gäste: (.*?) ");
Pattern pricePupilPattern = Pattern.compile("Schüler:(.*?) ");
Pattern priceStudentPattern = Pattern.compile(" \\s*(.*?) ");
Pattern[] patterns = new Pattern[] {menuTypePattern, menuMenuPattern, priceNormalPattern, pricePupilPattern, priceStudentPattern};
if (!dayMatcher.find())
return false;
do
{
Date day = dateFormat.parse(dayMatcher.group(1));
Calendar calendar = Calendar.getInstance();
calendar.setTime(day);
Long timestamp = Long.valueOf(calendar.getTimeInMillis());
db.delete("menus", "cafeteriaid = ? AND day = ?", new String[] { String.valueOf(cafeteriaid), timestamp.toString() });
Matcher menuRowMatcher = menuRowPattern.matcher(dayMatcher.group(2).replaceAll("<tr.*?<th.*?</tr>", " "));
while (menuRowMatcher.find())
{
String menuRow = menuRowMatcher.group();
String[] results = matchPatterns(menuRow, patterns);
String menuType = results[0];
String menuMenu = results[1];
String priceNormal = results[2];
String pricePupil = results[3];
String priceStudent = results[4];
Double normalprice = priceNormal != null ? Double.valueOf(priceNormal.replace(',', '.')) : null;
Double pupilprice = pricePupil != null ? Double.valueOf(pricePupil.replace(',', '.')) : null;
Double studentprice = priceStudent != null ? Double.valueOf(priceStudent.replace(',', '.')) : null;
menuMenu = menuMenu.replace("<br />", ", ");
ContentValues values = new ContentValues();
values.put("cafeteriaid", cid);
values.put("type", menuType);
values.put("menu", menuMenu);
values.put("normalprice", normalprice);
values.put("pupilprice", pupilprice);
values.put("studentprice", studentprice);
values.put("day", timestamp);
db.insert("menus", null, values);
}
} while (dayMatcher.find());
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parsePage" | "public static boolean parsePage(String htmlCode, SQLiteDatabase db, int cafeteriaid) throws ParseException
{
Integer cid = Integer.valueOf(cafeteriaid);
htmlCode = StringUtils.substringAfter(htmlCode, "<div class=\"\">");
htmlCode = StringUtils.substringBefore(htmlCode, "<table class");
htmlCode = htmlCode.replace("\n", " ");
SimpleDateFormat dateFormat = new SimpleDateFormat("d.M.y");
Pattern dayPattern = Pattern.compile("<div.*?>.*?, (.*?)</div>.*?<table.*?>(.*?)</table>");
Matcher dayMatcher = dayPattern.matcher(htmlCode);
Pattern menuRowPattern = Pattern.compile("<tr.*?</tr>");
Pattern menuTypePattern = Pattern.compile("<td.*?>(.*?)</td>");
Pattern menuMenuPattern = Pattern.compile("<td.*?>\\s*(.*?)\\s* ");
Pattern priceNormalPattern = Pattern.compile("<td.*?Gäste: (.*?) ");
Pattern pricePupilPattern = Pattern.compile("Schüler:(.*?) ");
Pattern priceStudentPattern = Pattern.compile(" \\s*(.*?) ");
Pattern[] patterns = new Pattern[] {menuTypePattern, menuMenuPattern, priceNormalPattern, pricePupilPattern, priceStudentPattern};
if (!dayMatcher.find())
return false;
do
{
Date day = dateFormat.parse(dayMatcher.group(1));
Calendar calendar = Calendar.getInstance();
calendar.setTime(day);
Long timestamp = Long.valueOf(calendar.getTimeInMillis());
Matcher menuRowMatcher = menuRowPattern.matcher(dayMatcher.group(2).replaceAll("<tr.*?<th.*?</tr>", " "));
while (menuRowMatcher.find())
{
String menuRow = menuRowMatcher.group();
String[] results = matchPatterns(menuRow, patterns);
String menuType = results[0];
String menuMenu = results[1];
String priceNormal = results[2];
String pricePupil = results[3];
String priceStudent = results[4];
Double normalprice = priceNormal != null ? Double.valueOf(priceNormal.replace(',', '.')) : null;
Double pupilprice = pricePupil != null ? Double.valueOf(pricePupil.replace(',', '.')) : null;
Double studentprice = priceStudent != null ? Double.valueOf(priceStudent.replace(',', '.')) : null;
menuMenu = menuMenu.replace("<br />", ", ");
ContentValues values = new ContentValues();
values.put("cafeteriaid", cid);
values.put("type", menuType);
values.put("menu", menuMenu);
values.put("normalprice", normalprice);
values.put("pupilprice", pupilprice);
values.put("studentprice", studentprice);
values.put("day", timestamp);
db.insert("menus", null, values);
}
<MASK>db.delete("menus", "cafeteriaid = ? AND day = ?", new String[] { String.valueOf(cafeteriaid), timestamp.toString() });</MASK>
} while (dayMatcher.find());
return true;
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args)
{
try{output = new BufferedWriter(new FileWriter("[email protected]"));}catch(IOException e){e.printStackTrace();}
Classifier c = ClassifierTrainer.getClassifier(ClassifierType.NB, DataType.ONE, null);
Agent agent = new MLAgent(c);
String[] ops = {
"-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg off -le off -ls 98886", // no enemies, no blocks, no gaps
"-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg off -le on -ls 31646", // enemies
"-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg on -le off -ls 16007", // just gaps
"-vis off -ll 256 -lb on -lco off -lca off -ltb off -lg off -le on -ls 19682", //enemies, blocks
"-vis off -ll 256 -lb on -lco off -lca off -ltb off -lg on -ls 79612"}; // enemies, blocks, gaps
for(int diff = 1; diff < 10; diff++){
for(String o : ops){
options = new MarioAIOptions(args);
options.setArgs(o);
options.setLevelDifficulty(diff);
evaluate(agent);
}
}
try{output.close();}catch(IOException e){e.printStackTrace();}
System.exit(0);
}" | 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)
{
try{output = new BufferedWriter(new FileWriter("[email protected]"));}catch(IOException e){e.printStackTrace();}
Classifier c = ClassifierTrainer.getClassifier(ClassifierType.NB, DataType.ONE, null);
Agent agent = new MLAgent(c);
<MASK>options = new MarioAIOptions(args);</MASK>
String[] ops = {
"-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg off -le off -ls 98886", // no enemies, no blocks, no gaps
"-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg off -le on -ls 31646", // enemies
"-vis off -ll 256 -lb off -lco off -lca off -ltb off -lg on -le off -ls 16007", // just gaps
"-vis off -ll 256 -lb on -lco off -lca off -ltb off -lg off -le on -ls 19682", //enemies, blocks
"-vis off -ll 256 -lb on -lco off -lca off -ltb off -lg on -ls 79612"}; // enemies, blocks, gaps
for(int diff = 1; diff < 10; diff++){
for(String o : ops){
options.setArgs(o);
options.setLevelDifficulty(diff);
evaluate(agent);
}
}
try{output.close();}catch(IOException e){e.printStackTrace();}
System.exit(0);
}" |
Inversion-Mutation | megadiff | "public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_main);
mSetupData = (AbstractSetupData)getLastNonConfigurationInstance();
if (mSetupData == null) {
mSetupData = new CMSetupWizardData(this);
}
if (savedInstanceState != null) {
mSetupData.load(savedInstanceState.getBundle("data"));
}
mSetupData.registerListener(this);
mPagerAdapter = new CMPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
mNextButton = (Button) findViewById(R.id.next_button);
mPrevButton = (Button) findViewById(R.id.prev_button);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position < mPageList.size()) {
onPageLoaded(mPageList.get(position));
}
}
});
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doNext();
}
});
mPrevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doPrevious();
}
});
onPageTreeChanged();
doSimCheck();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_main);
mSetupData = (AbstractSetupData)getLastNonConfigurationInstance();
if (mSetupData == null) {
mSetupData = new CMSetupWizardData(this);
}
if (savedInstanceState != null) {
mSetupData.load(savedInstanceState.getBundle("data"));
}
mSetupData.registerListener(this);
mPagerAdapter = new CMPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
mNextButton = (Button) findViewById(R.id.next_button);
mPrevButton = (Button) findViewById(R.id.prev_button);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position < mPageList.size()) {
onPageLoaded(mPageList.get(position));
}
}
});
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doNext();
}
});
mPrevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doPrevious();
}
});
<MASK>doSimCheck();</MASK>
onPageTreeChanged();
}" |
Inversion-Mutation | megadiff | "public void process() {
if (src == null && dest == null) {
throw new IllegalArgumentException("Source and destination shouldn't be null together");
}
ZipEntryTransformerEntry[] transformersArray = getTransformersArray();
File destinationFile = null;
try {
destinationFile = getDestinationFile();
ZipOutputStream out = null;
ZipEntryOrInfoAdapter zipEntryAdapter = null;
if (destinationFile.isFile()) {
out = ZipFileUtil.createZipOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile)), charset);
zipEntryAdapter = new ZipEntryOrInfoAdapter(new CopyingCallback(transformersArray, out, preserveTimestamps), null);
}
else { // directory
zipEntryAdapter = new ZipEntryOrInfoAdapter(new UnpackingCallback(transformersArray, destinationFile), null);
}
try {
processAllEntries(zipEntryAdapter);
}
finally {
IOUtils.closeQuietly(out);
}
handleInPlaceActions(destinationFile);
}
catch (IOException e) {
ZipExceptionUtil.rethrow(e);
}
finally {
if (isInPlace()) {
// destinationZip is a temporary file
FileUtils.deleteQuietly(destinationFile);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "process" | "public void process() {
if (src == null && dest == null) {
throw new IllegalArgumentException("Source and destination shouldn't be null together");
}
ZipEntryTransformerEntry[] transformersArray = getTransformersArray();
File destinationFile = null;
try {
destinationFile = getDestinationFile();
ZipOutputStream out = null;
ZipEntryOrInfoAdapter zipEntryAdapter = null;
if (destinationFile.isFile()) {
out = ZipFileUtil.createZipOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile)), charset);
zipEntryAdapter = new ZipEntryOrInfoAdapter(new CopyingCallback(transformersArray, out, preserveTimestamps), null);
}
else { // directory
zipEntryAdapter = new ZipEntryOrInfoAdapter(new UnpackingCallback(transformersArray, destinationFile), null);
}
try {
processAllEntries(zipEntryAdapter);
<MASK>handleInPlaceActions(destinationFile);</MASK>
}
finally {
IOUtils.closeQuietly(out);
}
}
catch (IOException e) {
ZipExceptionUtil.rethrow(e);
}
finally {
if (isInPlace()) {
// destinationZip is a temporary file
FileUtils.deleteQuietly(destinationFile);
}
}
}" |
Inversion-Mutation | megadiff | "public void onEnable() {
spaceRTK = this;
final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION);
type = configuration.getString("SpaceModule.Type", "Bukkit");
configuration.set("SpaceModule.Type", type = "Bukkit");
salt = configuration.getString("General.Salt", "<default>");
if (salt.equals("<default>")) {
salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
configuration.set("General.Salt", salt);
}
worldContainer = new File(configuration.getString("General.WorldContainer", "."));
if (type.equals("Bukkit"))
port = configuration.getInt("SpaceBukkit.Port", 2011);
rPort = configuration.getInt("SpaceRTK.Port", 2012);
backupDirName = configuration.getString("General.BackupDirectory", "Backups");
backupLogs = configuration.getBoolean("General.BackupLogs", true);
try {
configuration.save(SpaceModule.CONFIGURATION);
} catch (IOException e) {
e.printStackTrace();
}
try {
pingListener = new PingListener();
pingListener.startup();
} catch (IOException e) {
e.printStackTrace();
}
File backupDir = new File(SpaceRTK.getInstance().worldContainer.getPath() + File.separator + SpaceRTK.getInstance().backupDirName);
for(File f : baseDir.listFiles()) {
if(f.isDirectory()) {
if(f.getName().equalsIgnoreCase(backupDirName) && !f.getName().equals(backupDirName)) {
f.renameTo(backupDir);
}
}
}
pluginsManager = new PluginsManager();
actionsManager = new ActionsManager();
actionsManager.register(FileActions.class);
actionsManager.register(PluginActions.class);
actionsManager.register(SchedulerActions.class);
actionsManager.register(ServerActions.class);
panelListener = new PanelListener();
Scheduler.loadJobs();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable" | "public void onEnable() {
spaceRTK = this;
final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(SpaceModule.CONFIGURATION);
type = configuration.getString("SpaceModule.Type", "Bukkit");
configuration.set("SpaceModule.Type", type = "Bukkit");
salt = configuration.getString("General.Salt", "<default>");
if (salt.equals("<default>")) {
salt = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
configuration.set("General.Salt", salt);
}
worldContainer = new File(configuration.getString("General.WorldContainer", "."));
if (type.equals("Bukkit"))
port = configuration.getInt("SpaceBukkit.Port", 2011);
rPort = configuration.getInt("SpaceRTK.Port", 2012);
backupDirName = configuration.getString("General.BackupDirectory", "Backups");
backupLogs = configuration.getBoolean("General.BackupLogs", true);
try {
configuration.save(SpaceModule.CONFIGURATION);
} catch (IOException e) {
e.printStackTrace();
}
try {
pingListener = new PingListener();
} catch (IOException e) {
e.printStackTrace();
}
<MASK>pingListener.startup();</MASK>
File backupDir = new File(SpaceRTK.getInstance().worldContainer.getPath() + File.separator + SpaceRTK.getInstance().backupDirName);
for(File f : baseDir.listFiles()) {
if(f.isDirectory()) {
if(f.getName().equalsIgnoreCase(backupDirName) && !f.getName().equals(backupDirName)) {
f.renameTo(backupDir);
}
}
}
pluginsManager = new PluginsManager();
actionsManager = new ActionsManager();
actionsManager.register(FileActions.class);
actionsManager.register(PluginActions.class);
actionsManager.register(SchedulerActions.class);
actionsManager.register(ServerActions.class);
panelListener = new PanelListener();
Scheduler.loadJobs();
}" |
Inversion-Mutation | megadiff | "public void play(int x, int y) {
Play play = new Play(this.id, x, y);
try {
this.lock();
this.output.writeUTF("PLAY");
this.output.writeObject(play);
this.output.flush();
this.game.play(play);
} catch (IOException ex) {
Logger.getLogger(NetworkController.class.getName()).log(Level.SEVERE, null, ex);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "play" | "public void play(int x, int y) {
Play play = new Play(this.id, x, y);
try {
this.output.writeUTF("PLAY");
this.output.writeObject(play);
this.output.flush();
this.game.play(play);
<MASK>this.lock();</MASK>
} catch (IOException ex) {
Logger.getLogger(NetworkController.class.getName()).log(Level.SEVERE, null, ex);
}
}" |
Inversion-Mutation | megadiff | "@UsesMocks ({Activity.class, AuthProviderListener.class, SocializeException.class, AuthProviderResponse.class})
public void testAuthenticate() {
final String appId = "foobar";
Activity context = AndroidMock.createNiceMock(Activity.class);
AuthProviderListener listener = AndroidMock.createMock(AuthProviderListener.class);
SocializeException error = AndroidMock.createMock(SocializeException.class);
AuthProviderResponse response = AndroidMock.createMock(AuthProviderResponse.class);
ListenerHolder holder = new ListenerHolder() {
@Override
public void push(String key, SocializeListener listener) {
addResult(listener);
}
@Override
public void remove(String key) {
addResult(key);
}
@Override
public <L extends SocializeListener> L pop(String key) {
return null;
}
};
context.startActivity((Intent)AndroidMock.anyObject());
listener.onError(error);
listener.onAuthSuccess(response);
listener.onAuthFail(error);
AndroidMock.replay(context);
AndroidMock.replay(listener);
FacebookAuthProvider provider = new FacebookAuthProvider();
provider.init(context, holder);
FacebookAuthProviderInfo fb = new FacebookAuthProviderInfo();
fb.setAppId(appId);
provider.authenticate(fb, listener);
// We should have a listener from the put method
AuthProviderListener wrapper = getNextResult();
assertNotNull(wrapper);
// Test the listener
wrapper.onError(error);
String key = getNextResult();
assertNotNull(key);
assertEquals("auth", key);
wrapper.onAuthSuccess(response);
key = getNextResult();
assertNotNull(key);
assertEquals("auth", key);
wrapper.onAuthFail(error);
key = getNextResult();
assertNotNull(key);
assertEquals("auth", key);
AndroidMock.verify(context);
AndroidMock.verify(listener);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testAuthenticate" | "@UsesMocks ({Activity.class, AuthProviderListener.class, SocializeException.class, AuthProviderResponse.class})
public void testAuthenticate() {
final String appId = "foobar";
Activity context = AndroidMock.createNiceMock(Activity.class);
AuthProviderListener listener = AndroidMock.createMock(AuthProviderListener.class);
SocializeException error = AndroidMock.createMock(SocializeException.class);
AuthProviderResponse response = AndroidMock.createMock(AuthProviderResponse.class);
ListenerHolder holder = new ListenerHolder() {
@Override
public void push(String key, SocializeListener listener) {
addResult(listener);
}
@Override
public void remove(String key) {
}
@Override
public <L extends SocializeListener> L pop(String key) {
<MASK>addResult(key);</MASK>
return null;
}
};
context.startActivity((Intent)AndroidMock.anyObject());
listener.onError(error);
listener.onAuthSuccess(response);
listener.onAuthFail(error);
AndroidMock.replay(context);
AndroidMock.replay(listener);
FacebookAuthProvider provider = new FacebookAuthProvider();
provider.init(context, holder);
FacebookAuthProviderInfo fb = new FacebookAuthProviderInfo();
fb.setAppId(appId);
provider.authenticate(fb, listener);
// We should have a listener from the put method
AuthProviderListener wrapper = getNextResult();
assertNotNull(wrapper);
// Test the listener
wrapper.onError(error);
String key = getNextResult();
assertNotNull(key);
assertEquals("auth", key);
wrapper.onAuthSuccess(response);
key = getNextResult();
assertNotNull(key);
assertEquals("auth", key);
wrapper.onAuthFail(error);
key = getNextResult();
assertNotNull(key);
assertEquals("auth", key);
AndroidMock.verify(context);
AndroidMock.verify(listener);
}" |
Inversion-Mutation | megadiff | "public boolean match(IFileInfo fileInfo) throws CoreException {
if (provider == null) {
IFilterMatcherDescriptor filterDescriptor = project.getWorkspace().getFilterMatcherDescriptor(getId());
if (filterDescriptor != null)
provider = ((FilterDescriptor) filterDescriptor).createFilter();
if (provider == null) {
String message = NLS.bind(Messages.filters_missingFilterType, getId());
throw new CoreException(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, Platform.PLUGIN_ERROR, message, new Error()));
}
provider.initialize(project, description.getFileInfoMatcherDescription().getArguments());
}
if (provider != null)
return provider.matches(fileInfo);
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "match" | "public boolean match(IFileInfo fileInfo) throws CoreException {
if (provider == null) {
IFilterMatcherDescriptor filterDescriptor = project.getWorkspace().getFilterMatcherDescriptor(getId());
if (filterDescriptor != null)
provider = ((FilterDescriptor) filterDescriptor).createFilter();
<MASK>provider.initialize(project, description.getFileInfoMatcherDescription().getArguments());</MASK>
if (provider == null) {
String message = NLS.bind(Messages.filters_missingFilterType, getId());
throw new CoreException(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, Platform.PLUGIN_ERROR, message, new Error()));
}
}
if (provider != null)
return provider.matches(fileInfo);
return false;
}" |
Inversion-Mutation | megadiff | "private boolean handleCase () throws IOException {
LinkedList<Integer> crossingTimes = new LinkedList<Integer>();
String l;
i.readLine();
for (l = i.readLine(); l != null && !l.isEmpty(); l = i.readLine()) {
crossingTimes.add(new Integer(l.trim()));
}
Collections.sort(crossingTimes);
List<String> steps = new LinkedList<String>();
int totalTime = cross(crossingTimes, steps);
if (totalTime < 0) {
System.err.println("Input error");
return false;
}
o.println(totalTime);
for (String s : steps) {
o.println(s);
}
if (l != null) {
o.println();
return true;
} else {
return false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleCase" | "private boolean handleCase () throws IOException {
LinkedList<Integer> crossingTimes = new LinkedList<Integer>();
String l;
i.readLine();
for (l = i.readLine(); l != null && !l.isEmpty(); l = i.readLine()) {
crossingTimes.add(new Integer(l.trim()));
}
Collections.sort(crossingTimes);
List<String> steps = new LinkedList<String>();
int totalTime = cross(crossingTimes, steps);
if (totalTime < 0) {
System.err.println("Input error");
return false;
}
o.println(totalTime);
for (String s : steps) {
o.println(s);
}
<MASK>o.println();</MASK>
if (l != null) {
return true;
} else {
return false;
}
}" |
Inversion-Mutation | megadiff | "public void deleteData() throws SQLException, IOException {
update("delete from budget_line_items");
update("delete from budget_file_info");
update("delete from role_rights where roleId not in(1)");
update("delete from role_assignments where userId not in (1)");
update("delete from fulfillment_role_assignments");
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 pod_line_items");
update("delete from pod");
update("delete from orders");
update("delete from requisition_status_changes");
update("delete from user_password_reset_tokens");
update("delete from comments");
update("delete from epi_use_line_items");
update("delete from epi_inventory_line_items");
update("delete from refrigerator_problems");
update("delete from refrigerator_readings");
update("delete from full_coverages");
update("delete from facility_visits");
update("delete from distributions");
update("delete from refrigerators");
update("delete from users where userName not like('Admin%')");
deleteRnrData();
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 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 budget_line_items");
update("delete from budget_file_info");
update("delete from role_rights where roleId not in(1)");
update("delete from role_assignments where userId not in (1)");
update("delete from fulfillment_role_assignments");
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 pod_line_items");
update("delete from pod");
update("delete from orders");
update("delete from requisition_status_changes");
update("delete from user_password_reset_tokens");
update("delete from comments");
update("delete from epi_use_line_items");
update("delete from epi_inventory_line_items");
update("delete from refrigerator_problems");
update("delete from refrigerator_readings");
update("delete from full_coverages");
update("delete from facility_visits");
update("delete from distributions");
update("delete from users where userName not like('Admin%')");
deleteRnrData();
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 facility_ftp_details");
<MASK>update("delete from refrigerators");</MASK>
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");
}" |
Inversion-Mutation | megadiff | "@Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
adapter.setCanNotifyOnChange(false);
if (view.getFirstVisiblePosition() == 0 && view.getChildAt(0) != null && view.getChildAt(0).getTop() == 0)
{
if (scrollState == SCROLL_STATE_IDLE)
{
adapter.setCanNotifyOnChange(true);
int before = adapter.getCount();
adapter.notifyDataSetChanged();
int after = adapter.getCount();
int addCount = after - before;
if (addCount > 0)
{
view.setSelection(addCount + 1);
adapter.setCanNotifyOnChange(false);
Notificator.info(addCount + "件の新着があります");
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onScrollStateChanged" | "@Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
adapter.setCanNotifyOnChange(false);
if (view.getFirstVisiblePosition() == 0 && view.getChildAt(0) != null && view.getChildAt(0).getTop() == 0)
{
if (scrollState == SCROLL_STATE_IDLE)
{
adapter.setCanNotifyOnChange(true);
int before = adapter.getCount();
adapter.notifyDataSetChanged();
int after = adapter.getCount();
int addCount = after - before;
<MASK>view.setSelection(addCount + 1);</MASK>
if (addCount > 0)
{
adapter.setCanNotifyOnChange(false);
Notificator.info(addCount + "件の新着があります");
}
}
}
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) {
state.setup();
try {
ur=new UDPReceiver();
us=new UDPSender();
} catch (SocketException | UnknownHostException e) {
System.out.println(e.getMessage());
System.out.println("Could not set up UDP socket");
System.exit(-1);
}
Thread tcpListen=new Thread(tcp);
tcpListen.start();
Thread irThread=new Thread(ir);
irThread.start();
long timeEnteredState=System.currentTimeMillis();
Message udpMessage=null;
Message tcpMessage=null;
System.out.println("Welcome to our chat client");
System.out.println("To quit, type :quit");
System.out.println("To disconnect at any time, type :dc");
System.out.println("To change your username, type :user <new username>");
while(!error && !done){
if(lastState==null || !state.state.getClass().equals(lastState.getClass())){
firstCall=true;
timeEnteredState=System.currentTimeMillis();
}
else{
firstCall=false;
}
input=ir.getSubmitted();
if(input.startsWith(":dc")){
System.out.println("Disconnecting");
try{
tcp.close();
}
catch(Exception e){}
state.state=new Disconnected();
continue;
}
else if(input.startsWith(":quit")){
done=true;
System.out.println("Quitting");
continue;
}
else if(input.startsWith(":user")){
if(input.length()<7){
System.out.println("An argument is required");
continue;
}
User.setUserName(input.substring(6).trim());
System.out.println("Your username has been set to \""+User.getUserName()+"\"");
continue;
}
else if (input.equals("")) {
udpMessage = ur.read();
if(udpMessage==null){
tcpMessage = tcp.read();
if(tcpMessage instanceof ErrorMessage && tcpMessage.getCorrect()){
System.out.println("An error occured while communicating.\nDisconnecting");
try {
tcp.close();
} catch (Exception e) {}
state.state=new Disconnected();
continue;
}
}
else{
System.out.println("I have a udp message");
System.out.println(udpMessage.getCorrect());
}
}
lastState = state.getState();
state.process(input,tcp,us,udpMessage,tcpMessage,timeEnteredState,firstCall);
}
System.out.println("Hit enter to finish exiting");
try {
tcp.close();
} catch (Exception e1) {}
try{
tcp.stop();
}catch(Exception e){}
try{
ir.stop();
}
catch(Exception e){}
try {
ur.stop();
} catch (Exception e) {}
}" | 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) {
state.setup();
try {
ur=new UDPReceiver();
us=new UDPSender();
} catch (SocketException | UnknownHostException e) {
System.out.println(e.getMessage());
System.out.println("Could not set up UDP socket");
System.exit(-1);
}
Thread tcpListen=new Thread(tcp);
tcpListen.start();
Thread irThread=new Thread(ir);
irThread.start();
long timeEnteredState=System.currentTimeMillis();
Message udpMessage=null;
Message tcpMessage=null;
System.out.println("Welcome to our chat client");
System.out.println("To quit, type :quit");
System.out.println("To disconnect at any time, type :dc");
System.out.println("To change your username, type :user <new username>");
while(!error && !done){
if(lastState==null || !state.state.getClass().equals(lastState.getClass())){
firstCall=true;
timeEnteredState=System.currentTimeMillis();
}
else{
firstCall=false;
}
input=ir.getSubmitted();
if(input.startsWith(":dc")){
System.out.println("Disconnecting");
try{
tcp.close();
}
catch(Exception e){}
state.state=new Disconnected();
continue;
}
else if(input.startsWith(":quit")){
done=true;
System.out.println("Quitting");
continue;
}
else if(input.startsWith(":user")){
if(input.length()<7){
System.out.println("An argument is required");
continue;
}
User.setUserName(input.substring(6).trim());
System.out.println("Your username has been set to \""+User.getUserName()+"\"");
continue;
}
else if (input.equals("")) {
udpMessage = ur.read();
if(udpMessage==null){
tcpMessage = tcp.read();
if(tcpMessage instanceof ErrorMessage && tcpMessage.getCorrect()){
System.out.println("An error occured while communicating.\nDisconnecting");
try {
tcp.close();
} catch (Exception e) {}
state.state=new Disconnected();
continue;
}
}
else{
System.out.println("I have a udp message");
System.out.println(udpMessage.getCorrect());
}
}
lastState = state.getState();
state.process(input,tcp,us,udpMessage,tcpMessage,timeEnteredState,firstCall);
}
try {
tcp.close();
} catch (Exception e1) {}
try{
tcp.stop();
}catch(Exception e){}
try{
ir.stop();
}
catch(Exception e){}
try {
ur.stop();
} catch (Exception e) {}
<MASK>System.out.println("Hit enter to finish exiting");</MASK>
}" |
Inversion-Mutation | megadiff | "private String asHex(byte buf[])
{
StringBuilder strBuf = new StringBuilder(buf.length * 2);
// make sure it contains a letter!
strBuf.append("h");
for (int i = 0; i < buf.length; i++)
{
if ((buf[i] & 0xff) < 0x10)
{
strBuf.append("0");
}
strBuf.append(Long.toString(buf[i] & 0xff, 16));
}
if (strBuf.length() <= 6)
{
while (strBuf.length() <= 6)
{
strBuf.append("0");
}
}
return strBuf.toString().substring(0, 6);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "asHex" | "private String asHex(byte buf[])
{
StringBuilder strBuf = new StringBuilder(buf.length * 2);
// make sure it contains a letter!
strBuf.append("h");
for (int i = 0; i < buf.length; i++)
{
if ((buf[i] & 0xff) < 0x10)
{
strBuf.append("0");
<MASK>strBuf.append(Long.toString(buf[i] & 0xff, 16));</MASK>
}
}
if (strBuf.length() <= 6)
{
while (strBuf.length() <= 6)
{
strBuf.append("0");
}
}
return strBuf.toString().substring(0, 6);
}" |
Inversion-Mutation | megadiff | "private void layoutComponents() {
setVisible(false);
removeAll();
int index = 0;
if (trigger == null) {
add(new TextLabel("You must add at least one trigger before you can add conditions."),
"alignx center, aligny top, grow, push, w 90%!");
} else if (trigger.getType().getArgNames().length == 0) {
add(new TextLabel("Trigger does not have any arguments."),
"alignx center, aligny top, grow, push, w 90%!");
} else {
synchronized (conditions) {
for (ActionConditionDisplayPanel condition : conditions) {
add(new JLabel(index + "."), "aligny top");
add(condition, "growx, pushx, aligny top");
index++;
}
}
if (index == 0) {
add(new JLabel("No conditions."),
"alignx center, aligny top, growx, pushx");
}
}
setVisible(true);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "layoutComponents" | "private void layoutComponents() {
setVisible(false);
removeAll();
int index = 0;
if (trigger == null) {
add(new TextLabel("You must add at least one trigger before you can add conditions."),
"alignx center, aligny top, grow, push, w 90%!");
} else if (trigger.getType().getArgNames().length == 0) {
add(new TextLabel("Trigger does not have any arguments."),
"alignx center, aligny top, grow, push, w 90%!");
} else {
synchronized (conditions) {
for (ActionConditionDisplayPanel condition : conditions) {
<MASK>index++;</MASK>
add(new JLabel(index + "."), "aligny top");
add(condition, "growx, pushx, aligny top");
}
}
if (index == 0) {
add(new JLabel("No conditions."),
"alignx center, aligny top, growx, pushx");
}
}
setVisible(true);
}" |
Inversion-Mutation | megadiff | "private void startInternal(final StandardContext standardContext) {
if (isIgnored(standardContext)) return;
final CoreContainerSystem cs = getContainerSystem();
final Assembler a = getAssembler();
if (a == null) {
logger.warning("OpenEJB has not been initialized so war will not be scanned for nested modules " + standardContext.getPath());
return;
}
AppContext appContext = null;
//Look for context info, maybe context is already scanned
ContextInfo contextInfo = getContextInfo(standardContext);
final ClassLoader classLoader = standardContext.getLoader().getClassLoader();
if (contextInfo == null) {
final AppModule appModule = loadApplication(standardContext);
if (appModule != null) {
try {
contextInfo = addContextInfo(standardContext.getHostname(), standardContext);
contextInfo.standardContext = standardContext; // ensure to do it before an exception can be thrown
contextInfo.appInfo = configurationFactory.configureApplication(appModule);
appContext = a.createApplication(contextInfo.appInfo, classLoader);
// todo add watched resources to context
} catch (Exception e) {
logger.error("Unable to deploy collapsed ear in war " + standardContext.getPath() + ": Exception: " + e.getMessage(), e);
undeploy(standardContext, contextInfo);
// just to force tomee to start without EE part
if (System.getProperty(TOMEE_EAT_EXCEPTION_PROP) == null) {
final TomEERuntimeException tre = new TomEERuntimeException(e);
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
dem.saveDeploymentException(contextInfo.appInfo, tre);
throw tre;
}
return;
}
}
} else {
contextInfo.standardContext = standardContext;
}
WebAppInfo webAppInfo = null;
// appInfo is null when deployment fails
if (contextInfo.appInfo != null) {
for (final WebAppInfo w : contextInfo.appInfo.webApps) {
if (("/" + w.contextRoot).equals(standardContext.getPath()) || isRootApplication(standardContext)) {
webAppInfo = w;
if (appContext == null) {
appContext = cs.getAppContext(contextInfo.appInfo.appId);
}
break;
}
}
}
if (webAppInfo != null) {
if (appContext == null) {
appContext = getContainerSystem().getAppContext(contextInfo.appInfo.appId);
}
// save jsf stuff
final Map<String, Set<String>> scannedJsfClasses = new HashMap<String, Set<String>>();
for (final ClassListInfo info : webAppInfo.jsfAnnotatedClasses) {
scannedJsfClasses.put(info.name, info.list);
}
jsfClasses.put(standardContext.getLoader().getClassLoader(), scannedJsfClasses);
try {
// determine the injections
final Set<Injection> injections = new HashSet<Injection>();
injections.addAll(appContext.getInjections());
if (!contextInfo.appInfo.webAppAlone) {
updateInjections(injections, classLoader, false);
for (final BeanContext bean : appContext.getBeanContexts()) { // TODO: how if the same class in multiple webapps?
updateInjections(bean.getInjections(), classLoader, true);
}
}
injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
// jndi bindings
final Map<String, Object> bindings = new HashMap<String, Object>();
bindings.putAll(appContext.getBindings());
bindings.putAll(getJndiBuilder(classLoader, webAppInfo, injections).buildBindings(JndiEncBuilder.JndiScope.comp));
// merge OpenEJB jndi into Tomcat jndi
final TomcatJndiBuilder jndiBuilder = new TomcatJndiBuilder(standardContext, webAppInfo, injections);
jndiBuilder.mergeJndi();
// add WebDeploymentInfo to ContainerSystem
final WebContext webContext = new WebContext(appContext);
webContext.setJndiEnc(new InitialContext());
webContext.setClassLoader(classLoader);
webContext.setId(webAppInfo.moduleId);
webContext.setContextRoot(webAppInfo.contextRoot);
webContext.setBindings(bindings);
webContext.getInjections().addAll(injections);
appContext.getWebContexts().add(webContext);
cs.addWebContext(webContext);
if (!contextInfo.appInfo.webAppAlone) {
new CdiBuilder().build(contextInfo.appInfo, appContext, appContext.getBeanContexts(), webContext);
}
standardContext.setInstanceManager(new JavaeeInstanceManager(webContext, standardContext));
standardContext.getServletContext().setAttribute(InstanceManager.class.getName(), standardContext.getInstanceManager());
} catch (Exception e) {
logger.error("Error merging Java EE JNDI entries in to war " + standardContext.getPath() + ": Exception: " + e.getMessage(), e);
}
final JspFactory factory = JspFactory.getDefaultFactory();
if (factory != null) {
final JspApplicationContext applicationCtx = factory.getJspApplicationContext(standardContext.getServletContext());
final WebBeansContext context = appContext.getWebBeansContext();
if (context != null && context.getBeanManagerImpl().isInUse()) {
// Registering ELResolver with JSP container
final ELAdaptor elAdaptor = context.getService(ELAdaptor.class);
final ELResolver resolver = elAdaptor.getOwbELResolver();
applicationCtx.addELResolver(resolver);
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "startInternal" | "private void startInternal(final StandardContext standardContext) {
if (isIgnored(standardContext)) return;
final CoreContainerSystem cs = getContainerSystem();
final Assembler a = getAssembler();
if (a == null) {
logger.warning("OpenEJB has not been initialized so war will not be scanned for nested modules " + standardContext.getPath());
return;
}
AppContext appContext = null;
//Look for context info, maybe context is already scanned
ContextInfo contextInfo = getContextInfo(standardContext);
final ClassLoader classLoader = standardContext.getLoader().getClassLoader();
if (contextInfo == null) {
final AppModule appModule = loadApplication(standardContext);
if (appModule != null) {
try {
contextInfo = addContextInfo(standardContext.getHostname(), standardContext);
contextInfo.standardContext = standardContext; // ensure to do it before an exception can be thrown
contextInfo.appInfo = configurationFactory.configureApplication(appModule);
appContext = a.createApplication(contextInfo.appInfo, classLoader);
// todo add watched resources to context
} catch (Exception e) {
<MASK>undeploy(standardContext, contextInfo);</MASK>
logger.error("Unable to deploy collapsed ear in war " + standardContext.getPath() + ": Exception: " + e.getMessage(), e);
// just to force tomee to start without EE part
if (System.getProperty(TOMEE_EAT_EXCEPTION_PROP) == null) {
final TomEERuntimeException tre = new TomEERuntimeException(e);
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
dem.saveDeploymentException(contextInfo.appInfo, tre);
throw tre;
}
return;
}
}
} else {
contextInfo.standardContext = standardContext;
}
WebAppInfo webAppInfo = null;
// appInfo is null when deployment fails
if (contextInfo.appInfo != null) {
for (final WebAppInfo w : contextInfo.appInfo.webApps) {
if (("/" + w.contextRoot).equals(standardContext.getPath()) || isRootApplication(standardContext)) {
webAppInfo = w;
if (appContext == null) {
appContext = cs.getAppContext(contextInfo.appInfo.appId);
}
break;
}
}
}
if (webAppInfo != null) {
if (appContext == null) {
appContext = getContainerSystem().getAppContext(contextInfo.appInfo.appId);
}
// save jsf stuff
final Map<String, Set<String>> scannedJsfClasses = new HashMap<String, Set<String>>();
for (final ClassListInfo info : webAppInfo.jsfAnnotatedClasses) {
scannedJsfClasses.put(info.name, info.list);
}
jsfClasses.put(standardContext.getLoader().getClassLoader(), scannedJsfClasses);
try {
// determine the injections
final Set<Injection> injections = new HashSet<Injection>();
injections.addAll(appContext.getInjections());
if (!contextInfo.appInfo.webAppAlone) {
updateInjections(injections, classLoader, false);
for (final BeanContext bean : appContext.getBeanContexts()) { // TODO: how if the same class in multiple webapps?
updateInjections(bean.getInjections(), classLoader, true);
}
}
injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
// jndi bindings
final Map<String, Object> bindings = new HashMap<String, Object>();
bindings.putAll(appContext.getBindings());
bindings.putAll(getJndiBuilder(classLoader, webAppInfo, injections).buildBindings(JndiEncBuilder.JndiScope.comp));
// merge OpenEJB jndi into Tomcat jndi
final TomcatJndiBuilder jndiBuilder = new TomcatJndiBuilder(standardContext, webAppInfo, injections);
jndiBuilder.mergeJndi();
// add WebDeploymentInfo to ContainerSystem
final WebContext webContext = new WebContext(appContext);
webContext.setJndiEnc(new InitialContext());
webContext.setClassLoader(classLoader);
webContext.setId(webAppInfo.moduleId);
webContext.setContextRoot(webAppInfo.contextRoot);
webContext.setBindings(bindings);
webContext.getInjections().addAll(injections);
appContext.getWebContexts().add(webContext);
cs.addWebContext(webContext);
if (!contextInfo.appInfo.webAppAlone) {
new CdiBuilder().build(contextInfo.appInfo, appContext, appContext.getBeanContexts(), webContext);
}
standardContext.setInstanceManager(new JavaeeInstanceManager(webContext, standardContext));
standardContext.getServletContext().setAttribute(InstanceManager.class.getName(), standardContext.getInstanceManager());
} catch (Exception e) {
logger.error("Error merging Java EE JNDI entries in to war " + standardContext.getPath() + ": Exception: " + e.getMessage(), e);
}
final JspFactory factory = JspFactory.getDefaultFactory();
if (factory != null) {
final JspApplicationContext applicationCtx = factory.getJspApplicationContext(standardContext.getServletContext());
final WebBeansContext context = appContext.getWebBeansContext();
if (context != null && context.getBeanManagerImpl().isInUse()) {
// Registering ELResolver with JSP container
final ELAdaptor elAdaptor = context.getService(ELAdaptor.class);
final ELResolver resolver = elAdaptor.getOwbELResolver();
applicationCtx.addELResolver(resolver);
}
}
}
}" |
Inversion-Mutation | megadiff | "public Crypto(){
keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
key = new SecretKeySpec(keyBytes, "AES");
try {
cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Crypto" | "public Crypto(){
<MASK>key = new SecretKeySpec(keyBytes, "AES");</MASK>
keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
try {
cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}" |
Inversion-Mutation | megadiff | "public RunAutomaton(Automaton a, int maxInterval, boolean tableize) {
this.maxInterval = maxInterval;
a.determinize();
points = a.getStartPoints();
final State[] states = a.getNumberedStates();
initial = a.initial.number;
size = states.length;
accept = new boolean[size];
transitions = new int[size * points.length];
for (int n = 0; n < size * points.length; n++)
transitions[n] = -1;
for (State s : states) {
int n = s.number;
accept[n] = s.accept;
for (int c = 0; c < points.length; c++) {
State q = s.step(points[c]);
if (q != null) transitions[n * points.length + c] = q.number;
}
}
/*
* Set alphabet table for optimal run performance.
*/
if (tableize) {
classmap = new int[maxInterval + 1];
int i = 0;
for (int j = 0; j <= maxInterval; j++) {
if (i + 1 < points.length && j == points[i + 1])
i++;
classmap[j] = i;
}
} else {
classmap = null;
}
this.automaton = a;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "RunAutomaton" | "public RunAutomaton(Automaton a, int maxInterval, boolean tableize) {
this.maxInterval = maxInterval;
a.determinize();
points = a.getStartPoints();
<MASK>initial = a.initial.number;</MASK>
final State[] states = a.getNumberedStates();
size = states.length;
accept = new boolean[size];
transitions = new int[size * points.length];
for (int n = 0; n < size * points.length; n++)
transitions[n] = -1;
for (State s : states) {
int n = s.number;
accept[n] = s.accept;
for (int c = 0; c < points.length; c++) {
State q = s.step(points[c]);
if (q != null) transitions[n * points.length + c] = q.number;
}
}
/*
* Set alphabet table for optimal run performance.
*/
if (tableize) {
classmap = new int[maxInterval + 1];
int i = 0;
for (int j = 0; j <= maxInterval; j++) {
if (i + 1 < points.length && j == points[i + 1])
i++;
classmap[j] = i;
}
} else {
classmap = null;
}
this.automaton = a;
}" |
Inversion-Mutation | megadiff | "public void clean() {
EngineWebResource.stopRestfulServer();
if (_db != null) _db.shutdown();
_db = null;
_server = null;
_txMgr = null;
_executorService = null;
_store = null;
_ds = null;
_scheduler = null;
_scheduler = null;
_webEngine = null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "clean" | "public void clean() {
EngineWebResource.stopRestfulServer();
if (_db != null) _db.shutdown();
_server = null;
_txMgr = null;
_executorService = null;
_store = null;
<MASK>_db = null;</MASK>
_ds = null;
_scheduler = null;
_scheduler = null;
_webEngine = null;
}" |
Inversion-Mutation | megadiff | "private void createProject() {
// get the target and try to resolve it.
int targetId = mSdkCommandLine.getParamTargetId();
IAndroidTarget[] targets = mSdkManager.getTargets();
if (targetId < 1 || targetId > targets.length) {
errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.",
SdkConstants.androidCmdName());
}
IAndroidTarget target = targets[targetId - 1];
ProjectCreator creator = new ProjectCreator(mSdkFolder,
mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE :
mSdkCommandLine.isSilent() ? OutputLevel.SILENT :
OutputLevel.NORMAL,
mSdkLog);
String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath());
String projectName = mSdkCommandLine.getParamName();
String packageName = mSdkCommandLine.getParamProjectPackage();
String activityName = mSdkCommandLine.getParamProjectActivity();
if (projectName != null &&
!ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) {
errorAndExit(
"Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
projectName, ProjectCreator.CHARS_PROJECT_NAME);
return;
}
if (activityName != null &&
!ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) {
errorAndExit(
"Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
activityName, ProjectCreator.CHARS_ACTIVITY_NAME);
return;
}
if (packageName != null &&
!ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) {
errorAndExit(
"Package name '%1$s' contains invalid characters.\n" +
"A package name must be constitued of two Java identifiers.\n" +
"Each identifier allowed characters are: %2$s",
packageName, ProjectCreator.CHARS_PACKAGE_NAME);
return;
}
creator.createProject(projectDir,
projectName,
packageName,
activityName,
target,
false /* isTestProject*/);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createProject" | "private void createProject() {
// get the target and try to resolve it.
int targetId = mSdkCommandLine.getParamTargetId();
IAndroidTarget[] targets = mSdkManager.getTargets();
if (targetId < 1 || targetId > targets.length) {
errorAndExit("Target id is not valid. Use '%s list targets' to get the target ids.",
SdkConstants.androidCmdName());
}
IAndroidTarget target = targets[targetId - 1];
ProjectCreator creator = new ProjectCreator(mSdkFolder,
mSdkCommandLine.isVerbose() ? OutputLevel.VERBOSE :
mSdkCommandLine.isSilent() ? OutputLevel.SILENT :
OutputLevel.NORMAL,
mSdkLog);
String projectDir = getProjectLocation(mSdkCommandLine.getParamLocationPath());
String projectName = mSdkCommandLine.getParamName();
String packageName = mSdkCommandLine.getParamProjectPackage();
String activityName = mSdkCommandLine.getParamProjectActivity();
if (projectName != null &&
!ProjectCreator.RE_PROJECT_NAME.matcher(projectName).matches()) {
errorAndExit(
"Project name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
projectName, ProjectCreator.CHARS_PROJECT_NAME);
return;
}
if (activityName != null &&
!ProjectCreator.RE_ACTIVITY_NAME.matcher(activityName).matches()) {
errorAndExit(
"Activity name '%1$s' contains invalid characters.\nAllowed characters are: %2$s",
<MASK>activityName,</MASK> ProjectCreator.CHARS_ACTIVITY_NAME);
return;
}
if (packageName != null &&
!ProjectCreator.RE_PACKAGE_NAME.matcher(packageName).matches()) {
errorAndExit(
"Package name '%1$s' contains invalid characters.\n" +
"A package name must be constitued of two Java identifiers.\n" +
"Each identifier allowed characters are: %2$s",
packageName, ProjectCreator.CHARS_PACKAGE_NAME);
return;
}
creator.createProject(projectDir,
projectName,
<MASK>activityName,</MASK>
packageName,
target,
false /* isTestProject*/);
}" |
Inversion-Mutation | megadiff | "protected Configuration(Properties props) {
this.props = props;
parseScenarioMapping(props);
performanceLoggerConfig = createPerformanceLogger();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Configuration" | "protected Configuration(Properties props) {
this.props = props;
<MASK>performanceLoggerConfig = createPerformanceLogger();</MASK>
parseScenarioMapping(props);
}" |
Inversion-Mutation | megadiff | "public boolean call() {
boolean bResult = false;
for (int i = 0; i < callbackInfo.size(); i++) {
try {
((INickInUse)callbackInfo.get(i)).onNickInUse(myParser);
bResult = true;
} catch (Exception e) {
ParserError ei = new ParserError(ParserError.errError, "Exception in onNickInUse");
ei.setException(e);
callErrorInfo(ei);
}
}
return bResult;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "call" | "public boolean call() {
boolean bResult = false;
for (int i = 0; i < callbackInfo.size(); i++) {
try {
((INickInUse)callbackInfo.get(i)).onNickInUse(myParser);
} catch (Exception e) {
ParserError ei = new ParserError(ParserError.errError, "Exception in onNickInUse");
ei.setException(e);
callErrorInfo(ei);
}
<MASK>bResult = true;</MASK>
}
return bResult;
}" |
Inversion-Mutation | megadiff | "private void listen(final InputStream is) {
final BufferedInputStream bi = new BufferedInputStream(is);
new Thread() {
@Override
public void run() {
try {
while(true) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
receive(bi, os);
final String name = new String(os.toByteArray(), UTF8);
os = new ByteArrayOutputStream();
receive(bi, os);
final String data = new String(os.toByteArray(), UTF8);
notifiers.get(name).notify(data);
}
} catch(final IOException ex) { /* ignored */ }
}
}.start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "listen" | "private void listen(final InputStream is) {
new Thread() {
@Override
public void run() {
try {
<MASK>final BufferedInputStream bi = new BufferedInputStream(is);</MASK>
while(true) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
receive(bi, os);
final String name = new String(os.toByteArray(), UTF8);
os = new ByteArrayOutputStream();
receive(bi, os);
final String data = new String(os.toByteArray(), UTF8);
notifiers.get(name).notify(data);
}
} catch(final IOException ex) { /* ignored */ }
}
}.start();
}" |
Inversion-Mutation | megadiff | "public void update() {
updateShape();
updateEdge();
if (!isContentVisible()) {
mainView.setVisible(false);
return;
}
mainView.setVisible(true);
mainView.updateTextColor(this);
mainView.updateFont(this);
createAttributeView();
if (attributeView != null) {
attributeView.update();
}
NodeViewFactory.getInstance().updateDetails(this);
if (contentPane != null) {
final int componentCount = contentPane.getComponentCount();
for (int i = 1; i < componentCount; i++) {
final Component component = contentPane.getComponent(i);
if (component instanceof JComponent) {
((JComponent) component).revalidate();
}
}
}
updateShortener(getModel());
mainView.updateText(getModel());
mainView.updateIcons(this);
updateCloud();
modelBackgroundColor = NodeStyleController.getController(getMap().getModeController()).getBackgroundColor(model);
revalidate();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "update" | "public void update() {
updateShape();
if (!isContentVisible()) {
mainView.setVisible(false);
return;
}
mainView.setVisible(true);
mainView.updateTextColor(this);
mainView.updateFont(this);
createAttributeView();
if (attributeView != null) {
attributeView.update();
}
NodeViewFactory.getInstance().updateDetails(this);
if (contentPane != null) {
final int componentCount = contentPane.getComponentCount();
for (int i = 1; i < componentCount; i++) {
final Component component = contentPane.getComponent(i);
if (component instanceof JComponent) {
((JComponent) component).revalidate();
}
}
}
updateShortener(getModel());
mainView.updateText(getModel());
mainView.updateIcons(this);
updateCloud();
<MASK>updateEdge();</MASK>
modelBackgroundColor = NodeStyleController.getController(getMap().getModeController()).getBackgroundColor(model);
revalidate();
}" |
Inversion-Mutation | megadiff | "@Override
public boolean check(List<Vec2> trace){
if(trace.size() < 2)
return true;
angle = Filters.getAngle(trace);
Vec2 beg = trace.get(0);
Vec2 end = trace.get(trace.size()-1);
vec_x = Math.abs(end.x - beg.x);
vec_y = Math.abs(end.y - beg.y);
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "check" | "@Override
public boolean check(List<Vec2> trace){
<MASK>angle = Filters.getAngle(trace);</MASK>
if(trace.size() < 2)
return true;
Vec2 beg = trace.get(0);
Vec2 end = trace.get(trace.size()-1);
vec_x = Math.abs(end.x - beg.x);
vec_y = Math.abs(end.y - beg.y);
return true;
}" |
Inversion-Mutation | megadiff | "public void test1ToManyJoinClob(boolean freelob, boolean commitAfterLobVerify) throws SQLException, IOException
{
PreparedStatement ps = prepareStatement(
"select c from testClob join jointab on jointab.id = testClob.id");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Clob clob = rs.getClob(1);
verify40KClob(clob.getCharacterStream());
if (freelob)
clob.free();
if (commitAfterLobVerify)
commit();
}
rs.close();
rs = ps.executeQuery();
while (rs.next()) {
verify40KClob(rs.getCharacterStream(1));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "test1ToManyJoinClob" | "public void test1ToManyJoinClob(boolean freelob, boolean commitAfterLobVerify) throws SQLException, IOException
{
PreparedStatement ps = prepareStatement(
"select c from testClob join jointab on jointab.id = testClob.id");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Clob clob = rs.getClob(1);
if (freelob)
clob.free();
if (commitAfterLobVerify)
commit();
<MASK>verify40KClob(clob.getCharacterStream());</MASK>
}
rs.close();
rs = ps.executeQuery();
while (rs.next()) {
verify40KClob(rs.getCharacterStream(1));
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
createButton(parent, IDialogConstants.CLIENT_ID + 1, Messages.DateSelectionDialog_Clear, false);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createButtonsForButtonBar" | "@Override
protected void createButtonsForButtonBar(Composite parent) {
<MASK>createButton(parent, IDialogConstants.CLIENT_ID + 1, Messages.DateSelectionDialog_Clear, false);</MASK>
super.createButtonsForButtonBar(parent);
}" |
Inversion-Mutation | megadiff | "public void badRequest(List<?> errors) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
result.use(representation()).from(errors, "errors").serialize();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "badRequest" | "public void badRequest(List<?> errors) {
<MASK>result.use(representation()).from(errors, "errors").serialize();</MASK>
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}" |
Inversion-Mutation | megadiff | "public void parse() {
if (parsed)
return;
header = new NXHeader(this, slea);
nodes = new NXNode[(int) header.getNodeCount()];
tables = new NXTables(header, slea);
populateNodesTable();
parsed = true;
populateNodeChildren();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parse" | "public void parse() {
if (parsed)
return;
header = new NXHeader(this, slea);
nodes = new NXNode[(int) header.getNodeCount()];
tables = new NXTables(header, slea);
populateNodesTable();
<MASK>populateNodeChildren();</MASK>
parsed = true;
}" |
Inversion-Mutation | megadiff | "@Override
protected void onApply() {
final String productName = targetProductSelector.getModel().getProductName();
if (productName == null || productName.isEmpty()) {
showErrorDialog("Please specify a target product name.");
targetProductSelector.getProductNameTextField().requestFocus();
return;
}
File productFile = targetProductSelector.getModel().getProductFile();
if (productFile.exists()) {
String message = "The specified output file\n\"{0}\"\n already exists.\n\n" +
"Do you want to overwrite the existing file?";
String formatedMessage = MessageFormat.format(message, productFile.getAbsolutePath());
final int answer = JOptionPane.showConfirmDialog(getJDialog(), formatedMessage,
getJDialog().getTitle(), JOptionPane.YES_NO_OPTION);
if (answer != JOptionPane.YES_OPTION) {
return;
}
}
String productDir = targetProductSelector.getModel().getProductDir().getAbsolutePath();
appContext.getPreferences().setPropertyString(BasicApp.PROPERTY_KEY_APP_LAST_SAVE_DIR, productDir);
Product targetProduct = null;
try {
targetProduct = createTargetProduct();
} catch (Exception e) {
showErrorDialog(e.getMessage());
}
if (targetProduct == null) {
return;
}
targetProduct.setName(targetProductSelector.getModel().getProductName());
if (targetProductSelector.getModel().isSaveToFileSelected()) {
targetProduct.setFileLocation(productFile);
final ProgressMonitorSwingWorker worker = new ProductWriterSwingWorker(targetProduct);
worker.executeWithBlocking();
} else if (targetProductSelector.getModel().isOpenInAppSelected()) {
// todo - check for existance
appContext.getProductManager().addProduct(targetProduct);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onApply" | "@Override
protected void onApply() {
final String productName = targetProductSelector.getModel().getProductName();
if (productName == null || productName.isEmpty()) {
showErrorDialog("Please specify a target product name.");
targetProductSelector.getProductNameTextField().requestFocus();
return;
}
File productFile = targetProductSelector.getModel().getProductFile();
if (productFile.exists()) {
String message = "The specified output file\n\"{0}\"\n already exists.\n\n" +
"Do you want to overwrite the existing file?";
String formatedMessage = MessageFormat.format(message, productFile.getAbsolutePath());
final int answer = JOptionPane.showConfirmDialog(getJDialog(), formatedMessage,
getJDialog().getTitle(), JOptionPane.YES_NO_OPTION);
if (answer != JOptionPane.YES_OPTION) {
return;
}
}
String productDir = targetProductSelector.getModel().getProductDir().getAbsolutePath();
appContext.getPreferences().setPropertyString(BasicApp.PROPERTY_KEY_APP_LAST_SAVE_DIR, productDir);
Product targetProduct = null;
try {
targetProduct = createTargetProduct();
} catch (Exception e) {
showErrorDialog(e.getMessage());
}
if (targetProduct == null) {
return;
}
targetProduct.setName(targetProductSelector.getModel().getProductName());
<MASK>targetProduct.setFileLocation(productFile);</MASK>
if (targetProductSelector.getModel().isSaveToFileSelected()) {
final ProgressMonitorSwingWorker worker = new ProductWriterSwingWorker(targetProduct);
worker.executeWithBlocking();
} else if (targetProductSelector.getModel().isOpenInAppSelected()) {
// todo - check for existance
appContext.getProductManager().addProduct(targetProduct);
}
}" |
Inversion-Mutation | megadiff | "public static void dismiss() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dismiss" | "public static void dismiss() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
<MASK>dialog = null;</MASK>
}
}" |
Inversion-Mutation | megadiff | "public void disconnect() throws IOException {
outputStream.flush();
socket.close();
inputStream = null;
outputStream = null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "disconnect" | "public void disconnect() throws IOException {
socket.close();
inputStream = null;
<MASK>outputStream.flush();</MASK>
outputStream = null;
}" |
Inversion-Mutation | megadiff | "@Override
public void showAds(final boolean show) {
if (isProVersion()) return;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (show) {
adView.loadAd(new AdRequest());
adView.setVisibility(View.VISIBLE);
} else {
adView.setVisibility(View.GONE);
}
}
});
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showAds" | "@Override
public void showAds(final boolean show) {
if (isProVersion()) return;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (show) {
<MASK>adView.setVisibility(View.VISIBLE);</MASK>
adView.loadAd(new AdRequest());
} else {
adView.setVisibility(View.GONE);
}
}
});
}" |
Inversion-Mutation | megadiff | "@Override
public void run() {
if (show) {
adView.loadAd(new AdRequest());
adView.setVisibility(View.VISIBLE);
} else {
adView.setVisibility(View.GONE);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run() {
if (show) {
<MASK>adView.setVisibility(View.VISIBLE);</MASK>
adView.loadAd(new AdRequest());
} else {
adView.setVisibility(View.GONE);
}
}" |
Inversion-Mutation | megadiff | "private void createNewProjects() {
StructureEdit se = null;
try {
se = StructureEdit.getStructureEditForWrite(project);
List comps = se.getComponentModelRoot().getComponents();
List removedComps = new ArrayList();
for (int i = 1;i<comps.size();i++) {
WorkbenchComponent comp = (WorkbenchComponent) comps.get(i);
IWorkspace ws = ResourcesPlugin.getWorkspace();
IProject newProj = ws.getRoot().getProject(comp.getName());
if (!newProj.exists()) {
try {
createProj(newProj,(!comp.getComponentType().getComponentTypeId().equals(J2EEProjectUtilities.ENTERPRISE_APPLICATION)));
WtpUtils.addNatures(newProj);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
addFacetsToProject(newProj,comp.getComponentType().getComponentTypeId(),comp.getComponentType().getVersion(),false);
removedComps.add(comp);
IFolder compFolder = project.getFolder(comp.getName());
if (compFolder.exists())
try {
compFolder.delete(true,null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
se.getComponentModelRoot().getComponents().removeAll(removedComps);
se.save(null);
} finally {
if (se != null)
se.dispose();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createNewProjects" | "private void createNewProjects() {
StructureEdit se = null;
try {
se = StructureEdit.getStructureEditForWrite(project);
List comps = se.getComponentModelRoot().getComponents();
List removedComps = new ArrayList();
for (int i = 1;i<comps.size();i++) {
WorkbenchComponent comp = (WorkbenchComponent) comps.get(i);
IWorkspace ws = ResourcesPlugin.getWorkspace();
IProject newProj = ws.getRoot().getProject(comp.getName());
if (!newProj.exists()) {
try {
createProj(newProj,(!comp.getComponentType().getComponentTypeId().equals(J2EEProjectUtilities.ENTERPRISE_APPLICATION)));
WtpUtils.addNatures(newProj);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
addFacetsToProject(newProj,comp.getComponentType().getComponentTypeId(),comp.getComponentType().getVersion(),false);
removedComps.add(comp);
IFolder compFolder = project.getFolder(comp.getName());
if (compFolder.exists())
try {
compFolder.delete(true,null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
<MASK>se.save(null);</MASK>
}
se.getComponentModelRoot().getComponents().removeAll(removedComps);
} finally {
if (se != null)
se.dispose();
}
}" |
Inversion-Mutation | megadiff | "protected void setup(Slot s, Rendered r) {
T t = map(r);
super.setup(s, r);
Location loc = s.os.get(PView.loc);
plain.copy(s.os);
s.os.put(PView.loc, loc);
if(t != null) {
Color col = newcol(t);
new States.ColState(col).prep(s.os);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setup" | "protected void setup(Slot s, Rendered r) {
T t = map(r);
Location loc = s.os.get(PView.loc);
plain.copy(s.os);
s.os.put(PView.loc, loc);
if(t != null) {
Color col = newcol(t);
new States.ColState(col).prep(s.os);
}
<MASK>super.setup(s, r);</MASK>
}" |
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 | "public static void showDialog()
{
if (Client.getOperatingSystem() == Client.OS.UNIX) {
// JKG 07Apr2006:
// On Linux, if a dialog is built, closed using setVisible(false),
// and then requested again using setVisible(true), it does
// not appear on top. I've tried using toFront(), requestFocus(),
// but none of that works. Instead, I brute force it and
// rebuild the dialog from scratch each time.
if (theDialog != null) theDialog.dispose();
theDialog = null;
}
if (theDialog == null)
{
JFrame jf;
if (TopLevel.isMDIMode())
jf = TopLevel.getCurrentJFrame();
else
jf = null;
theDialog = new GetInfoNode(jf, false);
}
theDialog.loadInfo();
if (!theDialog.isVisible()) {
theDialog.pack();
}
theDialog.setVisible(true);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showDialog" | "public static void showDialog()
{
if (Client.getOperatingSystem() == Client.OS.UNIX) {
// JKG 07Apr2006:
// On Linux, if a dialog is built, closed using setVisible(false),
// and then requested again using setVisible(true), it does
// not appear on top. I've tried using toFront(), requestFocus(),
// but none of that works. Instead, I brute force it and
// rebuild the dialog from scratch each time.
if (theDialog != null) theDialog.dispose();
theDialog = null;
}
if (theDialog == null)
{
JFrame jf;
if (TopLevel.isMDIMode())
jf = TopLevel.getCurrentJFrame();
else
jf = null;
theDialog = new GetInfoNode(jf, false);
}
theDialog.loadInfo();
if (!theDialog.isVisible()) {
theDialog.pack();
<MASK>theDialog.setVisible(true);</MASK>
}
}" |
Inversion-Mutation | megadiff | "public static Object getService(String serviceName, Class serviceType) {
Object proxy = null;
if (serviceName != null && serviceName.equals(ANY))
serviceName = null;
int tryNo = 0;
while (tryNo < LUS_REAPEAT) {
logger.info("trying to get service: " + serviceType + ":" + serviceName + "; attempt: "
+ tryNo + "...");
try {
tryNo++;
proxy = getService(serviceType, new Entry[] { new Name(
serviceName) }, null);
if (proxy != null)
break;
Thread.sleep(WAIT_FOR);
} catch (Exception e) {
logger.throwing("" + ServiceAccessor.class, "getService", e);
}
}
logger.info("got LUS service: " + serviceType + ":" + serviceName + "\n" + proxy);
return proxy;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getService" | "public static Object getService(String serviceName, Class serviceType) {
Object proxy = null;
if (serviceName != null && serviceName.equals(ANY))
serviceName = null;
int tryNo = 0;
while (tryNo < LUS_REAPEAT) {
logger.info("trying to get service: " + serviceType + ":" + serviceName + "; attempt: "
+ tryNo + "...");
try {
proxy = getService(serviceType, new Entry[] { new Name(
serviceName) }, null);
if (proxy != null)
break;
<MASK>tryNo++;</MASK>
Thread.sleep(WAIT_FOR);
} catch (Exception e) {
logger.throwing("" + ServiceAccessor.class, "getService", e);
}
}
logger.info("got LUS service: " + serviceType + ":" + serviceName + "\n" + proxy);
return proxy;
}" |
Inversion-Mutation | megadiff | "private static void setupStatic(NoItem instance) {
NoItem.instance = instance;
NoItem.config = new Config();
NoItem.permsManager = new PermMan();
NoItem.lists = new Lists();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setupStatic" | "private static void setupStatic(NoItem instance) {
NoItem.instance = instance;
<MASK>NoItem.permsManager = new PermMan();</MASK>
NoItem.config = new Config();
NoItem.lists = new Lists();
}" |
Inversion-Mutation | megadiff | "public void openConsole() {
if (fConsole == null) {
fConsole = new JavaStackTraceConsole(); //$NON-NLS-1$
fConsole.initializeDocument();
fConsoleManager.addConsoles(new IConsole[]{fConsole});
}
fConsoleManager.showConsoleView(fConsole);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "openConsole" | "public void openConsole() {
if (fConsole == null) {
fConsole = new JavaStackTraceConsole(); //$NON-NLS-1$
fConsoleManager.addConsoles(new IConsole[]{fConsole});
}
<MASK>fConsole.initializeDocument();</MASK>
fConsoleManager.showConsoleView(fConsole);
}" |
Inversion-Mutation | megadiff | "public void run(String[] args) {
if (args.length < 6 || args.length > 8) {
usage();
}
try {
int argNo = 0;
if (args[argNo].equals("-cg")) {
useCg = true;
++argNo;
}
hdrFilename = args[argNo++];
pbuffer_w = Integer.parseInt(args[argNo++]);
pbuffer_h = Integer.parseInt(args[argNo++]);
win_scale = Float.parseFloat(args[argNo++]);
blurWidth = Integer.parseInt(args[argNo++]);
blur_scale = Integer.parseInt(args[argNo++]);
if (argNo < args.length) {
modelFilename = args[argNo++];
}
blur_w = pbuffer_w / blur_scale;
blur_h = pbuffer_h / blur_scale;
win_w = (int) (pbuffer_w * win_scale);
win_h = (int) (pbuffer_h * win_scale);
} catch (NumberFormatException e) {
e.printStackTrace();
usage();
}
if (modelFilename != null) {
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(modelFilename);
if (in == null) {
throw new IOException("Unable to open model file " + modelFilename);
}
model = new ObjReader(in);
if (model.getVerticesPerFace() != 3) {
throw new IOException("Sorry, only triangle-based WaveFront OBJ files supported");
}
model.rescale(1.2f / model.getRadius());
++numModels;
modelno = 5;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
b['f'] = true; // fragment programs
b['g'] = true; // glare
b['l'] = true;
b[' '] = true; // animation
b['n'] = true; // upsampling smoothing
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(hdrFilename);
if (in == null) {
throw new IOException("Unable to open HDR file " + hdrFilename);
}
hdr = new HDRTexture(in);
hdr.analyze();
hdr.convert();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
canvas = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities());
canvas.addGLEventListener(new Listener());
canvas.setNoAutoRedrawMode(true);
animator = new Animator(canvas);
frame = new Frame("HDR test");
frame.setLayout(new BorderLayout());
canvas.setSize(win_w, win_h);
frame.add(canvas, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.show();
canvas.requestFocus();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
runExit();
}
});
animator.start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run(String[] args) {
if (args.length < 6 || args.length > 8) {
usage();
}
try {
int argNo = 0;
if (args[argNo].equals("-cg")) {
useCg = true;
++argNo;
}
hdrFilename = args[argNo++];
pbuffer_w = Integer.parseInt(args[argNo++]);
pbuffer_h = Integer.parseInt(args[argNo++]);
win_scale = Float.parseFloat(args[argNo++]);
blurWidth = Integer.parseInt(args[argNo++]);
blur_scale = Integer.parseInt(args[argNo++]);
if (argNo < args.length) {
modelFilename = args[argNo++];
}
blur_w = pbuffer_w / blur_scale;
blur_h = pbuffer_h / blur_scale;
win_w = (int) (pbuffer_w * win_scale);
win_h = (int) (pbuffer_h * win_scale);
} catch (NumberFormatException e) {
e.printStackTrace();
usage();
}
if (modelFilename != null) {
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(modelFilename);
if (in == null) {
throw new IOException("Unable to open model file " + modelFilename);
}
model = new ObjReader(in);
if (model.getVerticesPerFace() != 3) {
throw new IOException("Sorry, only triangle-based WaveFront OBJ files supported");
}
model.rescale(1.2f / model.getRadius());
++numModels;
modelno = 5;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
b['f'] = true; // fragment programs
b['g'] = true; // glare
b['l'] = true;
b[' '] = true; // animation
b['n'] = true; // upsampling smoothing
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(hdrFilename);
if (in == null) {
throw new IOException("Unable to open HDR file " + hdrFilename);
}
hdr = new HDRTexture(in);
hdr.analyze();
hdr.convert();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
canvas = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities());
canvas.addGLEventListener(new Listener());
canvas.setNoAutoRedrawMode(true);
animator = new Animator(canvas);
frame = new Frame("HDR test");
frame.setLayout(new BorderLayout());
<MASK>frame.setResizable(false);</MASK>
canvas.setSize(win_w, win_h);
frame.add(canvas, BorderLayout.CENTER);
frame.pack();
frame.show();
canvas.requestFocus();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
runExit();
}
});
animator.start();
}" |
Inversion-Mutation | megadiff | "@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case EDIT_TASK_MENU_ITEM:
Intent i = new Intent(this, TaskEditActivity.class);
i.putExtra("_id", info.id);
startActivityForResult(i, ACTIVITY_EDIT);
return true;
case DELETE_TASK_MENU_ITEM:
m_db.deleteTask(info.id);
m_task_cursor.requery();
// Update the App Widget, if necessary
startService(new Intent(this, TimesheetAppWidgetProvider.UpdateService.class));
return true;
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onContextItemSelected" | "@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case EDIT_TASK_MENU_ITEM:
Intent i = new Intent(this, TaskEditActivity.class);
<MASK>startActivityForResult(i, ACTIVITY_EDIT);</MASK>
i.putExtra("_id", info.id);
return true;
case DELETE_TASK_MENU_ITEM:
m_db.deleteTask(info.id);
m_task_cursor.requery();
// Update the App Widget, if necessary
startService(new Intent(this, TimesheetAppWidgetProvider.UpdateService.class));
return true;
}
return false;
}" |
Inversion-Mutation | megadiff | "public Collection<Api> parse() {
List<Api> apis = new ArrayList<Api>();
Map<String, Collection<Method>> apiMethods = new HashMap<String, Collection<Method>>();
for (MethodDoc method : classDoc.methods()) {
ApiMethodParser methodParser = parentMethod == null ?
new ApiMethodParser(options, rootPath, method) :
new ApiMethodParser(options, parentMethod, method);
Method parsedMethod = methodParser.parse();
if (parsedMethod == null) {
continue;
}
if (parsedMethod.isSubResource()) {
ClassDoc subResourceClassDoc = lookUpClassDoc(method.returnType());
if (subResourceClassDoc != null) {
// delete class from the dictionary to handle recursive sub-resources
Collection<ClassDoc> shrunkClasses = new ArrayList<ClassDoc>(classes);
shrunkClasses.remove(classDoc);
// recursively parse the sub-resource class
ApiClassParser subResourceParser = new ApiClassParser(options, subResourceClassDoc, shrunkClasses, parsedMethod);
apis.addAll(subResourceParser.parse());
models.addAll(subResourceParser.models());
}
continue;
}
models.addAll(methodParser.models());
String realPath = parsedMethod.getPath();
Collection<Method> matchingMethods = apiMethods.get(realPath);
if (matchingMethods == null) {
matchingMethods = new ArrayList<Method>();
apiMethods.put(realPath, matchingMethods);
}
matchingMethods.add(parsedMethod);
}
for (Map.Entry<String, Collection<Method>> apiEntries : apiMethods.entrySet()) {
Collection<Operation> operations = new ArrayList<Operation>(
transform(apiEntries.getValue(), new Function<Method, Operation>() {
@Override
public Operation apply(Method method) {
return new Operation(method);
}
})
);
apis.add(new Api(apiEntries.getKey(), "", operations));
}
Collections.sort(apis, new Comparator<Api>() {
@Override
public int compare(Api o1, Api o2) {
return o1.getPath().compareTo(o2.getPath());
}
});
return apis;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parse" | "public Collection<Api> parse() {
List<Api> apis = new ArrayList<Api>();
Map<String, Collection<Method>> apiMethods = new HashMap<String, Collection<Method>>();
for (MethodDoc method : classDoc.methods()) {
ApiMethodParser methodParser = parentMethod == null ?
new ApiMethodParser(options, rootPath, method) :
new ApiMethodParser(options, parentMethod, method);
Method parsedMethod = methodParser.parse();
if (parsedMethod == null) {
<MASK>continue;</MASK>
}
if (parsedMethod.isSubResource()) {
ClassDoc subResourceClassDoc = lookUpClassDoc(method.returnType());
if (subResourceClassDoc != null) {
// delete class from the dictionary to handle recursive sub-resources
Collection<ClassDoc> shrunkClasses = new ArrayList<ClassDoc>(classes);
shrunkClasses.remove(classDoc);
// recursively parse the sub-resource class
ApiClassParser subResourceParser = new ApiClassParser(options, subResourceClassDoc, shrunkClasses, parsedMethod);
apis.addAll(subResourceParser.parse());
models.addAll(subResourceParser.models());
<MASK>continue;</MASK>
}
}
models.addAll(methodParser.models());
String realPath = parsedMethod.getPath();
Collection<Method> matchingMethods = apiMethods.get(realPath);
if (matchingMethods == null) {
matchingMethods = new ArrayList<Method>();
apiMethods.put(realPath, matchingMethods);
}
matchingMethods.add(parsedMethod);
}
for (Map.Entry<String, Collection<Method>> apiEntries : apiMethods.entrySet()) {
Collection<Operation> operations = new ArrayList<Operation>(
transform(apiEntries.getValue(), new Function<Method, Operation>() {
@Override
public Operation apply(Method method) {
return new Operation(method);
}
})
);
apis.add(new Api(apiEntries.getKey(), "", operations));
}
Collections.sort(apis, new Comparator<Api>() {
@Override
public int compare(Api o1, Api o2) {
return o1.getPath().compareTo(o2.getPath());
}
});
return apis;
}" |
Inversion-Mutation | megadiff | "@Override
public void createControl(Composite parent) {
super.createControl(parent);
ProjectChooser projChooser = (ProjectChooser) form.getWidgetControl("project");
final PackageChooser pkgChooser = (PackageChooser) form.getWidgetControl("package");
OperationWizard wiz = (OperationWizard) getWizard();
IJavaProject project = wiz.getSelectedNuxeoProject();
projChooser.setNature(NuxeoNature.ID);
if (project != null) {
projChooser.setValue(project);
pkgChooser.setProject(project);
pkgChooser.setValue(wiz.getSelectedPackageFragment());
}
projChooser.addValueChangedListener(new ObjectChooser.ValueChangedListener<IJavaProject>() {
@Override
public void valueChanged(ObjectChooser<IJavaProject> source,
IJavaProject oldValue, IJavaProject newValue) {
pkgChooser.setProject(newValue);
}
});
// projChooser.addValueChangedListener(new
// ValueChangedListener<IJavaProject>() {
// @Override
// public void valueChanged(ObjectChooser<IJavaProject> source,
// IJavaProject oldValue, IJavaProject newValue) {
// if (newValue != null && !newValue.exists()) {
// return
// }
// }
// });
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createControl" | "@Override
public void createControl(Composite parent) {
super.createControl(parent);
ProjectChooser projChooser = (ProjectChooser) form.getWidgetControl("project");
final PackageChooser pkgChooser = (PackageChooser) form.getWidgetControl("package");
OperationWizard wiz = (OperationWizard) getWizard();
IJavaProject project = wiz.getSelectedNuxeoProject();
projChooser.setNature(NuxeoNature.ID);
if (project != null) {
projChooser.setValue(project);
pkgChooser.setProject(project);
}
<MASK>pkgChooser.setValue(wiz.getSelectedPackageFragment());</MASK>
projChooser.addValueChangedListener(new ObjectChooser.ValueChangedListener<IJavaProject>() {
@Override
public void valueChanged(ObjectChooser<IJavaProject> source,
IJavaProject oldValue, IJavaProject newValue) {
pkgChooser.setProject(newValue);
}
});
// projChooser.addValueChangedListener(new
// ValueChangedListener<IJavaProject>() {
// @Override
// public void valueChanged(ObjectChooser<IJavaProject> source,
// IJavaProject oldValue, IJavaProject newValue) {
// if (newValue != null && !newValue.exists()) {
// return
// }
// }
// });
}" |
Inversion-Mutation | megadiff | "private void listen(final InputStream is) {
new Thread() {
@Override
public void run() {
try {
final BufferedInputStream bi = new BufferedInputStream(is);
while(true) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
receive(bi, baos);
final String name = baos.toString("UTF-8");
baos = new ByteArrayOutputStream();
receive(bi, baos);
final String data = baos.toString("UTF-8");
notifiers.get(name).notify(data);
}
} catch(final Exception ex) { }
}
}.start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "listen" | "private void listen(final InputStream is) {
new Thread() {
@Override
public void run() {
try {
while(true) {
<MASK>final BufferedInputStream bi = new BufferedInputStream(is);</MASK>
ByteArrayOutputStream baos = new ByteArrayOutputStream();
receive(bi, baos);
final String name = baos.toString("UTF-8");
baos = new ByteArrayOutputStream();
receive(bi, baos);
final String data = baos.toString("UTF-8");
notifiers.get(name).notify(data);
}
} catch(final Exception ex) { }
}
}.start();
}" |
Inversion-Mutation | megadiff | "@Override
public void run() {
try {
final BufferedInputStream bi = new BufferedInputStream(is);
while(true) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
receive(bi, baos);
final String name = baos.toString("UTF-8");
baos = new ByteArrayOutputStream();
receive(bi, baos);
final String data = baos.toString("UTF-8");
notifiers.get(name).notify(data);
}
} catch(final Exception ex) { }
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run() {
try {
while(true) {
<MASK>final BufferedInputStream bi = new BufferedInputStream(is);</MASK>
ByteArrayOutputStream baos = new ByteArrayOutputStream();
receive(bi, baos);
final String name = baos.toString("UTF-8");
baos = new ByteArrayOutputStream();
receive(bi, baos);
final String data = baos.toString("UTF-8");
notifiers.get(name).notify(data);
}
} catch(final Exception ex) { }
}" |
Inversion-Mutation | megadiff | "public void main(IWContext iwc) throws Exception {
super.main(iwc);
init(iwc);
iwrb.getLocalizedString(WINDOW_NAME, "Update League Template Window");
addTitle(iwrb.getLocalizedString(WINDOW_NAME, "Update League Template Window"), TITLE_STYLECLASS);
if (group != null) {
if (group.getGroupType().equals(IWMemberConstants.GROUP_TYPE_CLUB_DIVISION_TEMPLATE)
|| group.getGroupType().equals(IWMemberConstants.GROUP_TYPE_LEAGUE)) {
String action = iwc.getParameter(ACTION);
if (action == null) {
addForm(iwc);
}
else if (action.equals(ACTION_CANCEL)) {
close();
}
else if (action.equals(ACTION_UPDATE)) {
updateChildren(iwc);
setOnLoad("window.opener.parent.frames['iwb_main'].location.reload()");
close();
}
}
else {
add(getResourceBundle(iwc).getLocalizedString(WRONG_GROUP_TYPE,
"Please select either a league, or a division template under a league."));
}
}
else {
add(getResourceBundle(iwc).getLocalizedString(WRONG_GROUP_TYPE,
"Please select either a league, or a division template under a league."));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main" | "public void main(IWContext iwc) throws Exception {
super.main(iwc);
iwrb.getLocalizedString(WINDOW_NAME, "Update League Template Window");
addTitle(iwrb.getLocalizedString(WINDOW_NAME, "Update League Template Window"), TITLE_STYLECLASS);
<MASK>init(iwc);</MASK>
if (group != null) {
if (group.getGroupType().equals(IWMemberConstants.GROUP_TYPE_CLUB_DIVISION_TEMPLATE)
|| group.getGroupType().equals(IWMemberConstants.GROUP_TYPE_LEAGUE)) {
String action = iwc.getParameter(ACTION);
if (action == null) {
addForm(iwc);
}
else if (action.equals(ACTION_CANCEL)) {
close();
}
else if (action.equals(ACTION_UPDATE)) {
updateChildren(iwc);
setOnLoad("window.opener.parent.frames['iwb_main'].location.reload()");
close();
}
}
else {
add(getResourceBundle(iwc).getLocalizedString(WRONG_GROUP_TYPE,
"Please select either a league, or a division template under a league."));
}
}
else {
add(getResourceBundle(iwc).getLocalizedString(WRONG_GROUP_TYPE,
"Please select either a league, or a division template under a league."));
}
}" |
Inversion-Mutation | megadiff | "public void init () {
initRenderer();
initGame();
initUi();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init" | "public void init () {
initRenderer();
<MASK>initUi();</MASK>
initGame();
}" |
Inversion-Mutation | megadiff | "@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding(defaultCharset);
}
chain.doFilter(request, response);
if (response.getCharacterEncoding() == null) {
response.setCharacterEncoding(defaultCharset);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doFilter" | "@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding(defaultCharset);
}
if (response.getCharacterEncoding() == null) {
response.setCharacterEncoding(defaultCharset);
}
<MASK>chain.doFilter(request, response);</MASK>
}" |
Inversion-Mutation | megadiff | "public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylyn.tests");
StatusHandler.addStatusHandler(new TestingStatusNotifier());
ResourcesUiBridgePlugin.getDefault().setResourceMonitoringEnabled(false);
// TODO: the order of these tests might still matter, but shouldn't
// $JUnit-BEGIN$
suite.addTest(AllJavaTests.suite());
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllIntegrationTests.suite());
suite.addTest(AllContextTests.suite());
suite.addTest(AllIdeTests.suite());
suite.addTest(AllTasksTests.suite());
suite.addTest(AllResourcesTests.suite());
suite.addTest(AllBugzillaTests.suite());
suite.addTest(AllMiscTests.suite());
suite.addTest(AllJiraTests.suite());
suite.addTest(AllTracTests.suite());
suite.addTestSuite(WebClientUtilTest.class);
suite.addTestSuite(SslProtocolSocketFactoryTest.class);
// $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.mylyn.tests");
StatusHandler.addStatusHandler(new TestingStatusNotifier());
ResourcesUiBridgePlugin.getDefault().setResourceMonitoringEnabled(false);
// TODO: the order of these tests might still matter, but shouldn't
// $JUnit-BEGIN$
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllIntegrationTests.suite());
suite.addTest(AllContextTests.suite());
suite.addTest(AllIdeTests.suite());
<MASK>suite.addTest(AllJavaTests.suite());</MASK>
suite.addTest(AllTasksTests.suite());
suite.addTest(AllResourcesTests.suite());
suite.addTest(AllBugzillaTests.suite());
suite.addTest(AllMiscTests.suite());
suite.addTest(AllJiraTests.suite());
suite.addTest(AllTracTests.suite());
suite.addTestSuite(WebClientUtilTest.class);
suite.addTestSuite(SslProtocolSocketFactoryTest.class);
// $JUnit-END$
return suite;
}" |
Inversion-Mutation | megadiff | "public void testGenerateAndReParsingIsTheSame() throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream ds = new DataOutputStream(buffer);
Object expected = createObject();
LOG.info("Created: " + expected);
openWireformat.marshal(expected, ds);
ds.close();
// now lets try parse it back again
ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray());
DataInputStream dis = new DataInputStream(in);
Object actual = openWireformat.unmarshal(dis);
assertBeansEqual("", new HashSet<Object>(), expected, actual);
LOG.info("Parsed: " + actual);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testGenerateAndReParsingIsTheSame" | "public void testGenerateAndReParsingIsTheSame() throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream ds = new DataOutputStream(buffer);
Object expected = createObject();
LOG.info("Created: " + expected);
openWireformat.marshal(expected, ds);
ds.close();
// now lets try parse it back again
ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray());
DataInputStream dis = new DataInputStream(in);
Object actual = openWireformat.unmarshal(dis);
LOG.info("Parsed: " + actual);
<MASK>assertBeansEqual("", new HashSet<Object>(), expected, actual);</MASK>
}" |
Inversion-Mutation | megadiff | "private static void initGraphics(int scalew, int scaleh, int atari_width, int atari_height, int atari_visible_width, int atari_left_margin){
canvas = new AtariCanvas();
canvas.atari_width = atari_width;
canvas.atari_height = atari_height;
canvas.atari_visible_width = atari_visible_width;
canvas.atari_left_margin = atari_left_margin;
canvas.init();
canvas.setFocusTraversalKeysEnabled(false); //allow Tab key to work
canvas.setFocusable(true);
frame.add(canvas);
frame.addWindowListener(new WindowAdapter() {
public void windowsGainedFocus(WindowEvent e) {
canvas.requestFocusInWindow();
}
public void windowClosing(WindowEvent e) {
canvas.setWindowClosed();
}
});
canvas.requestFocusInWindow();
canvas.setSize(new Dimension(canvas.width*scalew,canvas.height*scaleh));
canvas.scalew = scalew;
canvas.scaleh = scaleh;
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initGraphics" | "private static void initGraphics(int scalew, int scaleh, int atari_width, int atari_height, int atari_visible_width, int atari_left_margin){
canvas = new AtariCanvas();
canvas.atari_width = atari_width;
canvas.atari_height = atari_height;
canvas.atari_visible_width = atari_visible_width;
canvas.atari_left_margin = atari_left_margin;
canvas.init();
canvas.setFocusTraversalKeysEnabled(false); //allow Tab key to work
canvas.setFocusable(true);
frame.add(canvas);
frame.addWindowListener(new WindowAdapter() {
public void windowsGainedFocus(WindowEvent e) {
canvas.requestFocusInWindow();
}
public void windowClosing(WindowEvent e) {
canvas.setWindowClosed();
}
});
canvas.requestFocusInWindow();
canvas.setSize(new Dimension(canvas.width*scalew,canvas.height*scaleh));
canvas.scalew = scalew;
canvas.scaleh = scaleh;
<MASK>frame.pack();</MASK>
frame.setResizable(false);
frame.setVisible(true);
}" |
Inversion-Mutation | megadiff | "private String convertToBibtexFormat(String s)
{
String retu = "";
outerloop:
for (int k = 0; k < s.length(); k++){
for (int i = 0; i< checkList.length; i++) {
if (s.substring(k,k+1).equals(checkList[i][0])) {
retu += checkList[i][1];
continue outerloop;
}
}
retu += s.charAt(k);
}
return retu;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "convertToBibtexFormat" | "private String convertToBibtexFormat(String s)
{
String retu = "";
outerloop:
for (int k = 0; k < s.length(); k++){
for (int i = 0; i< checkList.length; i++) {
if (s.substring(k,k+1).equals(checkList[i][0])) {
retu += checkList[i][1];
continue outerloop;
}
<MASK>retu += s.charAt(k);</MASK>
}
}
return retu;
}" |
Inversion-Mutation | megadiff | "private void refresh() {
configDirs = configurationsDir.listFiles(FILTER);
if (configDirs == null) {
configDirs = NO_CONFIGS;
}
Arrays.sort(configDirs);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "refresh" | "private void refresh() {
configDirs = configurationsDir.listFiles(FILTER);
<MASK>Arrays.sort(configDirs);</MASK>
if (configDirs == null) {
configDirs = NO_CONFIGS;
}
}" |
Inversion-Mutation | megadiff | "public void removeLatestFutureContract(int applicationID, Date earliestAllowedRemoveDate, User performer) {
UserTransaction t = getSessionContext().getUserTransaction();
try {
t.begin();
ChildCareApplication application = getApplication(applicationID);
ChildCareContract latestContract = getLatestContractByApplication(applicationID);
SchoolClassMember latestMember = latestContract.getSchoolClassMember();
SchoolClassMemberLog log = null;
try {
log = getSchoolBusiness().getSchoolClassMemberLogHome().findLatestLogByUser(latestMember);
}
catch (FinderException fe) {
//No log found...
}
IWTimestamp earliestDate = new IWTimestamp(earliestAllowedRemoveDate);
IWTimestamp contractStart = new IWTimestamp(latestContract.getValidFromDate());
boolean removeContract = false;
boolean logRemoved = false;
if (log != null) {
IWTimestamp logStart = new IWTimestamp(log.getStartDate());
if (logStart.isLaterThan(contractStart)) {
// Only log needs to be removed
if (logStart.isLaterThanOrEquals(earliestDate)) {
log.remove();
logRemoved = true;
}
} else if (logStart.equals(contractStart)) {
// Log start equals contract start, remove both log and contract
if (logStart.isLaterThanOrEquals(earliestDate)) {
log.remove();
logRemoved = true;
removeContract = true;
}
} else if (contractStart.isLaterThanOrEquals(earliestDate)) {
// Don't remove log, only contract
removeContract = true;
}
} else if (contractStart.isLaterThanOrEquals(earliestDate)) {
removeContract = true;
}
if (removeContract) {
Contract contract = latestContract.getContract();
latestContract.remove();
if (contract != null) {
contract.setStatus("T");
contract.store();
}
ChildCareContract newLatestContract = getLatestContractByApplication(applicationID);
if (newLatestContract != null) {
newLatestContract.setTerminatedDate(application.getRejectionDate());
newLatestContract.store();
if (newLatestContract.getSchoolClassMemberId() != ((Integer) latestMember.getPrimaryKey()).intValue()) {
latestMember.remove();
latestMember = newLatestContract.getSchoolClassMember();
}
} else {
// No contracts, set application to status sent_in
application.setContractFileId(null);
application.setContractId(null);
application.setCareTime(null);
application.setRejectionDate(null);
application.setCancelConfirmationReceived(null);
application.setCancelMessage(null);
application.setHasDateSet(false);
application.setApplicationStatus(getStatusSentIn());
application.store();
changeCaseStatus(application, getCaseStatusOpen().getStatus(), performer);
latestMember.remove();
}
}
if (logRemoved) {
// Remove end date on prior log
try {
SchoolClassMemberLog priorLog = getSchoolBusiness().getSchoolClassMemberLogHome().findLatestLogByUser(latestMember);
if (priorLog != null) {
priorLog.setEndDate(application.getRejectionDate());
priorLog.store();
}
}
catch (FinderException fe) {
//No prior log found...
}
}
t.commit();
} catch (Exception e) {
e.printStackTrace();
try {
t.rollback();
} catch (SystemException ex) {
log(e);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeLatestFutureContract" | "public void removeLatestFutureContract(int applicationID, Date earliestAllowedRemoveDate, User performer) {
UserTransaction t = getSessionContext().getUserTransaction();
try {
t.begin();
ChildCareApplication application = getApplication(applicationID);
ChildCareContract latestContract = getLatestContractByApplication(applicationID);
SchoolClassMember latestMember = latestContract.getSchoolClassMember();
SchoolClassMemberLog log = null;
try {
log = getSchoolBusiness().getSchoolClassMemberLogHome().findLatestLogByUser(latestMember);
}
catch (FinderException fe) {
//No log found...
}
IWTimestamp earliestDate = new IWTimestamp(earliestAllowedRemoveDate);
<MASK>IWTimestamp logStart = new IWTimestamp(log.getStartDate());</MASK>
IWTimestamp contractStart = new IWTimestamp(latestContract.getValidFromDate());
boolean removeContract = false;
boolean logRemoved = false;
if (log != null) {
if (logStart.isLaterThan(contractStart)) {
// Only log needs to be removed
if (logStart.isLaterThanOrEquals(earliestDate)) {
log.remove();
logRemoved = true;
}
} else if (logStart.equals(contractStart)) {
// Log start equals contract start, remove both log and contract
if (logStart.isLaterThanOrEquals(earliestDate)) {
log.remove();
logRemoved = true;
removeContract = true;
}
} else if (contractStart.isLaterThanOrEquals(earliestDate)) {
// Don't remove log, only contract
removeContract = true;
}
} else if (contractStart.isLaterThanOrEquals(earliestDate)) {
removeContract = true;
}
if (removeContract) {
Contract contract = latestContract.getContract();
latestContract.remove();
if (contract != null) {
contract.setStatus("T");
contract.store();
}
ChildCareContract newLatestContract = getLatestContractByApplication(applicationID);
if (newLatestContract != null) {
newLatestContract.setTerminatedDate(application.getRejectionDate());
newLatestContract.store();
if (newLatestContract.getSchoolClassMemberId() != ((Integer) latestMember.getPrimaryKey()).intValue()) {
latestMember.remove();
latestMember = newLatestContract.getSchoolClassMember();
}
} else {
// No contracts, set application to status sent_in
application.setContractFileId(null);
application.setContractId(null);
application.setCareTime(null);
application.setRejectionDate(null);
application.setCancelConfirmationReceived(null);
application.setCancelMessage(null);
application.setHasDateSet(false);
application.setApplicationStatus(getStatusSentIn());
application.store();
changeCaseStatus(application, getCaseStatusOpen().getStatus(), performer);
latestMember.remove();
}
}
if (logRemoved) {
// Remove end date on prior log
try {
SchoolClassMemberLog priorLog = getSchoolBusiness().getSchoolClassMemberLogHome().findLatestLogByUser(latestMember);
if (priorLog != null) {
priorLog.setEndDate(application.getRejectionDate());
priorLog.store();
}
}
catch (FinderException fe) {
//No prior log found...
}
}
t.commit();
} catch (Exception e) {
e.printStackTrace();
try {
t.rollback();
} catch (SystemException ex) {
log(e);
}
}
}" |
Inversion-Mutation | megadiff | "public void clear() {
setState(ClearDisplayState.getInstance());
setContent(INITIAL_VALUE);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "clear" | "public void clear() {
<MASK>setContent(INITIAL_VALUE);</MASK>
setState(ClearDisplayState.getInstance());
}" |
Inversion-Mutation | megadiff | "public void readTaskList(TaskList tlist, File inFile) {
initExtensions();
MylarTasklistPlugin.getDefault().restoreTaskHandlerState();
hasCaughtException = false;
try {
// parse file
//
if (!inFile.exists())
return;
Document doc = openAsDOM(inFile);
if (doc == null) {
handleException(inFile, null, new MylarExternalizerException("Tasklist was not well formed XML"));
return;
}
// read root node to get version number
//
Element root = doc.getDocumentElement();
readVersion = root.getAttribute("Version");
if (readVersion.equals("1.0.0")) {
MylarPlugin.log("version: " + readVersion + " not supported", this);
// NodeList list = root.getChildNodes();
// for (int i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// readTasksToNewFormat(child, tlist);
// //tlist.addRootTask(readTaskAndSubTasks(child, null, tlist));
// }
} else {
NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
boolean wasRead = false;
try {
if (child.getNodeName().endsWith(DefaultTaskListExternalizer.TAG_CATEGORY)) {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadCategory(child)) {
externalizer.readCategory(child, tlist);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadCategory(child)) {
defaultExternalizer.readCategory(child, tlist);
} else {
// MylarPlugin.log("Did not read: " +
// child.getNodeName(), this);
}
} else {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadTask(child)) {
// TODO add the tasks properly
ITask newTask = externalizer.readTask(child, tlist, null, null);
ITaskHandler taskHandler = MylarTasklistPlugin.getDefault().getTaskHandlerForElement(newTask);
if(taskHandler != null){
newTask = taskHandler.taskAdded(newTask);
}
tlist.addRootTask(newTask);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadTask(child)) {
tlist.addRootTask(defaultExternalizer.readTask(child, tlist, null, null));
} else {
// MylarPlugin.log("Did not read: " + child.getNodeName(), this);
}
}
} catch (Exception e) {
handleException(inFile, child, e);
}
}
}
} catch (Exception e) {
handleException(inFile, null, e);
}
if (hasCaughtException) {
// if exception was caught, write out the new task file, so that it doesn't happen again.
// this is OK, since the original (corrupt) tasklist is saved.
// TODO: The problem with this is that if the orignal tasklist has tasks and bug reports, but a
// task is corrupted, the new tasklist that is written will not include the bug reports (since the
// bugzilla externalizer is not loaded. So there is a potentila that we can lose bug reports.
writeTaskList(tlist, inFile);
}
MylarTasklistPlugin.getDefault().restoreTaskHandlerState();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "readTaskList" | "public void readTaskList(TaskList tlist, File inFile) {
<MASK>MylarTasklistPlugin.getDefault().restoreTaskHandlerState();</MASK>
initExtensions();
hasCaughtException = false;
try {
// parse file
//
if (!inFile.exists())
return;
Document doc = openAsDOM(inFile);
if (doc == null) {
handleException(inFile, null, new MylarExternalizerException("Tasklist was not well formed XML"));
return;
}
// read root node to get version number
//
Element root = doc.getDocumentElement();
readVersion = root.getAttribute("Version");
if (readVersion.equals("1.0.0")) {
MylarPlugin.log("version: " + readVersion + " not supported", this);
// NodeList list = root.getChildNodes();
// for (int i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// readTasksToNewFormat(child, tlist);
// //tlist.addRootTask(readTaskAndSubTasks(child, null, tlist));
// }
} else {
NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
boolean wasRead = false;
try {
if (child.getNodeName().endsWith(DefaultTaskListExternalizer.TAG_CATEGORY)) {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadCategory(child)) {
externalizer.readCategory(child, tlist);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadCategory(child)) {
defaultExternalizer.readCategory(child, tlist);
} else {
// MylarPlugin.log("Did not read: " +
// child.getNodeName(), this);
}
} else {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadTask(child)) {
// TODO add the tasks properly
ITask newTask = externalizer.readTask(child, tlist, null, null);
ITaskHandler taskHandler = MylarTasklistPlugin.getDefault().getTaskHandlerForElement(newTask);
if(taskHandler != null){
newTask = taskHandler.taskAdded(newTask);
}
tlist.addRootTask(newTask);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadTask(child)) {
tlist.addRootTask(defaultExternalizer.readTask(child, tlist, null, null));
} else {
// MylarPlugin.log("Did not read: " + child.getNodeName(), this);
}
}
} catch (Exception e) {
handleException(inFile, child, e);
}
}
}
} catch (Exception e) {
handleException(inFile, null, e);
}
if (hasCaughtException) {
// if exception was caught, write out the new task file, so that it doesn't happen again.
// this is OK, since the original (corrupt) tasklist is saved.
// TODO: The problem with this is that if the orignal tasklist has tasks and bug reports, but a
// task is corrupted, the new tasklist that is written will not include the bug reports (since the
// bugzilla externalizer is not loaded. So there is a potentila that we can lose bug reports.
writeTaskList(tlist, inFile);
}
<MASK>MylarTasklistPlugin.getDefault().restoreTaskHandlerState();</MASK>
}" |
Inversion-Mutation | megadiff | "static void analyzeUnlockingFunction(CFGNode node, Function function,
Element parameter) {
String lockName;
String description;
BackTrack backTrackNode;
lockName = CodeAnalyzer.parseStringVariable(parameter);
logger.info("Unlocking function detected - unlocking "+lockName);
for(FunctionState data : function.getFunctionStates()) {
data.lockDown(lockName);
description = "unlocking "+lockName
+ " - still locked: "+data.getLockStack();
backTrackNode = data.getBackTrack().peekLast();
if(backTrackNode.getCFGNodeID().equals(node.getNumber())) {
backTrackNode.setDescription(description);
} else {
backTrackNode = new BackTrack(node.getNumber(),node.getLine(),
node.getColumn(),description,
function.getFileName());
data.getBackTrack().addLast(backTrackNode);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "analyzeUnlockingFunction" | "static void analyzeUnlockingFunction(CFGNode node, Function function,
Element parameter) {
String lockName;
String description;
BackTrack backTrackNode;
lockName = CodeAnalyzer.parseStringVariable(parameter);
logger.info("Unlocking function detected - unlocking "+lockName);
for(FunctionState data : function.getFunctionStates()) {
description = "unlocking "+lockName
+ " - still locked: "+data.getLockStack();
<MASK>data.lockDown(lockName);</MASK>
backTrackNode = data.getBackTrack().peekLast();
if(backTrackNode.getCFGNodeID().equals(node.getNumber())) {
backTrackNode.setDescription(description);
} else {
backTrackNode = new BackTrack(node.getNumber(),node.getLine(),
node.getColumn(),description,
function.getFileName());
data.getBackTrack().addLast(backTrackNode);
}
}
}" |
Inversion-Mutation | megadiff | "public InsProgressSprite(String spritePath) {
super(spritePath);
this.mirror = new InsAlignment();
this.initProgress();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "InsProgressSprite" | "public InsProgressSprite(String spritePath) {
super(spritePath);
<MASK>this.initProgress();</MASK>
this.mirror = new InsAlignment();
}" |
Inversion-Mutation | megadiff | "public static CharSequence scrape(final String url, final boolean isPost, final String request, String encoding, final boolean cookieHandling)
throws IOException
{
if (encoding == null)
encoding = SCRAPE_DEFAULT_ENCODING;
int tries = 3;
while (true)
{
try
{
final StringBuilder buffer = new StringBuilder(SCRAPE_INITIAL_CAPACITY);
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(request != null);
connection.setConnectTimeout(SCRAPE_CONNECT_TIMEOUT);
connection.setReadTimeout(SCRAPE_READ_TIMEOUT);
connection.addRequestProperty("User-Agent", SCRAPE_USER_AGENT);
// workaround to disable Vodafone compression
connection.addRequestProperty("Cache-Control", "no-cache");
if (cookieHandling && stateCookie != null)
{
connection.addRequestProperty("Cookie", stateCookie);
}
if (request != null)
{
if (isPost)
{
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Content-Length", Integer.toString(request.length()));
}
final Writer writer = new OutputStreamWriter(connection.getOutputStream(), encoding);
writer.write(request);
writer.close();
}
final Reader pageReader = new InputStreamReader(connection.getInputStream(), encoding);
copy(pageReader, buffer);
pageReader.close();
if (buffer.length() > 0)
{
if (cookieHandling)
{
for (final Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet())
{
if (entry.getKey().equalsIgnoreCase("set-cookie"))
{
for (final String value : entry.getValue())
{
if (value.startsWith("NSC_"))
{
stateCookie = value.split(";", 2)[0];
}
}
}
}
}
return buffer;
}
else
{
if (tries-- > 0)
System.out.println("got empty page, retrying...");
else
throw new IOException("got empty page: " + url);
}
}
catch (final SocketTimeoutException x)
{
if (tries-- > 0)
System.out.println("socket timed out, retrying...");
else
throw x;
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "scrape" | "public static CharSequence scrape(final String url, final boolean isPost, final String request, String encoding, final boolean cookieHandling)
throws IOException
{
if (encoding == null)
encoding = SCRAPE_DEFAULT_ENCODING;
<MASK>final StringBuilder buffer = new StringBuilder(SCRAPE_INITIAL_CAPACITY);</MASK>
int tries = 3;
while (true)
{
try
{
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(request != null);
connection.setConnectTimeout(SCRAPE_CONNECT_TIMEOUT);
connection.setReadTimeout(SCRAPE_READ_TIMEOUT);
connection.addRequestProperty("User-Agent", SCRAPE_USER_AGENT);
// workaround to disable Vodafone compression
connection.addRequestProperty("Cache-Control", "no-cache");
if (cookieHandling && stateCookie != null)
{
connection.addRequestProperty("Cookie", stateCookie);
}
if (request != null)
{
if (isPost)
{
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Content-Length", Integer.toString(request.length()));
}
final Writer writer = new OutputStreamWriter(connection.getOutputStream(), encoding);
writer.write(request);
writer.close();
}
final Reader pageReader = new InputStreamReader(connection.getInputStream(), encoding);
copy(pageReader, buffer);
pageReader.close();
if (buffer.length() > 0)
{
if (cookieHandling)
{
for (final Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet())
{
if (entry.getKey().equalsIgnoreCase("set-cookie"))
{
for (final String value : entry.getValue())
{
if (value.startsWith("NSC_"))
{
stateCookie = value.split(";", 2)[0];
}
}
}
}
}
return buffer;
}
else
{
if (tries-- > 0)
System.out.println("got empty page, retrying...");
else
throw new IOException("got empty page: " + url);
}
}
catch (final SocketTimeoutException x)
{
if (tries-- > 0)
System.out.println("socket timed out, retrying...");
else
throw x;
}
}
}" |
Inversion-Mutation | megadiff | "public void testVersioningArtifactDirectory()
throws Exception
{
List<String> orderedVersions = new ArrayList<String>();
orderedVersions.add( "1.0.0-alpha-5" );
orderedVersions.add( "1.0.0-beta-3" );
orderedVersions.add( "1.0.0-beta-4" );
orderedVersions.add( "1.0.0-beta-6-SNAPSHOT" );
orderedVersions.add( "1.0.0" );
orderedVersions.add( "1.0.1" );
orderedVersions.add( "1.0.3-SNAPSHOT" );
orderedVersions.add( "1.1-M1" );
orderedVersions.add( "1.2.0-beta-1" );
orderedVersions.add( "1.2.0-SNAPSHOT" );
orderedVersions.add( "1.2.0" );
orderedVersions.add( "1.2.0.5-SNAPSHOT" );
orderedVersions.add( "1.3.0-SNAPSHOT" );
List<String> unorderedVersions = new ArrayList<String>();
unorderedVersions.add( "1.3.0-SNAPSHOT" );
unorderedVersions.add( "1.2.0-SNAPSHOT" );
unorderedVersions.add( "1.2.0.5-SNAPSHOT" );
unorderedVersions.add( "1.0.1" );
unorderedVersions.add( "1.0.3-SNAPSHOT" );
unorderedVersions.add( "1.1-M1" );
unorderedVersions.add( "1.0.0-alpha-5" );
unorderedVersions.add( "1.2.0" );
unorderedVersions.add( "1.2.0-beta-1" );
unorderedVersions.add( "1.0.0" );
unorderedVersions.add( "1.0.0-beta-3" );
unorderedVersions.add( "1.0.0-beta-4" );
unorderedVersions.add( "1.0.0-beta-6-SNAPSHOT" );
Metadata metadata = new Metadata();
new ArtifactDirMetadataProcessor( null ).versioning( metadata, unorderedVersions );
assertEquals( orderedVersions, metadata.getVersioning().getVersions() );
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testVersioningArtifactDirectory" | "public void testVersioningArtifactDirectory()
throws Exception
{
List<String> orderedVersions = new ArrayList<String>();
orderedVersions.add( "1.0.0-alpha-5" );
orderedVersions.add( "1.0.0-beta-3" );
orderedVersions.add( "1.0.0-beta-4" );
orderedVersions.add( "1.0.0-beta-6-SNAPSHOT" );
orderedVersions.add( "1.0.0" );
orderedVersions.add( "1.0.1" );
orderedVersions.add( "1.0.3-SNAPSHOT" );
orderedVersions.add( "1.1-M1" );
<MASK>orderedVersions.add( "1.2.0-SNAPSHOT" );</MASK>
orderedVersions.add( "1.2.0-beta-1" );
orderedVersions.add( "1.2.0" );
orderedVersions.add( "1.2.0.5-SNAPSHOT" );
orderedVersions.add( "1.3.0-SNAPSHOT" );
List<String> unorderedVersions = new ArrayList<String>();
unorderedVersions.add( "1.3.0-SNAPSHOT" );
un<MASK>orderedVersions.add( "1.2.0-SNAPSHOT" );</MASK>
unorderedVersions.add( "1.2.0.5-SNAPSHOT" );
unorderedVersions.add( "1.0.1" );
unorderedVersions.add( "1.0.3-SNAPSHOT" );
unorderedVersions.add( "1.1-M1" );
unorderedVersions.add( "1.0.0-alpha-5" );
unorderedVersions.add( "1.2.0" );
unorderedVersions.add( "1.2.0-beta-1" );
unorderedVersions.add( "1.0.0" );
unorderedVersions.add( "1.0.0-beta-3" );
unorderedVersions.add( "1.0.0-beta-4" );
unorderedVersions.add( "1.0.0-beta-6-SNAPSHOT" );
Metadata metadata = new Metadata();
new ArtifactDirMetadataProcessor( null ).versioning( metadata, unorderedVersions );
assertEquals( orderedVersions, metadata.getVersioning().getVersions() );
}" |
Inversion-Mutation | megadiff | "@Override
public void OnPlayerDeathEvent(RunsafePlayerDeathEvent runsafePlayerDeathEvent)
{
String originalMessage = runsafePlayerDeathEvent.getDeathMessage();
runsafePlayerDeathEvent.setDeathMessage("");
if (!this.hideDeathWorlds.contains(runsafePlayerDeathEvent.getEntity().getWorld().getName()))
{
Death deathType = this.deathParser.getDeathType(originalMessage);
if (deathType == Death.UNKNOWN)
{
console.writeColoured("Unknown death message detected: \"%s\"", originalMessage);
}
String deathName = deathType.name().toLowerCase();
String deathTag = deathName;
String entityName = null;
String killerName = null;
if (deathType.hasEntityInvolved())
{
killerName = this.deathParser.getInvolvedEntityName(originalMessage, deathType);
entityName = this.deathParser.isEntityName(killerName);
deathTag = String.format(
"%s_%s",
deathName,
(entityName != null ? entityName : "Player")
);
}
String customDeathMessage = this.deathParser.getCustomDeathMessage(deathTag);
if (customDeathMessage == null)
{
console.writeColoured("No custom death message '%s' defined, using original..", deathTag);
return;
}
RunsafePlayer player = runsafePlayerDeathEvent.getEntity();
if (deathType.hasEntityInvolved() && entityName == null)
{
RunsafePlayer killer = RunsafeServer.Instance.getPlayer(killerName);
if (killer != null)
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName(), killer.getPrettyName()));
}
else
{
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName()));
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "OnPlayerDeathEvent" | "@Override
public void OnPlayerDeathEvent(RunsafePlayerDeathEvent runsafePlayerDeathEvent)
{
runsafePlayerDeathEvent.setDeathMessage("");
if (!this.hideDeathWorlds.contains(runsafePlayerDeathEvent.getEntity().getWorld().getName()))
{
<MASK>String originalMessage = runsafePlayerDeathEvent.getDeathMessage();</MASK>
Death deathType = this.deathParser.getDeathType(originalMessage);
if (deathType == Death.UNKNOWN)
{
console.writeColoured("Unknown death message detected: \"%s\"", originalMessage);
}
String deathName = deathType.name().toLowerCase();
String deathTag = deathName;
String entityName = null;
String killerName = null;
if (deathType.hasEntityInvolved())
{
killerName = this.deathParser.getInvolvedEntityName(originalMessage, deathType);
entityName = this.deathParser.isEntityName(killerName);
deathTag = String.format(
"%s_%s",
deathName,
(entityName != null ? entityName : "Player")
);
}
String customDeathMessage = this.deathParser.getCustomDeathMessage(deathTag);
if (customDeathMessage == null)
{
console.writeColoured("No custom death message '%s' defined, using original..", deathTag);
return;
}
RunsafePlayer player = runsafePlayerDeathEvent.getEntity();
if (deathType.hasEntityInvolved() && entityName == null)
{
RunsafePlayer killer = RunsafeServer.Instance.getPlayer(killerName);
if (killer != null)
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName(), killer.getPrettyName()));
}
else
{
RunsafeServer.Instance.broadcastMessage(String.format(customDeathMessage, player.getPrettyName()));
}
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void closeWebSocket() throws WebSocketException {
transitionTo(State.CLOSING);
pipeline.sendUpstream(this, null, new CloseFrame());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "closeWebSocket" | "@Override
protected void closeWebSocket() throws WebSocketException {
<MASK>pipeline.sendUpstream(this, null, new CloseFrame());</MASK>
transitionTo(State.CLOSING);
}" |
Inversion-Mutation | megadiff | "@Override
public void render(Graphics2D g) {
background.draw(g, 0, 0);
this.returnButton.draw(g);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "render" | "@Override
public void render(Graphics2D g) {
<MASK>this.returnButton.draw(g);</MASK>
background.draw(g, 0, 0);
}" |
Inversion-Mutation | megadiff | "public ServiceStatus runTestscript(String scriptAndParams)
throws ExecutionException {
Process p;
try {
p = rt.exec("scripts/" + scriptAndParams);
} catch (IOException e) {
throw new ExecutionException(e);
}
CompleteReader cr = new CompleteReader(p.getInputStream());
try {
int max = 0;
ReturnCode retCode = RETCODE_TIMEOUT;
while (max++ < 60) {
try {
int retval = p.exitValue();
retCode = ReturnCode.fromOrdinal(retval);
} catch (IllegalThreadStateException e) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
throw new ExecutionException(e1);
}
retCode = RETCODE_TIMEOUT;
}
}
ServiceStatus ss = new ServiceStatus(retCode, cr.getReadData(), -1);
p.destroy();
return ss;
} catch (Throwable t) {
t.printStackTrace();
try {
cr.interrupt();
} catch (Throwable t2) {
}
}
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "runTestscript" | "public ServiceStatus runTestscript(String scriptAndParams)
throws ExecutionException {
Process p;
try {
p = rt.exec("scripts/" + scriptAndParams);
} catch (IOException e) {
throw new ExecutionException(e);
}
CompleteReader cr = new CompleteReader(p.getInputStream());
try {
int max = 0;
ReturnCode retCode = RETCODE_TIMEOUT;
while (max++ < 60) {
try {
int retval = p.exitValue();
retCode = ReturnCode.fromOrdinal(retval);
} catch (IllegalThreadStateException e) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
throw new ExecutionException(e1);
}
retCode = RETCODE_TIMEOUT;
}
}
<MASK>p.destroy();</MASK>
ServiceStatus ss = new ServiceStatus(retCode, cr.getReadData(), -1);
return ss;
} catch (Throwable t) {
t.printStackTrace();
try {
cr.interrupt();
} catch (Throwable t2) {
}
}
return null;
}" |
Inversion-Mutation | megadiff | "public void executeQueries(boolean prepare,boolean verbose) throws SQLException{
rowsExpected=new int[queries.size()]; //initialize the array with correct size
String query="";
if(prepare){
if (verbose)
System.out.println("=====================> Using java.sql.PreparedStatement <====================");
}else{
if (verbose)
System.out.println("=====================> Using java.sql.Statement <====================");
}
try{
for(int k=0;k<queries.size();k++){
query=(String)queries.get(k);
String [] times=new String [StaticValues.ITER];
int rowsReturned=0;
for (int i=0;i<StaticValues.ITER;i++){
Statement stmt=null;
ResultSet rs=null;
PreparedStatement pstmt=null;
if(prepare){
pstmt=conn.prepareStatement(query);
}else{
stmt=conn.createStatement();
}
long start=System.currentTimeMillis();
if(prepare)
rs=pstmt.executeQuery();
else
rs=stmt.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
int totalCols=rsmd.getColumnCount();
while(rs.next()){
String row="";
for(int j=1;j<=totalCols;j++){
row+=rs.getString(j)+" | ";
}
rowsReturned++;
}
long time_taken=(System.currentTimeMillis() - start);
if (verbose){
System.out.println("Time required to execute:");
System.out.println(query);
System.out.println("Total Rows returned = "+rowsReturned);
System.out.println("==> "+time_taken+" milliseconds "+" OR "+TestUtils.getTime(time_taken));
}
times[i]=TestUtils.getTime(time_taken);
rs.close();
if(prepare){
pstmt.close();
}else{
stmt.close();
}
rowsExpected[k]=rowsReturned;//add expected rows for respective queries
rowsReturned=0;
}//end for loop to run StaticValues.ITER times
if(prepare){
prepStmtRunResults.add(times);
}else{
stmtRunResults.add(times);
}
}
}catch(SQLException sqe){
throw new SQLException("Failed query:\n "+query+"\n SQLState= "+sqe.getSQLState()+"\n ErrorCode= "+sqe.getErrorCode()+"\n Message= "+sqe.getMessage());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeQueries" | "public void executeQueries(boolean prepare,boolean verbose) throws SQLException{
rowsExpected=new int[queries.size()]; //initialize the array with correct size
String query="";
if(prepare){
if (verbose)
System.out.println("=====================> Using java.sql.PreparedStatement <====================");
}else{
if (verbose)
System.out.println("=====================> Using java.sql.Statement <====================");
}
try{
for(int k=0;k<queries.size();k++){
query=(String)queries.get(k);
String [] times=new String [StaticValues.ITER];
int rowsReturned=0;
for (int i=0;i<StaticValues.ITER;i++){
Statement stmt=null;
ResultSet rs=null;
PreparedStatement pstmt=null;
if(prepare){
pstmt=conn.prepareStatement(query);
}else{
stmt=conn.createStatement();
}
long start=System.currentTimeMillis();
if(prepare)
rs=pstmt.executeQuery();
else
rs=stmt.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
int totalCols=rsmd.getColumnCount();
while(rs.next()){
String row="";
for(int j=1;j<=totalCols;j++){
row+=rs.getString(j)+" | ";
}
rowsReturned++;
}
long time_taken=(System.currentTimeMillis() - start);
if (verbose){
System.out.println("Time required to execute:");
System.out.println(query);
System.out.println("Total Rows returned = "+rowsReturned);
System.out.println("==> "+time_taken+" milliseconds "+" OR "+TestUtils.getTime(time_taken));
<MASK>times[i]=TestUtils.getTime(time_taken);</MASK>
}
rs.close();
if(prepare){
pstmt.close();
}else{
stmt.close();
}
rowsExpected[k]=rowsReturned;//add expected rows for respective queries
rowsReturned=0;
}//end for loop to run StaticValues.ITER times
if(prepare){
prepStmtRunResults.add(times);
}else{
stmtRunResults.add(times);
}
}
}catch(SQLException sqe){
throw new SQLException("Failed query:\n "+query+"\n SQLState= "+sqe.getSQLState()+"\n ErrorCode= "+sqe.getErrorCode()+"\n Message= "+sqe.getMessage());
}
}" |
Inversion-Mutation | megadiff | "@Override
public void pointerTick() {
resetPointer();
if(!gate.world().isRemote) {
gate.scheduleTick(2);
gate.setState(0xB0 | gate.state()&0xF);
gate.onOutputChange(0xB);
tickSound();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "pointerTick" | "@Override
public void pointerTick() {
resetPointer();
if(!gate.world().isRemote) {
gate.setState(0xB0 | gate.state()&0xF);
gate.onOutputChange(0xB);
<MASK>gate.scheduleTick(2);</MASK>
tickSound();
}
}" |
Inversion-Mutation | megadiff | "@Test
public void testSchedulingWithDueTime() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(5);
final AtomicInteger counter = new AtomicInteger();
long start = System.currentTimeMillis();
Schedulers.threadPoolForComputation().schedule(null, new Func2<Scheduler, String, Subscription>() {
@Override
public Subscription call(Scheduler scheduler, String state) {
System.out.println("doing work");
counter.incrementAndGet();
latch.countDown();
if (latch.getCount() == 0) {
return Subscriptions.empty();
} else {
return scheduler.schedule(state, this, new Date(System.currentTimeMillis() + 50));
}
}
}, new Date(System.currentTimeMillis() + 100));
if (!latch.await(3000, TimeUnit.MILLISECONDS)) {
fail("didn't execute ... timed out");
}
long end = System.currentTimeMillis();
assertEquals(5, counter.get());
if ((end - start) < 250) {
fail("it should have taken over 250ms since each step was scheduled 50ms in the future");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testSchedulingWithDueTime" | "@Test
public void testSchedulingWithDueTime() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(5);
final AtomicInteger counter = new AtomicInteger();
long start = System.currentTimeMillis();
Schedulers.threadPoolForComputation().schedule(null, new Func2<Scheduler, String, Subscription>() {
@Override
public Subscription call(Scheduler scheduler, String state) {
System.out.println("doing work");
<MASK>latch.countDown();</MASK>
counter.incrementAndGet();
if (latch.getCount() == 0) {
return Subscriptions.empty();
} else {
return scheduler.schedule(state, this, new Date(System.currentTimeMillis() + 50));
}
}
}, new Date(System.currentTimeMillis() + 100));
if (!latch.await(3000, TimeUnit.MILLISECONDS)) {
fail("didn't execute ... timed out");
}
long end = System.currentTimeMillis();
assertEquals(5, counter.get());
if ((end - start) < 250) {
fail("it should have taken over 250ms since each step was scheduled 50ms in the future");
}
}" |
Inversion-Mutation | megadiff | "@Override
public Subscription call(Scheduler scheduler, String state) {
System.out.println("doing work");
counter.incrementAndGet();
latch.countDown();
if (latch.getCount() == 0) {
return Subscriptions.empty();
} else {
return scheduler.schedule(state, this, new Date(System.currentTimeMillis() + 50));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "call" | "@Override
public Subscription call(Scheduler scheduler, String state) {
System.out.println("doing work");
<MASK>latch.countDown();</MASK>
counter.incrementAndGet();
if (latch.getCount() == 0) {
return Subscriptions.empty();
} else {
return scheduler.schedule(state, this, new Date(System.currentTimeMillis() + 50));
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
DatabaseInstance = SQLiteBooksDatabase.Instance();
if (DatabaseInstance == null) {
DatabaseInstance = new SQLiteBooksDatabase(this, "LIBRARY");
}
if (LibraryInstance == null) {
LibraryInstance = new Library();
startService(new Intent(getApplicationContext(), InitializationService.class));
}
myItems = new LinkedList<FBTree>();
myItems.add(new TopLevelTree(
myResource.getResource(PATH_FAVORITES),
R.drawable.ic_list_library_favorites,
new OpenTreeRunnable(LibraryInstance, new StartTreeActivityRunnable(PATH_FAVORITES, null) {
public void run() {
if (LibraryInstance.favorites().hasChildren()) {
super.run();
} else {
UIUtil.showErrorMessage(LibraryTopLevelActivity.this, "noFavorites");
}
}
})
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_RECENT),
R.drawable.ic_list_library_recent,
new OpenTreeRunnable(LibraryInstance, PATH_RECENT)
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_BY_AUTHOR),
R.drawable.ic_list_library_authors,
new OpenTreeRunnable(LibraryInstance, PATH_BY_AUTHOR)
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_BY_TITLE),
R.drawable.ic_list_library_books,
new OpenTreeRunnable(LibraryInstance, PATH_BY_TITLE)
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_BY_TAG),
R.drawable.ic_list_library_tags,
new OpenTreeRunnable(LibraryInstance, PATH_BY_TAG)
));
myItems.add(new TopLevelTree(
myResource.getResource("fileTree"),
R.drawable.ic_list_library_folder,
new Runnable() {
public void run() {
startActivity(
new Intent(LibraryTopLevelActivity.this, FileManager.class)
.putExtra(SELECTED_BOOK_PATH_KEY, mySelectedBookPath)
);
}
}
));
setListAdapter(new LibraryAdapter(myItems));
onNewIntent(getIntent());
}" | 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) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
DatabaseInstance = SQLiteBooksDatabase.Instance();
if (DatabaseInstance == null) {
DatabaseInstance = new SQLiteBooksDatabase(this, "LIBRARY");
}
if (LibraryInstance == null) {
LibraryInstance = new Library();
startService(new Intent(getApplicationContext(), InitializationService.class));
}
myItems.add(new TopLevelTree(
myResource.getResource(PATH_FAVORITES),
R.drawable.ic_list_library_favorites,
new OpenTreeRunnable(LibraryInstance, new StartTreeActivityRunnable(PATH_FAVORITES, null) {
public void run() {
if (LibraryInstance.favorites().hasChildren()) {
super.run();
} else {
UIUtil.showErrorMessage(LibraryTopLevelActivity.this, "noFavorites");
}
}
})
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_RECENT),
R.drawable.ic_list_library_recent,
new OpenTreeRunnable(LibraryInstance, PATH_RECENT)
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_BY_AUTHOR),
R.drawable.ic_list_library_authors,
new OpenTreeRunnable(LibraryInstance, PATH_BY_AUTHOR)
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_BY_TITLE),
R.drawable.ic_list_library_books,
new OpenTreeRunnable(LibraryInstance, PATH_BY_TITLE)
));
myItems.add(new TopLevelTree(
myResource.getResource(PATH_BY_TAG),
R.drawable.ic_list_library_tags,
new OpenTreeRunnable(LibraryInstance, PATH_BY_TAG)
));
myItems.add(new TopLevelTree(
myResource.getResource("fileTree"),
R.drawable.ic_list_library_folder,
new Runnable() {
public void run() {
startActivity(
new Intent(LibraryTopLevelActivity.this, FileManager.class)
.putExtra(SELECTED_BOOK_PATH_KEY, mySelectedBookPath)
);
}
}
));
<MASK>myItems = new LinkedList<FBTree>();</MASK>
setListAdapter(new LibraryAdapter(myItems));
onNewIntent(getIntent());
}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.