type
stringclasses 1
value | dataset
stringclasses 1
value | input
stringlengths 75
160k
| instruction
stringlengths 117
171
| output
stringlengths 88
168k
|
---|---|---|---|---|
Inversion-Mutation | megadiff | "@Override
public void onScanCompleted(String path, Uri uri) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mActivity, R.string.added_face_to_gallery_toast, Toast.LENGTH_LONG).show();
mActivity = null;
}
});
mConn.disconnect();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onScanCompleted" | "@Override
public void onScanCompleted(String path, Uri uri) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mActivity, R.string.added_face_to_gallery_toast, Toast.LENGTH_LONG).show();
}
});
mConn.disconnect();
<MASK>mActivity = null;</MASK>
}" |
Inversion-Mutation | megadiff | "@Test
public void testSampling() throws Exception {
AbstractContinuousDistribution dist = (AbstractContinuousDistribution) makeDistribution();
final int sampleSize = 1000;
dist.reseedRandomGenerator(1000); // Use fixed seed
double[] sample = dist.sample(sampleSize);
double[] quartiles = TestUtils.getDistributionQuartiles(dist);
double[] expected = {250, 250, 250, 250};
long[] counts = new long[4];
for (int i = 0; i < sampleSize; i++) {
TestUtils.updateCounts(sample[i], counts, quartiles);
}
TestUtils.assertChiSquareAccept(expected, counts, 0.001);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testSampling" | "@Test
public void testSampling() throws Exception {
AbstractContinuousDistribution dist = (AbstractContinuousDistribution) makeDistribution();
final int sampleSize = 1000;
double[] sample = dist.sample(sampleSize);
double[] quartiles = TestUtils.getDistributionQuartiles(dist);
double[] expected = {250, 250, 250, 250};
long[] counts = new long[4];
<MASK>dist.reseedRandomGenerator(1000); // Use fixed seed</MASK>
for (int i = 0; i < sampleSize; i++) {
TestUtils.updateCounts(sample[i], counts, quartiles);
}
TestUtils.assertChiSquareAccept(expected, counts, 0.001);
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("loadUrlTimeoutValue", 10000);
super.loadUrl("file:///android_asset/www/index.html");
// Display vertical scrollbar and hide horizontal scrollBar
super.appView.setVerticalScrollBarEnabled(true);
super.appView.setHorizontalScrollBarEnabled(false);
// set scrollbar style
super.appView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<MASK>super.loadUrl("file:///android_asset/www/index.html");</MASK>
super.setIntegerProperty("loadUrlTimeoutValue", 10000);
// Display vertical scrollbar and hide horizontal scrollBar
super.appView.setVerticalScrollBarEnabled(true);
super.appView.setHorizontalScrollBarEnabled(false);
// set scrollbar style
super.appView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
}" |
Inversion-Mutation | megadiff | "public void setBody(Body body) throws MessagingException
{
this.mBody = body;
setHeader("MIME-Version", "1.0");
if (body instanceof com.fsck.k9.mail.Multipart)
{
com.fsck.k9.mail.Multipart multipart = ((com.fsck.k9.mail.Multipart)body);
multipart.setParent(this);
setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType());
}
else if (body instanceof TextBody)
{
setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n charset=utf-8",
getMimeType()));
setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setBody" | "public void setBody(Body body) throws MessagingException
{
this.mBody = body;
if (body instanceof com.fsck.k9.mail.Multipart)
{
com.fsck.k9.mail.Multipart multipart = ((com.fsck.k9.mail.Multipart)body);
multipart.setParent(this);
setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType());
<MASK>setHeader("MIME-Version", "1.0");</MASK>
}
else if (body instanceof TextBody)
{
setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n charset=utf-8",
getMimeType()));
setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
}
}" |
Inversion-Mutation | megadiff | "public void check(Event event) {
if (!checkerEnabled) {
return;
}
checkerEnabled = false;
System.out.print("Received event id " + event.id + "\nStates: ["); //DBG
for (State state : states) //DBG
System.out.println("\n vertex: " + state.vertex + //DBG
"\n events:" + state.events.size() + //DBG
"\n bindings:" + state.store.size()); //DBG
System.out.println("]"); //DBG
HashSet<State> newActiveStates = new HashSet<State>();
for (State state : states) {
if (!automaton.isObservable(event.id, state.vertex)) {
newActiveStates.add(state);
continue;
}
state = state.pushEvent(event);
if (state.events.size() < automaton.maximumTransitionDepths[state.vertex]) {
newActiveStates.add(state);
continue;
}
boolean anyEnabled = false;
for (Transition transition : automaton.transitions[state.vertex]) {
//DBG System.out.print("try " + state.vertex + " -> " + transition.target //DBG
//DBG + " with events"); //DBG
//DBG for (Event e : state.events) System.out.print(" " + e.id); //DBG
//DBG System.out.println(); //DBG
// evaluate transition
Treap<Binding> store = state.store;
Queue<Event> events = state.events;
Queue<Event> consumed = Queue.empty();
int i;
for (i = 0; i < transition.steps.length; ++i) {
TransitionStep step = transition.steps[i];
Event stepEvent = events.top();
events = events.pop();
consumed = consumed.push(stepEvent);
if (!step.evaluateGuard(stepEvent, store)) {
break;
}
//DBG System.out.println("step"); //DBG
store = step.action.apply(stepEvent, store);
}
// record transition
if (i == transition.steps.length) {
//DBG System.out.println("tran"); //DBG
anyEnabled = true;
newActiveStates.add(State.make(transition.target, store,
events, consumed, state));
// check for error state
String msg = automaton.errorMessages[transition.target];
if (msg != null) {
reportError(msg);
}
}
}
if (!anyEnabled) {
//DBG System.out.println("stay"); //DBG
newActiveStates.add(state.popEvent());
}
}
states = newActiveStates;
checkerEnabled = true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "check" | "public void check(Event event) {
if (!checkerEnabled) {
return;
}
checkerEnabled = false;
System.out.print("Received event id " + event.id + "\nStates: ["); //DBG
for (State state : states) //DBG
System.out.println("\n vertex: " + state.vertex + //DBG
"\n events:" + state.events.size() + //DBG
"\n bindings:" + state.store.size()); //DBG
System.out.println("]"); //DBG
HashSet<State> newActiveStates = new HashSet<State>();
for (State state : states) {
<MASK>state = state.pushEvent(event);</MASK>
if (!automaton.isObservable(event.id, state.vertex)) {
newActiveStates.add(state);
continue;
}
if (state.events.size() < automaton.maximumTransitionDepths[state.vertex]) {
newActiveStates.add(state);
continue;
}
boolean anyEnabled = false;
for (Transition transition : automaton.transitions[state.vertex]) {
//DBG System.out.print("try " + state.vertex + " -> " + transition.target //DBG
//DBG + " with events"); //DBG
//DBG for (Event e : state.events) System.out.print(" " + e.id); //DBG
//DBG System.out.println(); //DBG
// evaluate transition
Treap<Binding> store = state.store;
Queue<Event> events = state.events;
Queue<Event> consumed = Queue.empty();
int i;
for (i = 0; i < transition.steps.length; ++i) {
TransitionStep step = transition.steps[i];
Event stepEvent = events.top();
events = events.pop();
consumed = consumed.push(stepEvent);
if (!step.evaluateGuard(stepEvent, store)) {
break;
}
//DBG System.out.println("step"); //DBG
store = step.action.apply(stepEvent, store);
}
// record transition
if (i == transition.steps.length) {
//DBG System.out.println("tran"); //DBG
anyEnabled = true;
newActiveStates.add(State.make(transition.target, store,
events, consumed, state));
// check for error state
String msg = automaton.errorMessages[transition.target];
if (msg != null) {
reportError(msg);
}
}
}
if (!anyEnabled) {
//DBG System.out.println("stay"); //DBG
newActiveStates.add(state.popEvent());
}
}
states = newActiveStates;
checkerEnabled = true;
}" |
Inversion-Mutation | megadiff | "private void sendFile( String filename, HttpServletResponse response ) throws IOException
{
log.info("Requested download of [" + filename + "]");
DownloadableFilesRegistry filesRegistry = (DownloadableFilesRegistry) getComponent("DownloadableFilesRegistry");
Experiments experiments = (Experiments) getComponent("Experiments");
if (!filesRegistry.doesExist(filename)) {
log.error("File [" + filename + "] is not in files registry");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
String fileLocation = filesRegistry.getLocation(filename);
String contentType = getServletContext().getMimeType(fileLocation);
if (null != contentType) {
log.debug("Setting content type to [" + contentType + "]");
response.setContentType(contentType);
} else {
log.warn("Download servlet was unable to determine content type for [" + fileLocation + "]");
}
log.debug("Checking file [" + fileLocation + "]");
File file = new File(fileLocation);
if (!file.exists()) {
log.error("File [" + fileLocation + "] does not exist");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (!experiments.isFilePublic(fileLocation)) {
log.error("Attempting to download file for the experiment that is not present in the index");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
FileInputStream fileInputStream = null;
ServletOutputStream servletOutStream = null;
try {
fileInputStream = new FileInputStream(file);
int size = fileInputStream.available();
response.setContentLength(size);
servletOutStream = response.getOutputStream();
int bytesRead;
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
while ( true ) {
bytesRead = fileInputStream.read(buffer, 0, TRANSFER_BUFFER_SIZE);
if (bytesRead == -1) break;
servletOutStream.write(buffer, 0, bytesRead);
servletOutStream.flush();
}
log.info("Download of [" + filename + "] completed, sent [" + size + "] bytes");
} finally {
if (null != fileInputStream)
fileInputStream.close();
if (null != servletOutStream)
servletOutStream.close();
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sendFile" | "private void sendFile( String filename, HttpServletResponse response ) throws IOException
{
log.info("Requested download of [" + filename + "]");
DownloadableFilesRegistry filesRegistry = (DownloadableFilesRegistry) getComponent("DownloadableFilesRegistry");
Experiments experiments = (Experiments) getComponent("Experiments");
if (!filesRegistry.doesExist(filename)) {
log.error("File [" + filename + "] is not in files registry");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
String fileLocation = filesRegistry.getLocation(filename);
String contentType = getServletContext().getMimeType(fileLocation);
if (null != contentType) {
log.debug("Setting content type to [" + contentType + "]");
response.setContentType(contentType);
} else {
log.warn("Download servlet was unable to determine content type for [" + fileLocation + "]");
}
log.debug("Checking file [" + fileLocation + "]");
File file = new File(fileLocation);
if (!file.exists()) {
log.error("File [" + fileLocation + "] does not exist");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else if (!experiments.isFilePublic(fileLocation)) {
log.error("Attempting to download file for the experiment that is not present in the index");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
FileInputStream fileInputStream = null;
ServletOutputStream servletOutStream = null;
try {
fileInputStream = new FileInputStream(file);
int size = fileInputStream.available();
response.setContentLength(size);
servletOutStream = response.getOutputStream();
int bytesRead;
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
while ( true ) {
bytesRead = fileInputStream.read(buffer, 0, TRANSFER_BUFFER_SIZE);
if (bytesRead == -1) break;
servletOutStream.write(buffer, 0, bytesRead);
servletOutStream.flush();
<MASK>log.info("Download of [" + filename + "] completed, sent [" + size + "] bytes");</MASK>
}
} finally {
if (null != fileInputStream)
fileInputStream.close();
if (null != servletOutStream)
servletOutStream.close();
}
}
}
}" |
Inversion-Mutation | megadiff | "protected List<EEFGenModel> initEEFGenModel() throws IOException {
if (!selectedFiles.isEmpty()) {
for (IFile selectedFile : selectedFiles) {
ResourceSet resourceSet = new ResourceSetImpl();
URI modelURI = URI.createPlatformResourceURI(selectedFile.getFullPath().toString(), true);
String fileExtension = modelURI.fileExtension();
if (fileExtension == null || fileExtension.length() == 0) {
fileExtension = Resource.Factory.Registry.DEFAULT_EXTENSION;
}
final Resource.Factory.Registry registry = Resource.Factory.Registry.INSTANCE;
final Object resourceFactory = registry.getExtensionToFactoryMap().get(fileExtension);
if (resourceFactory != null) {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
resourceFactory);
} else {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
new XMIResourceFactoryImpl());
}
Resource res = resourceSet.createResource(modelURI);
res.load(Collections.EMPTY_MAP);
EcoreUtil.resolveAll(resourceSet);
if (res.getContents().size() > 0) {
EObject object = res.getContents().get(0);
if (object instanceof EEFGenModel) {
eefGenModels.add((EEFGenModel)object);
}
}
}
}
return eefGenModels;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initEEFGenModel" | "protected List<EEFGenModel> initEEFGenModel() throws IOException {
if (!selectedFiles.isEmpty()) {
<MASK>ResourceSet resourceSet = new ResourceSetImpl();</MASK>
for (IFile selectedFile : selectedFiles) {
URI modelURI = URI.createPlatformResourceURI(selectedFile.getFullPath().toString(), true);
String fileExtension = modelURI.fileExtension();
if (fileExtension == null || fileExtension.length() == 0) {
fileExtension = Resource.Factory.Registry.DEFAULT_EXTENSION;
}
final Resource.Factory.Registry registry = Resource.Factory.Registry.INSTANCE;
final Object resourceFactory = registry.getExtensionToFactoryMap().get(fileExtension);
if (resourceFactory != null) {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
resourceFactory);
} else {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
new XMIResourceFactoryImpl());
}
Resource res = resourceSet.createResource(modelURI);
res.load(Collections.EMPTY_MAP);
EcoreUtil.resolveAll(resourceSet);
if (res.getContents().size() > 0) {
EObject object = res.getContents().get(0);
if (object instanceof EEFGenModel) {
eefGenModels.add((EEFGenModel)object);
}
}
}
}
return eefGenModels;
}" |
Inversion-Mutation | megadiff | "public Object intercept(Object enhanced, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
final String methodName = method.getName();
try {
synchronized (lazyLoader) {
if (WRITE_REPLACE_METHOD.equals(methodName)) {
Object original = null;
if (constructorArgTypes.isEmpty()) {
original = objectFactory.create(type);
} else {
original = objectFactory.create(type, constructorArgTypes, constructorArgs);
}
PropertyCopier.copyBeanProperties(type, enhanced, original);
if (lazyLoader.size() > 0) {
return new SerialStateHolder(original, lazyLoader.getPropertyNames(), objectFactory, constructorArgTypes, constructorArgs);
} else {
return original;
}
} else {
if (lazyLoader.size() > 0 && !FINALIZE_METHOD.equals(methodName)) {
if (aggressive || objectMethods.contains(methodName)) {
lazyLoader.loadAll();
} else if (PropertyNamer.isProperty(methodName)) {
final String property = PropertyNamer.methodToProperty(methodName);
if (lazyLoader.hasLoader(property)) {
lazyLoader.load(property);
}
}
}
}
}
return methodProxy.invokeSuper(enhanced, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "intercept" | "public Object intercept(Object enhanced, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
final String methodName = method.getName();
try {
synchronized (lazyLoader) {
if (WRITE_REPLACE_METHOD.equals(methodName)) {
Object original = null;
if (constructorArgTypes.isEmpty()) {
original = objectFactory.create(type);
} else {
original = objectFactory.create(type, constructorArgTypes, constructorArgs);
}
PropertyCopier.copyBeanProperties(type, enhanced, original);
if (lazyLoader.size() > 0) {
return new SerialStateHolder(original, lazyLoader.getPropertyNames(), objectFactory, constructorArgTypes, constructorArgs);
} else {
return original;
}
} else {
if (lazyLoader.size() > 0 && !FINALIZE_METHOD.equals(methodName)) {
if (aggressive || objectMethods.contains(methodName)) {
lazyLoader.loadAll();
} else if (PropertyNamer.isProperty(methodName)) {
final String property = PropertyNamer.methodToProperty(methodName);
if (lazyLoader.hasLoader(property)) {
lazyLoader.load(property);
}
}
}
<MASK>return methodProxy.invokeSuper(enhanced, args);</MASK>
}
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}" |
Inversion-Mutation | megadiff | "private void loadClass(final String classname) {
try {
if (classloader == null) {
if (getKeyValue("requires", "parent", "").isEmpty()) {
classloader = new PluginClassLoader(this);
} else {
final String parentName = getKeyValue("requires", "parent", "");
final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(parentName);
if (pi == null) {
lastError = "Required parent '" + parentName + "' was not found";
return;
} else {
pi.addChild(this);
PluginClassLoader parentCL = pi.getPluginClassLoader();
if (parentCL == null) {
// Parent appears not to be loaded.
pi.loadPlugin();
parentCL = pi.getPluginClassLoader();
if (parentCL == null) {
lastError = "Unable to get classloader from required parent '" + parentName + "' for "+getName();
return;
}
}
classloader = parentCL.getSubClassLoader(this);
}
}
}
// Don't reload a class if its already loaded.
if (classloader.isClassLoaded(classname, true)) {
lastError = "Classloader says we are already loaded.";
return;
}
final Class<?> c = classloader.loadClass(classname);
if (c == null) {
lastError = "Class '"+classname+"' was not able to load.";
return;
}
final Constructor<?> constructor = c.getConstructor(new Class[]{});
// Only try and construct the main class, anything else should be constructed
// by the plugin itself.
if (classname.equals(getMainClass())) {
final Object temp = constructor.newInstance(new Object[]{});
if (temp instanceof Plugin) {
final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites();
if (prerequisites.isFailure()) {
if (!tempLoaded) {
lastError = "Prerequisites for plugin not met. ('" + filename + ":" + getMainClass() + "' -> '" + prerequisites.getFailureReason() + "') ";
Logger.userError(ErrorLevel.LOW, lastError);
}
} else {
plugin = (Plugin) temp;
LOGGER.finer(getName() + ": Setting domain 'plugin-" + getName() + "'");
plugin.setPluginInfo(this);
plugin.setDomain("plugin-" + getName());
if (!tempLoaded) {
try {
plugin.onLoad();
} catch (LinkageError e) {
lastError = "Error in onLoad for " + getName() + ":" + e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, lastError, e);
unloadPlugin();
} catch (Exception e) {
lastError = "Error in onLoad for " + getName() + ":" + e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, lastError, e);
unloadPlugin();
}
}
}
}
}
} catch (ClassNotFoundException cnfe) {
lastError = "Class not found ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + cnfe.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, cnfe);
} catch (NoSuchMethodException nsme) {
// Don't moan about missing constructors for any class thats not the main Class
lastError = "Constructor missing ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + nsme.getMessage();
if (classname.equals(getMainClass())) {
Logger.userError(ErrorLevel.LOW, lastError, nsme);
}
} catch (IllegalAccessException iae) {
lastError = "Unable to access constructor ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + iae.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, iae);
} catch (InvocationTargetException ite) {
lastError = "Unable to invoke target ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + ite.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ite);
} catch (InstantiationException ie) {
lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + ie.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ie);
} catch (NoClassDefFoundError ncdf) {
lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - Unable to find class: " + ncdf.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ncdf);
} catch (VerifyError ve) {
lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - Incompatible: " + ve.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ve);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadClass" | "private void loadClass(final String classname) {
try {
if (classloader == null) {
if (getKeyValue("requires", "parent", "").isEmpty()) {
classloader = new PluginClassLoader(this);
} else {
final String parentName = getKeyValue("requires", "parent", "");
final PluginInfo pi = PluginManager.getPluginManager().getPluginInfoByName(parentName);
if (pi == null) {
lastError = "Required parent '" + parentName + "' was not found";
return;
} else {
pi.addChild(this);
PluginClassLoader parentCL = pi.getPluginClassLoader();
if (parentCL == null) {
// Parent appears not to be loaded.
pi.loadPlugin();
parentCL = pi.getPluginClassLoader();
if (parentCL == null) {
lastError = "Unable to get classloader from required parent '" + parentName + "' for "+getName();
return;
}
}
classloader = parentCL.getSubClassLoader(this);
}
}
}
// Don't reload a class if its already loaded.
if (classloader.isClassLoaded(classname, true)) {
lastError = "Classloader says we are already loaded.";
return;
}
final Class<?> c = classloader.loadClass(classname);
if (c == null) {
lastError = "Class '"+classname+"' was not able to load.";
return;
}
final Constructor<?> constructor = c.getConstructor(new Class[]{});
// Only try and construct the main class, anything else should be constructed
// by the plugin itself.
if (classname.equals(getMainClass())) {
final Object temp = constructor.newInstance(new Object[]{});
if (temp instanceof Plugin) {
final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites();
if (prerequisites.isFailure()) {
if (!tempLoaded) {
lastError = "Prerequisites for plugin not met. ('" + filename + ":" + getMainClass() + "' -> '" + prerequisites.getFailureReason() + "') ";
Logger.userError(ErrorLevel.LOW, lastError);
}
} else {
plugin = (Plugin) temp;
LOGGER.finer(getName() + ": Setting domain 'plugin-" + getName() + "'");
<MASK>plugin.setDomain("plugin-" + getName());</MASK>
plugin.setPluginInfo(this);
if (!tempLoaded) {
try {
plugin.onLoad();
} catch (LinkageError e) {
lastError = "Error in onLoad for " + getName() + ":" + e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, lastError, e);
unloadPlugin();
} catch (Exception e) {
lastError = "Error in onLoad for " + getName() + ":" + e.getMessage();
Logger.userError(ErrorLevel.MEDIUM, lastError, e);
unloadPlugin();
}
}
}
}
}
} catch (ClassNotFoundException cnfe) {
lastError = "Class not found ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + cnfe.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, cnfe);
} catch (NoSuchMethodException nsme) {
// Don't moan about missing constructors for any class thats not the main Class
lastError = "Constructor missing ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + nsme.getMessage();
if (classname.equals(getMainClass())) {
Logger.userError(ErrorLevel.LOW, lastError, nsme);
}
} catch (IllegalAccessException iae) {
lastError = "Unable to access constructor ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + iae.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, iae);
} catch (InvocationTargetException ite) {
lastError = "Unable to invoke target ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + ite.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ite);
} catch (InstantiationException ie) {
lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - " + ie.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ie);
} catch (NoClassDefFoundError ncdf) {
lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - Unable to find class: " + ncdf.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ncdf);
} catch (VerifyError ve) {
lastError = "Unable to instantiate plugin ('" + filename + ":" + classname + ":" + classname.equals(getMainClass()) + "') - Incompatible: " + ve.getMessage();
Logger.userError(ErrorLevel.LOW, lastError, ve);
}
}" |
Inversion-Mutation | megadiff | "private Value evalCons(Cons sexp) {
String fn = ((Symbol) sexp.head).sym;
if (fn.equals("ite")) {
return isTrue(eval(sexp.args.get(0))) ? eval(sexp.args.get(1)) : eval(sexp.args.get(2));
} else if (fn.equals("and")) {
for (Sexp arg : sexp.args) {
if (!isTrue(eval(arg))) {
return BoolValue.FALSE;
}
}
return BoolValue.TRUE;
}
List<Value> args = new ArrayList<>();
for (Sexp arg : sexp.args) {
args.add(eval(arg));
}
return evalFunction(fn, args);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "evalCons" | "private Value evalCons(Cons sexp) {
String fn = ((Symbol) sexp.head).sym;
if (fn.equals("ite")) {
return isTrue(eval(sexp.args.get(0))) ? eval(sexp.args.get(1)) : eval(sexp.args.get(2));
} else if (fn.equals("and")) {
for (Sexp arg : sexp.args) {
if (!isTrue(eval(arg))) {
return BoolValue.FALSE;
}
<MASK>return BoolValue.TRUE;</MASK>
}
}
List<Value> args = new ArrayList<>();
for (Sexp arg : sexp.args) {
args.add(eval(arg));
}
return evalFunction(fn, args);
}" |
Inversion-Mutation | megadiff | "@Override
public boolean inputSet() {
try {
if (trace)
GitTraceLocation.getTrace().traceEntry(
GitTraceLocation.HISTORYVIEW.getLocation());
if (this.input != null)
return true;
cancelRefreshJob();
Object o = super.getInput();
if (o == null) {
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
if (o instanceof IResource) {
RepositoryMapping mapping = RepositoryMapping
.getMapping((IResource) o);
if (mapping != null) {
Repository repo = mapping.getRepository();
input = new HistoryPageInput(repo,
new IResource[] { (IResource) o });
showHead(repo);
}
} else if (o instanceof RepositoryTreeNode) {
RepositoryTreeNode repoNode = (RepositoryTreeNode) o;
Repository repo = repoNode.getRepository();
switch (repoNode.getType()) {
case FILE:
File file = ((FileNode) repoNode).getObject();
input = new HistoryPageInput(repo, new File[] { file });
showHead(repo);
break;
case FOLDER:
File folder = ((FolderNode) repoNode).getObject();
input = new HistoryPageInput(repo, new File[] { folder });
showHead(repo);
break;
case REF:
input = new HistoryPageInput(repo);
showRef(((RefNode) repoNode).getObject(), repo);
break;
case ADDITIONALREF:
input = new HistoryPageInput(repo);
showRef(((AdditionalRefNode) repoNode).getObject(), repo);
break;
case TAG:
input = new HistoryPageInput(repo);
showTag(((TagNode) repoNode).getObject(), repo);
break;
default:
input = new HistoryPageInput(repo);
showHead(repo);
break;
}
} else if (o instanceof HistoryPageInput)
input = (HistoryPageInput) o;
else if (o instanceof IAdaptable) {
IResource resource = (IResource) ((IAdaptable) o)
.getAdapter(IResource.class);
if (resource != null) {
RepositoryMapping mapping = RepositoryMapping
.getMapping(resource);
Repository repo = mapping.getRepository();
input = new HistoryPageInput(repo,
new IResource[] { resource });
}
}
if (input == null) {
this.name = ""; //$NON-NLS-1$
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
Repository db = input.getRepository();
if (resolveHead(db, true) == null) {
this.name = ""; //$NON-NLS-1$
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
final IResource[] inResources = input.getItems();
final File[] inFiles = input.getFileList();
if (inResources != null && inResources.length == 0) {
this.name = ""; //$NON-NLS-1$
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
this.name = calculateName(input);
// disable the filters if we have a Repository as input
boolean filtersActive = inResources != null || inFiles != null;
actions.showAllRepoVersionsAction.setEnabled(filtersActive);
actions.showAllProjectVersionsAction.setEnabled(filtersActive);
// the repository itself has no notion of projects
actions.showAllFolderVersionsAction.setEnabled(inResources != null);
actions.showAllResourceVersionsAction.setEnabled(filtersActive);
setErrorMessage(null);
try {
initAndStartRevWalk(false);
} catch (IllegalStateException e) {
Activator.handleError(e.getMessage(), e, true);
return false;
}
return true;
} finally {
if (trace)
GitTraceLocation.getTrace().traceExit(
GitTraceLocation.HISTORYVIEW.getLocation());
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "inputSet" | "@Override
public boolean inputSet() {
try {
if (trace)
GitTraceLocation.getTrace().traceEntry(
GitTraceLocation.HISTORYVIEW.getLocation());
if (this.input != null)
return true;
cancelRefreshJob();
<MASK>setErrorMessage(null);</MASK>
Object o = super.getInput();
if (o == null) {
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
if (o instanceof IResource) {
RepositoryMapping mapping = RepositoryMapping
.getMapping((IResource) o);
if (mapping != null) {
Repository repo = mapping.getRepository();
input = new HistoryPageInput(repo,
new IResource[] { (IResource) o });
showHead(repo);
}
} else if (o instanceof RepositoryTreeNode) {
RepositoryTreeNode repoNode = (RepositoryTreeNode) o;
Repository repo = repoNode.getRepository();
switch (repoNode.getType()) {
case FILE:
File file = ((FileNode) repoNode).getObject();
input = new HistoryPageInput(repo, new File[] { file });
showHead(repo);
break;
case FOLDER:
File folder = ((FolderNode) repoNode).getObject();
input = new HistoryPageInput(repo, new File[] { folder });
showHead(repo);
break;
case REF:
input = new HistoryPageInput(repo);
showRef(((RefNode) repoNode).getObject(), repo);
break;
case ADDITIONALREF:
input = new HistoryPageInput(repo);
showRef(((AdditionalRefNode) repoNode).getObject(), repo);
break;
case TAG:
input = new HistoryPageInput(repo);
showTag(((TagNode) repoNode).getObject(), repo);
break;
default:
input = new HistoryPageInput(repo);
showHead(repo);
break;
}
} else if (o instanceof HistoryPageInput)
input = (HistoryPageInput) o;
else if (o instanceof IAdaptable) {
IResource resource = (IResource) ((IAdaptable) o)
.getAdapter(IResource.class);
if (resource != null) {
RepositoryMapping mapping = RepositoryMapping
.getMapping(resource);
Repository repo = mapping.getRepository();
input = new HistoryPageInput(repo,
new IResource[] { resource });
}
}
if (input == null) {
this.name = ""; //$NON-NLS-1$
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
Repository db = input.getRepository();
if (resolveHead(db, true) == null) {
this.name = ""; //$NON-NLS-1$
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
final IResource[] inResources = input.getItems();
final File[] inFiles = input.getFileList();
if (inResources != null && inResources.length == 0) {
this.name = ""; //$NON-NLS-1$
setErrorMessage(UIText.GitHistoryPage_NoInputMessage);
return false;
}
this.name = calculateName(input);
// disable the filters if we have a Repository as input
boolean filtersActive = inResources != null || inFiles != null;
actions.showAllRepoVersionsAction.setEnabled(filtersActive);
actions.showAllProjectVersionsAction.setEnabled(filtersActive);
// the repository itself has no notion of projects
actions.showAllFolderVersionsAction.setEnabled(inResources != null);
actions.showAllResourceVersionsAction.setEnabled(filtersActive);
try {
initAndStartRevWalk(false);
} catch (IllegalStateException e) {
Activator.handleError(e.getMessage(), e, true);
return false;
}
return true;
} finally {
if (trace)
GitTraceLocation.getTrace().traceExit(
GitTraceLocation.HISTORYVIEW.getLocation());
}
}" |
Inversion-Mutation | megadiff | "@Override
public void build(XmlWriter sceneXml, XmlWriter assetsXml, String sceneName) throws IOException {
sceneXml.
element("gameObject").
attribute("name", name).
element("pos").
attribute("x", pos.x).
attribute("y", pos.y).
pop().
element("scale").
attribute("x", scale.x).
attribute("y", scale.y).
pop().
attribute("rot", rot);
for (Component component : components) {
component.build(sceneXml, assetsXml, sceneName);
sceneXml.pop();
}
Enumeration children = children();
while (children.hasMoreElements()) {
GameObject childGo = (GameObject) children.nextElement();
childGo.build(sceneXml, assetsXml, sceneName);
sceneXml.pop();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "build" | "@Override
public void build(XmlWriter sceneXml, XmlWriter assetsXml, String sceneName) throws IOException {
sceneXml.
<MASK>attribute("name", name).</MASK>
element("gameObject").
element("pos").
attribute("x", pos.x).
attribute("y", pos.y).
pop().
element("scale").
attribute("x", scale.x).
attribute("y", scale.y).
pop().
attribute("rot", rot);
for (Component component : components) {
component.build(sceneXml, assetsXml, sceneName);
sceneXml.pop();
}
Enumeration children = children();
while (children.hasMoreElements()) {
GameObject childGo = (GameObject) children.nextElement();
childGo.build(sceneXml, assetsXml, sceneName);
sceneXml.pop();
}
}" |
Inversion-Mutation | megadiff | "public List<CopyTask> computeTasksList() throws IOException {
checkArgs(sources, target);
// Compute the recursive target list, so that subsequent existence checks on subfiles work
if (target.isDirectory()) {
target.grecursiveList();
}
for (GeneralizedFile source: sources) {
logger.info("Check " + source.getAbsoluteAddress());
if (!source.exists()) {
throw new FileNotFoundException(source.getAbsoluteAddress());
}
if (source.isDirectory()) {
if (recurseInSources) {
List<? extends GeneralizedFile> subfiles = source.grecursiveList();
for (GeneralizedFile subfile: subfiles) {
if (subfile.givenName().equals(source.givenName())) {
continue;
}
String dstRoot = FileManipulation.getSonPath(source.givenName(),
subfile.givenName(),
source.fileSeparator());
if (includeLastPathElementInTarget &&
(target.exists() || sources.size() > 1)) {
dstRoot = FileManipulation.concat(source.getFileName(),
dstRoot, source.fileSeparator());
}
addCandidate(subfile, target, dstRoot);
}
}
} else if (source.isFile()) {
if (target.isDirectory() || target.givenName().endsWith(target.fileSeparator())) {
addCandidate(source, target, source.getFileName());
} else {
addCandidate(source, target, "");
}
} else {
throw new IOException("Source is neither a file nor a directory " + source.getAbsoluteAddress());
}
}
return taskList;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "computeTasksList" | "public List<CopyTask> computeTasksList() throws IOException {
checkArgs(sources, target);
// Compute the recursive target list, so that subsequent existence checks on subfiles work
if (target.isDirectory()) {
target.grecursiveList();
}
for (GeneralizedFile source: sources) {
logger.info("Check " + source.getAbsoluteAddress());
if (!source.exists()) {
throw new FileNotFoundException(source.getAbsoluteAddress());
}
if (source.isDirectory()) {
if (recurseInSources) {
List<? extends GeneralizedFile> subfiles = source.grecursiveList();
for (GeneralizedFile subfile: subfiles) {
if (subfile.givenName().equals(source.givenName())) {
continue;
}
String dstRoot = FileManipulation.getSonPath(source.givenName(),
subfile.givenName(),
source.fileSeparator());
if (includeLastPathElementInTarget &&
(target.exists() || sources.size() > 1)) {
dstRoot = FileManipulation.concat(source.getFileName(),
dstRoot, source.fileSeparator());
<MASK>addCandidate(subfile, target, dstRoot);</MASK>
}
}
}
} else if (source.isFile()) {
if (target.isDirectory() || target.givenName().endsWith(target.fileSeparator())) {
addCandidate(source, target, source.getFileName());
} else {
addCandidate(source, target, "");
}
} else {
throw new IOException("Source is neither a file nor a directory " + source.getAbsoluteAddress());
}
}
return taskList;
}" |
Inversion-Mutation | megadiff | "private synchronized void paintBuffered(Graphics g) {
do {
GraphicsConfiguration config = getGraphicsConfiguration();
int width = getWidth();
int height = getHeight();
if (backBuffer == null || width != backBuffer.getWidth() || height != backBuffer.getHeight() || backBuffer.validate(config) == VolatileImage.IMAGE_INCOMPATIBLE) {
if (backBuffer != null) {
backBufferGraphics.dispose();
backBuffer.flush();
}
backBuffer = config.createCompatibleVolatileImage(width, height);
backBufferGraphics = backBuffer.createGraphics();
}
backBufferGraphics.setClip(g.getClip());
paintUnbuffered(backBufferGraphics);
g.drawImage(backBuffer, 0, 0, this);
} while (backBuffer.contentsLost());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "paintBuffered" | "private synchronized void paintBuffered(Graphics g) {
do {
GraphicsConfiguration config = getGraphicsConfiguration();
int width = getWidth();
int height = getHeight();
if (backBuffer == null || width != backBuffer.getWidth() || height != backBuffer.getHeight() || backBuffer.validate(config) == VolatileImage.IMAGE_INCOMPATIBLE) {
if (backBuffer != null) {
backBufferGraphics.dispose();
backBuffer.flush();
}
backBuffer = config.createCompatibleVolatileImage(width, height);
backBufferGraphics = backBuffer.createGraphics();
}
backBufferGraphics.setClip(g.getClip());
paintUnbuffered(backBufferGraphics);
} while (backBuffer.contentsLost());
<MASK>g.drawImage(backBuffer, 0, 0, this);</MASK>
}" |
Inversion-Mutation | megadiff | "public void onEnable() {
try {
initsuccess = false;
deleteConfirm = new HashMap<String, String>();
server = this.getServer();
dataFolder = this.getDataFolder();
if (!new File(dataFolder, "config.yml").isFile()) {
this.writeDefaultConfigFromJar();
}
this.getConfiguration().load();
if(this.getConfiguration().getInt("ResidenceVersion", 0) == 0)
{
this.writeDefaultConfigFromJar();
this.getConfiguration().load();
System.out.println("[Residence] Config Invalid, wrote default...");
}
cmanager = new ConfigManager(this.getConfiguration());
String multiworld = cmanager.getMultiworldPlugin();
if (multiworld != null) {
Plugin plugin = server.getPluginManager().getPlugin(multiworld);
if (plugin != null) {
if (!plugin.isEnabled()) {
System.out.println("[Residence] - Enabling multiworld plugin: " + multiworld);
server.getPluginManager().enablePlugin(plugin);
}
}
}
gmanager = new PermissionManager(this.getConfiguration());
imanager = new WorldItemManager(this.getConfiguration());
wmanager = new WorldFlagManager(this.getConfiguration());
chatmanager = new ChatManager();
rentmanager = new RentManager();
try
{
File langFile = new File(new File(dataFolder, "Language"), cmanager.getLanguage() + ".yml");
if(this.checkNewLanguageVersion())
this.writeDefaultLanguageFile();
if(langFile.isFile())
{
Configuration langconfig = new Configuration(langFile);
langconfig.load();
helppages = HelpEntry.parseHelp(langconfig, "CommandHelp");
HelpEntry.setLinesPerPage(langconfig.getInt("HelpLinesPerPage", 7));
InformationPager.setLinesPerPage(langconfig.getInt("HelpLinesPerPage", 7));
language = Language.parseText(langconfig, "Language");
}
else
System.out.println("[Residence] Language file does not exist...");
}
catch (Exception ex)
{
System.out.println("[Residence] Failed to load language file: " + cmanager.getLanguage() + ".yml, Error: " + ex.getMessage());
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
helppages = new HelpEntry("");
language = new Language();
}
economy = null;
if (!dataFolder.isDirectory()) {
dataFolder.mkdirs();
}
String econsys = cmanager.getEconomySystem();
if (this.getConfiguration().getBoolean("Global.EnableEconomy", false) && econsys != null) {
if (econsys.toLowerCase().equals("iconomy")) {
this.loadIConomy();
} else if (econsys.toLowerCase().equals("mineconomy")) {
this.loadMineConomy();
} else if (econsys.toLowerCase().equals("boseconomy")) {
this.loadBOSEconomy();
} else if (econsys.toLowerCase().equals("essentials")) {
this.loadEssentialsEconomy();
} else if (econsys.toLowerCase().equals("realeconomy")) {
this.loadRealEconomy();
} else {
System.out.println("[Residence] Unknown economy system: " + econsys);
}
}
this.loadYml();
if (rmanager == null) {
rmanager = new ResidenceManager();
}
if (leasemanager == null) {
leasemanager = new LeaseManager(rmanager);
}
if (tmanager == null) {
tmanager = new TransactionManager(rmanager, gmanager);
}
if (pmanager == null) {
pmanager = new PermissionListManager();
}
if (firstenable) {
if(!this.isEnabled())
return;
FlagPermissions.initValidFlags();
smanager = new SelectionManager();
blistener = new ResidenceBlockListener();
plistener = new ResidencePlayerListener();
elistener = new ResidenceEntityListener();
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.BLOCK_BREAK, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_IGNITE, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_BURN, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_FROMTO, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_EMPTY, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_FILL, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.CREATURE_SPAWN, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.EXPLOSION_PRIME, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PAINTING_PLACE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PAINTING_BREAK, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_SPREAD, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENDERMAN_PICKUP, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENDERMAN_PLACE, elistener, Priority.Lowest, this);
if(cmanager.enableSpout())
{
slistener = new ResidenceSpoutListener();
pm.registerEvent(Event.Type.CUSTOM_EVENT, slistener, Priority.Lowest, this);
}
firstenable = false;
}
else
{
plistener.reload();
}
int autosaveInt = cmanager.getAutoSaveInterval();
if (autosaveInt < 1) {
autosaveInt = 1;
}
autosaveInt = (autosaveInt * 60) * 20;
autosaveBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, autoSave, autosaveInt, autosaveInt);
healBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, doHeals, 20, 20);
if (cmanager.useLeases()) {
int leaseInterval = cmanager.getLeaseCheckInterval();
if (leaseInterval < 1) {
leaseInterval = 1;
}
leaseInterval = (leaseInterval * 60) * 20;
leaseBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, leaseExpire, leaseInterval, leaseInterval);
}
if(cmanager.enabledRentSystem())
{
int rentint = cmanager.getRentCheckInterval();
if(rentint < 1)
rentint = 1;
rentint = (rentint * 60) * 20;
rentBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, rentExpire, rentint, rentint);
}
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Enabled! Version " + this.getDescription().getVersion() + " by bekvon");
initsuccess = true;
} catch (Exception ex) {
initsuccess = false;
getServer().getPluginManager().disablePlugin(this);
System.out.println("[Residence] - FAILED INITIALIZATION! DISABLED! ERROR:");
Logger.getLogger(Residence.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 "onEnable" | "public void onEnable() {
try {
initsuccess = false;
deleteConfirm = new HashMap<String, String>();
server = this.getServer();
dataFolder = this.getDataFolder();
if (!new File(dataFolder, "config.yml").isFile()) {
this.writeDefaultConfigFromJar();
}
this.getConfiguration().load();
if(this.getConfiguration().getInt("ResidenceVersion", 0) == 0)
{
this.writeDefaultConfigFromJar();
this.getConfiguration().load();
System.out.println("[Residence] Config Invalid, wrote default...");
}
cmanager = new ConfigManager(this.getConfiguration());
String multiworld = cmanager.getMultiworldPlugin();
if (multiworld != null) {
Plugin plugin = server.getPluginManager().getPlugin(multiworld);
if (plugin != null) {
if (!plugin.isEnabled()) {
<MASK>server.getPluginManager().enablePlugin(plugin);</MASK>
System.out.println("[Residence] - Enabling multiworld plugin: " + multiworld);
}
}
}
gmanager = new PermissionManager(this.getConfiguration());
imanager = new WorldItemManager(this.getConfiguration());
wmanager = new WorldFlagManager(this.getConfiguration());
chatmanager = new ChatManager();
rentmanager = new RentManager();
try
{
File langFile = new File(new File(dataFolder, "Language"), cmanager.getLanguage() + ".yml");
if(this.checkNewLanguageVersion())
this.writeDefaultLanguageFile();
if(langFile.isFile())
{
Configuration langconfig = new Configuration(langFile);
langconfig.load();
helppages = HelpEntry.parseHelp(langconfig, "CommandHelp");
HelpEntry.setLinesPerPage(langconfig.getInt("HelpLinesPerPage", 7));
InformationPager.setLinesPerPage(langconfig.getInt("HelpLinesPerPage", 7));
language = Language.parseText(langconfig, "Language");
}
else
System.out.println("[Residence] Language file does not exist...");
}
catch (Exception ex)
{
System.out.println("[Residence] Failed to load language file: " + cmanager.getLanguage() + ".yml, Error: " + ex.getMessage());
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
helppages = new HelpEntry("");
language = new Language();
}
economy = null;
if (!dataFolder.isDirectory()) {
dataFolder.mkdirs();
}
String econsys = cmanager.getEconomySystem();
if (this.getConfiguration().getBoolean("Global.EnableEconomy", false) && econsys != null) {
if (econsys.toLowerCase().equals("iconomy")) {
this.loadIConomy();
} else if (econsys.toLowerCase().equals("mineconomy")) {
this.loadMineConomy();
} else if (econsys.toLowerCase().equals("boseconomy")) {
this.loadBOSEconomy();
} else if (econsys.toLowerCase().equals("essentials")) {
this.loadEssentialsEconomy();
} else if (econsys.toLowerCase().equals("realeconomy")) {
this.loadRealEconomy();
} else {
System.out.println("[Residence] Unknown economy system: " + econsys);
}
}
this.loadYml();
if (rmanager == null) {
rmanager = new ResidenceManager();
}
if (leasemanager == null) {
leasemanager = new LeaseManager(rmanager);
}
if (tmanager == null) {
tmanager = new TransactionManager(rmanager, gmanager);
}
if (pmanager == null) {
pmanager = new PermissionListManager();
}
if (firstenable) {
if(!this.isEnabled())
return;
FlagPermissions.initValidFlags();
smanager = new SelectionManager();
blistener = new ResidenceBlockListener();
plistener = new ResidencePlayerListener();
elistener = new ResidenceEntityListener();
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.BLOCK_BREAK, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_IGNITE, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_BURN, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_FROMTO, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_EMPTY, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_FILL, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.CREATURE_SPAWN, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.EXPLOSION_PRIME, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PAINTING_PLACE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PAINTING_BREAK, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_SPREAD, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENDERMAN_PICKUP, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENDERMAN_PLACE, elistener, Priority.Lowest, this);
if(cmanager.enableSpout())
{
slistener = new ResidenceSpoutListener();
pm.registerEvent(Event.Type.CUSTOM_EVENT, slistener, Priority.Lowest, this);
}
firstenable = false;
}
else
{
plistener.reload();
}
int autosaveInt = cmanager.getAutoSaveInterval();
if (autosaveInt < 1) {
autosaveInt = 1;
}
autosaveInt = (autosaveInt * 60) * 20;
autosaveBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, autoSave, autosaveInt, autosaveInt);
healBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, doHeals, 20, 20);
if (cmanager.useLeases()) {
int leaseInterval = cmanager.getLeaseCheckInterval();
if (leaseInterval < 1) {
leaseInterval = 1;
}
leaseInterval = (leaseInterval * 60) * 20;
leaseBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, leaseExpire, leaseInterval, leaseInterval);
}
if(cmanager.enabledRentSystem())
{
int rentint = cmanager.getRentCheckInterval();
if(rentint < 1)
rentint = 1;
rentint = (rentint * 60) * 20;
rentBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, rentExpire, rentint, rentint);
}
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Enabled! Version " + this.getDescription().getVersion() + " by bekvon");
initsuccess = true;
} catch (Exception ex) {
initsuccess = false;
getServer().getPluginManager().disablePlugin(this);
System.out.println("[Residence] - FAILED INITIALIZATION! DISABLED! ERROR:");
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
}
}" |
Inversion-Mutation | megadiff | "private boolean login(String username, String host, int port) {
Client client = freeColClient.getClient();
Canvas canvas = freeColClient.getCanvas();
if (client != null) {
client.disconnect();
}
try {
client = new Client(host, port, freeColClient.getPreGameInputHandler());
} catch (ConnectException e) {
canvas.errorMessage("server.couldNotConnect");
return false;
} catch (IOException e) {
canvas.errorMessage("server.couldNotConnect");
return false;
}
freeColClient.setClient(client);
Connection c = client.getConnection();
XMLStreamReader in = null;
try {
XMLStreamWriter out = c.ask();
out.writeStartElement("login");
out.writeAttribute("username", username);
out.writeAttribute("freeColVersion", FreeCol.getVersion());
out.writeEndElement();
in = c.getReply();
if (in.getLocalName().equals("loginConfirmed")) {
final String startGameStr = in.getAttributeValue(null, "startGame");
boolean startGame = (startGameStr != null) && Boolean.valueOf(startGameStr).booleanValue();
boolean isCurrentPlayer = Boolean.valueOf(in.getAttributeValue(null, "isCurrentPlayer")).booleanValue();
in.nextTag();
Game game = new Game(freeColClient.getModelController(), in, username);
Player thisPlayer = game.getPlayerByName(username);
freeColClient.setGame(game);
freeColClient.setMyPlayer(thisPlayer);
c.endTransmission(in);
// If (true) --> reconnect
if (startGame) {
freeColClient.setSingleplayer(false);
freeColClient.getPreGameController().startGame();
if (isCurrentPlayer) {
freeColClient.getInGameController().setCurrentPlayer(thisPlayer);
}
}
} else if (in.getLocalName().equals("error")) {
canvas.errorMessage(in.getAttributeValue(null, "messageID"), in.getAttributeValue(null, "message"));
c.endTransmission(in);
return false;
} else {
logger.warning("Unkown message received: " + in.getLocalName());
c.endTransmission(in);
return false;
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
canvas.errorMessage(null, "Could not send XML to the server.");
try {
c.endTransmission(in);
} catch (IOException ie) {
logger.warning("Exception while trying to end transmission: " + ie.toString());
}
}
freeColClient.setLoggedIn(true);
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "login" | "private boolean login(String username, String host, int port) {
Client client = freeColClient.getClient();
Canvas canvas = freeColClient.getCanvas();
if (client != null) {
client.disconnect();
}
try {
client = new Client(host, port, freeColClient.getPreGameInputHandler());
} catch (ConnectException e) {
canvas.errorMessage("server.couldNotConnect");
return false;
} catch (IOException e) {
canvas.errorMessage("server.couldNotConnect");
return false;
}
freeColClient.setClient(client);
Connection c = client.getConnection();
XMLStreamReader in = null;
try {
XMLStreamWriter out = c.ask();
out.writeStartElement("login");
out.writeAttribute("username", username);
out.writeAttribute("freeColVersion", FreeCol.getVersion());
out.writeEndElement();
in = c.getReply();
if (in.getLocalName().equals("loginConfirmed")) {
final String startGameStr = in.getAttributeValue(null, "startGame");
boolean startGame = (startGameStr != null) && Boolean.valueOf(startGameStr).booleanValue();
boolean isCurrentPlayer = Boolean.valueOf(in.getAttributeValue(null, "isCurrentPlayer")).booleanValue();
in.nextTag();
Game game = new Game(freeColClient.getModelController(), in, username);
Player thisPlayer = game.getPlayerByName(username);
freeColClient.setGame(game);
freeColClient.setMyPlayer(thisPlayer);
// If (true) --> reconnect
if (startGame) {
freeColClient.setSingleplayer(false);
freeColClient.getPreGameController().startGame();
if (isCurrentPlayer) {
freeColClient.getInGameController().setCurrentPlayer(thisPlayer);
}
}
<MASK>c.endTransmission(in);</MASK>
} else if (in.getLocalName().equals("error")) {
canvas.errorMessage(in.getAttributeValue(null, "messageID"), in.getAttributeValue(null, "message"));
<MASK>c.endTransmission(in);</MASK>
return false;
} else {
logger.warning("Unkown message received: " + in.getLocalName());
<MASK>c.endTransmission(in);</MASK>
return false;
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
canvas.errorMessage(null, "Could not send XML to the server.");
try {
<MASK>c.endTransmission(in);</MASK>
} catch (IOException ie) {
logger.warning("Exception while trying to end transmission: " + ie.toString());
}
}
freeColClient.setLoggedIn(true);
return true;
}" |
Inversion-Mutation | megadiff | "public final synchronized void get(final long index, final byte[] b, final int start) throws IOException {
Long idx = Long.valueOf(index);
final byte[] bb;
synchronized (this) {
assert b.length - start >= efs.recordsize;
bb = buffer.get(idx);
if (bb == null) {
if (index >= size()) throw new IndexOutOfBoundsException("kelondroBufferedEcoFS.get(" + index + ") outside bounds (" + this.size() + ")");
efs.get(index, b, start);
return;
}
}
System.arraycopy(bb, 0, b, start, efs.recordsize);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "get" | "public final synchronized void get(final long index, final byte[] b, final int start) throws IOException {
Long idx = Long.valueOf(index);
final byte[] bb;
synchronized (this) {
assert b.length - start >= efs.recordsize;
<MASK>if (index >= size()) throw new IndexOutOfBoundsException("kelondroBufferedEcoFS.get(" + index + ") outside bounds (" + this.size() + ")");</MASK>
bb = buffer.get(idx);
if (bb == null) {
efs.get(index, b, start);
return;
}
}
System.arraycopy(bb, 0, b, start, efs.recordsize);
}" |
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 | "protected void cleanup(Context ctx) throws IOException, InterruptedException {
super.cleanup(ctx);
instance.maybeCallMethod("cleanup", ctx);
instance.cleanup(ctx.getConfiguration());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cleanup" | "protected void cleanup(Context ctx) throws IOException, InterruptedException {
super.cleanup(ctx);
<MASK>instance.cleanup(ctx.getConfiguration());</MASK>
instance.maybeCallMethod("cleanup", ctx);
}" |
Inversion-Mutation | megadiff | "public static Result showSubmissions() {
Map<String, String> dataMap = Form.form().bindFromRequest().data();
String taskTitle = dataMap.get("task");
SelectEntity<PhoenixTask> taskSelector = new SelectEntity<PhoenixTask>();
taskSelector.addKey("title", taskTitle);
WebResource wrGetSubmissions = PhoenixSubmission.getResource(CLIENT, BASE_URI);
SelectEntity<PhoenixSubmission> submissionSelector = new SelectEntity<PhoenixSubmission>();
submissionSelector.addKey("task", taskSelector);
ClientResponse post = wrGetSubmissions.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, submissionSelector);
if (post.getStatus() == 200){
List<PhoenixSubmission> submissions = EntityUtil.extractEntityList(post);
return ok(showSubmissions.render("showSubmissions", submissions));
}else{
return ok(stringShower.render("show Submissions", "Ups, da ist ein Fehler aufgetreten!(" + post.getStatus() + ")"));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "showSubmissions" | "public static Result showSubmissions() {
Map<String, String> dataMap = Form.form().bindFromRequest().data();
String taskTitle = dataMap.get("task");
SelectEntity<PhoenixTask> taskSelector = new SelectEntity<PhoenixTask>();
taskSelector.addKey("title", taskTitle);
WebResource wrGetSubmissions = PhoenixSubmission.getResource(CLIENT, BASE_URI);
SelectEntity<PhoenixSubmission> submissionSelector = new SelectEntity<PhoenixSubmission>();
submissionSelector.addKey("task", taskSelector);
ClientResponse post = wrGetSubmissions.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, submissionSelector);
<MASK>List<PhoenixSubmission> submissions = EntityUtil.extractEntityList(post);</MASK>
if (post.getStatus() == 200){
return ok(showSubmissions.render("showSubmissions", submissions));
}else{
return ok(stringShower.render("show Submissions", "Ups, da ist ein Fehler aufgetreten!(" + post.getStatus() + ")"));
}
}" |
Inversion-Mutation | megadiff | "public int queue(OutboundMessage message) throws Exception
{
if ((getPreQueueHook() != null) && !getPreQueueHook().process(message))
{
message.setSentStatus(SentStatus.Failed);
message.setFailureCause(FailureCause.Cancelled);
return 0;
}
int messageCount = 0;
LinkedList<OutboundMessage> messageList = distributeToGroup(message);
for (OutboundMessage m : messageList)
{
logger.debug("Queued: " + message.toShortString());
if (this.messageQueue.add(m)) messageCount++;
}
return messageCount;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "queue" | "public int queue(OutboundMessage message) throws Exception
{
<MASK>int messageCount = 0;</MASK>
if ((getPreQueueHook() != null) && !getPreQueueHook().process(message))
{
message.setSentStatus(SentStatus.Failed);
message.setFailureCause(FailureCause.Cancelled);
return 0;
}
LinkedList<OutboundMessage> messageList = distributeToGroup(message);
for (OutboundMessage m : messageList)
{
logger.debug("Queued: " + message.toShortString());
if (this.messageQueue.add(m)) messageCount++;
}
return messageCount;
}" |
Inversion-Mutation | megadiff | "private void handleUpdateSchedule() {
final SchedulerToolbarController localThis = this;
scheduleCreatorDialog.setTitle( MSGS.scheduleEditor() );
final List<Schedule> scheduleList = schedulesListCtrl.getSelectedSchedules();
scheduleCreatorDialog.setOnOkHandler( new ICallback<MessageDialog>() {
public void onHandle(MessageDialog d) {
localThis.updateScheduleWithNewScheduleType();
}
});
this.scheduleCreatorDialog.setOnValidateHandler( new IResponseCallback<MessageDialog, Boolean>() {
public Boolean onHandle( MessageDialog schedDlg ) {
return isUpdateScheduleCreatorDialogValid();
}
});
// the update button should be enabled/disabled to guarantee that one and only one schedule is selected
assert scheduleList.size() == 1 : "When clicking update, exactly one schedule should be selected."; //$NON-NLS-1$
Schedule sched = scheduleList.get( 0 );
try {
initScheduleCreatorDialog( sched );
scheduleCreatorDialog.center();
scheduleCreatorDialog.getScheduleEditor().setFocus();
} catch (CronParseException e) {
final MessageDialog errorDialog = new MessageDialog( MSGS.error(),
MSGS.invalidCronInInitOfRecurrenceDialog( sched.getCronString(), e.getMessage() ) );
errorDialog.setOnOkHandler( new ICallback<MessageDialog>() {
public void onHandle(MessageDialog messageDialog ) {
errorDialog.hide();
scheduleCreatorDialog.center();
}
});
errorDialog.center();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleUpdateSchedule" | "private void handleUpdateSchedule() {
final SchedulerToolbarController localThis = this;
scheduleCreatorDialog.setTitle( MSGS.scheduleEditor() );
final List<Schedule> scheduleList = schedulesListCtrl.getSelectedSchedules();
scheduleCreatorDialog.setOnOkHandler( new ICallback<MessageDialog>() {
public void onHandle(MessageDialog d) {
localThis.updateScheduleWithNewScheduleType();
}
});
this.scheduleCreatorDialog.setOnValidateHandler( new IResponseCallback<MessageDialog, Boolean>() {
public Boolean onHandle( MessageDialog schedDlg ) {
return isUpdateScheduleCreatorDialogValid();
}
});
// the update button should be enabled/disabled to guarantee that one and only one schedule is selected
assert scheduleList.size() == 1 : "When clicking update, exactly one schedule should be selected."; //$NON-NLS-1$
Schedule sched = scheduleList.get( 0 );
try {
<MASK>scheduleCreatorDialog.center();</MASK>
initScheduleCreatorDialog( sched );
scheduleCreatorDialog.getScheduleEditor().setFocus();
} catch (CronParseException e) {
final MessageDialog errorDialog = new MessageDialog( MSGS.error(),
MSGS.invalidCronInInitOfRecurrenceDialog( sched.getCronString(), e.getMessage() ) );
errorDialog.setOnOkHandler( new ICallback<MessageDialog>() {
public void onHandle(MessageDialog messageDialog ) {
errorDialog.hide();
<MASK>scheduleCreatorDialog.center();</MASK>
}
});
errorDialog.center();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onResumeAfterSuper() {
if (mActivity.mOpenCameraFail || mActivity.mCameraDisabled)
return;
mZoomValue = 0;
showVideoSnapshotUI(false);
mUI.enableShutter(false);
if (!mPreviewing && mStartPreviewThread == null) {
resetEffect();
openCamera();
if (mActivity.mOpenCameraFail) {
Util.showErrorAndFinish(mActivity,
R.string.cannot_connect_camera);
return;
} else if (mActivity.mCameraDisabled) {
Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
return;
}
readVideoPreferences();
resizeForPreviewAspectRatio();
CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
screenNail.cancelAcquire();
if (screenNail.getSurfaceTexture() == null) {
screenNail.acquireSurfaceTexture();
}
mStartPreviewThread = new StartPreviewThread();
mStartPreviewThread.start();
} else {
// preview already started
mUI.enableShutter(true);
}
// Initializing it here after the preview is started.
mUI.initializeZoom(mParameters);
keepScreenOnAwhile();
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(mPreferences,
mContentResolver);
mLocationManager.recordLocation(recordLocation);
if (mPreviewing) {
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
// Dismiss open menu if exists.
PopupManager.getInstance(mActivity).notifyShowPopup(null);
UsageStatistics.onContentViewChanged(
UsageStatistics.COMPONENT_CAMERA, "VideoModule");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onResumeAfterSuper" | "@Override
public void onResumeAfterSuper() {
if (mActivity.mOpenCameraFail || mActivity.mCameraDisabled)
return;
<MASK>mUI.enableShutter(false);</MASK>
mZoomValue = 0;
showVideoSnapshotUI(false);
if (!mPreviewing && mStartPreviewThread == null) {
resetEffect();
openCamera();
if (mActivity.mOpenCameraFail) {
Util.showErrorAndFinish(mActivity,
R.string.cannot_connect_camera);
return;
} else if (mActivity.mCameraDisabled) {
Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
return;
}
readVideoPreferences();
resizeForPreviewAspectRatio();
CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
screenNail.cancelAcquire();
if (screenNail.getSurfaceTexture() == null) {
screenNail.acquireSurfaceTexture();
}
mStartPreviewThread = new StartPreviewThread();
mStartPreviewThread.start();
} else {
// preview already started
mUI.enableShutter(true);
}
// Initializing it here after the preview is started.
mUI.initializeZoom(mParameters);
keepScreenOnAwhile();
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(mPreferences,
mContentResolver);
mLocationManager.recordLocation(recordLocation);
if (mPreviewing) {
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
// Dismiss open menu if exists.
PopupManager.getInstance(mActivity).notifyShowPopup(null);
UsageStatistics.onContentViewChanged(
UsageStatistics.COMPONENT_CAMERA, "VideoModule");
}" |
Inversion-Mutation | megadiff | "public void stop(BundleContext inContext) throws Exception {
unregisterGCTrigger();
GCActivator.context = null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stop" | "public void stop(BundleContext inContext) throws Exception {
<MASK>GCActivator.context = null;</MASK>
unregisterGCTrigger();
}" |
Inversion-Mutation | megadiff | "public static void sparks(GL2 gl, Color color) {
//Use the same seed every time
Random r = new Random(0);
float[] c = new float[4];
convertColor(color, c);
for (int i = 0; i < 3; i++)
c[i] = c[i] * .3f + .7f;
gl.glColor4fv(c, 0);
for (int i = 0; i < 200; i++) {
final float z = 2 * (r.nextFloat() * r.nextFloat() * r.nextFloat());
final float x = z * (r.nextFloat() - 0.5f);
final float y = z * (r.nextFloat() - 0.5f);
gl.glPointSize(1);
gl.glBegin(GL.GL_POINTS);
gl.glVertex3f(x, y, z * 2);
gl.glEnd();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "sparks" | "public static void sparks(GL2 gl, Color color) {
//Use the same seed every time
Random r = new Random(0);
float[] c = new float[4];
convertColor(color, c);
for (int i = 0; i < 3; i++)
c[i] = c[i] * .3f + .7f;
gl.glColor4fv(c, 0);
for (int i = 0; i < 200; i++) {
final float z = 2 * (r.nextFloat() * r.nextFloat() * r.nextFloat());
final float x = z * (r.nextFloat() - 0.5f);
final float y = z * (r.nextFloat() - 0.5f);
<MASK>gl.glBegin(GL.GL_POINTS);</MASK>
gl.glPointSize(1);
gl.glVertex3f(x, y, z * 2);
gl.glEnd();
}
}" |
Inversion-Mutation | megadiff | "protected void doWriteObject(final Object original, final boolean unshared) throws IOException {
final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory;
final ObjectResolver objectResolver = this.objectResolver;
Object obj = original;
Class<?> objClass;
int id;
boolean isArray, isEnum;
SerializableClass info;
boolean unreplaced = true;
final int configuredVersion = this.configuredVersion;
try {
for (;;) {
if (obj == null) {
write(ID_NULL);
return;
}
final int rid;
if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) {
final int diff = rid - instanceSeq;
if (diff >= -256) {
write(ID_REPEAT_OBJECT_NEAR);
write(diff);
} else if (diff >= -65536) {
write(ID_REPEAT_OBJECT_NEARISH);
writeShort(diff);
} else {
write(ID_REPEAT_OBJECT_FAR);
writeInt(rid);
}
return;
}
final ObjectTable.Writer objectTableWriter;
if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) {
write(ID_PREDEFINED_OBJECT);
if (configuredVersion == 1) {
objectTableWriter.writeObject(getBlockMarshaller(), obj);
writeEndBlock();
} else {
objectTableWriter.writeObject(this, obj);
}
return;
}
objClass = obj.getClass();
id = getBasicClasses(configuredVersion).get(objClass, -1);
// First, non-replaceable classes
if (id == ID_CLASS_CLASS) {
final Class<?> classObj = (Class<?>) obj;
// If a class is one we have an entry for, we just write that byte directly.
// These guys can't be written directly though, otherwise they'll get confused with the objects
// of the corresponding type.
final int cid = BASIC_CLASSES_V2.get(classObj, -1);
switch (cid) {
case -1:
case ID_SINGLETON_MAP_OBJECT:
case ID_SINGLETON_SET_OBJECT:
case ID_SINGLETON_LIST_OBJECT:
case ID_EMPTY_MAP_OBJECT:
case ID_EMPTY_SET_OBJECT:
case ID_EMPTY_LIST_OBJECT: {
// If the class is one of the above special object types, then we write a
// full NEW_OBJECT+CLASS_CLASS header followed by the class byte, or if there is none, write
// the full class descriptor.
write(ID_NEW_OBJECT);
writeClassClass(classObj);
return;
}
default: {
write(cid);
return;
}
}
// not reached
}
isEnum = obj instanceof Enum;
isArray = objClass.isArray();
// objects with id != -1 will never make use of the "info" param in *any* way
info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass);
// replace once - objects with id != -1 will not have replacement methods but might be globally replaced
if (unreplaced) {
if (info != null) {
// check for a user replacement
if (info.hasWriteReplace()) {
obj = info.callWriteReplace(obj);
}
}
// Check for a global replacement
obj = objectResolver.writeReplace(obj);
if (obj != original) {
unreplaced = false;
continue;
} else {
break;
}
} else {
break;
}
}
if (isEnum) {
// objClass cannot equal Enum.class because it is abstract
final Enum<?> theEnum = (Enum<?>) obj;
// enums are always shared
write(ID_NEW_OBJECT);
writeEnumClass(theEnum.getDeclaringClass());
writeString(theEnum.name());
instanceCache.put(obj, instanceSeq++);
return;
}
// Now replaceable classes
switch (id) {
case ID_BYTE_CLASS: {
write(ID_BYTE_OBJECT);
writeByte(((Byte) obj).byteValue());
return;
}
case ID_BOOLEAN_CLASS: {
write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE);
return;
}
case ID_CHARACTER_CLASS: {
write(ID_CHARACTER_OBJECT);
writeChar(((Character) obj).charValue());
return;
}
case ID_DOUBLE_CLASS: {
write(ID_DOUBLE_OBJECT);
writeDouble(((Double) obj).doubleValue());
return;
}
case ID_FLOAT_CLASS: {
write(ID_FLOAT_OBJECT);
writeFloat(((Float) obj).floatValue());
return;
}
case ID_INTEGER_CLASS: {
write(ID_INTEGER_OBJECT);
writeInt(((Integer) obj).intValue());
return;
}
case ID_LONG_CLASS: {
write(ID_LONG_OBJECT);
writeLong(((Long) obj).longValue());
return;
}
case ID_SHORT_CLASS: {
write(ID_SHORT_OBJECT);
writeShort(((Short) obj).shortValue());
return;
}
case ID_STRING_CLASS: {
final String string = (String) obj;
final int len = string.length();
if (len == 0) {
write(ID_STRING_EMPTY);
// don't cache empty strings
return;
} else if (len <= 0x100) {
write(ID_STRING_SMALL);
write(len);
} else if (len <= 0x10000) {
write(ID_STRING_MEDIUM);
writeShort(len);
} else {
write(ID_STRING_LARGE);
writeInt(len);
}
shallowFlush();
UTFUtils.writeUTFBytes(byteOutput, string);
if (unshared) {
instanceCache.put(obj, -1);
instanceSeq++;
} else {
instanceCache.put(obj, instanceSeq++);
}
return;
}
case ID_BYTE_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final byte[] bytes = (byte[]) obj;
final int len = bytes.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_BYTE);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_BYTE);
write(bytes, 0, len);
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_BYTE);
write(bytes, 0, len);
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_BYTE);
write(bytes, 0, len);
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_BOOLEAN_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final boolean[] booleans = (boolean[]) obj;
final int len = booleans.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_BOOLEAN);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_BOOLEAN);
writeBooleanArray(booleans);
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_BOOLEAN);
writeBooleanArray(booleans);
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_BOOLEAN);
writeBooleanArray(booleans);
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CHAR_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final char[] chars = (char[]) obj;
final int len = chars.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_CHAR);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_CHAR);
for (int i = 0; i < len; i ++) {
writeChar(chars[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_CHAR);
for (int i = 0; i < len; i ++) {
writeChar(chars[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_CHAR);
for (int i = 0; i < len; i ++) {
writeChar(chars[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_SHORT_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final short[] shorts = (short[]) obj;
final int len = shorts.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_SHORT);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_SHORT);
for (int i = 0; i < len; i ++) {
writeShort(shorts[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_SHORT);
for (int i = 0; i < len; i ++) {
writeShort(shorts[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_SHORT);
for (int i = 0; i < len; i ++) {
writeShort(shorts[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_INT_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final int[] ints = (int[]) obj;
final int len = ints.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_INT);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_INT);
for (int i = 0; i < len; i ++) {
writeInt(ints[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_INT);
for (int i = 0; i < len; i ++) {
writeInt(ints[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_INT);
for (int i = 0; i < len; i ++) {
writeInt(ints[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_LONG_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final long[] longs = (long[]) obj;
final int len = longs.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_LONG);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_LONG);
for (int i = 0; i < len; i ++) {
writeLong(longs[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_LONG);
for (int i = 0; i < len; i ++) {
writeLong(longs[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_LONG);
for (int i = 0; i < len; i ++) {
writeLong(longs[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_FLOAT_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final float[] floats = (float[]) obj;
final int len = floats.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_FLOAT);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_FLOAT);
for (int i = 0; i < len; i ++) {
writeFloat(floats[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_FLOAT);
for (int i = 0; i < len; i ++) {
writeFloat(floats[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_FLOAT);
for (int i = 0; i < len; i ++) {
writeFloat(floats[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_DOUBLE_ARRAY_CLASS: {
if (! unshared) {
instanceCache.put(obj, instanceSeq++);
}
final double[] doubles = (double[]) obj;
final int len = doubles.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_DOUBLE);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_DOUBLE);
for (int i = 0; i < len; i ++) {
writeDouble(doubles[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_DOUBLE);
for (int i = 0; i < len; i ++) {
writeDouble(doubles[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_DOUBLE);
for (int i = 0; i < len; i ++) {
writeDouble(doubles[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_HASH_SET:
case ID_CC_LINKED_HASH_SET:
case ID_CC_TREE_SET:
case ID_CC_ARRAY_LIST:
case ID_CC_LINKED_LIST:
case ID_CC_VECTOR:
case ID_CC_STACK:
case ID_CC_ARRAY_DEQUE: {
instanceCache.put(obj, instanceSeq++);
final Collection<?> collection = (Collection<?>) obj;
final int len = collection.size();
if (len == 0) {
write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
} else if (len <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(len);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
for (Object o : collection) {
doWriteObject(o, false);
}
} else if (len <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(len);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
for (Object o : collection) {
doWriteObject(o, false);
}
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(len);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
for (Object o : collection) {
doWriteObject(o, false);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_ENUM_SET_PROXY: {
final Enum[] elements = getEnumSetElements(obj);
final int len = elements.length;
if (len == 0) {
write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY);
write(id);
writeClass(getEnumSetElementType(obj));
instanceCache.put(obj, instanceSeq++);
} else if (len <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(len);
write(id);
writeClass(getEnumSetElementType(obj));
instanceCache.put(obj, instanceSeq++);
for (Object o : elements) {
doWriteObject(o, false);
}
} else if (len <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(len);
write(id);
writeClass(getEnumSetElementType(obj));
instanceCache.put(obj, instanceSeq++);
for (Object o : elements) {
doWriteObject(o, false);
}
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(len);
write(id);
writeClass(getEnumSetElementType(obj));
instanceCache.put(obj, instanceSeq++);
for (Object o : elements) {
doWriteObject(o, false);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_HASH_MAP:
case ID_CC_HASHTABLE:
case ID_CC_IDENTITY_HASH_MAP:
case ID_CC_LINKED_HASH_MAP:
case ID_CC_TREE_MAP:
case ID_CC_ENUM_MAP: {
instanceCache.put(obj, instanceSeq++);
final Map<?, ?> map = (Map<?, ?>) obj;
final int len = map.size();
if (len == 0) {
write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
} else if (len <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(len);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
}
} else if (len <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(len);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
}
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(len);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_EMPTY_MAP_OBJECT:
case ID_EMPTY_SET_OBJECT:
case ID_EMPTY_LIST_OBJECT:
case ID_REVERSE_ORDER_OBJECT: {
write(id);
return;
}
case ID_SINGLETON_MAP_OBJECT: {
instanceCache.put(obj, instanceSeq++);
write(id);
final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next();
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_SINGLETON_LIST_OBJECT:
case ID_SINGLETON_SET_OBJECT: {
instanceCache.put(obj, instanceSeq++);
write(id);
doWriteObject(((Collection)obj).iterator().next(), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_REVERSE_ORDER2_OBJECT: {
instanceCache.put(obj, instanceSeq++);
write(id);
try {
doWriteObject(Protocol.reverseOrder2Field.get(obj), false);
} catch (IllegalAccessException e) {
throw new InvalidObjectException("Cannot access standard field for reverse-order comparator");
}
return;
}
case ID_CC_CONCURRENT_HASH_MAP:
case ID_CC_COPY_ON_WRITE_ARRAY_LIST:
case ID_CC_COPY_ON_WRITE_ARRAY_SET: {
info = registry.lookup(objClass);
break;
}
case ID_PAIR: {
instanceCache.put(obj, instanceSeq++);
write(id);
Pair<?, ?> pair = (Pair<?, ?>) obj;
doWriteObject(pair.getA(), unshared);
doWriteObject(pair.getB(), unshared);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_NCOPIES: {
List<?> list = (List<?>) obj;
int size = list.size();
if (size == 0) {
write(ID_EMPTY_LIST_OBJECT);
return;
}
instanceCache.put(obj, instanceSeq++);
if (size <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(size);
} else if (size <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(size);
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(size);
}
write(id);
doWriteObject(list.iterator().next(), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case -1: break;
default: throw new NotSerializableException(objClass.getName());
}
if (isArray) {
final Object[] objects = (Object[]) obj;
final int len = objects.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
writeClass(objClass.getComponentType());
instanceCache.put(obj, instanceSeq++);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
writeClass(objClass.getComponentType());
instanceCache.put(obj, instanceSeq++);
for (int i = 0; i < len; i++) {
doWriteObject(objects[i], unshared);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
writeClass(objClass.getComponentType());
instanceCache.put(obj, instanceSeq++);
for (int i = 0; i < len; i++) {
doWriteObject(objects[i], unshared);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
writeClass(objClass.getComponentType());
instanceCache.put(obj, instanceSeq++);
for (int i = 0; i < len; i++) {
doWriteObject(objects[i], unshared);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// serialize proxies efficiently
if (Proxy.isProxyClass(objClass)) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
writeProxyClass(objClass);
instanceCache.put(obj, instanceSeq++);
doWriteObject(Proxy.getInvocationHandler(obj), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// it's a user type
// user type #1: externalizer
Externalizer externalizer;
if (externalizers.containsKey(objClass)) {
externalizer = externalizers.get(objClass);
} else {
externalizer = classExternalizerFactory.getExternalizer(objClass);
externalizers.put(objClass, externalizer);
}
if (externalizer != null) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
writeExternalizerClass(objClass, externalizer);
instanceCache.put(obj, instanceSeq++);
final ObjectOutput objectOutput;
objectOutput = getObjectOutput();
externalizer.writeExternal(obj, objectOutput);
writeEndBlock();
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// user type #2: externalizable
if (obj instanceof Externalizable) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
final Externalizable ext = (Externalizable) obj;
final ObjectOutput objectOutput = getObjectOutput();
writeExternalizableClass(objClass);
instanceCache.put(obj, instanceSeq++);
ext.writeExternal(objectOutput);
writeEndBlock();
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// user type #3: serializable
if (serializabilityChecker.isSerializable(objClass)) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
writeSerializableClass(objClass);
instanceCache.put(obj, instanceSeq++);
doWriteSerializableObject(info, obj, objClass);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
throw new NotSerializableException(objClass.getName());
} finally {
if (! unreplaced && obj != original) {
final int replId = instanceCache.get(obj, -1);
if (replId != -1) {
instanceCache.put(original, replId);
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doWriteObject" | "protected void doWriteObject(final Object original, final boolean unshared) throws IOException {
final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory;
final ObjectResolver objectResolver = this.objectResolver;
Object obj = original;
Class<?> objClass;
int id;
boolean isArray, isEnum;
SerializableClass info;
boolean unreplaced = true;
final int configuredVersion = this.configuredVersion;
try {
for (;;) {
if (obj == null) {
write(ID_NULL);
return;
}
final int rid;
if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) {
final int diff = rid - instanceSeq;
if (diff >= -256) {
write(ID_REPEAT_OBJECT_NEAR);
write(diff);
} else if (diff >= -65536) {
write(ID_REPEAT_OBJECT_NEARISH);
writeShort(diff);
} else {
write(ID_REPEAT_OBJECT_FAR);
writeInt(rid);
}
return;
}
final ObjectTable.Writer objectTableWriter;
if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) {
write(ID_PREDEFINED_OBJECT);
if (configuredVersion == 1) {
objectTableWriter.writeObject(getBlockMarshaller(), obj);
writeEndBlock();
} else {
objectTableWriter.writeObject(this, obj);
}
return;
}
objClass = obj.getClass();
id = getBasicClasses(configuredVersion).get(objClass, -1);
// First, non-replaceable classes
if (id == ID_CLASS_CLASS) {
final Class<?> classObj = (Class<?>) obj;
// If a class is one we have an entry for, we just write that byte directly.
// These guys can't be written directly though, otherwise they'll get confused with the objects
// of the corresponding type.
final int cid = BASIC_CLASSES_V2.get(classObj, -1);
switch (cid) {
case -1:
case ID_SINGLETON_MAP_OBJECT:
case ID_SINGLETON_SET_OBJECT:
case ID_SINGLETON_LIST_OBJECT:
case ID_EMPTY_MAP_OBJECT:
case ID_EMPTY_SET_OBJECT:
case ID_EMPTY_LIST_OBJECT: {
// If the class is one of the above special object types, then we write a
// full NEW_OBJECT+CLASS_CLASS header followed by the class byte, or if there is none, write
// the full class descriptor.
write(ID_NEW_OBJECT);
writeClassClass(classObj);
return;
}
default: {
write(cid);
return;
}
}
// not reached
}
isEnum = obj instanceof Enum;
isArray = objClass.isArray();
// objects with id != -1 will never make use of the "info" param in *any* way
info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass);
// replace once - objects with id != -1 will not have replacement methods but might be globally replaced
if (unreplaced) {
if (info != null) {
// check for a user replacement
if (info.hasWriteReplace()) {
obj = info.callWriteReplace(obj);
}
}
// Check for a global replacement
obj = objectResolver.writeReplace(obj);
if (obj != original) {
unreplaced = false;
continue;
} else {
break;
}
} else {
break;
}
}
if (isEnum) {
// objClass cannot equal Enum.class because it is abstract
final Enum<?> theEnum = (Enum<?>) obj;
// enums are always shared
write(ID_NEW_OBJECT);
writeEnumClass(theEnum.getDeclaringClass());
writeString(theEnum.name());
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
return;
}
// Now replaceable classes
switch (id) {
case ID_BYTE_CLASS: {
write(ID_BYTE_OBJECT);
writeByte(((Byte) obj).byteValue());
return;
}
case ID_BOOLEAN_CLASS: {
write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE);
return;
}
case ID_CHARACTER_CLASS: {
write(ID_CHARACTER_OBJECT);
writeChar(((Character) obj).charValue());
return;
}
case ID_DOUBLE_CLASS: {
write(ID_DOUBLE_OBJECT);
writeDouble(((Double) obj).doubleValue());
return;
}
case ID_FLOAT_CLASS: {
write(ID_FLOAT_OBJECT);
writeFloat(((Float) obj).floatValue());
return;
}
case ID_INTEGER_CLASS: {
write(ID_INTEGER_OBJECT);
writeInt(((Integer) obj).intValue());
return;
}
case ID_LONG_CLASS: {
write(ID_LONG_OBJECT);
writeLong(((Long) obj).longValue());
return;
}
case ID_SHORT_CLASS: {
write(ID_SHORT_OBJECT);
writeShort(((Short) obj).shortValue());
return;
}
case ID_STRING_CLASS: {
final String string = (String) obj;
final int len = string.length();
if (len == 0) {
write(ID_STRING_EMPTY);
// don't cache empty strings
return;
} else if (len <= 0x100) {
write(ID_STRING_SMALL);
write(len);
} else if (len <= 0x10000) {
write(ID_STRING_MEDIUM);
writeShort(len);
} else {
write(ID_STRING_LARGE);
writeInt(len);
}
shallowFlush();
UTFUtils.writeUTFBytes(byteOutput, string);
if (unshared) {
instanceCache.put(obj, -1);
instanceSeq++;
} else {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
return;
}
case ID_BYTE_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final byte[] bytes = (byte[]) obj;
final int len = bytes.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_BYTE);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_BYTE);
write(bytes, 0, len);
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_BYTE);
write(bytes, 0, len);
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_BYTE);
write(bytes, 0, len);
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_BOOLEAN_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final boolean[] booleans = (boolean[]) obj;
final int len = booleans.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_BOOLEAN);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_BOOLEAN);
writeBooleanArray(booleans);
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_BOOLEAN);
writeBooleanArray(booleans);
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_BOOLEAN);
writeBooleanArray(booleans);
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CHAR_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final char[] chars = (char[]) obj;
final int len = chars.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_CHAR);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_CHAR);
for (int i = 0; i < len; i ++) {
writeChar(chars[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_CHAR);
for (int i = 0; i < len; i ++) {
writeChar(chars[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_CHAR);
for (int i = 0; i < len; i ++) {
writeChar(chars[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_SHORT_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final short[] shorts = (short[]) obj;
final int len = shorts.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_SHORT);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_SHORT);
for (int i = 0; i < len; i ++) {
writeShort(shorts[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_SHORT);
for (int i = 0; i < len; i ++) {
writeShort(shorts[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_SHORT);
for (int i = 0; i < len; i ++) {
writeShort(shorts[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_INT_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final int[] ints = (int[]) obj;
final int len = ints.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_INT);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_INT);
for (int i = 0; i < len; i ++) {
writeInt(ints[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_INT);
for (int i = 0; i < len; i ++) {
writeInt(ints[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_INT);
for (int i = 0; i < len; i ++) {
writeInt(ints[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_LONG_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final long[] longs = (long[]) obj;
final int len = longs.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_LONG);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_LONG);
for (int i = 0; i < len; i ++) {
writeLong(longs[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_LONG);
for (int i = 0; i < len; i ++) {
writeLong(longs[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_LONG);
for (int i = 0; i < len; i ++) {
writeLong(longs[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_FLOAT_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final float[] floats = (float[]) obj;
final int len = floats.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_FLOAT);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_FLOAT);
for (int i = 0; i < len; i ++) {
writeFloat(floats[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_FLOAT);
for (int i = 0; i < len; i ++) {
writeFloat(floats[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_FLOAT);
for (int i = 0; i < len; i ++) {
writeFloat(floats[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_DOUBLE_ARRAY_CLASS: {
if (! unshared) {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
}
final double[] doubles = (double[]) obj;
final int len = doubles.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
write(ID_PRIM_DOUBLE);
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
write(ID_PRIM_DOUBLE);
for (int i = 0; i < len; i ++) {
writeDouble(doubles[i]);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
write(ID_PRIM_DOUBLE);
for (int i = 0; i < len; i ++) {
writeDouble(doubles[i]);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
write(ID_PRIM_DOUBLE);
for (int i = 0; i < len; i ++) {
writeDouble(doubles[i]);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_HASH_SET:
case ID_CC_LINKED_HASH_SET:
case ID_CC_TREE_SET:
case ID_CC_ARRAY_LIST:
case ID_CC_LINKED_LIST:
case ID_CC_VECTOR:
case ID_CC_STACK:
case ID_CC_ARRAY_DEQUE: {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
final Collection<?> collection = (Collection<?>) obj;
final int len = collection.size();
if (len == 0) {
write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
} else if (len <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(len);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
for (Object o : collection) {
doWriteObject(o, false);
}
} else if (len <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(len);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
for (Object o : collection) {
doWriteObject(o, false);
}
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(len);
write(id);
if (id == ID_CC_TREE_SET) {
doWriteObject(((TreeSet)collection).comparator(), false);
}
for (Object o : collection) {
doWriteObject(o, false);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_ENUM_SET_PROXY: {
final Enum[] elements = getEnumSetElements(obj);
final int len = elements.length;
if (len == 0) {
write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY);
write(id);
writeClass(getEnumSetElementType(obj));
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
} else if (len <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(len);
write(id);
writeClass(getEnumSetElementType(obj));
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
for (Object o : elements) {
doWriteObject(o, false);
}
} else if (len <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(len);
write(id);
writeClass(getEnumSetElementType(obj));
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
for (Object o : elements) {
doWriteObject(o, false);
}
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(len);
write(id);
writeClass(getEnumSetElementType(obj));
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
for (Object o : elements) {
doWriteObject(o, false);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_HASH_MAP:
case ID_CC_HASHTABLE:
case ID_CC_IDENTITY_HASH_MAP:
case ID_CC_LINKED_HASH_MAP:
case ID_CC_TREE_MAP:
case ID_CC_ENUM_MAP: {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
final Map<?, ?> map = (Map<?, ?>) obj;
final int len = map.size();
if (len == 0) {
write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
} else if (len <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(len);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
}
} else if (len <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(len);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
}
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(len);
write(id);
switch (id) {
case ID_CC_TREE_MAP: doWriteObject(((TreeMap)map).comparator(), false); break;
case ID_CC_ENUM_MAP: writeClass(getEnumMapKeyType(obj)); break;
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_EMPTY_MAP_OBJECT:
case ID_EMPTY_SET_OBJECT:
case ID_EMPTY_LIST_OBJECT:
case ID_REVERSE_ORDER_OBJECT: {
write(id);
return;
}
case ID_SINGLETON_MAP_OBJECT: {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
write(id);
final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next();
doWriteObject(entry.getKey(), false);
doWriteObject(entry.getValue(), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_SINGLETON_LIST_OBJECT:
case ID_SINGLETON_SET_OBJECT: {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
write(id);
doWriteObject(((Collection)obj).iterator().next(), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_REVERSE_ORDER2_OBJECT: {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
write(id);
try {
doWriteObject(Protocol.reverseOrder2Field.get(obj), false);
} catch (IllegalAccessException e) {
throw new InvalidObjectException("Cannot access standard field for reverse-order comparator");
}
return;
}
case ID_CC_CONCURRENT_HASH_MAP:
case ID_CC_COPY_ON_WRITE_ARRAY_LIST:
case ID_CC_COPY_ON_WRITE_ARRAY_SET: {
info = registry.lookup(objClass);
break;
}
case ID_PAIR: {
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
write(id);
Pair<?, ?> pair = (Pair<?, ?>) obj;
doWriteObject(pair.getA(), unshared);
doWriteObject(pair.getB(), unshared);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case ID_CC_NCOPIES: {
List<?> list = (List<?>) obj;
int size = list.size();
if (size == 0) {
write(ID_EMPTY_LIST_OBJECT);
return;
}
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
if (size <= 256) {
write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL);
write(size);
} else if (size <= 65536) {
write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM);
writeShort(size);
} else {
write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE);
writeInt(size);
}
write(id);
doWriteObject(list.iterator().next(), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
case -1: break;
default: throw new NotSerializableException(objClass.getName());
}
if (isArray) {
final Object[] objects = (Object[]) obj;
final int len = objects.length;
if (len == 0) {
write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY);
writeClass(objClass.getComponentType());
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
} else if (len <= 256) {
write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL);
write(len);
writeClass(objClass.getComponentType());
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
for (int i = 0; i < len; i++) {
doWriteObject(objects[i], unshared);
}
} else if (len <= 65536) {
write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM);
writeShort(len);
writeClass(objClass.getComponentType());
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
for (int i = 0; i < len; i++) {
doWriteObject(objects[i], unshared);
}
} else {
write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE);
writeInt(len);
writeClass(objClass.getComponentType());
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
for (int i = 0; i < len; i++) {
doWriteObject(objects[i], unshared);
}
}
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// serialize proxies efficiently
if (Proxy.isProxyClass(objClass)) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
writeProxyClass(objClass);
doWriteObject(Proxy.getInvocationHandler(obj), false);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// it's a user type
// user type #1: externalizer
Externalizer externalizer;
if (externalizers.containsKey(objClass)) {
externalizer = externalizers.get(objClass);
} else {
externalizer = classExternalizerFactory.getExternalizer(objClass);
externalizers.put(objClass, externalizer);
}
if (externalizer != null) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
writeExternalizerClass(objClass, externalizer);
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
final ObjectOutput objectOutput;
objectOutput = getObjectOutput();
externalizer.writeExternal(obj, objectOutput);
writeEndBlock();
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// user type #2: externalizable
if (obj instanceof Externalizable) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
final Externalizable ext = (Externalizable) obj;
final ObjectOutput objectOutput = getObjectOutput();
writeExternalizableClass(objClass);
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
ext.writeExternal(objectOutput);
writeEndBlock();
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
// user type #3: serializable
if (serializabilityChecker.isSerializable(objClass)) {
write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT);
writeSerializableClass(objClass);
<MASK>instanceCache.put(obj, instanceSeq++);</MASK>
doWriteSerializableObject(info, obj, objClass);
if (unshared) {
instanceCache.put(obj, -1);
}
return;
}
throw new NotSerializableException(objClass.getName());
} finally {
if (! unreplaced && obj != original) {
final int replId = instanceCache.get(obj, -1);
if (replId != -1) {
instanceCache.put(original, replId);
}
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
int blockID = world.getBlockId(x, y, z);
int meta = world.getBlockMetadata(x, y, z);
TileEntity tile = world.getBlockTileEntity(x, y, z);
if ((tile instanceof IWrenchable) && ElectricItemUtils.getPlayerEnergy(player) > 99)
{
IWrenchable wrenchTile = (IWrenchable)tile;
if (player.isSneaking()) {
side = SIDE_OPPOSITE[side];
}
if ((side == wrenchTile.getFacing()) && (wrenchTile.wrenchCanRemove(player))) {
ItemStack dropBlock = wrenchTile.getWrenchDrop(player);
if (dropBlock != null)
{
world.setBlock(x, y, z, 0);
if (AddonUtils.isServerWorld(world))
{
float f = 0.7F;
double i = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double j = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double k = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
EntityItem entity = new EntityItem(world, i + x, j + y, k + z, dropBlock);
entity.delayBeforeCanPickup = 10;
world.spawnEntityInWorld(entity);
}
}
ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION));
return AddonUtils.isServerWorld(world);
}
if (AddonUtils.isServerWorld(world))
{
if ((side == 0) || (side == 1))
{
if (((wrenchTile instanceof IEnergySource)) && ((wrenchTile instanceof IEnergySink))) {
wrenchTile.setFacing((short)side);
}
}
else {
wrenchTile.setFacing((short)side);
}
ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION));
}
return AddonUtils.isServerWorld(world);
}
if ((tile instanceof IReconfigurableFacing)) {
if (AddonUtils.isServerWorld(world)) {
ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION));
return ((IReconfigurableFacing)tile).rotateBlock();
}
return false;
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onItemUseFirst" | "@Override
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
int blockID = world.getBlockId(x, y, z);
int meta = world.getBlockMetadata(x, y, z);
TileEntity tile = world.getBlockTileEntity(x, y, z);
if ((tile instanceof IWrenchable) && ElectricItemUtils.getPlayerEnergy(player) > 99)
{
IWrenchable wrenchTile = (IWrenchable)tile;
if (player.isSneaking()) {
side = SIDE_OPPOSITE[side];
}
if ((side == wrenchTile.getFacing()) && (wrenchTile.wrenchCanRemove(player))) {
ItemStack dropBlock = wrenchTile.getWrenchDrop(player);
if (dropBlock != null)
{
world.setBlock(x, y, z, 0);
if (AddonUtils.isServerWorld(world))
{
float f = 0.7F;
double i = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double j = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
double k = world.rand.nextFloat() * f + (1.0F - f) * 0.5D;
EntityItem entity = new EntityItem(world, i + x, j + y, k + z, dropBlock);
entity.delayBeforeCanPickup = 10;
world.spawnEntityInWorld(entity);
}
}
<MASK>ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION));</MASK>
return AddonUtils.isServerWorld(world);
}
if (AddonUtils.isServerWorld(world))
{
if ((side == 0) || (side == 1))
{
if (((wrenchTile instanceof IEnergySource)) && ((wrenchTile instanceof IEnergySink))) {
wrenchTile.setFacing((short)side);
<MASK>ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION));</MASK>
}
}
else {
wrenchTile.setFacing((short)side);
}
}
return AddonUtils.isServerWorld(world);
}
if ((tile instanceof IReconfigurableFacing)) {
if (AddonUtils.isServerWorld(world)) {
<MASK>ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION));</MASK>
return ((IReconfigurableFacing)tile).rotateBlock();
}
return false;
}
return false;
}" |
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 | "@AfterRender
void setJS() {
JSONObject setup = new JSONObject();
setup.put("id", getClientId());
JSONObject dataTableParams = new JSONObject();
if (getMode()) {
dataTableParams.put("sAjaxSource", resources.createEventLink("data").toAbsoluteURI());
dataTableParams.put("bServerSide", "true");
dataTableParams.put("bProcessing", "true");
}
dataTableParams.put("sPaginationType", "full_numbers");
dataTableParams.put("iDisplayLength", getRowsPerPage());
dataTableParams.put("aLengthMenu", new JSONLiteral("[[" + getRowsPerPage()
+ "," + (getRowsPerPage() * 2) + "," + (getRowsPerPage() * 4) + "],["
+ getRowsPerPage() + "," + (getRowsPerPage() * 2) + ","
+ (getRowsPerPage() * 4) + "]]"));
//We set the bSortable parameters for each column. Cf : http://www.datatables.net/usage/columns
JSONArray sortableConfs = new JSONArray();
for(String propertyName : getPropertyNames()){
sortableConfs.put(new JSONObject(String.format("{'bSortable': %s}", getModel().get(propertyName).isSortable())));
}
dataTableParams.put("aoColumns", sortableConfs);
JSONObject language = new JSONObject();
language.put("sProcessing", messages.get("datatable.sProcessing"));
language.put("sLengthMenu", messages.get("datatable.sLengthMenu"));
language.put("sZeroRecords", messages.get("datatable.sZeroRecords"));
language.put("sEmptyTable", messages.get("datatable.sEmptyTable"));
language.put("sLoadingRecords", messages.get("datatable.sLoadingRecords"));
language.put("sInfo", messages.get("datatable.sInfo"));
language.put("sInfoEmpty", messages.get("datatable.sInfoEmpty"));
language.put("sInfoFiltered", messages.get("datatable.sInfoFiltered"));
language.put("sInfoPostFix", messages.get("datatable.sInfoPostFix"));
language.put("sSearch", messages.get("datatable.sSearch"));
language.put("sUrl", messages.get("datatable.sUrl"));
dataTableParams.put("oLanguage", language);
JQueryUtils.merge(dataTableParams, getOptions());
setup.put("params", dataTableParams);
support.addInitializerCall("dataTable", setup);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setJS" | "@AfterRender
void setJS() {
JSONObject setup = new JSONObject();
setup.put("id", getClientId());
JSONObject dataTableParams = new JSONObject();
if (getMode()) {
dataTableParams.put("sAjaxSource", resources.createEventLink("data").toAbsoluteURI());
dataTableParams.put("bServerSide", "true");
dataTableParams.put("bProcessing", "true");
}
dataTableParams.put("sPaginationType", "full_numbers");
dataTableParams.put("iDisplayLength", getRowsPerPage());
dataTableParams.put("aLengthMenu", new JSONLiteral("[[" + getRowsPerPage()
+ "," + (getRowsPerPage() * 2) + "," + (getRowsPerPage() * 4) + "],["
+ getRowsPerPage() + "," + (getRowsPerPage() * 2) + ","
+ (getRowsPerPage() * 4) + "]]"));
<MASK>JQueryUtils.merge(dataTableParams, getOptions());</MASK>
//We set the bSortable parameters for each column. Cf : http://www.datatables.net/usage/columns
JSONArray sortableConfs = new JSONArray();
for(String propertyName : getPropertyNames()){
sortableConfs.put(new JSONObject(String.format("{'bSortable': %s}", getModel().get(propertyName).isSortable())));
}
dataTableParams.put("aoColumns", sortableConfs);
JSONObject language = new JSONObject();
language.put("sProcessing", messages.get("datatable.sProcessing"));
language.put("sLengthMenu", messages.get("datatable.sLengthMenu"));
language.put("sZeroRecords", messages.get("datatable.sZeroRecords"));
language.put("sEmptyTable", messages.get("datatable.sEmptyTable"));
language.put("sLoadingRecords", messages.get("datatable.sLoadingRecords"));
language.put("sInfo", messages.get("datatable.sInfo"));
language.put("sInfoEmpty", messages.get("datatable.sInfoEmpty"));
language.put("sInfoFiltered", messages.get("datatable.sInfoFiltered"));
language.put("sInfoPostFix", messages.get("datatable.sInfoPostFix"));
language.put("sSearch", messages.get("datatable.sSearch"));
language.put("sUrl", messages.get("datatable.sUrl"));
dataTableParams.put("oLanguage", language);
setup.put("params", dataTableParams);
support.addInitializerCall("dataTable", setup);
}" |
Inversion-Mutation | megadiff | "public void paintComponent(Graphics g) {
Rectangle bounds = getBounds();
int width = (int) bounds.getWidth() - 1;
int height = (int) bounds.getHeight() - 1;
int min = toScreen(getLowValue());
int max = toScreen(getHighValue());
// Paint the full slider if the slider is marked as empty
if (empty) {
if (direction == LEFTRIGHT_TOPBOTTOM) {
min = ARROW_SZ;
max = (orientation == VERTICAL) ? (height - ARROW_SZ) : (width - ARROW_SZ);
} else {
min = (orientation == VERTICAL) ? (height - ARROW_SZ) : (width - ARROW_SZ);
max = ARROW_SZ;
}
}
Graphics2D g2 = (Graphics2D) g;
g2.setColor(getBackground());
g2.fillRect(0, 0, width, height);
g2.setColor(getForeground());
g2.setStroke(new BasicStroke(1));
g2.drawRect(0, 0, width, height);
customPaint(g2, width, height);
// Draw arrow and thumb backgrounds
if (orientation == VERTICAL) {
if (direction == LEFTRIGHT_TOPBOTTOM) {
g2.setColor(getForeground());
g2.fillRect(0, min - ARROW_SZ, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, min - ARROW_SZ, width, ARROW_SZ - 1);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(0, min, width, max - min - 1);
paint3DRectLighting(g2, 0, min, width, max - min - 1);
}
g2.setColor(getForeground());
g2.fillRect(0, max, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, max, width, ARROW_SZ - 1);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
min - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH,
ARROW_HEIGHT, true);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
max + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH, ARROW_HEIGHT, false);
} else {
g2.setColor(getForeground());
g2.fillRect(0, min, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, min, width, ARROW_SZ - 1);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(0, max, width, min - max - 1);
paint3DRectLighting(g2, 0, max, width, min - max - 1);
}
g2.setColor(getForeground());
g2.fillRect(0, max - ARROW_SZ, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, max - ARROW_SZ, width, ARROW_SZ - 1);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
min + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH, ARROW_HEIGHT, false);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
max - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH,
ARROW_HEIGHT, true);
}
} else {
if (direction == LEFTRIGHT_TOPBOTTOM) {
g2.setColor(getForeground());
g2.fillRect(min - ARROW_SZ, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, min - ARROW_SZ, 0, ARROW_SZ - 1, height);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(min, 0, max - min - 1, height);
paint3DRectLighting(g2, min, 0, max - min - 1, height);
}
g2.setColor(getForeground());
g2.fillRect(max, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, max, 0, ARROW_SZ - 1, height);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, min - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, true);
paintArrow(g2, max + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, false);
} else {
g2.setColor(getForeground());
g2.fillRect(min, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, min, 0, ARROW_SZ - 1, height);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(max, 0, min - max - 1, height);
paint3DRectLighting(g2, max, 0, min - max - 1, height);
}
g2.setColor(getForeground());
g2.fillRect(max - ARROW_SZ, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, max - ARROW_SZ, 0, ARROW_SZ - 1, height);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, min + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, true);
paintArrow(g2, max - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, false);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "paintComponent" | "public void paintComponent(Graphics g) {
Rectangle bounds = getBounds();
int width = (int) bounds.getWidth() - 1;
int height = (int) bounds.getHeight() - 1;
int min = toScreen(getLowValue());
int max = toScreen(getHighValue());
// Paint the full slider if the slider is marked as empty
if (empty) {
if (direction == LEFTRIGHT_TOPBOTTOM) {
min = ARROW_SZ;
max = (orientation == VERTICAL) ? (height - ARROW_SZ) : (width - ARROW_SZ);
} else {
min = (orientation == VERTICAL) ? (height - ARROW_SZ) : (width - ARROW_SZ);
max = ARROW_SZ;
}
}
Graphics2D g2 = (Graphics2D) g;
g2.setColor(getBackground());
g2.fillRect(0, 0, width, height);
g2.setColor(getForeground());
g2.drawRect(0, 0, width, height);
customPaint(g2, width, height);
// Draw arrow and thumb backgrounds
<MASK>g2.setStroke(new BasicStroke(1));</MASK>
if (orientation == VERTICAL) {
if (direction == LEFTRIGHT_TOPBOTTOM) {
g2.setColor(getForeground());
g2.fillRect(0, min - ARROW_SZ, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, min - ARROW_SZ, width, ARROW_SZ - 1);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(0, min, width, max - min - 1);
paint3DRectLighting(g2, 0, min, width, max - min - 1);
}
g2.setColor(getForeground());
g2.fillRect(0, max, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, max, width, ARROW_SZ - 1);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
min - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH,
ARROW_HEIGHT, true);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
max + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH, ARROW_HEIGHT, false);
} else {
g2.setColor(getForeground());
g2.fillRect(0, min, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, min, width, ARROW_SZ - 1);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(0, max, width, min - max - 1);
paint3DRectLighting(g2, 0, max, width, min - max - 1);
}
g2.setColor(getForeground());
g2.fillRect(0, max - ARROW_SZ, width, ARROW_SZ - 1);
paint3DRectLighting(g2, 0, max - ARROW_SZ, width, ARROW_SZ - 1);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
min + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH, ARROW_HEIGHT, false);
paintArrow(g2, (width - ARROW_WIDTH) / 2.0,
max - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0), ARROW_WIDTH,
ARROW_HEIGHT, true);
}
} else {
if (direction == LEFTRIGHT_TOPBOTTOM) {
g2.setColor(getForeground());
g2.fillRect(min - ARROW_SZ, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, min - ARROW_SZ, 0, ARROW_SZ - 1, height);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(min, 0, max - min - 1, height);
paint3DRectLighting(g2, min, 0, max - min - 1, height);
}
g2.setColor(getForeground());
g2.fillRect(max, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, max, 0, ARROW_SZ - 1, height);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, min - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, true);
paintArrow(g2, max + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, false);
} else {
g2.setColor(getForeground());
g2.fillRect(min, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, min, 0, ARROW_SZ - 1, height);
if (thumbColor != null) {
g2.setColor(thumbColor);
g2.fillRect(max, 0, min - max - 1, height);
paint3DRectLighting(g2, max, 0, min - max - 1, height);
}
g2.setColor(getForeground());
g2.fillRect(max - ARROW_SZ, 0, ARROW_SZ - 1, height);
paint3DRectLighting(g2, max - ARROW_SZ, 0, ARROW_SZ - 1, height);
// Draw arrows
g2.setColor(Color.black);
paintArrow(g2, min + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, true);
paintArrow(g2, max - ARROW_SZ + ((ARROW_SZ - ARROW_HEIGHT) / 2.0),
(height - ARROW_WIDTH) / 2.0, ARROW_HEIGHT, ARROW_WIDTH, false);
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
}
registerForContextMenu(mList);
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
<MASK>registerForContextMenu(mList);</MASK>
}
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}" |
Inversion-Mutation | megadiff | "public void testBuildIndex() {
try {
indexBuilder.startup();
// run buildIndex
indexBuilder.doCommand(new IndexAllCommand(), new IndexBuilderListener() {
public void buildSuccess(IndexBuilderEvent event) {
try {
// now query the index for the stuff that is in the test DB
SolrQuery q = new SolrQuery("*:*");
q.setRows(10);
q.setFields("");
q.addSortField("id", SolrQuery.ORDER.asc);
QueryResponse queryResponse = exptServer.query(q);
SolrDocumentList documentList = queryResponse.getResults();
if (documentList == null || documentList.size() < 1) {
fail("No experiments available");
}
// just check we have 2 experiments - as this is the number in our dataset
int expected = getDataSet().getTable("A2_EXPERIMENT").getRowCount();
int actual = documentList.size();
assertEquals("Wrong number of docs: expected " + expected +
", actual " + actual, expected, actual);
} catch (Exception e) {
fail();
} finally {
buildFinished = true;
}
}
public void buildError(IndexBuilderEvent event) {
buildFinished = true;
fail();
}
public void buildProgress(String progressStatus) {}
});
while(buildFinished != true) {
synchronized(this) { wait(100); };
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testBuildIndex" | "public void testBuildIndex() {
try {
indexBuilder.startup();
// run buildIndex
indexBuilder.doCommand(new IndexAllCommand(), new IndexBuilderListener() {
public void buildSuccess(IndexBuilderEvent event) {
try {
// now query the index for the stuff that is in the test DB
SolrQuery q = new SolrQuery("*:*");
q.setRows(10);
q.setFields("");
q.addSortField("id", SolrQuery.ORDER.asc);
QueryResponse queryResponse = exptServer.query(q);
SolrDocumentList documentList = queryResponse.getResults();
if (documentList == null || documentList.size() < 1) {
fail("No experiments available");
}
// just check we have 2 experiments - as this is the number in our dataset
int expected = getDataSet().getTable("A2_EXPERIMENT").getRowCount();
int actual = documentList.size();
assertEquals("Wrong number of docs: expected " + expected +
", actual " + actual, expected, actual);
} catch (Exception e) {
<MASK>fail();</MASK>
} finally {
buildFinished = true;
}
}
public void buildError(IndexBuilderEvent event) {
<MASK>fail();</MASK>
buildFinished = true;
}
public void buildProgress(String progressStatus) {}
});
while(buildFinished != true) {
synchronized(this) { wait(100); };
}
}
catch (Exception e) {
e.printStackTrace();
<MASK>fail();</MASK>
}
}" |
Inversion-Mutation | megadiff | "public void buildError(IndexBuilderEvent event) {
buildFinished = true;
fail();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildError" | "public void buildError(IndexBuilderEvent event) {
<MASK>fail();</MASK>
buildFinished = true;
}" |
Inversion-Mutation | megadiff | "private OnClickListener createOnClickVignetteButton() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
hideImageViews();
mImageShow.setVisibility(View.VISIBLE);
mImageShow.setShowControls(true);
ImagePreset preset = mImageShow.getImagePreset();
ImageFilter filter = preset.getFilter("Vignette");
if (filter == null) {
ImageFilterVignette vignette = new ImageFilterVignette();
ImagePreset copy = new ImagePreset(preset);
copy.add(vignette);
copy.setHistoryName(vignette.name());
copy.setIsFx(false);
filter = copy.getFilter("Vignette");
mImageShow.setImagePreset(copy);
}
mImageShow.setCurrentFilter(filter);
unselectPanelButtons(mColorsPanelButtons);
mVignetteButton.setSelected(true);
invalidateViews();
}
};
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createOnClickVignetteButton" | "private OnClickListener createOnClickVignetteButton() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
hideImageViews();
mImageShow.setVisibility(View.VISIBLE);
mImageShow.setShowControls(true);
ImagePreset preset = mImageShow.getImagePreset();
ImageFilter filter = preset.getFilter("Vignette");
if (filter == null) {
ImageFilterVignette vignette = new ImageFilterVignette();
ImagePreset copy = new ImagePreset(preset);
copy.add(vignette);
copy.setHistoryName(vignette.name());
copy.setIsFx(false);
filter = copy.getFilter("Vignette");
mImageShow.setImagePreset(copy);
<MASK>mImageShow.setCurrentFilter(filter);</MASK>
}
unselectPanelButtons(mColorsPanelButtons);
mVignetteButton.setSelected(true);
invalidateViews();
}
};
}" |
Inversion-Mutation | megadiff | "@Override
public void onClick(View v) {
hideImageViews();
mImageShow.setVisibility(View.VISIBLE);
mImageShow.setShowControls(true);
ImagePreset preset = mImageShow.getImagePreset();
ImageFilter filter = preset.getFilter("Vignette");
if (filter == null) {
ImageFilterVignette vignette = new ImageFilterVignette();
ImagePreset copy = new ImagePreset(preset);
copy.add(vignette);
copy.setHistoryName(vignette.name());
copy.setIsFx(false);
filter = copy.getFilter("Vignette");
mImageShow.setImagePreset(copy);
}
mImageShow.setCurrentFilter(filter);
unselectPanelButtons(mColorsPanelButtons);
mVignetteButton.setSelected(true);
invalidateViews();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onClick" | "@Override
public void onClick(View v) {
hideImageViews();
mImageShow.setVisibility(View.VISIBLE);
mImageShow.setShowControls(true);
ImagePreset preset = mImageShow.getImagePreset();
ImageFilter filter = preset.getFilter("Vignette");
if (filter == null) {
ImageFilterVignette vignette = new ImageFilterVignette();
ImagePreset copy = new ImagePreset(preset);
copy.add(vignette);
copy.setHistoryName(vignette.name());
copy.setIsFx(false);
filter = copy.getFilter("Vignette");
mImageShow.setImagePreset(copy);
<MASK>mImageShow.setCurrentFilter(filter);</MASK>
}
unselectPanelButtons(mColorsPanelButtons);
mVignetteButton.setSelected(true);
invalidateViews();
}" |
Inversion-Mutation | megadiff | "public Key createGroupPublicKey(GroupManager manager, MembershipList ml)
throws ContentEncodingException, IOException, ConfigurationException, InvalidKeyException, InvalidCipherTextException {
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(manager.getGroupKeyAlgorithm());
} catch (NoSuchAlgorithmException e) {
if (manager.getGroupKeyAlgorithm().equals(AccessControlManager.DEFAULT_GROUP_KEY_ALGORITHM)) {
Log.severe("Cannot find default group public key algorithm: " + AccessControlManager.DEFAULT_GROUP_KEY_ALGORITHM + ": " + e.getMessage());
throw new RuntimeException("Cannot find default group public key algorithm: " + AccessControlManager.DEFAULT_GROUP_KEY_ALGORITHM + ": " + e.getMessage());
}
throw new ConfigurationException("Specified group public key algorithm " + manager.getGroupKeyAlgorithm() + " not found. " + e.getMessage());
}
kpg.initialize(AccessControlManager.DEFAULT_GROUP_KEY_LENGTH);
KeyPair pair = kpg.generateKeyPair();
_groupPublicKey =
new PublicKeyObject(
AccessControlProfile.groupPublicKeyName(_groupNamespace, _groupFriendlyName),
pair.getPublic(),
_handle);
_groupPublicKey.saveToRepository();
_groupPublicKey.updateInBackground(true);
stopPrivateKeyDirectoryEnumeration();
_privKeyDirectory = null;
KeyDirectory newPrivateKeyDirectory = privateKeyDirectory(manager.getAccessManager()); // takes from new public key
Key privateKeyWrappingKey = WrappedKey.generateNonceKey();
try {
// write the private key
newPrivateKeyDirectory.addPrivateKeyBlock(pair.getPrivate(), privateKeyWrappingKey);
} catch (InvalidKeyException e) {
Log.warning("Unexpected -- InvalidKeyException wrapping key with keys we just generated! " + e.getMessage());
throw e;
}
// Wrap the private key in the public keys of all the members of the group
updateGroupPublicKey(manager, privateKeyWrappingKey, ml.membershipList().contents());
return privateKeyWrappingKey;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createGroupPublicKey" | "public Key createGroupPublicKey(GroupManager manager, MembershipList ml)
throws ContentEncodingException, IOException, ConfigurationException, InvalidKeyException, InvalidCipherTextException {
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(manager.getGroupKeyAlgorithm());
} catch (NoSuchAlgorithmException e) {
if (manager.getGroupKeyAlgorithm().equals(AccessControlManager.DEFAULT_GROUP_KEY_ALGORITHM)) {
Log.severe("Cannot find default group public key algorithm: " + AccessControlManager.DEFAULT_GROUP_KEY_ALGORITHM + ": " + e.getMessage());
throw new RuntimeException("Cannot find default group public key algorithm: " + AccessControlManager.DEFAULT_GROUP_KEY_ALGORITHM + ": " + e.getMessage());
}
throw new ConfigurationException("Specified group public key algorithm " + manager.getGroupKeyAlgorithm() + " not found. " + e.getMessage());
}
kpg.initialize(AccessControlManager.DEFAULT_GROUP_KEY_LENGTH);
KeyPair pair = kpg.generateKeyPair();
_groupPublicKey =
new PublicKeyObject(
AccessControlProfile.groupPublicKeyName(_groupNamespace, _groupFriendlyName),
pair.getPublic(),
_handle);
<MASK>_groupPublicKey.updateInBackground(true);</MASK>
_groupPublicKey.saveToRepository();
stopPrivateKeyDirectoryEnumeration();
_privKeyDirectory = null;
KeyDirectory newPrivateKeyDirectory = privateKeyDirectory(manager.getAccessManager()); // takes from new public key
Key privateKeyWrappingKey = WrappedKey.generateNonceKey();
try {
// write the private key
newPrivateKeyDirectory.addPrivateKeyBlock(pair.getPrivate(), privateKeyWrappingKey);
} catch (InvalidKeyException e) {
Log.warning("Unexpected -- InvalidKeyException wrapping key with keys we just generated! " + e.getMessage());
throw e;
}
// Wrap the private key in the public keys of all the members of the group
updateGroupPublicKey(manager, privateKeyWrappingKey, ml.membershipList().contents());
return privateKeyWrappingKey;
}" |
Inversion-Mutation | megadiff | "public float[] progressToday(TreeSet<Object[]> counts, Card card, boolean eta) {
try {
int doneCurrent = 0;
int[] leftCurrent = new int[]{0, 0, 0};
String[] cs = new String[]{"new", "lrn", "rev"};
long currentDid = 0;
// refresh deck progresses with fresh counts if necessary
if (counts != null || mCachedDeckCounts == null) {
if (mCachedDeckCounts == null) {
mCachedDeckCounts = new HashMap<Long, Pair<String[], long[]>>();
}
mCachedDeckCounts.clear();
if (counts == null) {
// reload counts
counts = (TreeSet<Object[]>)deckCounts()[0];
}
for (Object[] d : counts) {
int done = 0;
JSONObject deck = mCol.getDecks().get((Long) d[1]);
for (String s : cs) {
done += deck.getJSONArray(s + "Today").getInt(1);
}
mCachedDeckCounts.put((Long)d[1], new Pair<String[], long[]> ((String[])d[0], new long[]{done, (Integer)d[2], (Integer)d[3], (Integer)d[4]}));
}
}
// current selected deck
if (card != null) {
JSONObject deck = mCol.getDecks().current();
currentDid = deck.getLong("id");
for (String s : cs) {
doneCurrent += deck.getJSONArray(s + "Today").getInt(1);
}
int idx = countIdx(card);
leftCurrent = new int[]{ mNewCount + (idx == 1 ? 0 : 1), mLrnCount + (idx == 1 ? card.getLeft() / 1000 : 0), mRevCount + (idx == 1 ? 0 : 1)};
}
int doneAll = 0;
int[] leftAll = new int[]{0, 0, 0};
for (Map.Entry<Long, Pair<String[], long[]>> d : mCachedDeckCounts.entrySet()) {
boolean exclude = d.getKey() == currentDid; // || mCol.getDecks().isDyn(d.getKey());
if (d.getValue().first.length == 1) {
if (exclude) {
// don't count cached version of current deck
continue;
}
long[] c = d.getValue().second;
doneAll += c[0];
leftAll[0] += c[1];
leftAll[1] += c[2];
leftAll[2] += c[3];
} else if (exclude) {
// exclude cached values for current deck in order to avoid double count
long[] c = d.getValue().second;
doneAll -= c[0];
leftAll[0] -= c[1];
leftAll[1] -= c[2];
leftAll[2] -= c[3];
}
}
doneAll += doneCurrent;
leftAll[0] += leftCurrent[0];
leftAll[1] += leftCurrent[1];
leftAll[2] += leftCurrent[2];
int totalAll = doneAll + leftAll[0] + leftAll[1] + leftAll[2];
int totalCurrent = doneCurrent + leftCurrent[0] + leftCurrent[1] + leftCurrent[2];
float progressCurrent = -1;
if (totalCurrent != 0) {
progressCurrent = (float) doneCurrent / (float) totalCurrent;
}
float progressTotal = -1;
if (totalAll != 0) {
progressTotal = (float) doneAll / (float) totalAll;
}
return new float[]{ progressCurrent, progressTotal, totalAll - doneAll, eta ? eta(leftAll, false) : -1};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "progressToday" | "public float[] progressToday(TreeSet<Object[]> counts, Card card, boolean eta) {
try {
int doneCurrent = 0;
int[] leftCurrent = new int[]{0, 0, 0};
String[] cs = new String[]{"new", "lrn", "rev"};
long currentDid = 0;
// refresh deck progresses with fresh counts if necessary
if (counts != null || mCachedDeckCounts == null) {
if (mCachedDeckCounts == null) {
mCachedDeckCounts = new HashMap<Long, Pair<String[], long[]>>();
}
mCachedDeckCounts.clear();
if (counts == null) {
// reload counts
counts = (TreeSet<Object[]>)deckCounts()[0];
}
<MASK>int done = 0;</MASK>
for (Object[] d : counts) {
JSONObject deck = mCol.getDecks().get((Long) d[1]);
for (String s : cs) {
done += deck.getJSONArray(s + "Today").getInt(1);
}
mCachedDeckCounts.put((Long)d[1], new Pair<String[], long[]> ((String[])d[0], new long[]{done, (Integer)d[2], (Integer)d[3], (Integer)d[4]}));
}
}
// current selected deck
if (card != null) {
JSONObject deck = mCol.getDecks().current();
currentDid = deck.getLong("id");
for (String s : cs) {
doneCurrent += deck.getJSONArray(s + "Today").getInt(1);
}
int idx = countIdx(card);
leftCurrent = new int[]{ mNewCount + (idx == 1 ? 0 : 1), mLrnCount + (idx == 1 ? card.getLeft() / 1000 : 0), mRevCount + (idx == 1 ? 0 : 1)};
}
int doneAll = 0;
int[] leftAll = new int[]{0, 0, 0};
for (Map.Entry<Long, Pair<String[], long[]>> d : mCachedDeckCounts.entrySet()) {
boolean exclude = d.getKey() == currentDid; // || mCol.getDecks().isDyn(d.getKey());
if (d.getValue().first.length == 1) {
if (exclude) {
// don't count cached version of current deck
continue;
}
long[] c = d.getValue().second;
doneAll += c[0];
leftAll[0] += c[1];
leftAll[1] += c[2];
leftAll[2] += c[3];
} else if (exclude) {
// exclude cached values for current deck in order to avoid double count
long[] c = d.getValue().second;
doneAll -= c[0];
leftAll[0] -= c[1];
leftAll[1] -= c[2];
leftAll[2] -= c[3];
}
}
doneAll += doneCurrent;
leftAll[0] += leftCurrent[0];
leftAll[1] += leftCurrent[1];
leftAll[2] += leftCurrent[2];
int totalAll = doneAll + leftAll[0] + leftAll[1] + leftAll[2];
int totalCurrent = doneCurrent + leftCurrent[0] + leftCurrent[1] + leftCurrent[2];
float progressCurrent = -1;
if (totalCurrent != 0) {
progressCurrent = (float) doneCurrent / (float) totalCurrent;
}
float progressTotal = -1;
if (totalAll != 0) {
progressTotal = (float) doneAll / (float) totalAll;
}
return new float[]{ progressCurrent, progressTotal, totalAll - doneAll, eta ? eta(leftAll, false) : -1};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}" |
Inversion-Mutation | megadiff | "private ContextGuard(PyObject manager) {
__exit__method = manager.__getattr__("__exit__");
__enter__method = manager.__getattr__("__enter__");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "ContextGuard" | "private ContextGuard(PyObject manager) {
<MASK>__enter__method = manager.__getattr__("__enter__");</MASK>
__exit__method = manager.__getattr__("__exit__");
}" |
Inversion-Mutation | megadiff | "public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player) sender;
World world = player.getWorld();
this.deathMessage = "boom";
if(commandLabel.equalsIgnoreCase("smite")) {
if(args.length == 0) {
Block targetblock = player.getTargetBlock(null, 50);
Location location = targetblock.getLocation();
world.strikeLightning(location);
//get "blast-radius" config, defualt to 10 if none set. Thanks to morganm for the help :) no good deed goes un-noticed
int radius = getConfig().getInt("blast-radius", 10);
world.createExplosion(location, radius);
//To spawn a creeper no idea how this will work.. Will eventually include a var in the config.
world.spawnCreature(location, org.bukkit.entity.EntityType.CREEPER);
world.spawnCreature(location, org.bukkit.entity.EntityType.PIG_ZOMBIE);
//next line is for the player variable. /smite [playername] ~added in V1.0
} else if (args.length == 1) {
if(player.getServer().getPlayer(args[0]) != null) {
Player targetplayer = player.getServer().getPlayer(args[0]);
Location location = targetplayer.getLocation();
world.strikeLightning(location);
//get "blast-player" config, defualt to 0 if none set, set 0 to create no explosion. Thanks to morganm for the help :) no good deed goes un-noticed
int radius = getConfig().getInt("blast-player", 0);
world.createExplosion(location, radius);
//Spawns pig zombie ~Comp ~Added in V3.0
world.spawnCreature(location, org.bukkit.entity.EntityType.PIG_ZOMBIE);
//Shows spawner effect ~Comp ~Added in V3.0
world.playEffect(location, Effect.MOBSPAWNER_FLAMES, 0);
player.sendMessage(ChatColor.GRAY + "Smiting Player " + targetplayer.getDisplayName());
getServer().broadcastMessage(getName());
} else {
player.sendMessage(ChatColor.RED + "Error: The player is offline please use a different player. ");
}
} else if (args.length > 1) {
player.sendMessage(ChatColor.RED + "Error: Too Many Args!");
}
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCommand" | "public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player) sender;
World world = player.getWorld();
this.deathMessage = "boom";
if(commandLabel.equalsIgnoreCase("smite")) {
if(args.length == 0) {
Block targetblock = player.getTargetBlock(null, 50);
Location location = targetblock.getLocation();
world.strikeLightning(location);
//get "blast-radius" config, defualt to 10 if none set. Thanks to morganm for the help :) no good deed goes un-noticed
int radius = getConfig().getInt("blast-radius", 10);
world.createExplosion(location, radius);
//To spawn a creeper no idea how this will work.. Will eventually include a var in the config.
world.spawnCreature(location, org.bukkit.entity.EntityType.CREEPER);
world.spawnCreature(location, org.bukkit.entity.EntityType.PIG_ZOMBIE);
//next line is for the player variable. /smite [playername] ~added in V1.0
} else if (args.length == 1) {
if(player.getServer().getPlayer(args[0]) != null) {
Player targetplayer = player.getServer().getPlayer(args[0]);
Location location = targetplayer.getLocation();
world.strikeLightning(location);
//get "blast-player" config, defualt to 0 if none set, set 0 to create no explosion. Thanks to morganm for the help :) no good deed goes un-noticed
int radius = getConfig().getInt("blast-player", 0);
world.createExplosion(location, radius);
//Spawns pig zombie ~Comp ~Added in V3.0
world.spawnCreature(location, org.bukkit.entity.EntityType.PIG_ZOMBIE);
//Shows spawner effect ~Comp ~Added in V3.0
world.playEffect(location, Effect.MOBSPAWNER_FLAMES, 0);
player.sendMessage(ChatColor.GRAY + "Smiting Player " + targetplayer.getDisplayName());
} else {
player.sendMessage(ChatColor.RED + "Error: The player is offline please use a different player. ");
<MASK>getServer().broadcastMessage(getName());</MASK>
}
} else if (args.length > 1) {
player.sendMessage(ChatColor.RED + "Error: Too Many Args!");
}
}
return false;
}" |
Inversion-Mutation | megadiff | "public LinkerModule(InputStream in, ErrorHandler error) {
// scan wrap
Scanner read = new Scanner(in);
ScanWrap reader = new ScanWrap(read, error);
//String used for name
String ender = "";
//Number of records
int mod = 0;
int link = 0;
int text = 0;
//value checking
boolean isValid = true;
boolean add = true;
//checks for an H
String check = reader.readString(ScanWrap.notcolon, "loaderNoHeader");
if (!reader.go("disreguard"))
return;
//Runs through header record
if (check.equalsIgnoreCase("H")) {
this.progName = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
this.loadAddr = reader.readInt(ScanWrap.hex4, "loaderHNoAddr", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.loadAddr);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.prgTotalLen = reader
.readInt(ScanWrap.hex4, "loaderHNoPrL", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.prgTotalLen);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.execStart = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.execStart);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.date = reader.readString(ScanWrap.datep, "loaderHNoDate");
if (!reader.go("disreguard"))
return;
this.version = reader.readInt(ScanWrap.dec4, "loaderHNoVer", 10);
if (!reader.go("disreguard"))
return;
reader.readString(ScanWrap.notcolon, "loaderHNoLLMM");
if (!reader.go("disreguard"))
return;
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
}else{
error.reportError(makeError("loaderNoHeader"),0,0);
return;
}
//checks for L or T record
check = reader.readString(ScanWrap.notcolon, "");
if (!reader.go("disreguard"))
return;
//loops to get all the L and T records from object file
while (check.equals("L") || check.equals("T")) {
TextModRecord theRecordsForTextMod = new TextModRecord();
String entryLabel = "";
int entryAddr = 0;
//gets all information from linker record
if (check.equals("L")) {
link++;
entryLabel = reader.readString(ScanWrap.notcolon, "");
if (!reader.go("disreguard"))
return;
entryAddr = reader.readInt(ScanWrap.hex4, "loaderNoEXS",
16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(entryAddr);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
linkRecord.put(entryLabel, entryAddr);
check = reader.readString(ScanWrap.notcolon, "invalidRecord");
if (!reader.go("disreguard"))
return;
//gets all information out of Text record
} else if (check.equals("T")) {
text++;
theRecordsForTextMod.text.assignedLC = reader.readInt(ScanWrap.hex4, "textLC", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(theRecordsForTextMod.text.assignedLC);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
theRecordsForTextMod.text.instrData = reader.readString(ScanWrap.notcolon, "textData");
if (!reader.go("disreguard"))
return;
theRecordsForTextMod.text.flagHigh = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0);
if (!reader.go("disreguard"))
return;
if(!(theRecordsForTextMod.text.flagHigh == 'A' || theRecordsForTextMod.text.flagHigh == 'R' || theRecordsForTextMod.text.flagHigh == 'E' || theRecordsForTextMod.text.flagHigh == 'C')){
error.reportError(makeError("modHLS"), 0, 0);
add = false;
}
theRecordsForTextMod.text.flagLow = reader.readString(ScanWrap.notcolon, "textStatus")
.charAt(0);
if (!reader.go("disreguard"))
return;
if(!(theRecordsForTextMod.text.flagLow == 'A' || theRecordsForTextMod.text.flagLow == 'R' || theRecordsForTextMod.text.flagLow == 'E' || theRecordsForTextMod.text.flagLow == 'C')){
error.reportError(makeError("modHLS"), 0, 0);
add = false;
}
theRecordsForTextMod.text.modHigh = reader.readInt(ScanWrap.notcolon, "textMod", 16);
if (!reader.go("disreguard"))
return;
//check for mod high
if(theRecordsForTextMod.text.modHigh>16 || theRecordsForTextMod.text.modHigh<0)
{
error.reportError(makeError("invalidMods"),0,0);
return;
}
theRecordsForTextMod.text.modLow = reader.readInt(ScanWrap.notcolon, "textMod", 16);
if (!reader.go("disreguard"))
return;
//check for mod low
if(theRecordsForTextMod.text.modLow>16 || theRecordsForTextMod.text.modLow<0)
{
error.reportError(makeError("invalidMods"),0,0);
return;
}
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
check = reader.readString(ScanWrap.notcolon, "invalidRecord");
if (!reader.go("disreguard"))
return;
//gets all mod records for a text record
while (check.equals("M")) {
ModRecord modification = new ModRecord();
mod++;
modification.hex = reader.readInt(ScanWrap.hex4, "modHex", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(modification.hex);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
boolean run = true;
String loop = "";
boolean firstRun = true;
while (run) {
MiddleMod midtemp = new MiddleMod();
if(firstRun){
midtemp.plusMin = reader.readString(ScanWrap.notcolon,
"modPm").charAt(0);
firstRun=false;
}else{
midtemp.plusMin = loop.charAt(0);
}
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidPlusMin(midtemp.plusMin);
if(!isValid){
error.reportError(makeError("invalidPlus"),0,0);
return;
}
midtemp.addrType = reader.readString(ScanWrap.notcolon,
"modFlag").charAt(0);
if (!reader.go("disreguard"))
return;
if(!(midtemp.addrType == 'E' || midtemp.addrType == 'R' || midtemp.addrType == 'N')){
error.reportError(makeError("modFlag"), 0, 0);
add = false;
}
midtemp.linkerLabel = reader.readString(
ScanWrap.notcolon, "modLink");
if (!reader.go("disreguard"))
return;
loop = reader.readString(ScanWrap.notcolon, "modHLS");
if (!reader.go("disreguard"))
return;
if (loop.equals("")) {
run = false;
}
modification.midMod.add(midtemp);
}
loop = reader.readString(ScanWrap.notcolon, "modHLS");
if (!reader.go("disreguard"))
return;
modification.HLS = loop.charAt(0);
if(!(modification.HLS == 'H' || modification.HLS == 'L' || modification.HLS == 'S')){
error.reportError(makeError("modHLS"), 0, 0);
add = false;
}
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
theRecordsForTextMod.mods.add(modification);
check = reader.readString(ScanWrap.notcolon, "invalidRecord");
if (!reader.go("disreguard"))
return;
}// end of mod record
if(add){
textMod.add(theRecordsForTextMod);
}else{
add = true;
}
}// end of text record
}//end of while loop checking for linking records and text records
//checks for an end record
if (check.equals("E")) {
this.endRec = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endRec);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.endLink = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endLink);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.endText = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endText);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.endMod = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endMod);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
}else{
error.reportError(makeError("loaderNoEnd"),0,0);
return;
}
//warnings for amount of mod text and link records
if(link != this.endLink){
error.reportWarning(makeError("linkMatch"), 0, 0);
}else if(text != this.endText){
error.reportWarning(makeError("textMatch"), 0, 0);
}else if(mod != this.endMod){
error.reportWarning(makeError("modMatch"), 0, 0);
}else if((link+text+mod+2) != this.endRec){
error.reportWarning(makeError("totalMatch"), 0, 0);
}
//program ran successful. Checks for more in file
this.success = true;
if (read.hasNext()) {
this.done = false;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "LinkerModule" | "public LinkerModule(InputStream in, ErrorHandler error) {
// scan wrap
Scanner read = new Scanner(in);
ScanWrap reader = new ScanWrap(read, error);
//String used for name
String ender = "";
//Number of records
int mod = 0;
int link = 0;
int text = 0;
//value checking
boolean isValid = true;
boolean add = true;
//checks for an H
String check = reader.readString(ScanWrap.notcolon, "loaderNoHeader");
if (!reader.go("disreguard"))
return;
//Runs through header record
if (check.equalsIgnoreCase("H")) {
this.progName = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
this.loadAddr = reader.readInt(ScanWrap.hex4, "loaderHNoAddr", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.loadAddr);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.prgTotalLen = reader
.readInt(ScanWrap.hex4, "loaderHNoPrL", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.prgTotalLen);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.execStart = reader.readInt(ScanWrap.hex4, "loaderNoEXS", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.execStart);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.date = reader.readString(ScanWrap.datep, "loaderHNoDate");
if (!reader.go("disreguard"))
return;
this.version = reader.readInt(ScanWrap.dec4, "loaderHNoVer", 10);
if (!reader.go("disreguard"))
return;
reader.readString(ScanWrap.notcolon, "loaderHNoLLMM");
if (!reader.go("disreguard"))
return;
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
}else{
error.reportError(makeError("loaderNoHeader"),0,0);
return;
}
//checks for L or T record
check = reader.readString(ScanWrap.notcolon, "");
if (!reader.go("disreguard"))
return;
//loops to get all the L and T records from object file
while (check.equals("L") || check.equals("T")) {
TextModRecord theRecordsForTextMod = new TextModRecord();
String entryLabel = "";
int entryAddr = 0;
//gets all information from linker record
if (check.equals("L")) {
link++;
entryLabel = reader.readString(ScanWrap.notcolon, "");
if (!reader.go("disreguard"))
return;
entryAddr = reader.readInt(ScanWrap.hex4, "loaderNoEXS",
16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(entryAddr);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
linkRecord.put(entryLabel, entryAddr);
check = reader.readString(ScanWrap.notcolon, "invalidRecord");
if (!reader.go("disreguard"))
return;
//gets all information out of Text record
} else if (check.equals("T")) {
text++;
theRecordsForTextMod.text.assignedLC = reader.readInt(ScanWrap.hex4, "textLC", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(theRecordsForTextMod.text.assignedLC);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
theRecordsForTextMod.text.instrData = reader.readString(ScanWrap.notcolon, "textData");
if (!reader.go("disreguard"))
return;
theRecordsForTextMod.text.flagHigh = reader.readString(ScanWrap.notcolon, "textStatus").charAt(0);
if (!reader.go("disreguard"))
return;
if(!(theRecordsForTextMod.text.flagHigh == 'A' || theRecordsForTextMod.text.flagHigh == 'R' || theRecordsForTextMod.text.flagHigh == 'E' || theRecordsForTextMod.text.flagHigh == 'C')){
error.reportError(makeError("modHLS"), 0, 0);
add = false;
}
theRecordsForTextMod.text.flagLow = reader.readString(ScanWrap.notcolon, "textStatus")
.charAt(0);
if (!reader.go("disreguard"))
return;
if(!(theRecordsForTextMod.text.flagLow == 'A' || theRecordsForTextMod.text.flagLow == 'R' || theRecordsForTextMod.text.flagLow == 'E' || theRecordsForTextMod.text.flagLow == 'C')){
error.reportError(makeError("modHLS"), 0, 0);
add = false;
}
theRecordsForTextMod.text.modHigh = reader.readInt(ScanWrap.notcolon, "textMod", 16);
if (!reader.go("disreguard"))
return;
//check for mod high
if(theRecordsForTextMod.text.modHigh>16 || theRecordsForTextMod.text.modHigh<0)
{
error.reportError(makeError("invalidMods"),0,0);
return;
}
theRecordsForTextMod.text.modLow = reader.readInt(ScanWrap.notcolon, "textMod", 16);
if (!reader.go("disreguard"))
return;
//check for mod low
if(theRecordsForTextMod.text.modLow>16 || theRecordsForTextMod.text.modLow<0)
{
error.reportError(makeError("invalidMods"),0,0);
return;
}
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
check = reader.readString(ScanWrap.notcolon, "invalidRecord");
if (!reader.go("disreguard"))
return;
//gets all mod records for a text record
while (check.equals("M")) {
<MASK>MiddleMod midtemp = new MiddleMod();</MASK>
ModRecord modification = new ModRecord();
mod++;
modification.hex = reader.readInt(ScanWrap.hex4, "modHex", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(modification.hex);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
boolean run = true;
String loop = "";
boolean firstRun = true;
while (run) {
if(firstRun){
midtemp.plusMin = reader.readString(ScanWrap.notcolon,
"modPm").charAt(0);
firstRun=false;
}else{
midtemp.plusMin = loop.charAt(0);
}
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidPlusMin(midtemp.plusMin);
if(!isValid){
error.reportError(makeError("invalidPlus"),0,0);
return;
}
midtemp.addrType = reader.readString(ScanWrap.notcolon,
"modFlag").charAt(0);
if (!reader.go("disreguard"))
return;
if(!(midtemp.addrType == 'E' || midtemp.addrType == 'R' || midtemp.addrType == 'N')){
error.reportError(makeError("modFlag"), 0, 0);
add = false;
}
midtemp.linkerLabel = reader.readString(
ScanWrap.notcolon, "modLink");
if (!reader.go("disreguard"))
return;
loop = reader.readString(ScanWrap.notcolon, "modHLS");
if (!reader.go("disreguard"))
return;
if (loop.equals("")) {
run = false;
}
modification.midMod.add(midtemp);
}
loop = reader.readString(ScanWrap.notcolon, "modHLS");
if (!reader.go("disreguard"))
return;
modification.HLS = loop.charAt(0);
if(!(modification.HLS == 'H' || modification.HLS == 'L' || modification.HLS == 'S')){
error.reportError(makeError("modHLS"), 0, 0);
add = false;
}
// some kind of error checking
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
theRecordsForTextMod.mods.add(modification);
check = reader.readString(ScanWrap.notcolon, "invalidRecord");
if (!reader.go("disreguard"))
return;
}// end of mod record
if(add){
textMod.add(theRecordsForTextMod);
}else{
add = true;
}
}// end of text record
}//end of while loop checking for linking records and text records
//checks for an end record
if (check.equals("E")) {
this.endRec = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endRec);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.endLink = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endLink);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.endText = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endText);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
this.endMod = reader.readInt(ScanWrap.hex4, "endRecords", 16);
if (!reader.go("disreguard"))
return;
//error checking
isValid = OperandChecker.isValidMem(this.endMod);
if(!isValid){
error.reportError(makeError("invalidValue"),0,0);
return;
}
ender = reader.readString(ScanWrap.notcolon, "loaderNoName");
if (!reader.go("disreguard"))
return;
if(!ender.equals(this.progName)){
error.reportWarning(makeError("noMatch"), 0, 0);
}
}else{
error.reportError(makeError("loaderNoEnd"),0,0);
return;
}
//warnings for amount of mod text and link records
if(link != this.endLink){
error.reportWarning(makeError("linkMatch"), 0, 0);
}else if(text != this.endText){
error.reportWarning(makeError("textMatch"), 0, 0);
}else if(mod != this.endMod){
error.reportWarning(makeError("modMatch"), 0, 0);
}else if((link+text+mod+2) != this.endRec){
error.reportWarning(makeError("totalMatch"), 0, 0);
}
//program ran successful. Checks for more in file
this.success = true;
if (read.hasNext()) {
this.done = false;
}
}" |
Inversion-Mutation | megadiff | "private GeometryCollection generateSearchGeomCollection() {
int collectionSize = 0;
for (final GeomWrapper gw : geomWrappers) {
if (gw.isSelected()) {
collectionSize++;
}
}
final Geometry[] geoms = new Geometry[collectionSize];
final int buffer = jsGeomBuffer.getValue();
int i = 0;
GeometryFactory gf = null;
for (final GeomWrapper gw : geomWrappers) {
if (gw.isSelected()) {
Geometry g = gw.getGeometry();
if (buffer != 0) {
g = g.buffer(buffer);
}
if (gf == null) {
gf = g.getFactory();
}
geoms[i] = g;
i++;
}
}
return new GeometryCollection(geoms, gf);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "generateSearchGeomCollection" | "private GeometryCollection generateSearchGeomCollection() {
int collectionSize = 0;
for (final GeomWrapper gw : geomWrappers) {
if (gw.isSelected()) {
collectionSize++;
}
}
final Geometry[] geoms = new Geometry[collectionSize];
final int buffer = jsGeomBuffer.getValue();
int i = 0;
GeometryFactory gf = null;
for (final GeomWrapper gw : geomWrappers) {
if (gw.isSelected()) {
Geometry g = gw.getGeometry();
if (buffer != 0) {
g = g.buffer(buffer);
}
if (gf == null) {
gf = g.getFactory();
}
geoms[i] = g;
}
<MASK>i++;</MASK>
}
return new GeometryCollection(geoms, gf);
}" |
Inversion-Mutation | megadiff | "private Hashtable selectDynamicUnBind(Vector scps, ServiceReference serviceReference) {
try {
if (Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): entered", null); //$NON-NLS-1$
}
Hashtable unbindTable = null; // ReferenceDescription:subTable
for (int i = 0; i < scps.size(); i++) {
Hashtable unbindSubTable = null; // scp:sr
ServiceComponentProp scp = (ServiceComponentProp) scps.elementAt(i);
if (scp.getState() < ServiceComponentProp.DISPOSING) {
//do not check disposed components
continue;
}
Vector references = scp.references;
// some components may not contain references and it is
// absolutely valid
if (references != null) {
for (int j = 0; j < references.size(); j++) {
Reference reference = (Reference) references.elementAt(j);
// Does the scp require this service, use the Reference
// object to check
if (reference.dynamicUnbindReference(serviceReference)) {
if (Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): unbinding " + scp.toString(), null); //$NON-NLS-1$
}
if (unbindSubTable == null) {
unbindSubTable = new Hashtable(11);
}
unbindSubTable.put(scp, serviceReference);
if (unbindTable == null) {
unbindTable = new Hashtable(11);
}
unbindTable.put(reference, unbindSubTable);
} else {
if (Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): not unbinding " + scp + " service ref=" + serviceReference, null); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
}
if (unbindTable != null && Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): unbindTable is " + unbindTable.toString(), null); //$NON-NLS-1$
}
return unbindTable;
} catch (Throwable t) {
Activator.log.error(Messages.UNEXPECTED_EXCEPTION, t);
return null;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "selectDynamicUnBind" | "private Hashtable selectDynamicUnBind(Vector scps, ServiceReference serviceReference) {
try {
if (Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): entered", null); //$NON-NLS-1$
}
Hashtable unbindTable = null; // ReferenceDescription:subTable
<MASK>Hashtable unbindSubTable = null; // scp:sr</MASK>
for (int i = 0; i < scps.size(); i++) {
ServiceComponentProp scp = (ServiceComponentProp) scps.elementAt(i);
if (scp.getState() < ServiceComponentProp.DISPOSING) {
//do not check disposed components
continue;
}
Vector references = scp.references;
// some components may not contain references and it is
// absolutely valid
if (references != null) {
for (int j = 0; j < references.size(); j++) {
Reference reference = (Reference) references.elementAt(j);
// Does the scp require this service, use the Reference
// object to check
if (reference.dynamicUnbindReference(serviceReference)) {
if (Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): unbinding " + scp.toString(), null); //$NON-NLS-1$
}
if (unbindSubTable == null) {
unbindSubTable = new Hashtable(11);
}
unbindSubTable.put(scp, serviceReference);
if (unbindTable == null) {
unbindTable = new Hashtable(11);
}
unbindTable.put(reference, unbindSubTable);
} else {
if (Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): not unbinding " + scp + " service ref=" + serviceReference, null); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
}
if (unbindTable != null && Activator.DEBUG) {
Activator.log.debug("Resolver.selectDynamicUnBind(): unbindTable is " + unbindTable.toString(), null); //$NON-NLS-1$
}
return unbindTable;
} catch (Throwable t) {
Activator.log.error(Messages.UNEXPECTED_EXCEPTION, t);
return null;
}
}" |
Inversion-Mutation | megadiff | "@RequestMapping(value = "/accession", method = RequestMethod.POST)
public void doAccession(@RequestParam("file")MultipartFile file, HttpServletResponse response) {
//convert input into a sample data object
InputStream is;
try {
is = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to recieve that SampleTab file. Contact administrator for more information.");
//TODO output nice webpage of error
return;
//note: maximum upload filesize specified in sampletab-accessioner-config.xml
}
//parse the input
SampleTabParser<SampleData> parser = new SampleTabParser<SampleData>();
final List<ErrorItem> errorItems;
errorItems = new ArrayList<ErrorItem>();
parser.addErrorItemListener(new ErrorItemListener() {
public void errorOccurred(ErrorItem item) {
errorItems.add(item);
}
});
SampleData st = null;
try{
//TODO error listener
st = parser.parse(is);
} catch (ParseException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to parse that SampleTab file. Contact administrator for more information.");
//TODO output nice webpage of error
return;
}
//see if parsing threw errors
if (!errorItems.isEmpty()) {
// there are error items, print them and fail
StringBuilder sb = new StringBuilder();
for (ErrorItem item : errorItems) {
//look up the error code by ID to get human-readable string
ErrorCode code = null;
for (ErrorCode ec : ErrorCode.values()) {
if (item.getErrorCode() == ec.getIntegerValue()) {
code = ec;
break;
}
}
if (code != null) {
sb.append("Listener reported error...").append("\n");
sb.append("\tError Code: ").append(item.getErrorCode()).append(" [").append(code.getErrorMessage())
.append("]").append("\n");
sb.append("\tType: ").append(item.getErrorType()).append("\n");
} else {
sb.append("Listener reported error...");
sb.append("\tError Code: ").append(item.getErrorCode()).append("\n");
}
sb.append("\tLine: ").append(item.getLine() != -1 ? item.getLine() : "n/a").append("\n");
sb.append("\tColumn: ").append(item.getCol() != -1 ? item.getCol() : "n/a").append("\n");
sb.append("\tAdditional comment: ").append(item.getComment()).append("\n");
sb.append("\n");
}
respondSimpleError(response, sb.toString());
return;
}
//assign accessions
Accessioner a;
try {
a = getAccessioner();
st = a.convert(st);
} catch (ClassNotFoundException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to connect to accession database. Contact administrator for more information.");
//TODO output nice webpage of error
return;
} catch (SQLException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to connect to accession database. Contact administrator for more information.");
//TODO output nice webpage of error
return;
} catch (ParseException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to assign accessions. Contact administrator for more information.");
//TODO output nice webpage of error
return;
}
//set it to be marked as a download file
response.setContentType("application/octet-stream");
//set the filename to download it as
response.addHeader("Content-Disposition","attachment; filename=sampletab.txt");
//writer to the output stream
try {
Writer out = new OutputStreamWriter(response.getOutputStream());
SampleTabWriter sampletabwriter = new SampleTabWriter(out);
sampletabwriter.write(st);
sampletabwriter.close();
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to output SampleTab. Contact administrator for more information.");
return;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doAccession" | "@RequestMapping(value = "/accession", method = RequestMethod.POST)
public void doAccession(@RequestParam("file")MultipartFile file, HttpServletResponse response) {
//convert input into a sample data object
InputStream is;
try {
is = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to recieve that SampleTab file. Contact administrator for more information.");
//TODO output nice webpage of error
return;
//note: maximum upload filesize specified in sampletab-accessioner-config.xml
}
//parse the input
SampleTabParser<SampleData> parser = new SampleTabParser<SampleData>();
final List<ErrorItem> errorItems;
errorItems = new ArrayList<ErrorItem>();
parser.addErrorItemListener(new ErrorItemListener() {
public void errorOccurred(ErrorItem item) {
errorItems.add(item);
}
});
SampleData st = null;
try{
//TODO error listener
st = parser.parse(is);
} catch (ParseException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to parse that SampleTab file. Contact administrator for more information.");
//TODO output nice webpage of error
return;
}
//see if parsing threw errors
if (!errorItems.isEmpty()) {
// there are error items, print them and fail
StringBuilder sb = new StringBuilder();
for (ErrorItem item : errorItems) {
//look up the error code by ID to get human-readable string
ErrorCode code = null;
for (ErrorCode ec : ErrorCode.values()) {
if (item.getErrorCode() == ec.getIntegerValue()) {
code = ec;
break;
}
}
if (code != null) {
sb.append("Listener reported error...").append("\n");
sb.append("\tError Code: ").append(item.getErrorCode()).append(" [").append(code.getErrorMessage())
.append("]").append("\n");
sb.append("\tType: ").append(item.getErrorType()).append("\n");
} else {
sb.append("Listener reported error...");
sb.append("\tError Code: ").append(item.getErrorCode()).append("\n");
}
sb.append("\tLine: ").append(item.getLine() != -1 ? item.getLine() : "n/a").append("\n");
sb.append("\tColumn: ").append(item.getCol() != -1 ? item.getCol() : "n/a").append("\n");
sb.append("\tAdditional comment: ").append(item.getComment()).append("\n");
sb.append("\n");
<MASK>respondSimpleError(response, sb.toString());</MASK>
}
return;
}
//assign accessions
Accessioner a;
try {
a = getAccessioner();
st = a.convert(st);
} catch (ClassNotFoundException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to connect to accession database. Contact administrator for more information.");
//TODO output nice webpage of error
return;
} catch (SQLException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to connect to accession database. Contact administrator for more information.");
//TODO output nice webpage of error
return;
} catch (ParseException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to assign accessions. Contact administrator for more information.");
//TODO output nice webpage of error
return;
}
//set it to be marked as a download file
response.setContentType("application/octet-stream");
//set the filename to download it as
response.addHeader("Content-Disposition","attachment; filename=sampletab.txt");
//writer to the output stream
try {
Writer out = new OutputStreamWriter(response.getOutputStream());
SampleTabWriter sampletabwriter = new SampleTabWriter(out);
sampletabwriter.write(st);
sampletabwriter.close();
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
respondSimpleError(response, "Unable to output SampleTab. Contact administrator for more information.");
return;
}
}" |
Inversion-Mutation | megadiff | "public StarTable[] makeStarTables( DataSource datsrc,
StoragePolicy storagePolicy)
throws IOException {
/* If there is a position, use makeStarTable. Otherwise, we want
* all the tables. */
String srcpos = datsrc.getPosition();
if ( srcpos != null && srcpos.trim().length() > 0 ) {
return new StarTable[] { makeStarTable( datsrc, false,
storagePolicy ) };
}
/* See if this looks like a fits-plus table. */
if ( ! isMagic( datsrc.getIntro() ) ) {
throw new TableFormatException(
"Doesn't look like a FITS-plus file" );
}
/* Get an input stream. */
ArrayDataInput in = FitsConstants.getInputStreamStart( datsrc );
try {
/* Read the metadata from the primary HDU. */
long[] posptr = new long[ 1 ];
TableElement[] tabEls = readMetadata( in, posptr );
long pos = posptr[ 0 ];
int nTable = tabEls.length;
StarTable[] outTables = new StarTable[ nTable ];
/* Read each table HDU in turn. */
for ( int itab = 0; itab < nTable; itab++ ) {
/* Make sure we have a usable stream positioned at the start
* of the right HDU. */
if ( in == null ) {
in = FitsConstants.getInputStreamStart( datsrc );
if ( pos > 0 ) {
if ( in instanceof RandomAccess ) {
((RandomAccess) in).seek( pos );
}
else {
IOUtils.skipBytes( in, pos );
}
}
}
/* Read the HDU header. */
Header hdr = new Header();
int headsize = FitsConstants.readHeader( hdr, in );
long datasize = FitsConstants.getDataSize( hdr );
long datpos = pos + headsize;
if ( ! "BINTABLE".equals( hdr.getStringValue( "XTENSION" ) ) ) {
throw new TableFormatException( "Non-BINTABLE at ext #"
+ itab + " - not FITS-plus" );
}
/* Read the BINTABLE. */
final StarTable dataTable;
if ( in instanceof RandomAccess ) {
dataTable = BintableStarTable
.makeRandomStarTable( hdr, (RandomAccess) in );
}
else {
dataTable = BintableStarTable
.makeSequentialStarTable( hdr, datsrc, datpos );
}
in = null;
/* Combine the data from the BINTABLE with the header from
* the VOTable to create an output table. */
outTables[ itab ] =
createFitsPlusTable( tabEls[ itab ], dataTable );
pos += headsize + datasize;
}
return outTables;
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "makeStarTables" | "public StarTable[] makeStarTables( DataSource datsrc,
StoragePolicy storagePolicy)
throws IOException {
/* If there is a position, use makeStarTable. Otherwise, we want
* all the tables. */
String srcpos = datsrc.getPosition();
if ( srcpos != null && srcpos.trim().length() > 0 ) {
return new StarTable[] { makeStarTable( datsrc, false,
storagePolicy ) };
}
/* See if this looks like a fits-plus table. */
if ( ! isMagic( datsrc.getIntro() ) ) {
throw new TableFormatException(
"Doesn't look like a FITS-plus file" );
}
/* Get an input stream. */
ArrayDataInput in = FitsConstants.getInputStreamStart( datsrc );
try {
/* Read the metadata from the primary HDU. */
long[] posptr = new long[ 1 ];
TableElement[] tabEls = readMetadata( in, posptr );
long pos = posptr[ 0 ];
int nTable = tabEls.length;
StarTable[] outTables = new StarTable[ nTable ];
/* Read each table HDU in turn. */
for ( int itab = 0; itab < nTable; itab++ ) {
/* Make sure we have a usable stream positioned at the start
* of the right HDU. */
if ( in == null ) {
in = FitsConstants.getInputStreamStart( datsrc );
if ( pos > 0 ) {
if ( in instanceof RandomAccess ) {
((RandomAccess) in).seek( pos );
}
else {
IOUtils.skipBytes( in, pos );
}
}
}
/* Read the HDU header. */
Header hdr = new Header();
int headsize = FitsConstants.readHeader( hdr, in );
long datasize = FitsConstants.getDataSize( hdr );
long datpos = pos + headsize;
if ( ! "BINTABLE".equals( hdr.getStringValue( "XTENSION" ) ) ) {
throw new TableFormatException( "Non-BINTABLE at ext #"
+ itab + " - not FITS-plus" );
}
/* Read the BINTABLE. */
final StarTable dataTable;
if ( in instanceof RandomAccess ) {
dataTable = BintableStarTable
.makeRandomStarTable( hdr, (RandomAccess) in );
}
else {
dataTable = BintableStarTable
.makeSequentialStarTable( hdr, datsrc, datpos );
<MASK>in = null;</MASK>
}
/* Combine the data from the BINTABLE with the header from
* the VOTable to create an output table. */
outTables[ itab ] =
createFitsPlusTable( tabEls[ itab ], dataTable );
pos += headsize + datasize;
}
return outTables;
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
}" |
Inversion-Mutation | megadiff | "private void loadIdentities() {
try {
final Map<String, InputStream> identityStreams = getResourceManager().getResourcesStartingWithAsInputStreams("META-INF/identities/");
unloadIdentities();
for (Map.Entry<String, InputStream> entry : identityStreams.entrySet()) {
final String name = entry.getKey();
final InputStream stream = entry.getValue();
if (name.endsWith("/")) {
// Don't try to load folders as identities
continue;
}
if (stream == null) {
//Don't add null streams
continue;
}
try {
final Identity thisIdentity = new Identity(stream, false);
IdentityManager.addIdentity(thisIdentity);
identities.add(thisIdentity);
} catch (final InvalidIdentityFileException ex) {
Logger.userError(ErrorLevel.MEDIUM, "Error with identity file '" + name + "' in plugin '" + getName() + "'", ex);
}
}
} catch (final IOException ioe) {
Logger.userError(ErrorLevel.MEDIUM, "Error finding identities in plugin '" + getName() + "'", ioe);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadIdentities" | "private void loadIdentities() {
try {
final Map<String, InputStream> identityStreams = getResourceManager().getResourcesStartingWithAsInputStreams("META-INF/identities/");
unloadIdentities();
for (Map.Entry<String, InputStream> entry : identityStreams.entrySet()) {
final String name = entry.getKey();
final InputStream stream = entry.getValue();
if (name.endsWith("/")) {
// Don't try to load folders as identities
continue;
}
if (stream == null) {
//Don't add null streams
continue;
}
try {
final Identity thisIdentity = new Identity(stream, false);
<MASK>identities.add(thisIdentity);</MASK>
IdentityManager.addIdentity(thisIdentity);
} catch (final InvalidIdentityFileException ex) {
Logger.userError(ErrorLevel.MEDIUM, "Error with identity file '" + name + "' in plugin '" + getName() + "'", ex);
}
}
} catch (final IOException ioe) {
Logger.userError(ErrorLevel.MEDIUM, "Error finding identities in plugin '" + getName() + "'", ioe);
}
}" |
Inversion-Mutation | megadiff | "public void setColorModel(Map<String, String> colorMap) {
if(tableModel == null) {
tableModel = new DefaultTableModel();
tableModel.addColumn(tr("Name"));
tableModel.addColumn(tr("Color"));
}
// clear old model:
while(tableModel.getRowCount() > 0) {
tableModel.removeRow(0);
}
// fill model with colors:
Map<String, String> colorKeyList = new TreeMap<String, String>();
Map<String, String> colorKeyList_mappaint = new TreeMap<String, String>();
Map<String, String> colorKeyList_layer = new TreeMap<String, String>();
for(String key : colorMap.keySet()) {
if(key.startsWith("layer ")) {
colorKeyList_layer.put(getName(key), key);
} else if(key.startsWith("mappaint.")) {
colorKeyList_mappaint.put(getName(key), key);
} else {
colorKeyList.put(getName(key), key);
}
}
for (Entry<String, String> k : colorKeyList.entrySet()) {
Vector<Object> row = new Vector<Object>(2);
row.add(k.getValue());
row.add(ColorHelper.html2color(colorMap.get(k.getValue())));
tableModel.addRow(row);
}
for (Entry<String, String> k : colorKeyList_mappaint.entrySet()) {
Vector<Object> row = new Vector<Object>(2);
row.add(k.getValue());
row.add(ColorHelper.html2color(colorMap.get(k.getValue())));
tableModel.addRow(row);
}
for (Entry<String, String> k : colorKeyList_layer.entrySet()) {
Vector<Object> row = new Vector<Object>(2);
row.add(k.getValue());
row.add(ColorHelper.html2color(colorMap.get(k.getValue())));
tableModel.addRow(row);
}
if(this.colors != null) {
this.colors.repaint();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setColorModel" | "public void setColorModel(Map<String, String> colorMap) {
if(tableModel == null) {
tableModel = new DefaultTableModel();
<MASK>tableModel.addColumn(tr("Color"));</MASK>
tableModel.addColumn(tr("Name"));
}
// clear old model:
while(tableModel.getRowCount() > 0) {
tableModel.removeRow(0);
}
// fill model with colors:
Map<String, String> colorKeyList = new TreeMap<String, String>();
Map<String, String> colorKeyList_mappaint = new TreeMap<String, String>();
Map<String, String> colorKeyList_layer = new TreeMap<String, String>();
for(String key : colorMap.keySet()) {
if(key.startsWith("layer ")) {
colorKeyList_layer.put(getName(key), key);
} else if(key.startsWith("mappaint.")) {
colorKeyList_mappaint.put(getName(key), key);
} else {
colorKeyList.put(getName(key), key);
}
}
for (Entry<String, String> k : colorKeyList.entrySet()) {
Vector<Object> row = new Vector<Object>(2);
row.add(k.getValue());
row.add(ColorHelper.html2color(colorMap.get(k.getValue())));
tableModel.addRow(row);
}
for (Entry<String, String> k : colorKeyList_mappaint.entrySet()) {
Vector<Object> row = new Vector<Object>(2);
row.add(k.getValue());
row.add(ColorHelper.html2color(colorMap.get(k.getValue())));
tableModel.addRow(row);
}
for (Entry<String, String> k : colorKeyList_layer.entrySet()) {
Vector<Object> row = new Vector<Object>(2);
row.add(k.getValue());
row.add(ColorHelper.html2color(colorMap.get(k.getValue())));
tableModel.addRow(row);
}
if(this.colors != null) {
this.colors.repaint();
}
}" |
Inversion-Mutation | megadiff | "public void render( Display display ) throws IOException {
HttpServletRequest request = ContextProvider.getRequest();
// Note [rst] Startup page created in LifecycleServiceHandler#runLifeCycle
// TODO [rh] should be replaced by requestCounter != 0
if( request.getParameter( RequestParams.UIROOT ) != null ) {
disposeWidgets();
renderRequestCounter();
renderTheme( display );
renderExitConfirmation( display );
renderEnableUiTests( display );
createSingletons( display );
renderShells( display );
renderFocus( display );
renderBeep( display );
writeUICallBackActivation( display );
markInitialized( display );
ActiveKeysUtil.renderActiveKeys( display );
ActiveKeysUtil.renderCancelKeys( display );
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "render" | "public void render( Display display ) throws IOException {
HttpServletRequest request = ContextProvider.getRequest();
// Note [rst] Startup page created in LifecycleServiceHandler#runLifeCycle
// TODO [rh] should be replaced by requestCounter != 0
if( request.getParameter( RequestParams.UIROOT ) != null ) {
<MASK>createSingletons( display );</MASK>
disposeWidgets();
renderRequestCounter();
renderTheme( display );
renderExitConfirmation( display );
renderEnableUiTests( display );
renderShells( display );
renderFocus( display );
renderBeep( display );
writeUICallBackActivation( display );
markInitialized( display );
ActiveKeysUtil.renderActiveKeys( display );
ActiveKeysUtil.renderCancelKeys( display );
}
}" |
Inversion-Mutation | megadiff | "public void onEnable() {
loadConfig();
if (ConnectionManager.initialize()) {
localization = Localization.getInstance(config.getString("language","de"));
commandList = new CommandList(getServer());
DatabaseManager dbManager = new DatabaseManager(getServer());
warpManager = new WarpManager(dbManager, config);
homeManager = new HomeManager(dbManager);
spawnManager = new SpawnManager(dbManager);
bankManager = new BankManager(dbManager);
getServer().getPluginManager().registerEvent(Type.PLAYER_RESPAWN,
new PlayerRespawnListener(), Priority.Normal, this);
log.printInfo("enabled");
}
else {
log.printWarning("Can't connect to database!");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onEnable" | "public void onEnable() {
loadConfig();
<MASK>commandList = new CommandList(getServer());</MASK>
if (ConnectionManager.initialize()) {
localization = Localization.getInstance(config.getString("language","de"));
DatabaseManager dbManager = new DatabaseManager(getServer());
warpManager = new WarpManager(dbManager, config);
homeManager = new HomeManager(dbManager);
spawnManager = new SpawnManager(dbManager);
bankManager = new BankManager(dbManager);
getServer().getPluginManager().registerEvent(Type.PLAYER_RESPAWN,
new PlayerRespawnListener(), Priority.Normal, this);
log.printInfo("enabled");
}
else {
log.printWarning("Can't connect to database!");
}
}" |
Inversion-Mutation | megadiff | "private void doDownload(final String requestId, final NasProductTemplate template) {
if (DownloadManagerDialog.showAskingForUserTitle(
CismapBroker.getInstance().getMappingComponent())) {
final String jobname = (!DownloadManagerDialog.getJobname().equals("")) ? DownloadManagerDialog
.getJobname() : null;
DownloadManager.instance()
.add(
new NASDownload(
"NAS-Download",
"",
jobname,
requestId,
template,
generateSearchGeomCollection()));
} else {
DownloadManager.instance()
.add(
new NASDownload(
"NAS-Download",
"",
"",
requestId,
template,
generateSearchGeomCollection()));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doDownload" | "private void doDownload(final String requestId, final NasProductTemplate template) {
if (DownloadManagerDialog.showAskingForUserTitle(
CismapBroker.getInstance().getMappingComponent())) {
final String jobname = (!DownloadManagerDialog.getJobname().equals("")) ? DownloadManagerDialog
.getJobname() : null;
DownloadManager.instance()
.add(
new NASDownload(
"NAS-Download",
<MASK>jobname,</MASK>
"",
requestId,
template,
generateSearchGeomCollection()));
} else {
DownloadManager.instance()
.add(
new NASDownload(
"NAS-Download",
"",
"",
requestId,
template,
generateSearchGeomCollection()));
}
}" |
Inversion-Mutation | megadiff | "@Override
public void run() {
try {
int count;
Socket socket = serverSocket.accept();
ois = new ObjectInputStream(socket.getInputStream());
byte[] buffer = new byte[bufferSize];
//Obtengo el archivo remoto
File pathRemoto = (File) ois.readObject();
//Extraigo el nombre
fileName = pathRemoto.getName();
//El archivo se escribe en "pathLocal/fileName"
String file = pathLocal.getPath() + "/" + fileName;
//Abro el archivo en disco
FileOutputStream fos = new FileOutputStream(file);
//Recibo el archivo y escribo en disco
while (!socket.isClosed() && (count = ois.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
ois.close();
fos.close();
if (!socket.isClosed()) {
socket.close();
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(ManejadorRecvFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(ManejadorSendFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ManejadorSendFiles.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(new JFrame(), "Fallo al recibir " + fileName);
}
JOptionPane.showMessageDialog(new JFrame(), "Finalizó recepción de " + fileName);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public void run() {
try {
int count;
Socket socket = serverSocket.accept();
ois = new ObjectInputStream(socket.getInputStream());
byte[] buffer = new byte[bufferSize];
//Obtengo el archivo remoto
File pathRemoto = (File) ois.readObject();
//Extraigo el nombre
fileName = pathRemoto.getName();
//El archivo se escribe en "pathLocal/fileName"
String file = pathLocal.getPath() + "/" + fileName;
//Abro el archivo en disco
FileOutputStream fos = new FileOutputStream(file);
//Recibo el archivo y escribo en disco
while (!socket.isClosed() && (count = ois.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
ois.close();
fos.close();
if (!socket.isClosed()) {
socket.close();
}
<MASK>JOptionPane.showMessageDialog(new JFrame(), "Finalizó recepción de " + fileName);</MASK>
} catch (ClassNotFoundException ex) {
Logger.getLogger(ManejadorRecvFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(ManejadorSendFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ManejadorSendFiles.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(new JFrame(), "Fallo al recibir " + fileName);
}
}" |
Inversion-Mutation | megadiff | "public void run() {
initialize();
while(getState().equals(READY)) {
//Pre-Cache SAY tags
//Issue 105: http://code.google.com/p/restcomm/issues/detail?id=105
if (context.getCall().getDirection() == Direction.OUTBOUND_DIAL){
if (configuration.getString("pre-cache-outbound").equalsIgnoreCase("true")){
TagIterator cacheIterator = resource.iterator();
while(cacheIterator.hasNext()){
final RcmlTag tag = (RcmlTag)cacheIterator.next();
if(!tag.hasBeenVisited() && tag.isVerb() && (tag instanceof Say)) {
try {
precache(tag);
} catch (VisitorException e) {}
}
}
}
}
// Start executing the document.
TagIterator iterator = resource.iterator();
while(iterator.hasNext()) {
final RcmlTag tag = (RcmlTag)iterator.next();
if(!tag.hasBeenVisited() && tag.isVerb()) {
// Make sure we're ready to execute the next tag.
assertState(READY);
setState(EXECUTING);
// Try to execute the next tag.
try { tag.accept(this); }
catch(final VisitorException ignored) { /* Handled in tag strategy. */ }
tag.setHasBeenVisited(true);
// Make sure the call is still in progress.
final Call call = context.getCall();
if(!(tag instanceof Pause)){
if(Call.Status.RINGING != call.getStatus() &&
Call.Status.IN_PROGRESS != call.getStatus())
{ setState(FINISHED); }
}
// Handle any state changes caused by executing the tag.
final State state = getState();
if(state.equals(REDIRECTED)) {
iterator = resource.iterator();
setState(READY);
} else if(state.equals(FINISHED) || state.equals(FAILED)) {
break;
} else {
setState(READY);
}
}
}
}
cleanup(context);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run() {
initialize();
while(getState().equals(READY)) {
//Pre-Cache SAY tags
//Issue 105: http://code.google.com/p/restcomm/issues/detail?id=105
if (context.getCall().getDirection() == Direction.OUTBOUND_DIAL){
if (configuration.getString("pre-cache-outbound").equalsIgnoreCase("true")){
TagIterator cacheIterator = resource.iterator();
while(cacheIterator.hasNext()){
final RcmlTag tag = (RcmlTag)cacheIterator.next();
if(!tag.hasBeenVisited() && tag.isVerb() && (tag instanceof Say)) {
try {
precache(tag);
} catch (VisitorException e) {}
}
}
}
}
// Start executing the document.
TagIterator iterator = resource.iterator();
while(iterator.hasNext()) {
final RcmlTag tag = (RcmlTag)iterator.next();
if(!tag.hasBeenVisited() && tag.isVerb()) {
// Make sure we're ready to execute the next tag.
assertState(READY);
setState(EXECUTING);
// Try to execute the next tag.
try { tag.accept(this); }
catch(final VisitorException ignored) { /* Handled in tag strategy. */ }
tag.setHasBeenVisited(true);
// Make sure the call is still in progress.
final Call call = context.getCall();
if(!(tag instanceof Pause)){
if(Call.Status.RINGING != call.getStatus() &&
Call.Status.IN_PROGRESS != call.getStatus())
{ setState(FINISHED); }
}
// Handle any state changes caused by executing the tag.
final State state = getState();
if(state.equals(REDIRECTED)) {
iterator = resource.iterator();
setState(READY);
} else if(state.equals(FINISHED) || state.equals(FAILED)) {
break;
} else {
setState(READY);
}
}
}
<MASK>cleanup(context);</MASK>
}
}" |
Inversion-Mutation | megadiff | "private void fillViews() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(VLCApplication.getAppContext());
float[] bands = null;
String[] presets = null;
try {
libVlc = Util.getLibVlcInstance();
bands = libVlc.getBands();
presets = libVlc.getPresets();
if (equalizer == null)
equalizer = Util.getFloatArray(preferences, "equalizer_values");
if (equalizer == null)
equalizer = new float[bands.length + 1];
} catch (LibVlcException e) {
e.printStackTrace();
}
// on/off
button.setChecked(libVlc.getEqualizer() != null);
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (libVlc == null)
return;
libVlc.setEqualizer(isChecked ? equalizer : null);
}
});
// presets
equalizer_presets.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, presets));
// Set the default selection asynchronously to prevent a layout initialization bug.
final int equalizer_preset_pref = preferences.getInt("equalizer_preset", 0);
equalizer_presets.post(new Runnable() {
@Override
public void run() {
equalizer_presets.setSelection(equalizer_preset_pref, false);
equalizer_presets.setOnItemSelectedListener(mPresetListener);
}
});
// preamp
preamp.setMax(40);
preamp.setProgress((int) equalizer[0] + 20);
preamp.setOnSeekBarChangeListener(mPreampListener);
// bands
for (int i = 0; i < bands.length; i++) {
float band = bands[i];
EqualizerBar bar = new EqualizerBar(getActivity(), band);
bar.setValue(equalizer[i + 1]);
bar.setListener(new BandListener(i + 1));
bands_layout.addView(bar);
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT, 1);
bar.setLayoutParams(params);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "fillViews" | "private void fillViews() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(VLCApplication.getAppContext());
float[] bands = null;
String[] presets = null;
try {
libVlc = Util.getLibVlcInstance();
bands = libVlc.getBands();
presets = libVlc.getPresets();
if (equalizer == null)
equalizer = Util.getFloatArray(preferences, "equalizer_values");
if (equalizer == null)
equalizer = new float[bands.length + 1];
} catch (LibVlcException e) {
e.printStackTrace();
}
// on/off
button.setChecked(libVlc.getEqualizer() != null);
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (libVlc == null)
return;
libVlc.setEqualizer(isChecked ? equalizer : null);
}
});
// presets
equalizer_presets.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, presets));
<MASK>equalizer_presets.setOnItemSelectedListener(mPresetListener);</MASK>
// Set the default selection asynchronously to prevent a layout initialization bug.
final int equalizer_preset_pref = preferences.getInt("equalizer_preset", 0);
equalizer_presets.post(new Runnable() {
@Override
public void run() {
equalizer_presets.setSelection(equalizer_preset_pref, false);
}
});
// preamp
preamp.setMax(40);
preamp.setProgress((int) equalizer[0] + 20);
preamp.setOnSeekBarChangeListener(mPreampListener);
// bands
for (int i = 0; i < bands.length; i++) {
float band = bands[i];
EqualizerBar bar = new EqualizerBar(getActivity(), band);
bar.setValue(equalizer[i + 1]);
bar.setListener(new BandListener(i + 1));
bands_layout.addView(bar);
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT, 1);
bar.setLayoutParams(params);
}
}" |
Inversion-Mutation | megadiff | "public boolean placeApplication(int applicationID, String subject, String body, int childCareTime, int groupID, int schoolTypeID, int employmentTypeID, User user, Locale locale) throws RemoteException {
try {
ChildCareApplication application = getChildCareApplicationHome().findByPrimaryKey(new Integer(applicationID));
application.setCareTime(childCareTime);
if (groupID != -1) {
IWTimestamp fromDate = new IWTimestamp(application.getFromDate());
getSchoolBusiness().storeSchoolClassMemberCC(application.getChildId(), groupID, schoolTypeID, fromDate.getTimestamp(), ((Integer)user.getPrimaryKey()).intValue());
sendMessageToParents(application, subject, body);
}
alterValidFromDate(application, application.getFromDate(), employmentTypeID, locale, user);
}
catch (FinderException e) {
e.printStackTrace();
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "placeApplication" | "public boolean placeApplication(int applicationID, String subject, String body, int childCareTime, int groupID, int schoolTypeID, int employmentTypeID, User user, Locale locale) throws RemoteException {
try {
ChildCareApplication application = getChildCareApplicationHome().findByPrimaryKey(new Integer(applicationID));
application.setCareTime(childCareTime);
<MASK>alterValidFromDate(application, application.getFromDate(), employmentTypeID, locale, user);</MASK>
if (groupID != -1) {
IWTimestamp fromDate = new IWTimestamp(application.getFromDate());
getSchoolBusiness().storeSchoolClassMemberCC(application.getChildId(), groupID, schoolTypeID, fromDate.getTimestamp(), ((Integer)user.getPrimaryKey()).intValue());
sendMessageToParents(application, subject, body);
}
}
catch (FinderException e) {
e.printStackTrace();
}
return false;
}" |
Inversion-Mutation | megadiff | "public static void poll(int delta) {
if (currentMusic != null) {
SoundStore.get().poll(delta);
if (!SoundStore.get().isMusicPlaying()) {
currentMusic = null;
currentMusic.fireMusicEnded();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "poll" | "public static void poll(int delta) {
if (currentMusic != null) {
SoundStore.get().poll(delta);
if (!SoundStore.get().isMusicPlaying()) {
<MASK>currentMusic.fireMusicEnded();</MASK>
currentMusic = null;
}
}
}" |
Inversion-Mutation | megadiff | "private void setup( boolean addFileUpload ) {
up = new FileUpload( new org.uberfire.mvp.Command() {
@Override
public void execute() {
uploadButtonClickHanlder.onClick( null );
}
}, addFileUpload );
up.setName( FileManagerFields.UPLOAD_FIELD_NAME_ATTACH );
form.setEncoding( FormPanel.ENCODING_MULTIPART );
form.setMethod( FormPanel.METHOD_POST );
form.addSubmitHandler( new Form.SubmitHandler() {
@Override
public void onSubmit( final Form.SubmitEvent event ) {
final String fileName = up.getFilename();
if ( fileName == null || "".equals( fileName ) ) {
Window.alert( CommonConstants.INSTANCE.UploadSelectAFile() );
event.cancel();
executeCallback( errorCallback );
return;
}
if ( validFileExtensions != null && validFileExtensions.length != 0 ) {
boolean isValid = false;
for ( String extension : validFileExtensions ) {
if ( fileName.endsWith( extension ) ) {
isValid = true;
break;
}
}
if ( !isValid ) {
Window.alert( CommonConstants.INSTANCE.UploadFileTypeNotSupported() );
event.cancel();
executeCallback( errorCallback );
return;
}
}
}
} );
form.addSubmitCompleteHandler( new Form.SubmitCompleteHandler() {
@Override
public void onSubmitComplete( final Form.SubmitCompleteEvent event ) {
if ( "OK".equalsIgnoreCase( event.getResults() ) ) {
executeCallback( successCallback );
Window.alert( CommonConstants.INSTANCE.UploadSuccess() );
} else {
executeCallback( errorCallback );
if ( event.getResults().contains( "org.uberfire.java.nio.file.FileAlreadyExistsException" ) ) {
Window.alert( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
} else if ( event.getResults().contains( "DecisionTableParseException" ) ) {
Window.alert( CommonConstants.INSTANCE.UploadGenericError() );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.UploadGenericError() );
} else {
Window.alert( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
}
}
reset();
}
} );
fields.add( up );
fields.add( fieldFilePath );
fields.add( fieldFileName );
fields.add( fieldFileFullPath );
fields.add( fieldFileOperation );
form.add( fields );
initWidget( form );
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setup" | "private void setup( boolean addFileUpload ) {
up = new FileUpload( new org.uberfire.mvp.Command() {
@Override
public void execute() {
uploadButtonClickHanlder.onClick( null );
}
}, addFileUpload );
up.setName( FileManagerFields.UPLOAD_FIELD_NAME_ATTACH );
form.setEncoding( FormPanel.ENCODING_MULTIPART );
form.setMethod( FormPanel.METHOD_POST );
form.addSubmitHandler( new Form.SubmitHandler() {
@Override
public void onSubmit( final Form.SubmitEvent event ) {
final String fileName = up.getFilename();
if ( fileName == null || "".equals( fileName ) ) {
Window.alert( CommonConstants.INSTANCE.UploadSelectAFile() );
event.cancel();
executeCallback( errorCallback );
return;
}
if ( validFileExtensions != null && validFileExtensions.length != 0 ) {
boolean isValid = false;
for ( String extension : validFileExtensions ) {
if ( fileName.endsWith( extension ) ) {
isValid = true;
break;
}
}
if ( !isValid ) {
Window.alert( CommonConstants.INSTANCE.UploadFileTypeNotSupported() );
event.cancel();
executeCallback( errorCallback );
return;
}
}
}
} );
form.addSubmitCompleteHandler( new Form.SubmitCompleteHandler() {
@Override
public void onSubmitComplete( final Form.SubmitCompleteEvent event ) {
<MASK>reset();</MASK>
if ( "OK".equalsIgnoreCase( event.getResults() ) ) {
executeCallback( successCallback );
Window.alert( CommonConstants.INSTANCE.UploadSuccess() );
} else {
executeCallback( errorCallback );
if ( event.getResults().contains( "org.uberfire.java.nio.file.FileAlreadyExistsException" ) ) {
Window.alert( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
} else if ( event.getResults().contains( "DecisionTableParseException" ) ) {
Window.alert( CommonConstants.INSTANCE.UploadGenericError() );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.UploadGenericError() );
} else {
Window.alert( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
}
}
}
} );
fields.add( up );
fields.add( fieldFilePath );
fields.add( fieldFileName );
fields.add( fieldFileFullPath );
fields.add( fieldFileOperation );
form.add( fields );
initWidget( form );
}" |
Inversion-Mutation | megadiff | "@Override
public void onSubmitComplete( final Form.SubmitCompleteEvent event ) {
if ( "OK".equalsIgnoreCase( event.getResults() ) ) {
executeCallback( successCallback );
Window.alert( CommonConstants.INSTANCE.UploadSuccess() );
} else {
executeCallback( errorCallback );
if ( event.getResults().contains( "org.uberfire.java.nio.file.FileAlreadyExistsException" ) ) {
Window.alert( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
} else if ( event.getResults().contains( "DecisionTableParseException" ) ) {
Window.alert( CommonConstants.INSTANCE.UploadGenericError() );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.UploadGenericError() );
} else {
Window.alert( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
}
}
reset();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onSubmitComplete" | "@Override
public void onSubmitComplete( final Form.SubmitCompleteEvent event ) {
<MASK>reset();</MASK>
if ( "OK".equalsIgnoreCase( event.getResults() ) ) {
executeCallback( successCallback );
Window.alert( CommonConstants.INSTANCE.UploadSuccess() );
} else {
executeCallback( errorCallback );
if ( event.getResults().contains( "org.uberfire.java.nio.file.FileAlreadyExistsException" ) ) {
Window.alert( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionFileAlreadyExists0( fieldFileName.getText() ) );
} else if ( event.getResults().contains( "DecisionTableParseException" ) ) {
Window.alert( CommonConstants.INSTANCE.UploadGenericError() );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.UploadGenericError() );
} else {
Window.alert( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
//ErrorPopup.showMessage( CommonConstants.INSTANCE.ExceptionGeneric0( event.getResults() ) );
}
}
}" |
Inversion-Mutation | megadiff | "protected WebSocketHandler postProcessMapping(WebSocket webSocket, AtmosphereRequest request, WebSocketHandler w) {
if (!wildcardMapping()) return w;
String path;
String pathInfo = null;
try {
pathInfo = request.getPathInfo();
} catch (IllegalStateException ex) {
// http://java.net/jira/browse/GRIZZLY-1301
}
if (pathInfo != null) {
path = request.getServletPath() + pathInfo;
} else {
path = request.getServletPath();
}
if (path == null || path.isEmpty()) {
path = "/";
}
synchronized (handlers) {
if (handlers.get(path) == null) {
// AtmosphereHandlerService
if (w.getClass().getAnnotation(WebSocketHandlerService.class) != null) {
String targetPath = w.getClass().getAnnotation(WebSocketHandlerService.class).path();
if (targetPath.indexOf("{") != -1 && targetPath.indexOf("}") != -1) {
try {
boolean singleton = w.getClass().getAnnotation(Singleton.class) != null;
if (!singleton) {
registerWebSocketHandler(path, framework.newClassInstance(w.getClass()));
} else {
registerWebSocketHandler(path, w);
}
w = handlers.get(path);
} catch (Throwable e) {
logger.warn("Unable to create WebSocketHandler", e);
}
}
}
}
webSocket.resource().setBroadcaster(framework.getBroadcasterFactory().lookup(path, true));
}
return w;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "postProcessMapping" | "protected WebSocketHandler postProcessMapping(WebSocket webSocket, AtmosphereRequest request, WebSocketHandler w) {
if (!wildcardMapping()) return w;
String path;
String pathInfo = null;
try {
pathInfo = request.getPathInfo();
} catch (IllegalStateException ex) {
// http://java.net/jira/browse/GRIZZLY-1301
}
if (pathInfo != null) {
path = request.getServletPath() + pathInfo;
} else {
path = request.getServletPath();
}
if (path == null || path.isEmpty()) {
path = "/";
}
synchronized (handlers) {
if (handlers.get(path) == null) {
// AtmosphereHandlerService
if (w.getClass().getAnnotation(WebSocketHandlerService.class) != null) {
String targetPath = w.getClass().getAnnotation(WebSocketHandlerService.class).path();
if (targetPath.indexOf("{") != -1 && targetPath.indexOf("}") != -1) {
try {
boolean singleton = w.getClass().getAnnotation(Singleton.class) != null;
if (!singleton) {
registerWebSocketHandler(path, framework.newClassInstance(w.getClass()));
} else {
registerWebSocketHandler(path, w);
}
w = handlers.get(path);
} catch (Throwable e) {
logger.warn("Unable to create WebSocketHandler", e);
}
}
}
}
}
<MASK>webSocket.resource().setBroadcaster(framework.getBroadcasterFactory().lookup(path, true));</MASK>
return w;
}" |
Inversion-Mutation | megadiff | "protected List<Customer> findCustomersFromDB() {
try {
List<Customer> customers = new ArrayList<Customer>();
List<Customer> customersInDb = mongoOperation.getCollection(CUSTOMERDAO_COLLECTION_NAME, Customer.class);
if (CollectionUtils.isNotEmpty(customersInDb)) {
for (Customer customer : customersInDb) {
List<String> applicableTechnologies = new ArrayList<String>();
List<String> customerApplicableTechnologies = customer.getApplicableTechnologies();
List<String> fromDB = getApplicableForomDB(customer.getId(), customerApplicableTechnologies);
if(CollectionUtils.isNotEmpty(customerApplicableTechnologies)) {
applicableTechnologies.addAll(customerApplicableTechnologies);
}
if(CollectionUtils.isNotEmpty(fromDB)) {
applicableTechnologies.addAll(fromDB);
}
List<Technology> technologies = createTechnology(applicableTechnologies);
List<TechnologyGroup> technologyGroups = createTechnologyInfo(technologies);
Map<String, List<TechnologyGroup>> appTypeMap = new HashMap<String, List<TechnologyGroup>>();
createAppTypeMap(technologyGroups, appTypeMap);
List<ApplicationType> applicationTypes = createApplicationTypes(appTypeMap);
customer.setApplicableAppTypes(applicationTypes);
customers.add(customer);
}
return customers;
}
} catch (Exception e) {
throw new PhrescoWebServiceException(e, EX_PHEX00005, CUSTOMERS_COLLECTION_NAME);
}
return null;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findCustomersFromDB" | "protected List<Customer> findCustomersFromDB() {
try {
List<Customer> customers = new ArrayList<Customer>();
<MASK>List<String> applicableTechnologies = new ArrayList<String>();</MASK>
List<Customer> customersInDb = mongoOperation.getCollection(CUSTOMERDAO_COLLECTION_NAME, Customer.class);
if (CollectionUtils.isNotEmpty(customersInDb)) {
for (Customer customer : customersInDb) {
List<String> customerApplicableTechnologies = customer.getApplicableTechnologies();
List<String> fromDB = getApplicableForomDB(customer.getId(), customerApplicableTechnologies);
if(CollectionUtils.isNotEmpty(customerApplicableTechnologies)) {
applicableTechnologies.addAll(customerApplicableTechnologies);
}
if(CollectionUtils.isNotEmpty(fromDB)) {
applicableTechnologies.addAll(fromDB);
}
List<Technology> technologies = createTechnology(applicableTechnologies);
List<TechnologyGroup> technologyGroups = createTechnologyInfo(technologies);
Map<String, List<TechnologyGroup>> appTypeMap = new HashMap<String, List<TechnologyGroup>>();
createAppTypeMap(technologyGroups, appTypeMap);
List<ApplicationType> applicationTypes = createApplicationTypes(appTypeMap);
customer.setApplicableAppTypes(applicationTypes);
customers.add(customer);
}
return customers;
}
} catch (Exception e) {
throw new PhrescoWebServiceException(e, EX_PHEX00005, CUSTOMERS_COLLECTION_NAME);
}
return null;
}" |
Inversion-Mutation | megadiff | "@Override
protected Iterable<Class<? extends Filter>> dependencies() {
List<Class<? extends Filter>> dependencies = new ArrayList<Class<? extends Filter>>();
dependencies.add(SourceFilter.class);
dependencies.add(StandardFilter.class);
dependencies.add(ResetFilter.class);
dependencies.add(ProfilingDatabaseFilter.class);
dependencies.add(CachingDatabaseFilter.class);
return dependencies;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dependencies" | "@Override
protected Iterable<Class<? extends Filter>> dependencies() {
List<Class<? extends Filter>> dependencies = new ArrayList<Class<? extends Filter>>();
dependencies.add(SourceFilter.class);
<MASK>dependencies.add(ResetFilter.class);</MASK>
dependencies.add(StandardFilter.class);
dependencies.add(ProfilingDatabaseFilter.class);
dependencies.add(CachingDatabaseFilter.class);
return dependencies;
}" |
Inversion-Mutation | megadiff | "@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService service = UserServiceFactory.getUserService();
User user = service.getCurrentUser();
if (user != null) {
String teamName = req.getParameter("teamName");
RequestDispatcher disp = req.getRequestDispatcher("CreateTeam.jsp");
if (teamName.trim().equals("")) {
disp.forward(req, resp);
} else {
PersistenceManager manager = PMF.get().getPersistenceManager();
Team team = null;
try {
team = manager.getObjectById(Team.class, teamName);
disp.forward(req, resp);
} catch (JDOObjectNotFoundException e) {
Team newTeam = new Team();
newTeam.setTeamKey(KeyFactory.createKey(
Team.class.getSimpleName(), teamName));
newTeam.setName(teamName);
newTeam.setMembers(new ArrayList<TeamMember>());
manager.makePersistent(newTeam);
req.setAttribute("team", newTeam);
disp = req.getRequestDispatcher("EditTeam.jsp");
disp.forward(req, resp);
}
}
} else {
resp.sendRedirect("/projectcontrol");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doGet" | "@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService service = UserServiceFactory.getUserService();
User user = service.getCurrentUser();
if (user != null) {
String teamName = req.getParameter("teamName");
RequestDispatcher disp = req.getRequestDispatcher("CreateTeam.jsp");
if (teamName.trim().equals("")) {
disp.forward(req, resp);
} else {
PersistenceManager manager = PMF.get().getPersistenceManager();
Team team = null;
try {
disp.forward(req, resp);
} catch (JDOObjectNotFoundException e) {
<MASK>team = manager.getObjectById(Team.class, teamName);</MASK>
Team newTeam = new Team();
newTeam.setTeamKey(KeyFactory.createKey(
Team.class.getSimpleName(), teamName));
newTeam.setName(teamName);
newTeam.setMembers(new ArrayList<TeamMember>());
manager.makePersistent(newTeam);
req.setAttribute("team", newTeam);
disp = req.getRequestDispatcher("EditTeam.jsp");
disp.forward(req, resp);
}
}
} else {
resp.sendRedirect("/projectcontrol");
}
}" |
Inversion-Mutation | megadiff | "@RequestMapping("/entity-details")
public String entityDetails(HttpServletRequest request) throws StorageException {
String view = request.getParameter("vt");
if (!"graph".equalsIgnoreCase(view))
view = "list";
request.setAttribute("view", view);
RequestUtils.params2attributes(request, "vt", "view_depth", "eid", "storage");
request.setAttribute("entity_view", "true");
String eid = (String) request.getParameter("eid");
if (null == eid)
return "redirect:/entities";
NeuroStorage neuroStorage = NMSServerConfig.getInstance().getStorage(request.getParameter("storage"));
if (null == neuroStorage)
{
request.setAttribute("storage_error", "Storage is not specified");
return "console/settings";
}
Entity e = neuroStorage.getEntityByUUID(eid);
if (null == e)
return "redirect:/query";
NetworkUtils.loadConnected(e, neuroStorage);
request.setAttribute("entity", e);
int depth = 1;
try
{
String depthStr = request.getParameter("view_depth");
if (null != depthStr && depthStr.length() > 0)
depth = Integer.parseInt(depthStr);
} catch (Exception ex)
{
ex.printStackTrace();
}
String queryStr = "select e(id='" + eid + "') / [depth='" + 2*depth + "']";
request.setAttribute("q", queryStr);
if ("graph".equalsIgnoreCase(view))
{
request.setAttribute("include_accordion_js", "true");
request.setAttribute("selected_tab", "graph");
}
return "console/e/details";
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "entityDetails" | "@RequestMapping("/entity-details")
public String entityDetails(HttpServletRequest request) throws StorageException {
String view = request.getParameter("vt");
if (!"graph".equalsIgnoreCase(view))
view = "list";
request.setAttribute("view", view);
RequestUtils.params2attributes(request, "vt", "view_depth", "eid", "storage");
request.setAttribute("entity_view", "true");
String eid = (String) request.getParameter("eid");
if (null == eid)
return "redirect:/entities";
NeuroStorage neuroStorage = NMSServerConfig.getInstance().getStorage(request.getParameter("storage"));
if (null == neuroStorage)
{
request.setAttribute("storage_error", "Storage is not specified");
return "console/settings";
}
Entity e = neuroStorage.getEntityByUUID(eid);
<MASK>NetworkUtils.loadConnected(e, neuroStorage);</MASK>
if (null == e)
return "redirect:/query";
request.setAttribute("entity", e);
int depth = 1;
try
{
String depthStr = request.getParameter("view_depth");
if (null != depthStr && depthStr.length() > 0)
depth = Integer.parseInt(depthStr);
} catch (Exception ex)
{
ex.printStackTrace();
}
String queryStr = "select e(id='" + eid + "') / [depth='" + 2*depth + "']";
request.setAttribute("q", queryStr);
if ("graph".equalsIgnoreCase(view))
{
request.setAttribute("include_accordion_js", "true");
request.setAttribute("selected_tab", "graph");
}
return "console/e/details";
}" |
Inversion-Mutation | megadiff | "public void instantiate(DataInputStream in) throws Exception {
d_x1 = in.readFloat();
d_y1 = in.readFloat();
d_x2 = in.readFloat();
d_y2 = in.readFloat();
d_id = in.readInt();
d_transparency = in.readInt();
if(d_id == GameActivity.getInstance().model().player().id()) {
d_transparency = 0;
} else {
GameActivity.getInstance().model().player().checkIfShot(d_x1, d_y1, d_x2, d_y2, d_id);
}
d_paint.setAlpha(d_transparency);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "instantiate" | "public void instantiate(DataInputStream in) throws Exception {
d_x1 = in.readFloat();
d_y1 = in.readFloat();
d_x2 = in.readFloat();
d_y2 = in.readFloat();
d_id = in.readInt();
if(d_id == GameActivity.getInstance().model().player().id()) {
d_transparency = 0;
} else {
<MASK>d_transparency = in.readInt();</MASK>
GameActivity.getInstance().model().player().checkIfShot(d_x1, d_y1, d_x2, d_y2, d_id);
}
d_paint.setAlpha(d_transparency);
}" |
Inversion-Mutation | megadiff | "protected int readComment(char c) throws IOException {
ISourcePosition startPosition = src.getPosition();
tokenBuffer.setLength(0);
tokenBuffer.append(c);
// FIXME: Consider making a better LexerSource.readLine
while ((c = src.read()) != '\n') {
if (c == EOF) {
break;
}
tokenBuffer.append(c);
}
src.unread(c);
// Store away each comment to parser result so IDEs can do whatever they want with them.
ISourcePosition position = startPosition.union(getPosition());
parserSupport.getResult().addComment(new CommentNode(position, tokenBuffer.toString()));
return c;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "readComment" | "protected int readComment(char c) throws IOException {
ISourcePosition startPosition = src.getPosition();
tokenBuffer.setLength(0);
<MASK>tokenBuffer.append(c);</MASK>
// FIXME: Consider making a better LexerSource.readLine
while ((c = src.read()) != '\n') {
<MASK>tokenBuffer.append(c);</MASK>
if (c == EOF) {
break;
}
}
src.unread(c);
// Store away each comment to parser result so IDEs can do whatever they want with them.
ISourcePosition position = startPosition.union(getPosition());
parserSupport.getResult().addComment(new CommentNode(position, tokenBuffer.toString()));
return c;
}" |
Inversion-Mutation | megadiff | "public void setValue(IValueReference value) {
IValue val = createValue();
if (val != null) {
if (value != null) {
IValue src = ((IValueProvider) value).getValue();
if (src == null)
return;
val.clear();
if (src instanceof Value
&& ((IValueProvider) value).isReference()) {
val.addReference(src);
} else {
val.addValue(src);
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setValue" | "public void setValue(IValueReference value) {
IValue val = createValue();
if (val != null) {
<MASK>val.clear();</MASK>
if (value != null) {
IValue src = ((IValueProvider) value).getValue();
if (src == null)
return;
if (src instanceof Value
&& ((IValueProvider) value).isReference()) {
val.addReference(src);
} else {
val.addValue(src);
}
}
}
}" |
Inversion-Mutation | megadiff | "public void exportXML(final java.io.Writer writer, final String indent, final Object any) throws Exception {
final StringBuffer sb_body = new StringBuffer();
sb_body.append(indent).append("<t2_layer_set\n");
final String in = indent + "\t";
super.exportXML(sb_body, in, any);
sb_body.append(in).append("layer_width=\"").append(layer_width).append("\"\n")
.append(in).append("layer_height=\"").append(layer_height).append("\"\n")
.append(in).append("rot_x=\"").append(rot_x).append("\"\n")
.append(in).append("rot_y=\"").append(rot_y).append("\"\n")
.append(in).append("rot_z=\"").append(rot_z).append("\"\n")
.append(in).append("snapshots_quality=\"").append(snapshots_quality).append("\"\n")
.append(in).append("snapshots_mode=\"").append(snapshot_modes[snapshots_mode]).append("\"\n")
// TODO: alpha! But it's not necessary.
;
sb_body.append(indent).append(">\n");
if (null != calibration) {
sb_body.append(in).append("<t2_calibration\n")
.append(in).append("\tpixelWidth=\"").append(calibration.pixelWidth).append("\"\n")
.append(in).append("\tpixelHeight=\"").append(calibration.pixelHeight).append("\"\n")
.append(in).append("\tpixelDepth=\"").append(calibration.pixelDepth).append("\"\n")
.append(in).append("\txOrigin=\"").append(calibration.xOrigin).append("\"\n")
.append(in).append("\tyOrigin=\"").append(calibration.yOrigin).append("\"\n")
.append(in).append("\tzOrigin=\"").append(calibration.zOrigin).append("\"\n")
.append(in).append("\tinfo=\"").append(calibration.info).append("\"\n")
.append(in).append("\tvalueUnit=\"").append(calibration.getValueUnit()).append("\"\n")
.append(in).append("\ttimeUnit=\"").append(calibration.getTimeUnit()).append("\"\n")
.append(in).append("\tunit=\"").append(calibration.getUnit()).append("\"\n")
.append(in).append("/>\n")
;
}
writer.write(sb_body.toString());
// export ZDisplayable objects
if (null != al_zdispl) {
for (Iterator it = al_zdispl.iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
sb_body.setLength(0);
zd.exportXML(sb_body, in, any);
writer.write(sb_body.toString()); // each separately, for they can be huge
}
}
// export Layer and contained Displayable objects
if (null != al_layers) {
//Utils.log("LayerSet " + id + " is saving " + al_layers.size() + " layers.");
for (Iterator it = al_layers.iterator(); it.hasNext(); ) {
sb_body.setLength(0);
((Layer)it.next()).exportXML(sb_body, in, any);
writer.write(sb_body.toString());
}
}
super.restXML(sb_body, in, any);
writer.write("</t2_layer_set>\n");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "exportXML" | "public void exportXML(final java.io.Writer writer, final String indent, final Object any) throws Exception {
final StringBuffer sb_body = new StringBuffer();
sb_body.append(indent).append("<t2_layer_set\n");
final String in = indent + "\t";
super.exportXML(sb_body, in, any);
sb_body.append(in).append("layer_width=\"").append(layer_width).append("\"\n")
.append(in).append("layer_height=\"").append(layer_height).append("\"\n")
.append(in).append("rot_x=\"").append(rot_x).append("\"\n")
.append(in).append("rot_y=\"").append(rot_y).append("\"\n")
.append(in).append("rot_z=\"").append(rot_z).append("\"\n")
.append(in).append("snapshots_quality=\"").append(snapshots_quality).append("\"\n")
.append(in).append("snapshots_mode=\"").append(snapshot_modes[snapshots_mode]).append("\"\n")
// TODO: alpha! But it's not necessary.
;
sb_body.append(indent).append(">\n");
if (null != calibration) {
sb_body.append(in).append("<t2_calibration\n")
.append(in).append("\tpixelWidth=\"").append(calibration.pixelWidth).append("\"\n")
.append(in).append("\tpixelHeight=\"").append(calibration.pixelHeight).append("\"\n")
.append(in).append("\tpixelDepth=\"").append(calibration.pixelDepth).append("\"\n")
.append(in).append("\txOrigin=\"").append(calibration.xOrigin).append("\"\n")
.append(in).append("\tyOrigin=\"").append(calibration.yOrigin).append("\"\n")
.append(in).append("\tzOrigin=\"").append(calibration.zOrigin).append("\"\n")
.append(in).append("\tinfo=\"").append(calibration.info).append("\"\n")
.append(in).append("\tvalueUnit=\"").append(calibration.getValueUnit()).append("\"\n")
.append(in).append("\ttimeUnit=\"").append(calibration.getTimeUnit()).append("\"\n")
.append(in).append("\tunit=\"").append(calibration.getUnit()).append("\"\n")
.append(in).append("/>\n")
;
}
writer.write(sb_body.toString());
// export ZDisplayable objects
if (null != al_zdispl) {
for (Iterator it = al_zdispl.iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
sb_body.setLength(0);
zd.exportXML(sb_body, in, any);
writer.write(sb_body.toString()); // each separately, for they can be huge
}
}
// export Layer and contained Displayable objects
if (null != al_layers) {
//Utils.log("LayerSet " + id + " is saving " + al_layers.size() + " layers.");
for (Iterator it = al_layers.iterator(); it.hasNext(); ) {
<MASK>((Layer)it.next()).exportXML(sb_body, in, any);</MASK>
sb_body.setLength(0);
writer.write(sb_body.toString());
}
}
super.restXML(sb_body, in, any);
writer.write("</t2_layer_set>\n");
}" |
Inversion-Mutation | megadiff | "void doAutoFocus(){
if(mCamera != null && mFocus != null){
mCamera.setPreviewCallback(null);
try{
mCamera.autoFocus(mFocus);
}catch(Exception e){
mPreviewCallback = new PreviewCallback(CameraPreview.this);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doAutoFocus" | "void doAutoFocus(){
<MASK>mCamera.setPreviewCallback(null);</MASK>
if(mCamera != null && mFocus != null){
try{
mCamera.autoFocus(mFocus);
}catch(Exception e){
mPreviewCallback = new PreviewCallback(CameraPreview.this);
}
}
}" |
Inversion-Mutation | megadiff | "public void saveUserAddons(ISdkLog log) {
FileOutputStream fos = null;
try {
String folder = AndroidLocation.getFolder();
File f = new File(folder, SRC_FILENAME);
fos = new FileOutputStream(f);
Properties props = new Properties();
int count = 0;
for (SdkSource s : getSources(SdkSourceCategory.USER_ADDONS)) {
props.setProperty(String.format("%s%02d", KEY_SRC, count), s.getUrl()); //$NON-NLS-1$
count++;
}
props.setProperty(KEY_COUNT, Integer.toString(count));
props.store( fos, "## User Sources for Android tool"); //$NON-NLS-1$
} catch (AndroidLocationException e) {
log.error(e, null);
} catch (IOException e) {
log.error(e, null);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "saveUserAddons" | "public void saveUserAddons(ISdkLog log) {
FileOutputStream fos = null;
try {
String folder = AndroidLocation.getFolder();
File f = new File(folder, SRC_FILENAME);
fos = new FileOutputStream(f);
Properties props = new Properties();
int count = 0;
for (SdkSource s : getSources(SdkSourceCategory.USER_ADDONS)) {
<MASK>count++;</MASK>
props.setProperty(String.format("%s%02d", KEY_SRC, count), s.getUrl()); //$NON-NLS-1$
}
props.setProperty(KEY_COUNT, Integer.toString(count));
props.store( fos, "## User Sources for Android tool"); //$NON-NLS-1$
} catch (AndroidLocationException e) {
log.error(e, null);
} catch (IOException e) {
log.error(e, null);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}" |
Inversion-Mutation | megadiff | "public void addProps(MarkerAnnotationAndPosition marker, IAnalysisPreferences analysisPreferences,
final String line, final PySelection ps, int offset, IPythonNature nature, final PyEdit edit,
List<ICompletionProposal> props)
throws BadLocationException, CoreException {
Integer id = (Integer) marker.markerAnnotation.getMarker().getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
if (handled.contains(id)) {
return;
}
handled.add(id);
final String messageToIgnore = analysisPreferences.getRequiredMessageToIgnore(id);
if (line.indexOf(messageToIgnore) != -1) {
//ok, move on...
return;
}
IgnoreCompletionProposal proposal = new IgnoreCompletionProposal(messageToIgnore, ps.getEndLineOffset(), 0,
offset, //note: the cursor position is unchanged!
annotationImage, messageToIgnore.substring(1), null, null,
PyCompletionProposal.PRIORITY_DEFAULT, edit) {
@Override
public void apply(IDocument document) {
FastStringBuffer strToAdd = new FastStringBuffer(messageToIgnore, 5);
int lineLen = line.length();
int endLineIndex = ps.getEndLineOffset();
boolean isComment = ParsingUtils.isCommentPartition(document, endLineIndex);
int whitespacesAtEnd = 0;
char c = '\0';
for (int i = lineLen - 1; i >= 0; i--) {
c = line.charAt(i);
if (c == ' ') {
whitespacesAtEnd += 1;
} else {
break;
}
}
if (isComment) {
if (whitespacesAtEnd == 0) {
strToAdd.insert(0, ' '); //it's a comment already, but as it has no spaces in the end, let's add one.
}
} else {
FormatStd formatStd = IgnoreErrorParticipant.this.format;
if (formatStd == null) {
if (edit != null) {
formatStd = edit.getFormatStd();
} else {
formatStd = PyFormatStd.getFormat();
}
}
strToAdd.insert(0, '#');
PyFormatStd.formatComment(formatStd, strToAdd);
//Just add spaces before the '#' if there's actually some content in the line.
if (c != '\r' && c != '\n' && c != '\0' && c != ' ') {
int spacesBeforeComment = formatStd.spacesBeforeComment;
if (spacesBeforeComment < 0) {
spacesBeforeComment = 1; //If 'manual', add a single space.
}
spacesBeforeComment = spacesBeforeComment - whitespacesAtEnd;
if (spacesBeforeComment > 0) {
strToAdd.insertN(0, ' ', spacesBeforeComment);
}
}
}
fReplacementString = strToAdd.toString();
super.apply(document);
}
};
props.add(proposal);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addProps" | "public void addProps(MarkerAnnotationAndPosition marker, IAnalysisPreferences analysisPreferences,
final String line, final PySelection ps, int offset, IPythonNature nature, final PyEdit edit,
List<ICompletionProposal> props)
throws BadLocationException, CoreException {
Integer id = (Integer) marker.markerAnnotation.getMarker().getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
if (handled.contains(id)) {
return;
}
handled.add(id);
final String messageToIgnore = analysisPreferences.getRequiredMessageToIgnore(id);
if (line.indexOf(messageToIgnore) != -1) {
//ok, move on...
return;
}
IgnoreCompletionProposal proposal = new IgnoreCompletionProposal(messageToIgnore, ps.getEndLineOffset(), 0,
offset, //note: the cursor position is unchanged!
annotationImage, messageToIgnore.substring(1), null, null,
PyCompletionProposal.PRIORITY_DEFAULT, edit) {
@Override
public void apply(IDocument document) {
FastStringBuffer strToAdd = new FastStringBuffer(messageToIgnore, 5);
int lineLen = line.length();
int endLineIndex = ps.getEndLineOffset();
boolean isComment = ParsingUtils.isCommentPartition(document, endLineIndex);
int whitespacesAtEnd = 0;
char c = '\0';
for (int i = lineLen - 1; i >= 0; i--) {
c = line.charAt(i);
if (c == ' ') {
whitespacesAtEnd += 1;
} else {
break;
}
}
if (isComment) {
if (whitespacesAtEnd == 0) {
strToAdd.insert(0, ' '); //it's a comment already, but as it has no spaces in the end, let's add one.
}
} else {
FormatStd formatStd = IgnoreErrorParticipant.this.format;
if (formatStd == null) {
if (edit != null) {
formatStd = edit.getFormatStd();
} else {
formatStd = PyFormatStd.getFormat();
}
}
strToAdd.insert(0, '#');
//Just add spaces before the '#' if there's actually some content in the line.
if (c != '\r' && c != '\n' && c != '\0' && c != ' ') {
int spacesBeforeComment = formatStd.spacesBeforeComment;
if (spacesBeforeComment < 0) {
spacesBeforeComment = 1; //If 'manual', add a single space.
}
spacesBeforeComment = spacesBeforeComment - whitespacesAtEnd;
if (spacesBeforeComment > 0) {
strToAdd.insertN(0, ' ', spacesBeforeComment);
}
}
<MASK>PyFormatStd.formatComment(formatStd, strToAdd);</MASK>
}
fReplacementString = strToAdd.toString();
super.apply(document);
}
};
props.add(proposal);
}" |
Inversion-Mutation | megadiff | "@Override
public void apply(IDocument document) {
FastStringBuffer strToAdd = new FastStringBuffer(messageToIgnore, 5);
int lineLen = line.length();
int endLineIndex = ps.getEndLineOffset();
boolean isComment = ParsingUtils.isCommentPartition(document, endLineIndex);
int whitespacesAtEnd = 0;
char c = '\0';
for (int i = lineLen - 1; i >= 0; i--) {
c = line.charAt(i);
if (c == ' ') {
whitespacesAtEnd += 1;
} else {
break;
}
}
if (isComment) {
if (whitespacesAtEnd == 0) {
strToAdd.insert(0, ' '); //it's a comment already, but as it has no spaces in the end, let's add one.
}
} else {
FormatStd formatStd = IgnoreErrorParticipant.this.format;
if (formatStd == null) {
if (edit != null) {
formatStd = edit.getFormatStd();
} else {
formatStd = PyFormatStd.getFormat();
}
}
strToAdd.insert(0, '#');
PyFormatStd.formatComment(formatStd, strToAdd);
//Just add spaces before the '#' if there's actually some content in the line.
if (c != '\r' && c != '\n' && c != '\0' && c != ' ') {
int spacesBeforeComment = formatStd.spacesBeforeComment;
if (spacesBeforeComment < 0) {
spacesBeforeComment = 1; //If 'manual', add a single space.
}
spacesBeforeComment = spacesBeforeComment - whitespacesAtEnd;
if (spacesBeforeComment > 0) {
strToAdd.insertN(0, ' ', spacesBeforeComment);
}
}
}
fReplacementString = strToAdd.toString();
super.apply(document);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "apply" | "@Override
public void apply(IDocument document) {
FastStringBuffer strToAdd = new FastStringBuffer(messageToIgnore, 5);
int lineLen = line.length();
int endLineIndex = ps.getEndLineOffset();
boolean isComment = ParsingUtils.isCommentPartition(document, endLineIndex);
int whitespacesAtEnd = 0;
char c = '\0';
for (int i = lineLen - 1; i >= 0; i--) {
c = line.charAt(i);
if (c == ' ') {
whitespacesAtEnd += 1;
} else {
break;
}
}
if (isComment) {
if (whitespacesAtEnd == 0) {
strToAdd.insert(0, ' '); //it's a comment already, but as it has no spaces in the end, let's add one.
}
} else {
FormatStd formatStd = IgnoreErrorParticipant.this.format;
if (formatStd == null) {
if (edit != null) {
formatStd = edit.getFormatStd();
} else {
formatStd = PyFormatStd.getFormat();
}
}
strToAdd.insert(0, '#');
//Just add spaces before the '#' if there's actually some content in the line.
if (c != '\r' && c != '\n' && c != '\0' && c != ' ') {
int spacesBeforeComment = formatStd.spacesBeforeComment;
if (spacesBeforeComment < 0) {
spacesBeforeComment = 1; //If 'manual', add a single space.
}
spacesBeforeComment = spacesBeforeComment - whitespacesAtEnd;
if (spacesBeforeComment > 0) {
strToAdd.insertN(0, ' ', spacesBeforeComment);
}
}
<MASK>PyFormatStd.formatComment(formatStd, strToAdd);</MASK>
}
fReplacementString = strToAdd.toString();
super.apply(document);
}" |
Inversion-Mutation | megadiff | "private void processTagStart(XmlPullParser parser, boolean isempty) {
if (justended) {
// avoid the pathological case where we have for example
// <td class="tmiblock1" rsf:id="tmiblock:"></td><td> which makes it
// hard to spot run ends on the basis of recursion uncession.
justended = false;
XMLLump backlump = newLump(parser);
backlump.nestingdepth--;
setLumpChars(backlump, null, 0, 0);
}
XMLLump headlump = newLump(parser);
if (roottagindex == -1)
roottagindex = headlump.lumpindex;
String tagname = parser.getName();
// standard text of |<tagname | to allow easy identification.
setLumpString(headlump, XMLLump.tagToText(tagname));
// HashMap forwardmap = new HashMap();
// headlump.forwardmap = forwardmap;
// current policy - every open tag gets a forwardmap, and separate lumps.
// eventually we only want a lump where there is an rsf:id.
int attrs = parser.getAttributeCount();
if (attrs > 0) {
headlump.attributemap = new HashMap(attrs < 3? (attrs + 1)*2 : attrs * 2);
for (int i = 0; i < attrs; ++i) {
String attrname = parser.getAttributeName(i);
String attrvalue = parser.getAttributeValue(i);
headlump.attributemap.put(attrname, attrvalue);
}
if (parseinterceptors != null) {
for (int i = 0; i < parseinterceptors.size(); ++i) {
TemplateParseInterceptor parseinterceptor = (TemplateParseInterceptor) parseinterceptors
.get(i);
parseinterceptor.adjustAttributes(tagname, headlump.attributemap);
}
}
boolean firstattr = true;
for (Iterator keyit = headlump.attributemap.keySet().iterator(); keyit
.hasNext();) {
String attrname = (String) keyit.next();
String attrvalue = (String) headlump.attributemap.get(attrname);
XMLLump frontlump = newLump(parser);
CharWrap lumpac = new CharWrap();
if (!firstattr) {
lumpac.append("\" ");
}
firstattr = false;
lumpac.append(attrname).append("=\"");
setLumpChars(frontlump, lumpac.storage, 0, lumpac.size);
// frontlump holds |" name="|
// valuelump just holds the value.
XMLLump valuelump = newLump(parser);
setLumpString(valuelump, attrvalue);
if (attrname.equals(XMLLump.ID_ATTRIBUTE)) {
String ID = attrvalue;
if (ID.startsWith(XMLLump.FORID_PREFIX)
&& ID.endsWith(XMLLump.FORID_SUFFIX)) {
ID = ID.substring(0, ID.length() - XMLLump.FORID_SUFFIX.length());
}
headlump.rsfID = ID;
XMLLump stacktop = findTopContainer();
stacktop.downmap.addLump(ID, headlump);
globalmap.addLump(ID, headlump);
SplitID split = new SplitID(ID);
if (split.prefix.equals(XMLLump.FORID_PREFIX)) {
// no special note, just prevent suffix logic.
}
// we need really to be able to locate 3 levels of id -
// for-message:message:to
// ideally we would also like to be able to locate repetition
// constructs too, hopefully the standard suffix-based computation
// will allow this. However we previously never allowed BOTH
// repetitious and non-repetitious constructs to share the same
// prefix, so revisit this to solve.
// }
else if (split.suffix != null) {
// a repetitive tag is found.
headlump.downmap = new XMLLumpMMap();
// Repetitions within a SCOPE should be UNIQUE and CONTIGUOUS.
XMLLump prevlast = stacktop.downmap.getFinal(split.prefix);
stacktop.downmap.setFinal(split.prefix, headlump);
if (prevlast != null) {
// only store transitions from non-initial state -
// TODO: see if transition system will ever be needed.
String prevsuffix = SplitID.getSuffix(prevlast.rsfID);
String transitionkey = split.prefix + SplitID.SEPARATOR
+ prevsuffix + XMLLump.TRANSITION_SEPARATOR + split.suffix;
stacktop.downmap.addLump(transitionkey, prevlast);
globalmap.addLump(transitionkey, prevlast);
}
}
} // end if rsf:id attribute
} // end for each attribute
}
XMLLump finallump = newLump(parser);
String closetext = attrs == 0 ? (isempty ? "/>"
: ">")
: (isempty ? "\"/>"
: "\">");
setLumpString(finallump, closetext);
headlump.open_end = finallump;
tagstack.add(nestingdepth, headlump);
if (isempty) {
processTagEnd(parser);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processTagStart" | "private void processTagStart(XmlPullParser parser, boolean isempty) {
if (justended) {
// avoid the pathological case where we have for example
// <td class="tmiblock1" rsf:id="tmiblock:"></td><td> which makes it
// hard to spot run ends on the basis of recursion uncession.
justended = false;
XMLLump backlump = newLump(parser);
backlump.nestingdepth--;
setLumpChars(backlump, null, 0, 0);
}
XMLLump headlump = newLump(parser);
if (roottagindex == -1)
roottagindex = headlump.lumpindex;
String tagname = parser.getName();
// standard text of |<tagname | to allow easy identification.
setLumpString(headlump, XMLLump.tagToText(tagname));
// HashMap forwardmap = new HashMap();
// headlump.forwardmap = forwardmap;
// current policy - every open tag gets a forwardmap, and separate lumps.
// eventually we only want a lump where there is an rsf:id.
int attrs = parser.getAttributeCount();
if (attrs > 0) {
headlump.attributemap = new HashMap(attrs < 3? (attrs + 1)*2 : attrs * 2);
for (int i = 0; i < attrs; ++i) {
String attrname = parser.getAttributeName(i);
String attrvalue = parser.getAttributeValue(i);
headlump.attributemap.put(attrname, attrvalue);
}
if (parseinterceptors != null) {
for (int i = 0; i < parseinterceptors.size(); ++i) {
TemplateParseInterceptor parseinterceptor = (TemplateParseInterceptor) parseinterceptors
.get(i);
parseinterceptor.adjustAttributes(tagname, headlump.attributemap);
}
}
boolean firstattr = true;
for (Iterator keyit = headlump.attributemap.keySet().iterator(); keyit
.hasNext();) {
String attrname = (String) keyit.next();
String attrvalue = (String) headlump.attributemap.get(attrname);
XMLLump frontlump = newLump(parser);
CharWrap lumpac = new CharWrap();
if (!firstattr) {
lumpac.append("\" ");
<MASK>firstattr = false;</MASK>
}
lumpac.append(attrname).append("=\"");
setLumpChars(frontlump, lumpac.storage, 0, lumpac.size);
// frontlump holds |" name="|
// valuelump just holds the value.
XMLLump valuelump = newLump(parser);
setLumpString(valuelump, attrvalue);
if (attrname.equals(XMLLump.ID_ATTRIBUTE)) {
String ID = attrvalue;
if (ID.startsWith(XMLLump.FORID_PREFIX)
&& ID.endsWith(XMLLump.FORID_SUFFIX)) {
ID = ID.substring(0, ID.length() - XMLLump.FORID_SUFFIX.length());
}
headlump.rsfID = ID;
XMLLump stacktop = findTopContainer();
stacktop.downmap.addLump(ID, headlump);
globalmap.addLump(ID, headlump);
SplitID split = new SplitID(ID);
if (split.prefix.equals(XMLLump.FORID_PREFIX)) {
// no special note, just prevent suffix logic.
}
// we need really to be able to locate 3 levels of id -
// for-message:message:to
// ideally we would also like to be able to locate repetition
// constructs too, hopefully the standard suffix-based computation
// will allow this. However we previously never allowed BOTH
// repetitious and non-repetitious constructs to share the same
// prefix, so revisit this to solve.
// }
else if (split.suffix != null) {
// a repetitive tag is found.
headlump.downmap = new XMLLumpMMap();
// Repetitions within a SCOPE should be UNIQUE and CONTIGUOUS.
XMLLump prevlast = stacktop.downmap.getFinal(split.prefix);
stacktop.downmap.setFinal(split.prefix, headlump);
if (prevlast != null) {
// only store transitions from non-initial state -
// TODO: see if transition system will ever be needed.
String prevsuffix = SplitID.getSuffix(prevlast.rsfID);
String transitionkey = split.prefix + SplitID.SEPARATOR
+ prevsuffix + XMLLump.TRANSITION_SEPARATOR + split.suffix;
stacktop.downmap.addLump(transitionkey, prevlast);
globalmap.addLump(transitionkey, prevlast);
}
}
} // end if rsf:id attribute
} // end for each attribute
}
XMLLump finallump = newLump(parser);
String closetext = attrs == 0 ? (isempty ? "/>"
: ">")
: (isempty ? "\"/>"
: "\">");
setLumpString(finallump, closetext);
headlump.open_end = finallump;
tagstack.add(nestingdepth, headlump);
if (isempty) {
processTagEnd(parser);
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void tearDown() throws Exception {
authorizationServiceReg.unregister();
super.tearDown();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tearDown" | "@Override
protected void tearDown() throws Exception {
<MASK>super.tearDown();</MASK>
authorizationServiceReg.unregister();
}" |
Inversion-Mutation | megadiff | "public void dispose() {
super.dispose();
htmlViewCombo.dispose();
xmlViewCombo.dispose();
editor.dispose();
rolesTable.dispose();
addRowButton.dispose();
removeRowButton.dispose();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "dispose" | "public void dispose() {
super.dispose();
htmlViewCombo.dispose();
xmlViewCombo.dispose();
<MASK>rolesTable.dispose();</MASK>
editor.dispose();
addRowButton.dispose();
removeRowButton.dispose();
}" |
Inversion-Mutation | megadiff | "@Timed
public List<Bookmark> findAll() {
final List<Order> orders = new ArrayList<>();
orders.add(new Order(Direction.DESC, "creationDate"));
orders.add(new Order(Direction.DESC, "modificationDate"));
return Lists.newArrayList(bookmarkRepository.findAll(new Sort(orders)));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findAll" | "@Timed
public List<Bookmark> findAll() {
final List<Order> orders = new ArrayList<>();
<MASK>orders.add(new Order(Direction.DESC, "modificationDate"));</MASK>
orders.add(new Order(Direction.DESC, "creationDate"));
return Lists.newArrayList(bookmarkRepository.findAll(new Sort(orders)));
}" |
Inversion-Mutation | megadiff | "private void deleteDigitalObject(Connection connection, String pid)
throws SQLException {
logFinest("Entered DefaultDOReplicator.deleteDigitalObject");
Statement st=null;
Statement st2=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking do table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT doDbID FROM "
+ "do WHERE doPID='" + pid + "'");
if (!results.next()) {
// must not be a digitalobject...exit early
logFinest(pid + " wasn't found in do table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("doDbID");
results.close();
logFinest(pid + " was found in do table (DBID="
+ dbid + ")");
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table...");
HashSet dissIds=new HashSet();
HashSet dissIdsInUse = new HashSet();
results=logAndExecuteQuery(st, "SELECT dissDbID from "
+ "doDissAssoc WHERE doDbID=" + dbid);
while (results.next()) {
dissIds.add(new Integer(results.getInt("dissDbID")));
}
results.close();
HashSet bMechIds = new HashSet();
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table unique to this object...");
Iterator iterator = dissIds.iterator();
while (iterator.hasNext())
{
Integer id = (Integer)iterator.next();
logFinest("Getting occurrences of dissDbID(s) in "
+ "doDissAssoc table...");
results=logAndExecuteQuery(st, "SELECT COUNT(*) from "
+ "doDissAssoc WHERE dissDbID=" + id);
while (results.next())
{
Integer i1 = new Integer(results.getInt("COUNT(*)"));
if ( i1.intValue() > 1 )
{
//dissIds.remove(id);
// A dissDbID that occurs more than once indicates that the
// disseminator is used by other objects. In this case, we
// do not want to remove the disseminator from the diss
// table so keep track of this dissDbID.
dissIdsInUse.add(id);
} else
{
ResultSet rs = null;
logFinest("Getting associated bMechDbID(s) that are unique "
+ "for this object in diss table...");
st2 = connection.createStatement();
rs=logAndExecuteQuery(st2, "SELECT bMechDbID from "
+ "diss WHERE dissDbID=" + id);
while (rs.next())
{
bMechIds.add(new Integer(rs.getInt("bMechDbID")));
}
rs.close();
st2.close();
}
}
results.close();
}
iterator = dissIdsInUse.iterator();
// Remove disseminator ids of those disseminators that were in
// use by one or more other objects to prevent them from being
// removed from the disseminator table in following code section.
while (iterator.hasNext() )
{
Integer id = (Integer)iterator.next();
dissIds.remove(id);
}
logFinest("Found " + dissIds.size() + " dissDbID(s).");
logFinest("Getting bMechDbIDs matching dsBindMapDbID(s) from dsBind "
+ "table...");
logFinest("Getting dsBindMapDbID(s) from dsBind "
+ "table...");
//HashSet bmapIds=new HashSet();
//results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM "
// + "dsBind WHERE doDbID=" + dbid);
//while (results.next()) {
// bmapIds.add(new Integer(results.getInt("dsBindMapDbID")));
//}
//results.close();
//logFinest("Found " + bmapIds.size() + " dsBindMapDbID(s).");
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from do table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM do "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from doDissAssoc "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "doDissAssoc WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBind table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from diss table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE "
+ inIntegerSetWhereConditionString("dissDbID", dissIds));
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindMap "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap "
+ "WHERE " + inIntegerSetWhereConditionString(
// "dsBindMapDbID", bmapIds));
"bMechDbID", bMechIds));
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null) st.close();
if (st2!=null) st2.close();
logFinest("Exiting DefaultDOReplicator.deleteDigitalObject");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "deleteDigitalObject" | "private void deleteDigitalObject(Connection connection, String pid)
throws SQLException {
logFinest("Entered DefaultDOReplicator.deleteDigitalObject");
Statement st=null;
Statement st2=null;
ResultSet results=null;
try {
st=connection.createStatement();
<MASK>st2 = connection.createStatement();</MASK>
//
// READ
//
logFinest("Checking do table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT doDbID FROM "
+ "do WHERE doPID='" + pid + "'");
if (!results.next()) {
// must not be a digitalobject...exit early
logFinest(pid + " wasn't found in do table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("doDbID");
results.close();
logFinest(pid + " was found in do table (DBID="
+ dbid + ")");
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table...");
HashSet dissIds=new HashSet();
HashSet dissIdsInUse = new HashSet();
results=logAndExecuteQuery(st, "SELECT dissDbID from "
+ "doDissAssoc WHERE doDbID=" + dbid);
while (results.next()) {
dissIds.add(new Integer(results.getInt("dissDbID")));
}
results.close();
HashSet bMechIds = new HashSet();
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table unique to this object...");
Iterator iterator = dissIds.iterator();
while (iterator.hasNext())
{
Integer id = (Integer)iterator.next();
logFinest("Getting occurrences of dissDbID(s) in "
+ "doDissAssoc table...");
results=logAndExecuteQuery(st, "SELECT COUNT(*) from "
+ "doDissAssoc WHERE dissDbID=" + id);
while (results.next())
{
Integer i1 = new Integer(results.getInt("COUNT(*)"));
if ( i1.intValue() > 1 )
{
//dissIds.remove(id);
// A dissDbID that occurs more than once indicates that the
// disseminator is used by other objects. In this case, we
// do not want to remove the disseminator from the diss
// table so keep track of this dissDbID.
dissIdsInUse.add(id);
} else
{
ResultSet rs = null;
logFinest("Getting associated bMechDbID(s) that are unique "
+ "for this object in diss table...");
rs=logAndExecuteQuery(st2, "SELECT bMechDbID from "
+ "diss WHERE dissDbID=" + id);
while (rs.next())
{
bMechIds.add(new Integer(rs.getInt("bMechDbID")));
}
rs.close();
st2.close();
}
}
results.close();
}
iterator = dissIdsInUse.iterator();
// Remove disseminator ids of those disseminators that were in
// use by one or more other objects to prevent them from being
// removed from the disseminator table in following code section.
while (iterator.hasNext() )
{
Integer id = (Integer)iterator.next();
dissIds.remove(id);
}
logFinest("Found " + dissIds.size() + " dissDbID(s).");
logFinest("Getting bMechDbIDs matching dsBindMapDbID(s) from dsBind "
+ "table...");
logFinest("Getting dsBindMapDbID(s) from dsBind "
+ "table...");
//HashSet bmapIds=new HashSet();
//results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM "
// + "dsBind WHERE doDbID=" + dbid);
//while (results.next()) {
// bmapIds.add(new Integer(results.getInt("dsBindMapDbID")));
//}
//results.close();
//logFinest("Found " + bmapIds.size() + " dsBindMapDbID(s).");
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from do table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM do "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from doDissAssoc "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "doDissAssoc WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBind table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from diss table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE "
+ inIntegerSetWhereConditionString("dissDbID", dissIds));
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindMap "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap "
+ "WHERE " + inIntegerSetWhereConditionString(
// "dsBindMapDbID", bmapIds));
"bMechDbID", bMechIds));
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null) st.close();
if (st2!=null) st2.close();
logFinest("Exiting DefaultDOReplicator.deleteDigitalObject");
}
}" |
Inversion-Mutation | megadiff | "public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
String com = ifd.getComment();
if (com == null) com = "";
return com.indexOf(FLUOVIEW_MAGIC_STRING) != -1 &&
ifd.containsKey(new Integer(MMHEADER)) ||
ifd.containsKey(new Integer(MMSTAMP));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "isThisType" | "public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
String com = ifd.getComment();
if (com == null) com = "";
<MASK>if (ifd == null) return false;</MASK>
return com.indexOf(FLUOVIEW_MAGIC_STRING) != -1 &&
ifd.containsKey(new Integer(MMHEADER)) ||
ifd.containsKey(new Integer(MMSTAMP));
}" |
Inversion-Mutation | megadiff | "public Gson create() {
List<TypeAdapter.Factory> factories = new ArrayList<TypeAdapter.Factory>();
factories.addAll(this.factories);
Collections.reverse(factories);
factories.addAll(this.hierarchyFactories);
addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories);
return new Gson(excluder, fieldNamingPolicy, instanceCreators,
serializeNulls, complexMapKeySerialization,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting,
serializeSpecialFloatingPointValues, longSerializationPolicy, factories);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "create" | "public Gson create() {
List<TypeAdapter.Factory> factories = new ArrayList<TypeAdapter.Factory>();
<MASK>factories.addAll(this.hierarchyFactories);</MASK>
factories.addAll(this.factories);
Collections.reverse(factories);
addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories);
return new Gson(excluder, fieldNamingPolicy, instanceCreators,
serializeNulls, complexMapKeySerialization,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting,
serializeSpecialFloatingPointValues, longSerializationPolicy, factories);
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) throws SQLException {
// BlockingQueue receives all client messages, allows reads only when non-empty, and supports threads
final BlockingQueue<Message> inMessages = new LinkedBlockingQueue<Message>();
final BlockingQueue<Message> outMessages = new LinkedBlockingQueue<Message>();
// Map from user id (integer) to User object
Map<Object, User> userMap = new HashMap<Object, User>();
// Map from tableNum to Table object
int numTables = 0;
Map<Object, Table> tableMap = new HashMap<Object, Table>();
// Runs the client interface server
MainServer mainServer = new MainServer(inMessages, outMessages);
mainServer.start(); // thread
// All of the server mechanics are handled by the MainServer and its subclasses,
// so that SetServer only has to read from inMessages to get incoming client messages,
// and write to outMessages to send them. These queues contain Message objects, which
// simply contain a clientID and a message string.
boolean isRunning = true;
Connection connection = null;
Statement stmt = null;
ResultSet usertable = null;
while(isRunning) // Messages are handled in the order they are received. If each message-handling is fast, there shouldn't be a problem.
{
try {
final Message inM = inMessages.take();
String [] splitM = inM.message.split("[;]"); // Message parts split by semicolons
switch(splitM[0].charAt(0)) {// Switch on first character in message (command character)
case 'R': // Register: R;Username;Password
if(splitM.length != 3) {System.err.println("Message Length Error!"); break;}
try {
connection = DriverManager
.getConnection("jdbc:mysql://199.98.20.119:3306/set","java", "eeonly1");
} catch (SQLException e) {
System.out.println("Connection Failed!");
e.printStackTrace();
return;
}
stmt = connection.createStatement();
usertable=stmt.executeQuery("SELECT * FROM `users` WHERE `username` = '"+splitM[1]+"';");
if (usertable.next()){
outMessages.put( new Message(inM.clientID, "X;R") );
System.out.println("User already exists");
}
else {
stmt.executeUpdate("INSERT INTO users (username, password) VALUES ('"+splitM[1]+"', '"+splitM[2]+"');");
System.out.println("User created");
outMessages.put( new Message(inM.clientID, "I;false;"+allTableString(tableMap)+";"+allUserString(userMap)) );
User newUser = new User(splitM[1], 1000, -1, false);
userMap.put(inM.clientID, newUser);
outMessages.put( new Message(-1, "U;" + splitM[1] + ";N/A") );
}
stmt.close();
connection.close();
break;
case 'L': // Login: L;Username;Password
if(splitM.length != 3) {System.err.println("Message Length Error!"); break;}
try {
connection = DriverManager
.getConnection("jdbc:mysql://199.98.20.119:3306/set","java", "eeonly1");
} catch (SQLException e) {
System.out.println("Connection Failed!");
e.printStackTrace();
return;
}
stmt = connection.createStatement();
usertable = stmt.executeQuery("SELECT * FROM `users` WHERE `username` = '"+splitM[1]+"';");
if (!usertable.next()){
System.out.println("User not found");
}
else{
boolean alreadyOnline = false;
Iterator<Entry<Object, User>> it = userMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Object, User> entry = (Map.Entry<Object, User>) it.next();
User curUser = entry.getValue();
if(curUser.username.compareTo(splitM[1]) == 0) {
alreadyOnline = true;
break;
}
}
if(alreadyOnline) {
outMessages.put( new Message(inM.clientID, "X;A") );
} else {
String passt = usertable.getString("password");
boolean isAdmin=false;
if (splitM[2].equals(passt)){
String accountType = usertable.getString("type");
int userRating = usertable.getInt("score");
if(accountType.equals("admin")){
isAdmin=true;
}
outMessages.put( new Message(inM.clientID, "I;"+isAdmin+";"+allTableString(tableMap)+";"+allUserString(userMap)) );
User newUser = new User(splitM[1], userRating, -1, isAdmin);
userMap.put(inM.clientID, newUser);
outMessages.put( new Message(-1, "U;" + splitM[1] + ";N/A") );
}
else{
outMessages.put( new Message(inM.clientID, "X;L") );
}
}
}
stmt.close();
connection.close();
break;
case 'T': // Create Table: T;Name;NumPlayers
if(splitM.length != 3) {System.err.println("Message Length Error!"); break;}
User userT = userMap.get(inM.clientID);
if(userT.currentTable >= 0) {
outMessages.put(new Message(inM.clientID, "A"));
break;
}
userT.currentTable = numTables;
Table newTable = new Table(splitM[1], 0, Integer.parseInt(splitM[2]));
newTable.addPlayer(inM.clientID);
// Give client "Table Made" message
outMessages.put( new Message(inM.clientID, newTable.playerString(userMap)) );
// Broadcast new table update
outMessages.put( new Message(-1, "U;" + numTables + ";" + newTable.name + ";" + newTable.numPlayers + ";" + newTable.maxPlayers + ";" + newTable.status()) );
outMessages.put( new Message(-1, "U;" + userT.username + ";" + numTables) );
tableMap.put(numTables, newTable);
numTables++;
break;
case 'J': // Join Table: J;TableNum
if(splitM.length != 2) {System.err.println("Message Length Error!"); break;}
User userJ = userMap.get(inM.clientID);
if(userJ.currentTable >= 0) {
outMessages.put(new Message(inM.clientID, "A"));
break;
}
userJ.currentTable = Integer.parseInt(splitM[1]);
Table tableJ = tableMap.get(userJ.currentTable);
if( tableJ != null ) {
if(tableJ.numPlayers < tableJ.maxPlayers) {
if(tableJ.numGoPressed < tableJ.maxPlayers) { // Game not in progress
tableJ.addPlayer(inM.clientID);
outMessages.put(new Message(-1, "U;" + userJ.currentTable + ";" + tableJ.name + ";" + tableJ.numPlayers + ";" + tableJ.maxPlayers + ";" + tableJ.status()));
outMessages.put( new Message(-1, "U;" + userJ.username + ";" + userJ.currentTable) );
sendToTable(outMessages, tableJ, tableJ.playerString(userMap));
} else { // Game in progress
userJ.currentTable = -1;
outMessages.put(new Message(inM.clientID, "H")); // Table is playing
}
} else {
userJ.currentTable = -1;
outMessages.put(new Message(inM.clientID, "F")); // Table is full
}
} else {
System.err.println("Table requested that does not exist!");
userJ.currentTable = -1;
outMessages.put(new Message(inM.clientID, "F")); // Pretend table is full
}
break;
case 'E': // Exit Table: E
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
User userE = userMap.get(inM.clientID);
if(userE.currentTable < 0) { // User exited non-existent table
System.err.println("User exited non-existent table!");
outMessages.put(new Message(inM.clientID, "E"));
break;
}
Table tableE = tableMap.get(userE.currentTable);
outMessages.put(new Message(inM.clientID, "E"));
if( tableE != null ) {
tableE.removePlayer(inM.clientID);
outMessages.put(new Message(-1, "U;" + userE.currentTable + ";" + tableE.name + ";" + tableE.numPlayers + ";" + tableE.maxPlayers + ";" + tableE.status()));
outMessages.put( new Message(-1, "U;" + userE.username + ";N/A") );
if(tableE.numPlayers > 0) {
sendToTable(outMessages, tableE, tableE.playerString(userMap));
} else {
tableMap.remove(userE.currentTable);
}
} else {
System.err.println("Player exited non-existant table!");
}
userE.currentTable = -1;
break;
case 'D': // Disconnect: D
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
mainServer.socketMap.remove(inM.clientID);
User userD = userMap.get(inM.clientID);
if(userD != null) {
outMessages.put( new Message(-1, "U;" + userD.username + ";X") );
if(userD.currentTable < 0) { // User not at table
userMap.remove(inM.clientID);
break;
}
Table tableD = tableMap.get(userD.currentTable);
if( tableD != null ) {
tableD.removePlayer(inM.clientID);
outMessages.put(new Message(-1, "U;" + userD.currentTable + ";" + tableD.name + ";" + tableD.numPlayers + ";" + tableD.maxPlayers + ";" + tableD.status()));
if(tableD.numPlayers > 0) {
sendToTable(outMessages, tableD, tableD.playerString(userMap));
if(tableD.numGoPressed == tableD.maxPlayers) { // Game is playing
Connection connectionD = null;
Statement stmtD = null;
connectionD = DriverManager.getConnection("jdbc:mysql://199.98.20.119:3306/set","java", "eeonly1");
stmtD = connectionD.createStatement();
stmtD.executeUpdate("UPDATE `users` SET `score`=score-10 WHERE `username`='"+userD.username+"';");
stmtD.close();
connectionD.close();
} else {
sendToTable(outMessages, tableD, "R"); // Table reset
tableD.numGoPressed = 0;
}
} else {
tableMap.remove(userD.currentTable);
}
} else {
System.err.println("Disconnect Table Error!");
}
userMap.remove(inM.clientID);
}
break;
case 'G': // 'Go' (Start game) Signal: G
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
User userG = userMap.get(inM.clientID);
Table tableG = tableMap.get(userG.currentTable);
if( tableG != null ) {
tableG.numGoPressed++;
if(tableG.numGoPressed == tableG.maxPlayers) {
//String cardOrder = "T;12;01;02;03;04;05;06;07;08;09;10;11;12";
tableG.resetScores();
sendToTable(outMessages, tableG, tableG.playerString(userMap));
tableG.initializeDeck();
sendToTable(outMessages, tableG, tableG.tableString());
inMessages.put(new Message(inM.clientID, "H")); //Initial set existence check
}
}
break;
case 'S': // Set made: S;Card1;Card2;Card3
if(splitM.length != 4) {System.err.println("Message Length Error!"); break;}
User userS = userMap.get(inM.clientID);
final Table tableS = tableMap.get(userS.currentTable);
if(tableS.setExists(Integer.parseInt(splitM[1]), Integer.parseInt(splitM[2]), Integer.parseInt(splitM[3]))) {
final int[] newCards = tableS.removeSet(Integer.parseInt(splitM[1]), Integer.parseInt(splitM[2]), Integer.parseInt(splitM[3]));
outMessages.put(new Message(inM.clientID, "Y"));
sendToTable(outMessages, tableS, "S;" + splitM[1] + ";" + splitM[2] + ";" + splitM[3]);
tableS.players.put(inM.clientID, tableS.players.get(inM.clientID) + 1);
sendToTable(outMessages, tableS, tableS.playerString(userMap));
if(newCards[0] >= 0) { // Table is 12 or less
if(newCards[1] >= 0) { // There is new cards
Thread sendNewCardsThread = new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Do nothing
}
try {
inMessages.put(new Message(inM.clientID, "H"));
} catch (InterruptedException e) {
System.err.println("Error in Set Checking Thread!");
}
sendToTable(outMessages, tableS, "N;" + newCards[0] + ";" + newCards[1] + ";" + newCards[2]);
}
};
sendNewCardsThread.start();
} else if(tableS.noMoreSets()) { // GAME OVER!!!
gameOver(outMessages, userMap, userS.currentTable, tableS);
}
} else {
inMessages.put(new Message(inM.clientID, "H"));
}
} // else ignore message
break;
case 'H': // Check for sets: H
// THE SERVER SENDS THIS MESSAGE TO ITSELF TO RECURSIVELY CHECK FOR SETS
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
User userH = userMap.get(inM.clientID);
final Table tableH = tableMap.get(userH.currentTable);
if(tableH.noMoreSets()) {
final int[] newCards = tableH.newCards();
if(newCards[1] >= 0) {
sendToTable(outMessages, tableH, "O");
Thread sendNewCardsThread = new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Do nothing
}
try {
inMessages.put(new Message(inM.clientID, "H"));
} catch (InterruptedException e) {
System.err.println("Error in Set Checking Thread!");
}
sendToTable(outMessages, tableH, "N;" + newCards[0] + ";" + newCards[1] + ";" + newCards[2]);
}
};
sendNewCardsThread.start();
} else {
gameOver(outMessages, userMap, userH.currentTable, tableH);
}
}
break;
case 'X': // Mistake made: X
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
outMessages.put(new Message(inM.clientID, "D")); // Reflect mistake back to MainClient
User userX = userMap.get(inM.clientID);
Table tableX = tableMap.get(userX.currentTable);
tableX.players.put(inM.clientID, tableX.players.get(inM.clientID) - 1);
sendToTable(outMessages, tableX, tableX.playerString(userMap));
break;
case 'C': // Chat sent: C;Message
if(splitM.length != 2) {System.err.println("Message Length Error!"); break;}
User userC = userMap.get(inM.clientID);
outMessages.put(new Message(-1, "C;" + userC.username + ";" + splitM[1]));
break;
case 'Q': // Table Chat: Q;Message
if(splitM.length != 2) {System.err.println("Message Length Error!"); break;}
User userQ = userMap.get(inM.clientID);
Table tableQ = tableMap.get(userQ.currentTable);
sendToTable(outMessages, tableQ, "Q;" + userQ.username + ";" + splitM[1]);
break;
}
} catch (InterruptedException e) {
// Do nothing?
}
}
}" | 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) throws SQLException {
// BlockingQueue receives all client messages, allows reads only when non-empty, and supports threads
final BlockingQueue<Message> inMessages = new LinkedBlockingQueue<Message>();
final BlockingQueue<Message> outMessages = new LinkedBlockingQueue<Message>();
// Map from user id (integer) to User object
Map<Object, User> userMap = new HashMap<Object, User>();
// Map from tableNum to Table object
int numTables = 0;
Map<Object, Table> tableMap = new HashMap<Object, Table>();
// Runs the client interface server
MainServer mainServer = new MainServer(inMessages, outMessages);
mainServer.start(); // thread
// All of the server mechanics are handled by the MainServer and its subclasses,
// so that SetServer only has to read from inMessages to get incoming client messages,
// and write to outMessages to send them. These queues contain Message objects, which
// simply contain a clientID and a message string.
boolean isRunning = true;
Connection connection = null;
Statement stmt = null;
ResultSet usertable = null;
while(isRunning) // Messages are handled in the order they are received. If each message-handling is fast, there shouldn't be a problem.
{
try {
final Message inM = inMessages.take();
String [] splitM = inM.message.split("[;]"); // Message parts split by semicolons
switch(splitM[0].charAt(0)) {// Switch on first character in message (command character)
case 'R': // Register: R;Username;Password
if(splitM.length != 3) {System.err.println("Message Length Error!"); break;}
try {
connection = DriverManager
.getConnection("jdbc:mysql://199.98.20.119:3306/set","java", "eeonly1");
} catch (SQLException e) {
System.out.println("Connection Failed!");
e.printStackTrace();
return;
}
stmt = connection.createStatement();
usertable=stmt.executeQuery("SELECT * FROM `users` WHERE `username` = '"+splitM[1]+"';");
if (usertable.next()){
outMessages.put( new Message(inM.clientID, "X;R") );
System.out.println("User already exists");
}
else {
stmt.executeUpdate("INSERT INTO users (username, password) VALUES ('"+splitM[1]+"', '"+splitM[2]+"');");
System.out.println("User created");
outMessages.put( new Message(inM.clientID, "I;false;"+allTableString(tableMap)+";"+allUserString(userMap)) );
User newUser = new User(splitM[1], 1000, -1, false);
userMap.put(inM.clientID, newUser);
outMessages.put( new Message(-1, "U;" + splitM[1] + ";N/A") );
}
stmt.close();
connection.close();
break;
case 'L': // Login: L;Username;Password
if(splitM.length != 3) {System.err.println("Message Length Error!"); break;}
try {
connection = DriverManager
.getConnection("jdbc:mysql://199.98.20.119:3306/set","java", "eeonly1");
} catch (SQLException e) {
System.out.println("Connection Failed!");
e.printStackTrace();
return;
}
stmt = connection.createStatement();
usertable = stmt.executeQuery("SELECT * FROM `users` WHERE `username` = '"+splitM[1]+"';");
if (!usertable.next()){
System.out.println("User not found");
}
else{
boolean alreadyOnline = false;
Iterator<Entry<Object, User>> it = userMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Object, User> entry = (Map.Entry<Object, User>) it.next();
User curUser = entry.getValue();
if(curUser.username.compareTo(splitM[1]) == 0) {
alreadyOnline = true;
break;
}
}
if(alreadyOnline) {
outMessages.put( new Message(inM.clientID, "X;A") );
} else {
String passt = usertable.getString("password");
boolean isAdmin=false;
if (splitM[2].equals(passt)){
String accountType = usertable.getString("type");
int userRating = usertable.getInt("score");
if(accountType.equals("admin")){
isAdmin=true;
}
outMessages.put( new Message(inM.clientID, "I;"+isAdmin+";"+allTableString(tableMap)+";"+allUserString(userMap)) );
User newUser = new User(splitM[1], userRating, -1, isAdmin);
userMap.put(inM.clientID, newUser);
outMessages.put( new Message(-1, "U;" + splitM[1] + ";N/A") );
}
else{
outMessages.put( new Message(inM.clientID, "X;L") );
}
}
}
stmt.close();
connection.close();
break;
case 'T': // Create Table: T;Name;NumPlayers
if(splitM.length != 3) {System.err.println("Message Length Error!"); break;}
User userT = userMap.get(inM.clientID);
if(userT.currentTable >= 0) {
outMessages.put(new Message(inM.clientID, "A"));
break;
}
userT.currentTable = numTables;
Table newTable = new Table(splitM[1], 0, Integer.parseInt(splitM[2]));
newTable.addPlayer(inM.clientID);
// Give client "Table Made" message
outMessages.put( new Message(inM.clientID, newTable.playerString(userMap)) );
// Broadcast new table update
outMessages.put( new Message(-1, "U;" + numTables + ";" + newTable.name + ";" + newTable.numPlayers + ";" + newTable.maxPlayers + ";" + newTable.status()) );
outMessages.put( new Message(-1, "U;" + userT.username + ";" + numTables) );
tableMap.put(numTables, newTable);
numTables++;
break;
case 'J': // Join Table: J;TableNum
if(splitM.length != 2) {System.err.println("Message Length Error!"); break;}
User userJ = userMap.get(inM.clientID);
if(userJ.currentTable >= 0) {
outMessages.put(new Message(inM.clientID, "A"));
break;
}
userJ.currentTable = Integer.parseInt(splitM[1]);
Table tableJ = tableMap.get(userJ.currentTable);
if( tableJ != null ) {
if(tableJ.numPlayers < tableJ.maxPlayers) {
if(tableJ.numGoPressed < tableJ.maxPlayers) { // Game not in progress
tableJ.addPlayer(inM.clientID);
outMessages.put(new Message(-1, "U;" + userJ.currentTable + ";" + tableJ.name + ";" + tableJ.numPlayers + ";" + tableJ.maxPlayers + ";" + tableJ.status()));
outMessages.put( new Message(-1, "U;" + userJ.username + ";" + userJ.currentTable) );
sendToTable(outMessages, tableJ, tableJ.playerString(userMap));
} else { // Game in progress
userJ.currentTable = -1;
outMessages.put(new Message(inM.clientID, "H")); // Table is playing
}
} else {
userJ.currentTable = -1;
outMessages.put(new Message(inM.clientID, "F")); // Table is full
}
} else {
System.err.println("Table requested that does not exist!");
userJ.currentTable = -1;
outMessages.put(new Message(inM.clientID, "F")); // Pretend table is full
}
break;
case 'E': // Exit Table: E
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
User userE = userMap.get(inM.clientID);
if(userE.currentTable < 0) { // User exited non-existent table
System.err.println("User exited non-existent table!");
outMessages.put(new Message(inM.clientID, "E"));
break;
}
Table tableE = tableMap.get(userE.currentTable);
outMessages.put(new Message(inM.clientID, "E"));
if( tableE != null ) {
tableE.removePlayer(inM.clientID);
outMessages.put(new Message(-1, "U;" + userE.currentTable + ";" + tableE.name + ";" + tableE.numPlayers + ";" + tableE.maxPlayers + ";" + tableE.status()));
outMessages.put( new Message(-1, "U;" + userE.username + ";N/A") );
if(tableE.numPlayers > 0) {
sendToTable(outMessages, tableE, tableE.playerString(userMap));
} else {
tableMap.remove(userE.currentTable);
}
} else {
System.err.println("Player exited non-existant table!");
}
userE.currentTable = -1;
break;
case 'D': // Disconnect: D
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
mainServer.socketMap.remove(inM.clientID);
User userD = userMap.get(inM.clientID);
if(userD != null) {
outMessages.put( new Message(-1, "U;" + userD.username + ";X") );
if(userD.currentTable < 0) { // User not at table
userMap.remove(inM.clientID);
break;
}
Table tableD = tableMap.get(userD.currentTable);
if( tableD != null ) {
tableD.removePlayer(inM.clientID);
if(tableD.numPlayers > 0) {
sendToTable(outMessages, tableD, tableD.playerString(userMap));
if(tableD.numGoPressed == tableD.maxPlayers) { // Game is playing
Connection connectionD = null;
Statement stmtD = null;
connectionD = DriverManager.getConnection("jdbc:mysql://199.98.20.119:3306/set","java", "eeonly1");
stmtD = connectionD.createStatement();
stmtD.executeUpdate("UPDATE `users` SET `score`=score-10 WHERE `username`='"+userD.username+"';");
stmtD.close();
connectionD.close();
} else {
sendToTable(outMessages, tableD, "R"); // Table reset
<MASK>outMessages.put(new Message(-1, "U;" + userD.currentTable + ";" + tableD.name + ";" + tableD.numPlayers + ";" + tableD.maxPlayers + ";" + tableD.status()));</MASK>
tableD.numGoPressed = 0;
}
} else {
tableMap.remove(userD.currentTable);
}
} else {
System.err.println("Disconnect Table Error!");
}
userMap.remove(inM.clientID);
}
break;
case 'G': // 'Go' (Start game) Signal: G
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
User userG = userMap.get(inM.clientID);
Table tableG = tableMap.get(userG.currentTable);
if( tableG != null ) {
tableG.numGoPressed++;
if(tableG.numGoPressed == tableG.maxPlayers) {
//String cardOrder = "T;12;01;02;03;04;05;06;07;08;09;10;11;12";
tableG.resetScores();
sendToTable(outMessages, tableG, tableG.playerString(userMap));
tableG.initializeDeck();
sendToTable(outMessages, tableG, tableG.tableString());
inMessages.put(new Message(inM.clientID, "H")); //Initial set existence check
}
}
break;
case 'S': // Set made: S;Card1;Card2;Card3
if(splitM.length != 4) {System.err.println("Message Length Error!"); break;}
User userS = userMap.get(inM.clientID);
final Table tableS = tableMap.get(userS.currentTable);
if(tableS.setExists(Integer.parseInt(splitM[1]), Integer.parseInt(splitM[2]), Integer.parseInt(splitM[3]))) {
final int[] newCards = tableS.removeSet(Integer.parseInt(splitM[1]), Integer.parseInt(splitM[2]), Integer.parseInt(splitM[3]));
outMessages.put(new Message(inM.clientID, "Y"));
sendToTable(outMessages, tableS, "S;" + splitM[1] + ";" + splitM[2] + ";" + splitM[3]);
tableS.players.put(inM.clientID, tableS.players.get(inM.clientID) + 1);
sendToTable(outMessages, tableS, tableS.playerString(userMap));
if(newCards[0] >= 0) { // Table is 12 or less
if(newCards[1] >= 0) { // There is new cards
Thread sendNewCardsThread = new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Do nothing
}
try {
inMessages.put(new Message(inM.clientID, "H"));
} catch (InterruptedException e) {
System.err.println("Error in Set Checking Thread!");
}
sendToTable(outMessages, tableS, "N;" + newCards[0] + ";" + newCards[1] + ";" + newCards[2]);
}
};
sendNewCardsThread.start();
} else if(tableS.noMoreSets()) { // GAME OVER!!!
gameOver(outMessages, userMap, userS.currentTable, tableS);
}
} else {
inMessages.put(new Message(inM.clientID, "H"));
}
} // else ignore message
break;
case 'H': // Check for sets: H
// THE SERVER SENDS THIS MESSAGE TO ITSELF TO RECURSIVELY CHECK FOR SETS
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
User userH = userMap.get(inM.clientID);
final Table tableH = tableMap.get(userH.currentTable);
if(tableH.noMoreSets()) {
final int[] newCards = tableH.newCards();
if(newCards[1] >= 0) {
sendToTable(outMessages, tableH, "O");
Thread sendNewCardsThread = new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Do nothing
}
try {
inMessages.put(new Message(inM.clientID, "H"));
} catch (InterruptedException e) {
System.err.println("Error in Set Checking Thread!");
}
sendToTable(outMessages, tableH, "N;" + newCards[0] + ";" + newCards[1] + ";" + newCards[2]);
}
};
sendNewCardsThread.start();
} else {
gameOver(outMessages, userMap, userH.currentTable, tableH);
}
}
break;
case 'X': // Mistake made: X
if(splitM.length != 1) {System.err.println("Message Length Error!"); break;}
outMessages.put(new Message(inM.clientID, "D")); // Reflect mistake back to MainClient
User userX = userMap.get(inM.clientID);
Table tableX = tableMap.get(userX.currentTable);
tableX.players.put(inM.clientID, tableX.players.get(inM.clientID) - 1);
sendToTable(outMessages, tableX, tableX.playerString(userMap));
break;
case 'C': // Chat sent: C;Message
if(splitM.length != 2) {System.err.println("Message Length Error!"); break;}
User userC = userMap.get(inM.clientID);
outMessages.put(new Message(-1, "C;" + userC.username + ";" + splitM[1]));
break;
case 'Q': // Table Chat: Q;Message
if(splitM.length != 2) {System.err.println("Message Length Error!"); break;}
User userQ = userMap.get(inM.clientID);
Table tableQ = tableMap.get(userQ.currentTable);
sendToTable(outMessages, tableQ, "Q;" + userQ.username + ";" + splitM[1]);
break;
}
} catch (InterruptedException e) {
// Do nothing?
}
}
}" |
Inversion-Mutation | megadiff | "public synchronized int read(byte[] b, int off, int len) throws IOException {
if (buf == null) throw new IOException("Stream is closed");
if (off < 0 || len < 0 || off+len > b.length) throw new ArrayIndexOutOfBoundsException();
if (len == 0) return 0;
if (pos == buf.length) return -1;
int reallen = buf.length-pos;
if (reallen == 0) return -1;
if (reallen > len) reallen = len;
System.arraycopy(buf, pos, b, off, reallen);
pos += reallen;
return reallen;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "read" | "public synchronized int read(byte[] b, int off, int len) throws IOException {
if (buf == null) throw new IOException("Stream is closed");
<MASK>if (pos == buf.length) return -1;</MASK>
if (off < 0 || len < 0 || off+len > b.length) throw new ArrayIndexOutOfBoundsException();
if (len == 0) return 0;
int reallen = buf.length-pos;
if (reallen == 0) return -1;
if (reallen > len) reallen = len;
System.arraycopy(buf, pos, b, off, reallen);
pos += reallen;
return reallen;
}" |
Inversion-Mutation | megadiff | "private void publish(RemoteServiceDescription rsd) {
synchronized (rsDescs) {
ServiceHooksProxy handler = new ServiceHooksProxy(rsd.getService());
Object service = Proxy.newProxyInstance(rsd.getServiceInterfaceClass().getClassLoader(), new Class[] { rsd
.getServiceInterfaceClass() }, handler);
handler.setRemoteServiceDescription(rsd);
RemoteServiceDescription rsDescFound = rsDescs.get(rsd.getProtocol() + "::" + rsd.getPath()); //$NON-NLS-1$
if (rsDescFound != null) {
LOGGER.log(LogService.LOG_WARNING, "A service endpoint with path=[" + rsd.getPath() //$NON-NLS-1$
+ "] and remoteType=[" + rsd.getProtocol() + "] already published... ignored"); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
if (rsd.getPath() == null) {
LOGGER.log(LogService.LOG_WARNING, "no path for service: " + service.toString() //$NON-NLS-1$
+ " Service not published remote"); //$NON-NLS-1$
return;
}
IServicePublisher servicePublisher = servicePublishers.get(rsd.getProtocol());
if (servicePublisher == null) {
LOGGER.log(LogService.LOG_INFO, "no publisher found for protocol " + rsd.getProtocol()); //$NON-NLS-1$
unpublishedServices.add(rsd);
return;
}
rsd.setService(service);
String url = null;
try {
url = servicePublisher.publishService(rsd);
} catch (RuntimeException e) {
LOGGER.log(LogService.LOG_ERROR, e.getMessage());
return;
}
// set full URL under which the service is available
rsd.setURL(url);
handler.setMessageContextAccessor(servicePublisher.getMessageContextAccessor());
rsDescs.put(rsd.getProtocol() + "::" + rsd.getPath(), rsd); //$NON-NLS-1$
LOGGER.log(LogService.LOG_DEBUG, "service endpoints count: " + rsDescs.size()); //$NON-NLS-1$
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "publish" | "private void publish(RemoteServiceDescription rsd) {
synchronized (rsDescs) {
ServiceHooksProxy handler = new ServiceHooksProxy(rsd.getService());
Object service = Proxy.newProxyInstance(rsd.getServiceInterfaceClass().getClassLoader(), new Class[] { rsd
.getServiceInterfaceClass() }, handler);
<MASK>rsd.setService(service);</MASK>
handler.setRemoteServiceDescription(rsd);
RemoteServiceDescription rsDescFound = rsDescs.get(rsd.getProtocol() + "::" + rsd.getPath()); //$NON-NLS-1$
if (rsDescFound != null) {
LOGGER.log(LogService.LOG_WARNING, "A service endpoint with path=[" + rsd.getPath() //$NON-NLS-1$
+ "] and remoteType=[" + rsd.getProtocol() + "] already published... ignored"); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
if (rsd.getPath() == null) {
LOGGER.log(LogService.LOG_WARNING, "no path for service: " + service.toString() //$NON-NLS-1$
+ " Service not published remote"); //$NON-NLS-1$
return;
}
IServicePublisher servicePublisher = servicePublishers.get(rsd.getProtocol());
if (servicePublisher == null) {
LOGGER.log(LogService.LOG_INFO, "no publisher found for protocol " + rsd.getProtocol()); //$NON-NLS-1$
unpublishedServices.add(rsd);
return;
}
String url = null;
try {
url = servicePublisher.publishService(rsd);
} catch (RuntimeException e) {
LOGGER.log(LogService.LOG_ERROR, e.getMessage());
return;
}
// set full URL under which the service is available
rsd.setURL(url);
handler.setMessageContextAccessor(servicePublisher.getMessageContextAccessor());
rsDescs.put(rsd.getProtocol() + "::" + rsd.getPath(), rsd); //$NON-NLS-1$
LOGGER.log(LogService.LOG_DEBUG, "service endpoints count: " + rsDescs.size()); //$NON-NLS-1$
}
}" |
Inversion-Mutation | megadiff | "private void handleToogleClick(Object source) {
ToggleButton button = (ToggleButton) source;
ToggleButton btn = null;
JobStep step = null;
for (int i = 0; i < stepBtns.size(); i++) {
btn = stepBtns.get(i);
if (btn.getText().equals(button.getText())) {
btn.setDown(true);
updateStep(i);
step = new JobStep(i, stepBtns.get(i).getText(), true);
NavButtonClickEvent event = new NavButtonClickEvent(step);
EventBus eventbus = EventBus.getInstance();
eventbus.fireEvent(event);
toolbar.getSave().disable();
// first step
if (i == 0) {
toolbar.getFinish().disable();
} // last step
else if (i + 1 == stepBtns.size()) {
toolbar.getFinish().enable();
toolbar.getSave().enable();
}
} else {
btn.setDown(false);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleToogleClick" | "private void handleToogleClick(Object source) {
ToggleButton button = (ToggleButton) source;
ToggleButton btn = null;
JobStep step = null;
for (int i = 0; i < stepBtns.size(); i++) {
btn = stepBtns.get(i);
if (btn.getText().equals(button.getText())) {
btn.setDown(true);
updateStep(i);
step = new JobStep(i, stepBtns.get(i).getText(), true);
NavButtonClickEvent event = new NavButtonClickEvent(step);
EventBus eventbus = EventBus.getInstance();
eventbus.fireEvent(event);
// first step
if (i == 0) {
toolbar.getFinish().disable();
<MASK>toolbar.getSave().disable();</MASK>
} // last step
else if (i + 1 == stepBtns.size()) {
toolbar.getFinish().enable();
toolbar.getSave().enable();
}
} else {
btn.setDown(false);
}
}
}" |
Inversion-Mutation | megadiff | "@Override
public void close() {
commitLock.writeLock().lock();
try {
if(closeInProgress) return;
checkState();
closeInProgress = true;
//notify background threads
itemsQueue.put(new CountDownLatch(0));
super.delete(newRecids.take(), Serializer.EMPTY_SERIALIZER);
//wait for background threads to shutdown
shutdownCondition.await();
//put preallocated recids back to store
for(Long recid = newRecids.poll(); recid!=null; recid = newRecids.poll()){
super.delete(recid, Serializer.EMPTY_SERIALIZER);
}
AsyncWriteEngine.super.close();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
commitLock.writeLock().unlock();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "close" | "@Override
public void close() {
commitLock.writeLock().lock();
try {
<MASK>checkState();</MASK>
if(closeInProgress) return;
closeInProgress = true;
//notify background threads
itemsQueue.put(new CountDownLatch(0));
super.delete(newRecids.take(), Serializer.EMPTY_SERIALIZER);
//wait for background threads to shutdown
shutdownCondition.await();
//put preallocated recids back to store
for(Long recid = newRecids.poll(); recid!=null; recid = newRecids.poll()){
super.delete(recid, Serializer.EMPTY_SERIALIZER);
}
AsyncWriteEngine.super.close();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
commitLock.writeLock().unlock();
}
}" |
Inversion-Mutation | megadiff | "@Override
protected LinkedList<ItemDetailsMetadata> defineMetadatas(final IFlowNodeItem task) {
final MetadataTaskBuilder metadatas = new MetadataTaskBuilder();
metadatas.addAppsName();
metadatas.addAppsVersion();
metadatas.addCaseId(task, true);
metadatas.addType();
metadatas.addState();
metadatas.addPriority();
if (task.isHumanTask()) {
metadatas.addAssignedTo();
if (isArchived()) {
metadatas.addExecutedBy();
}
}
if (!(task.getRootContainerProcess().ensureName().equals(task.getProcess().ensureName()))){
metadatas.AddSubAppsName();
metadatas.AddSubAppsVersion();
}
metadatas.addDueDate(getArchivedDateFormat());
metadatas.addLastUpdateDate(FORMAT.DISPLAY);
metadatas.addAssignedDate(FORMAT.DISPLAY);
return metadatas.build();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "defineMetadatas" | "@Override
protected LinkedList<ItemDetailsMetadata> defineMetadatas(final IFlowNodeItem task) {
final MetadataTaskBuilder metadatas = new MetadataTaskBuilder();
<MASK>metadatas.addCaseId(task, true);</MASK>
metadatas.addAppsName();
metadatas.addAppsVersion();
metadatas.addType();
metadatas.addState();
metadatas.addPriority();
if (task.isHumanTask()) {
metadatas.addAssignedTo();
if (isArchived()) {
metadatas.addExecutedBy();
}
}
if (!(task.getRootContainerProcess().ensureName().equals(task.getProcess().ensureName()))){
metadatas.AddSubAppsName();
metadatas.AddSubAppsVersion();
}
metadatas.addDueDate(getArchivedDateFormat());
metadatas.addLastUpdateDate(FORMAT.DISPLAY);
metadatas.addAssignedDate(FORMAT.DISPLAY);
return metadatas.build();
}" |
Inversion-Mutation | megadiff | "public final void setText(String message) {
if (!this.minecraft.running) {
throw new StopGameException();
} else {
text = message;
passServerCommand(message);
if (this.minecraft.session == null) {
HackState.setAllEnabled();
return;
}
String joinedString = new StringBuilder().append(title).append(" ").append(text)
.toString().toLowerCase();
if (joinedString.indexOf("-hax") > -1) {
HackState.setAllDisabled();
} else { // enable all, it's either +hax or nothing at all
HackState.setAllEnabled();
}
// then we can manually disable others here
if (joinedString.indexOf("+fly") > -1)
HackState.Fly = true;
else if (joinedString.indexOf("-fly") > -1)
HackState.Fly = false;
if (joinedString.indexOf("+noclip") > -1)
HackState.Noclip = true;
else if (joinedString.indexOf("-noclip") > -1)
HackState.Noclip = false;
if (joinedString.indexOf("+speed") > -1)
HackState.Speed = true;
else if (joinedString.indexOf("-speed") > -1)
HackState.Speed = false;
if ((joinedString.indexOf("+ophax") > -1) && this.minecraft.player.userType >= 100) {
HackState.setAllEnabled();
}
}
this.setProgress(-1);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setText" | "public final void setText(String message) {
if (!this.minecraft.running) {
throw new StopGameException();
} else {
<MASK>passServerCommand(message);</MASK>
text = message;
if (this.minecraft.session == null) {
HackState.setAllEnabled();
return;
}
String joinedString = new StringBuilder().append(title).append(" ").append(text)
.toString().toLowerCase();
if (joinedString.indexOf("-hax") > -1) {
HackState.setAllDisabled();
} else { // enable all, it's either +hax or nothing at all
HackState.setAllEnabled();
}
// then we can manually disable others here
if (joinedString.indexOf("+fly") > -1)
HackState.Fly = true;
else if (joinedString.indexOf("-fly") > -1)
HackState.Fly = false;
if (joinedString.indexOf("+noclip") > -1)
HackState.Noclip = true;
else if (joinedString.indexOf("-noclip") > -1)
HackState.Noclip = false;
if (joinedString.indexOf("+speed") > -1)
HackState.Speed = true;
else if (joinedString.indexOf("-speed") > -1)
HackState.Speed = false;
if ((joinedString.indexOf("+ophax") > -1) && this.minecraft.player.userType >= 100) {
HackState.setAllEnabled();
}
}
this.setProgress(-1);
}" |
Inversion-Mutation | megadiff | "private BundleInfo findBundle(final String target, String version, boolean removeMatch) {
ArrayList matches = (ArrayList) allBundles.get(target);
int numberOfMatches = matches != null ? matches.size() : 0;
if (numberOfMatches == 1) {
//TODO Need to check the version
return (BundleInfo) (removeMatch ? matches.remove(0) : matches.get(0));
}
if (numberOfMatches == 0)
return null;
if (version != null) {
for (Iterator iterator = matches.iterator(); iterator.hasNext();) {
BundleInfo bi = (BundleInfo) iterator.next();
if (bi.version.equals(version)) {
if (removeMatch)
iterator.remove();
return bi;
}
}
//TODO Need to log the fact that we could not find the version mentioned
return null;
}
String[] versions = new String[numberOfMatches];
int highest = 0;
for (int i = 0; i < versions.length; i++) {
versions[i] = ((BundleInfo) matches.get(i)).version;
}
highest = findMax(versions);
return (BundleInfo) (removeMatch ? matches.remove(highest) : matches.get(highest));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findBundle" | "private BundleInfo findBundle(final String target, String version, boolean removeMatch) {
ArrayList matches = (ArrayList) allBundles.get(target);
int numberOfMatches = matches != null ? matches.size() : 0;
if (numberOfMatches == 1) {
//TODO Need to check the version
return (BundleInfo) (removeMatch ? matches.remove(0) : matches.get(0));
}
if (numberOfMatches == 0)
return null;
if (version != null) {
for (Iterator iterator = matches.iterator(); iterator.hasNext();) {
BundleInfo bi = (BundleInfo) iterator.next();
if (bi.version.equals(version)) {
if (removeMatch)
iterator.remove();
return bi;
}
}
//TODO Need to log the fact that we could not find the version mentioned
return null;
}
String[] versions = new String[numberOfMatches];
int highest = 0;
for (int i = 0; i < versions.length; i++) {
versions[i] = ((BundleInfo) matches.get(i)).version;
<MASK>highest = findMax(versions);</MASK>
}
return (BundleInfo) (removeMatch ? matches.remove(highest) : matches.get(highest));
}" |
Inversion-Mutation | megadiff | "void allocate() {
edenLock.lock();
try {
MemoryBlock mb = factory.getBlock();
mb.setCreatedID(youngGcCount);
allocMax = mb.getBlockId();
allocList[allocMax] = mb;
// FIXME Single allocating thread
for (int i = 0; i < eden.width(); i++) {
// Must use getValue() to actually see bindable behaviour
MemoryBlockView mbv = eden.getValue(i, threadToCurrentTLAB.get(0));
if (mbv.getStatus() == MemoryStatus.FREE) {
mbv.setBlock(mb);
return;
}
}
// Now try allocating a new TLAB for this thread
// FIXME Single allocating thread
boolean gotNewTLAB = setNewTLABForThread(0);
System.out.println("Trying to get new TLAB: " + gotNewTLAB);
if (gotNewTLAB) {
// Have new TLAB, know we can allocate at offset 0
eden.getValue(0, threadToCurrentTLAB.get(0)).setBlock(mb);
return;
}
// Can't do anything in Eden, must collect
youngCollection();
// Eden is now reset, can allocate at offset 0 on current TLAB
eden.getValue(0, threadToCurrentTLAB.get(0)).setBlock(mb);
} catch (Exception e) {
e.printStackTrace();
} finally {
edenLock.unlock();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "allocate" | "void allocate() {
edenLock.lock();
try {
MemoryBlock mb = factory.getBlock();
allocMax = mb.getBlockId();
allocList[allocMax] = mb;
// FIXME Single allocating thread
for (int i = 0; i < eden.width(); i++) {
// Must use getValue() to actually see bindable behaviour
MemoryBlockView mbv = eden.getValue(i, threadToCurrentTLAB.get(0));
if (mbv.getStatus() == MemoryStatus.FREE) {
<MASK>mb.setCreatedID(youngGcCount);</MASK>
mbv.setBlock(mb);
return;
}
}
// Now try allocating a new TLAB for this thread
// FIXME Single allocating thread
boolean gotNewTLAB = setNewTLABForThread(0);
System.out.println("Trying to get new TLAB: " + gotNewTLAB);
if (gotNewTLAB) {
// Have new TLAB, know we can allocate at offset 0
eden.getValue(0, threadToCurrentTLAB.get(0)).setBlock(mb);
return;
}
// Can't do anything in Eden, must collect
youngCollection();
// Eden is now reset, can allocate at offset 0 on current TLAB
eden.getValue(0, threadToCurrentTLAB.get(0)).setBlock(mb);
} catch (Exception e) {
e.printStackTrace();
} finally {
edenLock.unlock();
}
}" |
Inversion-Mutation | megadiff | "public Object executeProgram(String main, IValue[] args) {
// Finalize the instruction generation of all functions
for (Function f : functionStore) {
f.finalize(functionMap, constructorMap, listing);
}
// Search for the "#module_init" function and check arguments
Function init_function = functionStore.get(functionMap.get("#module_init"));
if (init_function == null) {
throw new RuntimeException("PANIC: Code for #module_init not found");
}
if (init_function.nformals != 0) {
throw new RuntimeException("PANIC: " + "function \"#module_init\" should have one argument");
}
// Search for the "main" function and check arguments
Function main_function = functionStore.get(functionMap.get("main"));
if (main_function == null) {
throw new RuntimeException("PANIC: No function \"main\" found");
}
if (main_function.nformals != 1) {
throw new RuntimeException("PANIC: function \"main\" should have one argument");
}
// Perform a call to #module_init" at scope level = 0
Frame cf = new Frame(0, null, init_function.maxstack, init_function);
Frame root = cf; // we need the notion of the root frame, which represents the root environment
Object[] stack = cf.stack;
stack[0] = args; // pass the program argument to #module_init
int[] instructions = init_function.codeblock.getInstructions();
int pc = 0;
int sp = init_function.nlocals;
Stack<Coroutine> activeCoroutines = new Stack<>();
Frame ccf = null; // the start frame (i.e., the frame of the coroutine's main function) of the current active coroutine
try {
NEXT_INSTRUCTION: while (true) {
if(pc < 0 || pc >= instructions.length){
throw new RuntimeException("PANIC: " + main + " illegal pc: " + pc);
}
int op = instructions[pc++];
if (true) {
int startpc = pc - 1;
for (int i = 0; i < sp; i++) {
//stdout.println("\t" + i + ": " + stack[i]);
System.out.println("\t" + i + ": " + stack[i]);
}
//stdout.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
System.out.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
}
switch (op) {
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADTTYPE:
stack[sp++] = cf.function.typeConstantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(instructions[pc++]), root);
continue;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, gets the function code
Function fun = functionStore.get(instructions[pc++]);
int scope = instructions[pc++];
// Second, looks up the function environment frame into the stack of caller frames
for (Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scope) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOAD_NESTED_FUNCTION cannot find matching scope: " + scope);
}
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(instructions[pc++]);
case Opcode.OP_LOADLOC:
case Opcode.OP_LOADLOC_AS_REF:
stack[sp++] = (op == Opcode.OP_LOADLOC) ? stack[instructions[pc++]]
: new Reference(stack, instructions[pc++]);
continue;
case Opcode.OP_LOADLOCREF: {
Reference ref = (Reference) stack[instructions[pc++]];
stack[sp++] = ref.stack[ref.pos];
continue;
}
case Opcode.OP_LOADVARDYN:
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVAR_AS_REF: {
int s;
int pos;
if(op == Opcode.OP_LOADVARDYN){
s = ((IInteger)stack[-2]).intValue();
pos = ((IInteger)stack[-1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
stack[sp++] = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVAR cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARREF: {
int s = instructions[pc++];
int pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
Reference ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_STORELOC: {
stack[instructions[pc++]] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue;
}
case Opcode.OP_STORELOCREF:
Reference ref = (Reference) stack[instructions[pc++]];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp - 1; value remains on stack */
continue;
case Opcode.OP_STOREVARDYN:
case Opcode.OP_STOREVAR:
int s;
int pos;
if(op == Opcode.OP_STOREVARDYN){
s = ((IInteger)stack[sp - 2]).intValue();
pos = ((IInteger)stack[sp - 1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARREF:
s = instructions[pc++];
pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVARREF cannot find matching scope: " + s);
case Opcode.OP_JMP:
pc = instructions[pc];
continue;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_POP:
sp--;
continue;
case Opcode.OP_LABEL:
throw new RuntimeException("PANIC: label instruction at runtime");
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(instructions[pc++]);
int arity = constructor.getArity();
args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(instructions[pc++]);
previousScope = cf;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CALLDYN is executed");
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scope, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue;
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
Object rval = null;
boolean returns = op == Opcode.OP_RETURN1;
if(returns)
rval = stack[sp - 1];
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns)
return rval;
else
return vf.string("None");
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns)
stack[sp++] = rval;
continue;
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
stdout.println(((IString) stack[sp - 1]).getValue());
continue;
case Opcode.OP_CALLPRIM:
Primitive prim = Primitive.fromInteger(instructions[pc++]);
arity = instructions[pc++];
sp = prim.invoke(stack, sp, arity);
continue;
case Opcode.OP_INIT:
arity = instructions[pc++];
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scope, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("PANIC: unexpected argument type when INIT is executed.");
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp)
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp));
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
newCoroutine.suspend(newCoroutine.frame);
sp = sp - arity; /* CHANGED: place coroutine back on stack */
stack[sp++] = newCoroutine;
continue;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
if(op == Opcode.OP_CREATE){
fun = functionStore.get(instructions[pc++]);
previousScope = null;
} else {
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CREATEDYN is executed.");
}
}
arity = instructions[pc++];
Frame frame = new Frame(fun.scope, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // CHANGED: yield now always leaves an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = (op == Opcode.OP_YIELD1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
//if(op == Opcode.OP_YIELD1 /* && rval != null */) { /* CHANGED */
stack[sp++] = rval; // corresponding next will always find an entry on the stack
//}
continue;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue;
default:
throw new RuntimeException("PANIC: RVM main loop -- cannot decode instruction");
}
}
} catch (Exception e) {
stdout.println("PANIC: exception caused by invoking a primitive or illegal instruction sequence: " + e);
e.printStackTrace();
}
return FALSE;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeProgram" | "public Object executeProgram(String main, IValue[] args) {
// Finalize the instruction generation of all functions
for (Function f : functionStore) {
f.finalize(functionMap, constructorMap, listing);
}
// Search for the "#module_init" function and check arguments
Function init_function = functionStore.get(functionMap.get("#module_init"));
if (init_function == null) {
throw new RuntimeException("PANIC: Code for #module_init not found");
}
if (init_function.nformals != 0) {
throw new RuntimeException("PANIC: " + "function \"#module_init\" should have one argument");
}
// Search for the "main" function and check arguments
Function main_function = functionStore.get(functionMap.get("main"));
if (main_function == null) {
throw new RuntimeException("PANIC: No function \"main\" found");
}
if (main_function.nformals != 1) {
throw new RuntimeException("PANIC: function \"main\" should have one argument");
}
// Perform a call to #module_init" at scope level = 0
Frame cf = new Frame(0, null, init_function.maxstack, init_function);
Frame root = cf; // we need the notion of the root frame, which represents the root environment
Object[] stack = cf.stack;
stack[0] = args; // pass the program argument to #module_init
int[] instructions = init_function.codeblock.getInstructions();
int pc = 0;
int sp = init_function.nlocals;
Stack<Coroutine> activeCoroutines = new Stack<>();
Frame ccf = null; // the start frame (i.e., the frame of the coroutine's main function) of the current active coroutine
try {
NEXT_INSTRUCTION: while (true) {
if(pc < 0 || pc >= instructions.length){
throw new RuntimeException("PANIC: " + main + " illegal pc: " + pc);
}
int op = instructions[pc++];
if (true) {
int startpc = pc - 1;
for (int i = 0; i < sp; i++) {
//stdout.println("\t" + i + ": " + stack[i]);
System.out.println("\t" + i + ": " + stack[i]);
}
//stdout.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
System.out.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
}
switch (op) {
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADTTYPE:
stack[sp++] = cf.function.typeConstantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(instructions[pc++]), root);
continue;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, gets the function code
Function fun = functionStore.get(instructions[pc++]);
int scope = instructions[pc++];
// Second, looks up the function environment frame into the stack of caller frames
for (Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scope) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOAD_NESTED_FUNCTION cannot find matching scope: " + scope);
}
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(instructions[pc++]);
case Opcode.OP_LOADLOC:
case Opcode.OP_LOADLOC_AS_REF:
stack[sp++] = (op == Opcode.OP_LOADLOC) ? stack[instructions[pc++]]
: new Reference(stack, instructions[pc++]);
continue;
case Opcode.OP_LOADLOCREF: {
Reference ref = (Reference) stack[instructions[pc++]];
stack[sp++] = ref.stack[ref.pos];
continue;
}
case Opcode.OP_LOADVARDYN:
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVAR_AS_REF: {
int s;
int pos;
if(op == Opcode.OP_LOADVARDYN){
s = ((IInteger)stack[-2]).intValue();
pos = ((IInteger)stack[-1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
stack[sp++] = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVAR cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARREF: {
int s = instructions[pc++];
int pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
Reference ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_STORELOC: {
stack[instructions[pc++]] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue;
}
case Opcode.OP_STORELOCREF:
Reference ref = (Reference) stack[instructions[pc++]];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp - 1; value remains on stack */
continue;
case Opcode.OP_STOREVARDYN:
case Opcode.OP_STOREVAR:
int s;
int pos;
if(op == Opcode.OP_STOREVARDYN){
s = ((IInteger)stack[sp - 2]).intValue();
pos = ((IInteger)stack[sp - 1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARREF:
s = instructions[pc++];
pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVARREF cannot find matching scope: " + s);
case Opcode.OP_JMP:
pc = instructions[pc];
continue;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_POP:
sp--;
continue;
case Opcode.OP_LABEL:
throw new RuntimeException("PANIC: label instruction at runtime");
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(instructions[pc++]);
int arity = constructor.getArity();
args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(instructions[pc++]);
previousScope = cf;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CALLDYN is executed");
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scope, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue;
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
Object rval = null;
boolean returns = op == Opcode.OP_RETURN1;
if(returns)
rval = stack[sp - 1];
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns)
return rval;
else
return vf.string("None");
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns)
stack[sp++] = rval;
continue;
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
stdout.println(((IString) stack[sp - 1]).getValue());
continue;
case Opcode.OP_CALLPRIM:
Primitive prim = Primitive.fromInteger(instructions[pc++]);
<MASK>arity = instructions[pc++];</MASK>
sp = prim.invoke(stack, sp, arity);
continue;
case Opcode.OP_INIT:
<MASK>arity = instructions[pc++];</MASK>
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scope, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("PANIC: unexpected argument type when INIT is executed.");
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp)
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp));
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
newCoroutine.suspend(newCoroutine.frame);
sp = sp - arity; /* CHANGED: place coroutine back on stack */
stack[sp++] = newCoroutine;
continue;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
<MASK>arity = instructions[pc++];</MASK>
if(op == Opcode.OP_CREATE){
fun = functionStore.get(instructions[pc++]);
previousScope = null;
} else {
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CREATEDYN is executed.");
}
}
Frame frame = new Frame(fun.scope, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // CHANGED: yield now always leaves an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = (op == Opcode.OP_YIELD1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
//if(op == Opcode.OP_YIELD1 /* && rval != null */) { /* CHANGED */
stack[sp++] = rval; // corresponding next will always find an entry on the stack
//}
continue;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue;
default:
throw new RuntimeException("PANIC: RVM main loop -- cannot decode instruction");
}
}
} catch (Exception e) {
stdout.println("PANIC: exception caused by invoking a primitive or illegal instruction sequence: " + e);
e.printStackTrace();
}
return FALSE;
}" |
Inversion-Mutation | megadiff | "public void updateAlarm( Alarm alarm, AlarmEvent evt ) throws PersistenceException {
OrmHelper helper = this.getHelper();
// First handle any updates to foreign fields that are set directly in Alarm.
switch ( evt.getModifiedField() ) {
case AUDIO_SOURCE:
PersistenceExceptionDao<AudioSource, Integer> asDao = helper.getAudioSourceDao();
AudioSource audioSource = alarm.getAudioSource();
if ( evt.getOldValue() != null ) {
AudioSource old = (AudioSource) evt.getOldValue();
audioSource.setId( old.getId() );
asDao.update( audioSource );
} else {
asDao.create( alarm.getAudioSource() );
}
break;
/*
* TODO: Will AudioConfig really be directly set via Alarm#setAudioConfig?
* It can never be null so... Maybe use own event?
*/
case AUDIO_CONFIG:
helper.getAudioConfigDao().update( alarm.getAudioConfig() );
break;
default:
break;
}
helper.getAlarmDao().update( alarm );
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "updateAlarm" | "public void updateAlarm( Alarm alarm, AlarmEvent evt ) throws PersistenceException {
OrmHelper helper = this.getHelper();
// First handle any updates to foreign fields that are set directly in Alarm.
switch ( evt.getModifiedField() ) {
case AUDIO_SOURCE:
PersistenceExceptionDao<AudioSource, Integer> asDao = helper.getAudioSourceDao();
AudioSource audioSource = alarm.getAudioSource();
if ( evt.getOldValue() != null ) {
AudioSource old = (AudioSource) evt.getOldValue();
audioSource.setId( old.getId() );
asDao.update( audioSource );
} else {
asDao.create( alarm.getAudioSource() );
}
break;
/*
* TODO: Will AudioConfig really be directly set via Alarm#setAudioConfig?
* It can never be null so... Maybe use own event?
*/
case AUDIO_CONFIG:
helper.getAudioConfigDao().update( alarm.getAudioConfig() );
break;
default:
<MASK>helper.getAlarmDao().update( alarm );</MASK>
break;
}
}" |
Inversion-Mutation | megadiff | "public void mouseClicked(MouseEvent me) {
resetHideCounter();
synchronized(hotZones) {
for (HotZone hz : hotZones) {
if (hz.zone.contains(me.getPoint())) {
if (hz.operation == HotZone.ops.INC) {
hz.player.updateVP(+1);
}
else if (hz.operation == HotZone.ops.DEC) {
hz.player.updateVP(-1);
}
else if (hz.operation == HotZone.ops.LA) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LargestArmy);
}
else {
game.removeAchievement(Achievement.LargestArmy);
}
}
else if (hz.operation == HotZone.ops.LR) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LongestRoad);
}
else {
game.removeAchievement(Achievement.LongestRoad);
}
}
return;
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "mouseClicked" | "public void mouseClicked(MouseEvent me) {
synchronized(hotZones) {
<MASK>resetHideCounter();</MASK>
for (HotZone hz : hotZones) {
if (hz.zone.contains(me.getPoint())) {
if (hz.operation == HotZone.ops.INC) {
hz.player.updateVP(+1);
}
else if (hz.operation == HotZone.ops.DEC) {
hz.player.updateVP(-1);
}
else if (hz.operation == HotZone.ops.LA) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LargestArmy);
}
else {
game.removeAchievement(Achievement.LargestArmy);
}
}
else if (hz.operation == HotZone.ops.LR) {
if (hz.player != null) {
game.setAchievement(hz.player.getPlayerColor(), Achievement.LongestRoad);
}
else {
game.removeAchievement(Achievement.LongestRoad);
}
}
return;
}
}
}
}" |
Inversion-Mutation | megadiff | "static public void loadDataAndPrepareJob(
HttpServletRequest request,
HttpServletResponse response,
Properties parameters,
final ImportingJob job,
JSONObject config) throws IOException, ServletException {
JSONObject retrievalRecord = new JSONObject();
JSONUtilities.safePut(config, "retrievalRecord", retrievalRecord);
JSONUtilities.safePut(config, "state", "loading-raw-data");
final JSONObject progress = new JSONObject();
JSONUtilities.safePut(config, "progress", progress);
try {
ImportingUtilities.retrieveContentFromPostRequest(
request,
parameters,
job.getRawDataDir(),
retrievalRecord,
new Progress() {
@Override
public void setProgress(String message, int percent) {
if (message != null) {
JSONUtilities.safePut(progress, "message", message);
}
JSONUtilities.safePut(progress, "percent", percent);
}
@Override
public boolean isCanceled() {
return job.canceled;
}
}
);
} catch (Exception e) {
JSONUtilities.safePut(config, "state", "error");
JSONUtilities.safePut(config, "error", "Error uploading data");
JSONUtilities.safePut(config, "errorDetails", e.getLocalizedMessage());
return;
}
JSONArray fileSelectionIndexes = new JSONArray();
JSONUtilities.safePut(config, "fileSelection", fileSelectionIndexes);
String bestFormat = ImportingUtilities.autoSelectFiles(job, retrievalRecord, fileSelectionIndexes);
bestFormat = ImportingUtilities.guessBetterFormat(job, bestFormat);
JSONArray rankedFormats = new JSONArray();
ImportingUtilities.rankFormats(job, bestFormat, rankedFormats);
JSONUtilities.safePut(config, "rankedFormats", rankedFormats);
JSONUtilities.safePut(config, "state", "ready");
JSONUtilities.safePut(config, "hasData", true);
config.remove("progress");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadDataAndPrepareJob" | "static public void loadDataAndPrepareJob(
HttpServletRequest request,
HttpServletResponse response,
Properties parameters,
final ImportingJob job,
JSONObject config) throws IOException, ServletException {
JSONObject retrievalRecord = new JSONObject();
JSONUtilities.safePut(config, "retrievalRecord", retrievalRecord);
JSONUtilities.safePut(config, "state", "loading-raw-data");
final JSONObject progress = new JSONObject();
JSONUtilities.safePut(config, "progress", progress);
try {
ImportingUtilities.retrieveContentFromPostRequest(
request,
parameters,
job.getRawDataDir(),
retrievalRecord,
new Progress() {
@Override
public void setProgress(String message, int percent) {
if (message != null) {
JSONUtilities.safePut(progress, "message", message);
}
JSONUtilities.safePut(progress, "percent", percent);
}
@Override
public boolean isCanceled() {
return job.canceled;
}
}
);
} catch (Exception e) {
JSONUtilities.safePut(config, "state", "error");
JSONUtilities.safePut(config, "error", "Error uploading data");
JSONUtilities.safePut(config, "errorDetails", e.getLocalizedMessage());
return;
}
JSONArray fileSelectionIndexes = new JSONArray();
JSONUtilities.safePut(config, "fileSelection", fileSelectionIndexes);
String bestFormat = ImportingUtilities.autoSelectFiles(job, retrievalRecord, fileSelectionIndexes);
bestFormat = ImportingUtilities.guessBetterFormat(job, bestFormat);
JSONArray rankedFormats = new JSONArray();
<MASK>JSONUtilities.safePut(config, "rankedFormats", rankedFormats);</MASK>
ImportingUtilities.rankFormats(job, bestFormat, rankedFormats);
JSONUtilities.safePut(config, "state", "ready");
JSONUtilities.safePut(config, "hasData", true);
config.remove("progress");
}" |
Inversion-Mutation | megadiff | "@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Page page = (Page) component;
UIComponent config = page.getFacet("config");
UIComponent preinit = page.getFacet("preinit");
UIComponent postinit = page.getFacet("postinit");
writer.write("<!DOCTYPE html>\n");
writer.startElement("html", page);
if(page.getManifest() != null) {
writer.writeAttribute("manifest", page.getManifest(), "manifest");
}
writer.startElement("head", page);
//viewport meta
writer.startElement("meta", null);
writer.writeAttribute("name", "viewport", null);
writer.writeAttribute("content", "initial-scale=1.0", null);
writer.endElement("meta");
writer.startElement("title", null);
writer.write(page.getTitle());
writer.endElement("title");
if(preinit != null) {
preinit.encodeAll(context);
}
// jQuery first
if (context.isProjectStage(ProjectStage.Development)) {
renderResource(context, "jquery-2.0.2.js", "javax.faces.resource.Script", HelixLibraryName, null);
} else {
renderResource(context, "jquery-2.0.2.min.js", "javax.faces.resource.Script", HelixLibraryName, null);
}
// config options; must happen before we include jQuery Mobile, otherwise
// we miss the mobileinit event.
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
// Initialize jQuery Mobile
writer.write("$(document).bind('mobileinit', function(){");
writer.write("$.mobile.ajaxEnabled = false;");
//writer.write("$.mobile.linkBindingEnabled = false;");
writer.write("$.mobile.hashListeningEnabled = false;");
writer.write("$.mobile.pushStateEnabled = false;");
if(page.getLoadingMessage() != null) {
writer.write("$.mobile.loadingMessage = '" + page.getLoadingMessage() + "';");
}
if(page.getDefaultPageTransition() != null) {
writer.write("$.mobile.defaultPageTransition = '" + page.getDefaultPageTransition() + "';");
}
if(page.getDefaultDialogTransition() != null) {
writer.write("$.mobile.defaultDialogTransition = '" + page.getDefaultDialogTransition() + "';");
}
if(config != null) {
config.encodeAll(context);
}
writer.write("});");
writer.endElement("script");
// Then override with pf-mobile content.
renderResource(context, "helix-mobile-full.css", "javax.faces.resource.Stylesheet", HelixLibraryName, null);
renderResource(context, "css/helix.overrides.css", "javax.faces.resource.Stylesheet", HelixLibraryName, null);
renderResource(context, "cordova-full.js", "javax.faces.resource.Script", HelixLibraryName, null);
renderResource(context, "helix-mobile-full.js", "javax.faces.resource.Script", HelixLibraryName, null);
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
// Set a global variable with the context root.
writer.write("Helix.contextRoot = '" + context.getExternalContext().getRequestContextPath() + "';");
writer.endElement("script");
// Registered resources - from primefaces
UIViewRoot viewRoot = context.getViewRoot();
ListIterator<UIComponent> iter = (viewRoot.getComponentResources(context, "head")).listIterator();
while (iter.hasNext()) {
writer.write("\n");
UIComponent resource = (UIComponent) iter.next();
resource.encodeAll(context);
}
// Then handle the user's postinit facet.
if(postinit != null) {
List<UIComponent> children = postinit.getChildren();
for (UIComponent postinitChild : children) {
postinitChild.encodeAll(context);
}
}
writer.endElement("head");
writer.startElement("body", page);
writer.writeAttribute("style", "overflow: hidden;", null);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeBegin" | "@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Page page = (Page) component;
UIComponent config = page.getFacet("config");
UIComponent preinit = page.getFacet("preinit");
UIComponent postinit = page.getFacet("postinit");
writer.write("<!DOCTYPE html>\n");
writer.startElement("html", page);
if(page.getManifest() != null) {
writer.writeAttribute("manifest", page.getManifest(), "manifest");
}
writer.startElement("head", page);
//viewport meta
writer.startElement("meta", null);
writer.writeAttribute("name", "viewport", null);
writer.writeAttribute("content", "initial-scale=1.0", null);
writer.endElement("meta");
writer.startElement("title", null);
writer.write(page.getTitle());
writer.endElement("title");
if(preinit != null) {
preinit.encodeAll(context);
}
// jQuery first
if (context.isProjectStage(ProjectStage.Development)) {
renderResource(context, "jquery-2.0.2.js", "javax.faces.resource.Script", HelixLibraryName, null);
} else {
renderResource(context, "jquery-2.0.2.min.js", "javax.faces.resource.Script", HelixLibraryName, null);
}
// config options; must happen before we include jQuery Mobile, otherwise
// we miss the mobileinit event.
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
// Initialize jQuery Mobile
writer.write("$(document).bind('mobileinit', function(){");
writer.write("$.mobile.ajaxEnabled = false;");
//writer.write("$.mobile.linkBindingEnabled = false;");
writer.write("$.mobile.hashListeningEnabled = false;");
writer.write("$.mobile.pushStateEnabled = false;");
if(page.getLoadingMessage() != null) {
writer.write("$.mobile.loadingMessage = '" + page.getLoadingMessage() + "';");
}
if(page.getDefaultPageTransition() != null) {
writer.write("$.mobile.defaultPageTransition = '" + page.getDefaultPageTransition() + "';");
}
if(page.getDefaultDialogTransition() != null) {
writer.write("$.mobile.defaultDialogTransition = '" + page.getDefaultDialogTransition() + "';");
}
if(config != null) {
config.encodeAll(context);
}
writer.write("});");
writer.endElement("script");
// Then override with pf-mobile content.
renderResource(context, "helix-mobile-full.css", "javax.faces.resource.Stylesheet", HelixLibraryName, null);
renderResource(context, "css/helix.overrides.css", "javax.faces.resource.Stylesheet", HelixLibraryName, null);
<MASK>renderResource(context, "helix-mobile-full.js", "javax.faces.resource.Script", HelixLibraryName, null);</MASK>
renderResource(context, "cordova-full.js", "javax.faces.resource.Script", HelixLibraryName, null);
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
// Set a global variable with the context root.
writer.write("Helix.contextRoot = '" + context.getExternalContext().getRequestContextPath() + "';");
writer.endElement("script");
// Registered resources - from primefaces
UIViewRoot viewRoot = context.getViewRoot();
ListIterator<UIComponent> iter = (viewRoot.getComponentResources(context, "head")).listIterator();
while (iter.hasNext()) {
writer.write("\n");
UIComponent resource = (UIComponent) iter.next();
resource.encodeAll(context);
}
// Then handle the user's postinit facet.
if(postinit != null) {
List<UIComponent> children = postinit.getChildren();
for (UIComponent postinitChild : children) {
postinitChild.encodeAll(context);
}
}
writer.endElement("head");
writer.startElement("body", page);
writer.writeAttribute("style", "overflow: hidden;", null);
}" |
Inversion-Mutation | megadiff | "Postfix(String formula, FormulaManager fm) throws FormulaException {
// convert expression to postfix notation
String[] postfix = null;
int[] pfixcode = null;
String infix;
// convert string to char array
char[] charStr = formula.toCharArray();
// remove spaces and check parentheses
int numSpaces = 0;
int paren = 0;
for (int i=0; i<charStr.length; i++) {
if (charStr[i] == ' ') numSpaces++;
if (charStr[i] == '(') paren++;
if (charStr[i] == ')') paren--;
if (paren < 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"illegal placement of parentheses");
}
}
if (paren != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"parentheses are mismatched!");
}
int j = 0;
int newlen = charStr.length - numSpaces;
if (newlen == 0) return;
char[] exp = new char[newlen];
for (int i=0; i<charStr.length; i++) {
if (charStr[i] != ' ') exp[j++] = charStr[i];
}
infix = new String(exp);
// tokenize string
String ops = "(,)";
for (int i=0; i<fm.uOps.length; i++) ops = ops + fm.uOps[i];
for (int i=0; i<fm.bOps.length; i++) ops = ops + fm.bOps[i];
StringTokenizer tokenizer = new StringTokenizer(infix, ops, true);
int numTokens = tokenizer.countTokens();
// set up stacks
String[] funcStack = new String[numTokens]; // function stack
String[] opStack = new String[numTokens]; // operator stack
int[] opCodes = new int[numTokens]; // operator code stack
String[] pfix = new String[numTokens]; // final postfix ordering
int[] pcode = new int[numTokens]; // final postfix codes
int opPt = 0; // pointer into opStack
int funcPt = 0; // pointer into funcStack
int pfixlen = 0; // pointer into pfix
// flag for detecting unary operators
boolean unary = true;
// flag for detecting no-argument functions (e.g., x())
boolean zero = false;
// flag for detecting floating point numbers
boolean numeral = false;
// convert to postfix
String ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
String token = ntoken;
while (token != null) {
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (token.equals(")")) {
// right paren - pop ops until left paren reached (inclusive)
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[--opPt];
String op = opStack[opPt];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opcode = opCodes[opPt-1];
op = opStack[--opPt];
}
if (opcode == FUNC) {
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
String f = funcStack[--funcPt];
boolean implicit;
if (zero) {
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "0";
}
else {
int n = 1;
while (f.equals(",")) {
n++;
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
f = funcStack[--funcPt];
}
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "" + n;
}
if (!implicit) {
pcode[pfixlen] = FUNC;
pfix[pfixlen++] = f;
}
}
unary = false;
zero = false;
numeral = false;
}
if (token.equals("(")) {
// left paren - push onto operator stack
opCodes[opPt] = OTHER;
opStack[opPt++] = "(";
unary = true;
zero = false;
numeral = false;
}
else if (token.equals(",")) {
// comma - pop ops until left paren reached (exclusive), push comma
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[opPt-1];
String op = opStack[opPt-1];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
opPt--;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opcode = opCodes[opPt-1];
op = opStack[opPt-1];
}
funcStack[funcPt++] = ",";
unary = true;
zero = false;
numeral = false;
}
else if ((unary && fm.isUnaryOp(token)) || fm.isBinaryOp(token)) {
int num = -1;
if (numeral && token.equals(".") && ntoken != null) {
// special case for detecting floating point numbers
try {
num = Integer.parseInt(ntoken);
}
catch (NumberFormatException exc) { }
}
if (num > 0) {
pfix[pfixlen-1] = pfix[pfixlen-1] + "." + ntoken;
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = false;
zero = false;
numeral = false;
}
else {
// operator - pop ops with higher precedence, push op
boolean isUnary = (unary && fm.isUnaryOp(token));
int prec = (isUnary ? fm.getUnaryPrec(token)
: fm.getBinaryPrec(token));
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
prec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
opCodes[opPt] = (isUnary ? UNARY : BINARY);
opStack[opPt++] = token;
unary = true;
zero = false;
numeral = false;
}
}
else if (ntoken != null && ntoken.equals("(")) {
// function - push function name and left paren
if (fm.isFunction(token)) funcStack[funcPt++] = token;
else {
// implicit function - append token to postfix expression
funcStack[funcPt++] = IMPLICIT;
if (!token.equals(")")) {
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
}
// pop ops with higher precedence
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
fm.iPrec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
opPt--;
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
}
opCodes[opPt] = FUNC;
opStack[opPt++] = "(";
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = true;
zero = true;
numeral = false;
}
else if (!token.equals(")")) {
// variable - append token to postfix expression
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
unary = false;
zero = false;
try {
int num = Integer.parseInt(token);
numeral = true;
}
catch (NumberFormatException exc) {
numeral = false;
}
}
token = ntoken;
}
// pop remaining ops from stack
while (opPt > 0) {
pcode[pfixlen] = opCodes[opPt-1];
pfix[pfixlen++] = "" + opStack[--opPt];
}
// make sure stacks are empty
if (opPt != 0 || funcPt != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"stacks are not empty");
}
// return postfix array of tokens
tokens = new String[pfixlen];
codes = new int[pfixlen];
System.arraycopy(pfix, 0, tokens, 0, pfixlen);
System.arraycopy(pcode, 0, codes, 0, pfixlen);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Postfix" | "Postfix(String formula, FormulaManager fm) throws FormulaException {
// convert expression to postfix notation
String[] postfix = null;
int[] pfixcode = null;
String infix;
// convert string to char array
char[] charStr = formula.toCharArray();
// remove spaces and check parentheses
int numSpaces = 0;
int paren = 0;
for (int i=0; i<charStr.length; i++) {
if (charStr[i] == ' ') numSpaces++;
if (charStr[i] == '(') paren++;
if (charStr[i] == ')') paren--;
if (paren < 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"illegal placement of parentheses");
}
}
if (paren != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"parentheses are mismatched!");
}
int j = 0;
int newlen = charStr.length - numSpaces;
if (newlen == 0) return;
char[] exp = new char[newlen];
for (int i=0; i<charStr.length; i++) {
if (charStr[i] != ' ') exp[j++] = charStr[i];
}
infix = new String(exp);
// tokenize string
String ops = "(,)";
for (int i=0; i<fm.uOps.length; i++) ops = ops + fm.uOps[i];
for (int i=0; i<fm.bOps.length; i++) ops = ops + fm.bOps[i];
StringTokenizer tokenizer = new StringTokenizer(infix, ops, true);
int numTokens = tokenizer.countTokens();
// set up stacks
String[] funcStack = new String[numTokens]; // function stack
String[] opStack = new String[numTokens]; // operator stack
int[] opCodes = new int[numTokens]; // operator code stack
String[] pfix = new String[numTokens]; // final postfix ordering
int[] pcode = new int[numTokens]; // final postfix codes
int opPt = 0; // pointer into opStack
int funcPt = 0; // pointer into funcStack
int pfixlen = 0; // pointer into pfix
// flag for detecting unary operators
boolean unary = true;
// flag for detecting no-argument functions (e.g., x())
boolean zero = false;
// flag for detecting floating point numbers
boolean numeral = false;
// convert to postfix
String ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
String token = ntoken;
while (token != null) {
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (token.equals(")")) {
// right paren - pop ops until left paren reached (inclusive)
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[--opPt];
String op = opStack[opPt];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
opcode = opCodes[opPt-1];
op = opStack[--opPt];
}
if (opcode == FUNC) {
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
String f = funcStack[--funcPt];
boolean implicit;
if (zero) {
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "0";
}
else {
int n = 1;
while (f.equals(",")) {
n++;
if (funcPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: function stack " +
"unexpectedly empty");
}
f = funcStack[--funcPt];
}
implicit = f.equals(IMPLICIT);
pcode[pfixlen] = implicit ? FUNC : FUNCCONST;
pfix[pfixlen++] = "" + n;
}
if (!implicit) {
pcode[pfixlen] = FUNC;
pfix[pfixlen++] = f;
}
}
unary = false;
zero = false;
numeral = false;
}
if (token.equals("(")) {
// left paren - push onto operator stack
opCodes[opPt] = OTHER;
opStack[opPt++] = "(";
unary = true;
zero = false;
numeral = false;
}
else if (token.equals(",")) {
// comma - pop ops until left paren reached (exclusive), push comma
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
int opcode = opCodes[opPt-1];
String op = opStack[opPt-1];
while (!op.equals("(")) {
pcode[pfixlen] = opcode;
pfix[pfixlen++] = "" + op;
if (opPt < 1) {
throw new FormulaException("Unable to convert to postfix " +
"notation: operator stack " +
"unexpectedly empty");
}
<MASK>opPt--;</MASK>
opcode = opCodes[opPt-1];
op = opStack[opPt-1];
}
funcStack[funcPt++] = ",";
unary = true;
zero = false;
numeral = false;
}
else if ((unary && fm.isUnaryOp(token)) || fm.isBinaryOp(token)) {
int num = -1;
if (numeral && token.equals(".") && ntoken != null) {
// special case for detecting floating point numbers
try {
num = Integer.parseInt(ntoken);
}
catch (NumberFormatException exc) { }
}
if (num > 0) {
pfix[pfixlen-1] = pfix[pfixlen-1] + "." + ntoken;
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = false;
zero = false;
numeral = false;
}
else {
// operator - pop ops with higher precedence, push op
boolean isUnary = (unary && fm.isUnaryOp(token));
int prec = (isUnary ? fm.getUnaryPrec(token)
: fm.getBinaryPrec(token));
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
prec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
<MASK>opPt--;</MASK>
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
opCodes[opPt] = (isUnary ? UNARY : BINARY);
opStack[opPt++] = token;
unary = true;
zero = false;
numeral = false;
}
}
else if (ntoken != null && ntoken.equals("(")) {
// function - push function name and left paren
if (fm.isFunction(token)) funcStack[funcPt++] = token;
else {
// implicit function - append token to postfix expression
funcStack[funcPt++] = IMPLICIT;
if (!token.equals(")")) {
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
}
// pop ops with higher precedence
String sop;
int scode;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
while (sop != null &&
fm.iPrec >= (scode == UNARY ? fm.getUnaryPrec(sop)
: fm.getBinaryPrec(sop))) {
<MASK>opPt--;</MASK>
pcode[pfixlen] = scode;
pfix[pfixlen++] = "" + sop;
if (opPt < 1) {
sop = null;
scode = 0;
}
else {
sop = opStack[opPt-1];
scode = opCodes[opPt-1];
}
}
}
opCodes[opPt] = FUNC;
opStack[opPt++] = "(";
token = ntoken;
ntoken = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
unary = true;
zero = true;
numeral = false;
}
else if (!token.equals(")")) {
// variable - append token to postfix expression
pcode[pfixlen] = OTHER;
pfix[pfixlen++] = token;
unary = false;
zero = false;
try {
int num = Integer.parseInt(token);
numeral = true;
}
catch (NumberFormatException exc) {
numeral = false;
}
}
token = ntoken;
}
// pop remaining ops from stack
while (opPt > 0) {
pcode[pfixlen] = opCodes[opPt-1];
pfix[pfixlen++] = "" + opStack[--opPt];
}
// make sure stacks are empty
if (opPt != 0 || funcPt != 0) {
throw new FormulaException("Unable to convert to postfix notation: " +
"stacks are not empty");
}
// return postfix array of tokens
tokens = new String[pfixlen];
codes = new int[pfixlen];
System.arraycopy(pfix, 0, tokens, 0, pfixlen);
System.arraycopy(pcode, 0, codes, 0, pfixlen);
}" |
Inversion-Mutation | megadiff | "public SVDBClockingEventExpr clocking_event() throws SVParseException {
SVDBClockingEventExpr expr = new SVDBClockingEventExpr();
fLexer.readOperator("@");
// Check if there is an open brace - kill it if so
if (fLexer.peekOperator("(")) {
SVDBParenExpr p = new SVDBParenExpr();
p.setLocation(fLexer.getStartLocation());
fLexer.eatToken();
// Handle @(*)
if (fLexer.peekOperator("*")) {
// swallow the *
fLexer.readOperator("*");
expr.setClockingEventType(ClockingEventType.Any);
// TODO: How do I set the expression?
}
// grab the event expression
else {
expr.setClockingEventType(ClockingEventType.Expr);
p.setExpr(event_expression());
expr.setExpr(p);
}
fLexer.readOperator(")");
}
// handle @*
else if (fLexer.peekOperator("*")) {
expr.setClockingEventType(ClockingEventType.Any);
// swallow the *
fLexer.readOperator("*");
// TODO: How do I set the expression?
// expr.setExpr(idExpr());
}
// Handle @ some_event_name
else {
expr.setClockingEventType(ClockingEventType.Expr);
expr.setExpr(idExpr());
}
return expr;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "clocking_event" | "public SVDBClockingEventExpr clocking_event() throws SVParseException {
SVDBClockingEventExpr expr = new SVDBClockingEventExpr();
fLexer.readOperator("@");
// Check if there is an open brace - kill it if so
if (fLexer.peekOperator("(")) {
SVDBParenExpr p = new SVDBParenExpr();
p.setLocation(fLexer.getStartLocation());
fLexer.eatToken();
// Handle @(*)
if (fLexer.peekOperator("*")) {
// swallow the *
fLexer.readOperator("*");
expr.setClockingEventType(ClockingEventType.Any);
// TODO: How do I set the expression?
}
// grab the event expression
else {
expr.setClockingEventType(ClockingEventType.Expr);
p.setExpr(event_expression());
}
fLexer.readOperator(")");
<MASK>expr.setExpr(p);</MASK>
}
// handle @*
else if (fLexer.peekOperator("*")) {
expr.setClockingEventType(ClockingEventType.Any);
// swallow the *
fLexer.readOperator("*");
// TODO: How do I set the expression?
// expr.setExpr(idExpr());
}
// Handle @ some_event_name
else {
expr.setClockingEventType(ClockingEventType.Expr);
expr.setExpr(idExpr());
}
return expr;
}" |
Inversion-Mutation | megadiff | "private void initializeIndex(){
StandardAnalyzer analyzer=new StandardAnalyzer(Version.LUCENE_36);
try {
index=FSDirectory.open(new File(indexLocation));
reader = IndexReader.open(index);
IndexWriterConfig indexWriterConfig=new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
writer = new IndexWriter(index,indexWriterConfig);
searcher = new IndexSearcher(reader);
spellChecker= new SpellChecker(index);
Dictionary dictionary= new LuceneDictionary(reader, "contents");
IndexWriterConfig indexWriterSpellcheck=new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
spellChecker.indexDictionary(dictionary,indexWriterSpellcheck, true);
} catch (CorruptIndexException e) {
throw new IndexingException("Error while initializing index", e);
} catch (LockObtainFailedException e) {
throw new IndexingException("Error while initializing index", e);
} catch (IOException e) {
throw new IndexingException("Error while initializing index", e);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initializeIndex" | "private void initializeIndex(){
StandardAnalyzer analyzer=new StandardAnalyzer(Version.LUCENE_36);
try {
index=FSDirectory.open(new File(indexLocation));
IndexWriterConfig indexWriterConfig=new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
writer = new IndexWriter(index,indexWriterConfig);
<MASK>reader = IndexReader.open(index);</MASK>
searcher = new IndexSearcher(reader);
spellChecker= new SpellChecker(index);
Dictionary dictionary= new LuceneDictionary(reader, "contents");
IndexWriterConfig indexWriterSpellcheck=new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
spellChecker.indexDictionary(dictionary,indexWriterSpellcheck, true);
} catch (CorruptIndexException e) {
throw new IndexingException("Error while initializing index", e);
} catch (LockObtainFailedException e) {
throw new IndexingException("Error while initializing index", e);
} catch (IOException e) {
throw new IndexingException("Error while initializing index", e);
}
}" |
Inversion-Mutation | megadiff | "public void Bid(Player bidder, String[] inputArgs) {
AuctionBid bid = new AuctionBid(this, bidder, inputArgs);
if (bid.getError() != null) {
failBid(bid, bid.getError());
return;
}
if (owner.equals(bidder)) {
failBid(bid, "bid-fail-is-auction-owner");
return;
}
if (currentBid == null) {
setNewBid(bid, "bid-success-no-challenger");
return;
}
Integer previousBidAmount = currentBid.getBidAmount();
if (currentBid.getBidder().equals(bidder)) {
if (bid.raiseOwnBid(currentBid)) {
setNewBid(bid, "bid-success-update-own-bid");
} else {
if (bid.getMaxBidAmount() > currentBid.getMaxBidAmount()) {
setNewBid(bid, "bid-success-update-own-maxbid");
} else {
failBid(bid, "bid-fail-already-current-bidder");
}
}
return;
}
AuctionBid winner = null;
AuctionBid looser = null;
if (plugin.getConfig().getBoolean("use-old-bid-logic")) {
if (bid.getMaxBidAmount() > currentBid.getMaxBidAmount()) {
winner = bid;
looser = currentBid;
} else {
winner = currentBid;
looser = bid;
}
winner.raiseBid(Math.max(winner.getBidAmount(), Math.min(winner.getMaxBidAmount(), looser.getBidAmount() + minBidIncrement)));
} else {
// If you follow what this does, congratulations.
Integer baseBid = 0;
if (bid.getBidAmount() >= currentBid.getBidAmount() + minBidIncrement) {
baseBid = bid.getBidAmount();
} else {
baseBid = currentBid.getBidAmount() + minBidIncrement;
}
Integer prevSteps = (int) Math.floor((double)(currentBid.getMaxBidAmount() - baseBid + minBidIncrement) / minBidIncrement / 2);
Integer newSteps = (int) Math.floor((double)(bid.getMaxBidAmount() - baseBid) / minBidIncrement / 2);
if (newSteps >= prevSteps) {
winner = bid;
winner.raiseBid(baseBid + (Math.max(0, prevSteps) * minBidIncrement * 2));
looser = currentBid;
} else {
winner = currentBid;
winner.raiseBid(baseBid + (Math.max(0, newSteps + 1) * minBidIncrement * 2) - minBidIncrement);
looser = bid;
}
}
if (previousBidAmount <= winner.getBidAmount()) {
// Did the new bid win?
if (winner.equals(bid)) {
setNewBid(bid, "bid-success-outbid");
} else {
// Did the old bid have to raise the bid to stay winner?
if (previousBidAmount < winner.getBidAmount()) {
failBid(bid, "bid-fail-auto-outbid");
} else {
failBid(bid, null);
}
}
} else {
// Seriously don't know what could cause this, but might as well take care of it.
plugin.sendMessage("bid-fail-too-low", bid.getBidder(), this);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Bid" | "public void Bid(Player bidder, String[] inputArgs) {
AuctionBid bid = new AuctionBid(this, bidder, inputArgs);
<MASK>Integer previousBidAmount = currentBid.getBidAmount();</MASK>
if (bid.getError() != null) {
failBid(bid, bid.getError());
return;
}
if (owner.equals(bidder)) {
failBid(bid, "bid-fail-is-auction-owner");
return;
}
if (currentBid == null) {
setNewBid(bid, "bid-success-no-challenger");
return;
}
if (currentBid.getBidder().equals(bidder)) {
if (bid.raiseOwnBid(currentBid)) {
setNewBid(bid, "bid-success-update-own-bid");
} else {
if (bid.getMaxBidAmount() > currentBid.getMaxBidAmount()) {
setNewBid(bid, "bid-success-update-own-maxbid");
} else {
failBid(bid, "bid-fail-already-current-bidder");
}
}
return;
}
AuctionBid winner = null;
AuctionBid looser = null;
if (plugin.getConfig().getBoolean("use-old-bid-logic")) {
if (bid.getMaxBidAmount() > currentBid.getMaxBidAmount()) {
winner = bid;
looser = currentBid;
} else {
winner = currentBid;
looser = bid;
}
winner.raiseBid(Math.max(winner.getBidAmount(), Math.min(winner.getMaxBidAmount(), looser.getBidAmount() + minBidIncrement)));
} else {
// If you follow what this does, congratulations.
Integer baseBid = 0;
if (bid.getBidAmount() >= currentBid.getBidAmount() + minBidIncrement) {
baseBid = bid.getBidAmount();
} else {
baseBid = currentBid.getBidAmount() + minBidIncrement;
}
Integer prevSteps = (int) Math.floor((double)(currentBid.getMaxBidAmount() - baseBid + minBidIncrement) / minBidIncrement / 2);
Integer newSteps = (int) Math.floor((double)(bid.getMaxBidAmount() - baseBid) / minBidIncrement / 2);
if (newSteps >= prevSteps) {
winner = bid;
winner.raiseBid(baseBid + (Math.max(0, prevSteps) * minBidIncrement * 2));
looser = currentBid;
} else {
winner = currentBid;
winner.raiseBid(baseBid + (Math.max(0, newSteps + 1) * minBidIncrement * 2) - minBidIncrement);
looser = bid;
}
}
if (previousBidAmount <= winner.getBidAmount()) {
// Did the new bid win?
if (winner.equals(bid)) {
setNewBid(bid, "bid-success-outbid");
} else {
// Did the old bid have to raise the bid to stay winner?
if (previousBidAmount < winner.getBidAmount()) {
failBid(bid, "bid-fail-auto-outbid");
} else {
failBid(bid, null);
}
}
} else {
// Seriously don't know what could cause this, but might as well take care of it.
plugin.sendMessage("bid-fail-too-low", bid.getBidder(), this);
}
}" |
Inversion-Mutation | megadiff | "public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createDBObjects" | "public static void createDBObjects () {
/* Transponder Code = 1 */
Route debugRoute = Route.ParseRouteByTaxiways((new Waypoint(new LatLng(41.7258, -71.4368), false, false)), "");
debugRoute.addWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7258, -71.4368), false, false),
new Waypoint(new LatLng(41.7087976, -71.44134), false, false),
new Waypoint(new LatLng(41.73783, -71.41615), false, false),
new Waypoint(new LatLng(41.725, -71.433333), true, false)
));
//Transponder.Parse(1).setRoute(debugRoute);
//Transponder.Parse(2).setRoute(debugRoute);
ArrayList<Taxiway> taxiways = Lists.newArrayList();
Taxiway taxiway = new Taxiway('B');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.72853650684023, -71.42628192901611), false, false),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.726678855296136, -71.42430782318115), true, true),
new Waypoint(new LatLng(41.724180549563606, -71.42203330993652), false, false),
new Waypoint(new LatLng(41.72321963687659, -71.42310619354248), true, false),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('A');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.732027465276374, -71.42314910888672), false, false),
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.73074640164693, -71.42087459564209), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('C');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.43001556396484), false, false),
new Waypoint(new LatLng(41.72571797997234, -71.42877101898193), false, false),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true),
new Waypoint(new LatLng(41.72453288061494, -71.42598152160645), true, true),
new Waypoint(new LatLng(41.722707144234306, -71.42400741577148), false, true),
new Waypoint(new LatLng(41.71783826026642, -71.41907215118408), false, false),
new Waypoint(new LatLng(41.718414857887055, -71.41825675964355), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('E');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('F');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, true),
new Waypoint(new LatLng(41.73151504289037, -71.43237590789795), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('M');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.7312588301645, -71.42203330993652), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.727479573755126, -71.42520904541016), false, true),
new Waypoint(new LatLng(41.72626247775354, -71.42602443695068), true, true),
new Waypoint(new LatLng(41.725205507257044, -71.42696857452393), false, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('N');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72808811310961, -71.43435001373291), false, false),
<MASK>new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, true),</MASK>
new Waypoint(new LatLng(41.72869664669985, -71.43306255340576), false, false),
new Waypoint(new LatLng(41.729561395043916, -71.43237590789795), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, false),
new Waypoint(new LatLng(41.72972153234874, -71.42662525177002), false, true),
new Waypoint(new LatLng(41.729849641905204, -71.42327785491943), false, true),
new Waypoint(new LatLng(41.72988166925439, -71.42160415649414), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('S');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71610843636524, -71.43426418304443), false, true),
new Waypoint(new LatLng(41.714314495734975, -71.43537998199463), false, false),
new Waypoint(new LatLng(41.713769896707845, -71.43443584442139), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('T');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.72965747747473, -71.43061637878418), false, false),
new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, false),
new Waypoint(new LatLng(41.72094541960078, -71.4376974105835), false, false),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true),
new Waypoint(new LatLng(41.719536005117995, -71.43555164337158), false, true),
new Waypoint(new LatLng(41.71796639351807, -71.4325475692749), false, true),
new Waypoint(new LatLng(41.71754995951615, -71.43151760101318), true, true)
));
taxiways.add(taxiway);
taxiway = new Taxiway('V');
taxiway.setWaypoints(Arrays.asList(
new Waypoint(new LatLng(41.73228367493647, -71.42739772796631), false, true),
new Waypoint(new LatLng(41.72972153234874, -71.4296293258667), true, true),
new Waypoint(new LatLng(41.72575000938133, -71.43280506134033), false, true),
new Waypoint(new LatLng(41.72056103689838, -71.43701076507568), false, true)
));
taxiways.add(taxiway);
Airport kpvd = new Airport("kpvd", null, null, null, "");
kpvd.setTaxiways(taxiways);
kpvd.setRouteStartingPoints(Arrays.asList(new Waypoint(new LatLng(41.72575000938133, -71.4336633682251), false, true)));
ofy().save().entities(kpvd).now();
AtcUser josh = new AtcUser("[email protected]");
AtcUser hawk = new AtcUser("[email protected]");
AtcUser max = new AtcUser("[email protected]");
ofy().save().entity(josh).now();
ofy().save().entity(hawk).now();
ofy().save().entity(max).now();
}" |
Inversion-Mutation | megadiff | "public boolean isBaseLevelForKey(Slice userKey)
{
// Maybe use binary search to find right entry instead of linear search?
UserComparator userComparator = inputVersion.getInternalKeyComparator().getUserComparator();
for (int level = this.level + 2; level < NUM_LEVELS; level++) {
List<FileMetaData> files = inputVersion.getFiles(level);
while (levelPointers[level] < files.size()) {
FileMetaData f = files.get(levelPointers[level]);
if (userComparator.compare(userKey, f.getLargest().getUserKey()) <= 0) {
// We've advanced far enough
if (userComparator.compare(userKey, f.getSmallest().getUserKey()) >= 0) {
// Key falls in this file's range, so definitely not base level
return false;
}
break;
}
levelPointers[level]++;
}
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "isBaseLevelForKey" | "public boolean isBaseLevelForKey(Slice userKey)
{
// Maybe use binary search to find right entry instead of linear search?
UserComparator userComparator = inputVersion.getInternalKeyComparator().getUserComparator();
for (int level = this.level + 2; level < NUM_LEVELS; level++) {
List<FileMetaData> files = inputVersion.getFiles(level);
while (levelPointers[level] < files.size()) {
FileMetaData f = files.get(levelPointers[level]);
if (userComparator.compare(userKey, f.getLargest().getUserKey()) <= 0) {
// We've advanced far enough
if (userComparator.compare(userKey, f.getSmallest().getUserKey()) >= 0) {
// Key falls in this file's range, so definitely not base level
return false;
}
break;
}
}
<MASK>levelPointers[level]++;</MASK>
}
return true;
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) {
Grid g = new Grid();
GameDisplay display = new GameDisplay(g);
long s = System.currentTimeMillis();
while ((s - System.currentTimeMillis()) < 0){
if ((System.currentTimeMillis() - s) >= 1000){
display.redraw(g);
s = System.currentTimeMillis();
}
}
}" | 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) {
Grid g = new Grid();
GameDisplay display = new GameDisplay(g);
long <MASK>s = System.currentTimeMillis();</MASK>
while ((s - System.currentTimeMillis()) < 0){
<MASK>s = System.currentTimeMillis();</MASK>
if ((System.currentTimeMillis() - s) >= 1000){
display.redraw(g);
}
}
}" |
Inversion-Mutation | megadiff | "public void clearCache() {
String[] principalNames;
synchronized (m_storeLock) {
principalNames = m_store.keySet().toArray(new String[m_store.size()]);
}
// notify with a filter, that will be accepted nowhere
SERVICES.getService(IClientNotificationService.class).putNotification(new ResetAccessControlChangedNotification(), new SingleUserFilter(null, 0L));
clearCacheOfPrincipals(principalNames);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "clearCache" | "public void clearCache() {
String[] principalNames;
synchronized (m_storeLock) {
principalNames = m_store.keySet().toArray(new String[m_store.size()]);
}
<MASK>clearCacheOfPrincipals(principalNames);</MASK>
// notify with a filter, that will be accepted nowhere
SERVICES.getService(IClientNotificationService.class).putNotification(new ResetAccessControlChangedNotification(), new SingleUserFilter(null, 0L));
}" |
Inversion-Mutation | megadiff | "public Database(Client client_, String name_) throws SDBPException {
client = client_;
name = name_;
BigInteger bi = scaliendb_client.SDBP_GetDatabaseID(client.getPtr(), name);
databaseID = bi.longValue();
if (databaseID == 0)
throw new SDBPException(Status.toString(Status.SDBP_BADSCHEMA));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Database" | "public Database(Client client_, String name_) throws SDBPException {
client = client_;
BigInteger bi = scaliendb_client.SDBP_GetDatabaseID(client.getPtr(), name);
databaseID = bi.longValue();
if (databaseID == 0)
throw new SDBPException(Status.toString(Status.SDBP_BADSCHEMA));
<MASK>name = name_;</MASK>
}" |
Inversion-Mutation | megadiff | "public void processGetRequest(HTTPRequest request){
js = request.isParameterSet("js");
showold = request.isParameterSet("showold");
groupusk = request.isParameterSet("groupusk");
if (request.isParameterSet("request") && Search.hasSearch(request.getIntParam("request"))){
search = Search.getSearch(request.getIntParam("request"));
if(search!=null){
search.setMakeResultNode(groupusk, showold, true); // for the moment js will always be on for results, js detecting isnt being used
if(request.isParameterSet("indexname") && request.getParam("indexname").length() > 0){
library.addBookmark(request.getParam("indexname"), request.getParam("index"));
}
query = search.getQuery();
indexstring = search.getIndexURI();
String[] indexes = indexstring.split("[ ;]");
for (String string : indexes) {
if(string.length() > Library.BOOKMARK_PREFIX.length() && library.bookmarkKeys().contains(string.substring(Library.BOOKMARK_PREFIX.length())))
selectedBMIndexes.add(string);
else
etcIndexes += string.trim() + " ";
}
etcIndexes = etcIndexes.trim();
Logger.minor(this, "Refreshing request "+request.getIntParam("request")+" " +query);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processGetRequest" | "public void processGetRequest(HTTPRequest request){
js = request.isParameterSet("js");
showold = request.isParameterSet("showold");
groupusk = request.isParameterSet("groupusk");
if (request.isParameterSet("request") && Search.hasSearch(request.getIntParam("request"))){
search = Search.getSearch(request.getIntParam("request"));
<MASK>search.setMakeResultNode(groupusk, showold, true); // for the moment js will always be on for results, js detecting isnt being used</MASK>
if(search!=null){
if(request.isParameterSet("indexname") && request.getParam("indexname").length() > 0){
library.addBookmark(request.getParam("indexname"), request.getParam("index"));
}
query = search.getQuery();
indexstring = search.getIndexURI();
String[] indexes = indexstring.split("[ ;]");
for (String string : indexes) {
if(string.length() > Library.BOOKMARK_PREFIX.length() && library.bookmarkKeys().contains(string.substring(Library.BOOKMARK_PREFIX.length())))
selectedBMIndexes.add(string);
else
etcIndexes += string.trim() + " ";
}
etcIndexes = etcIndexes.trim();
Logger.minor(this, "Refreshing request "+request.getIntParam("request")+" " +query);
}
}
}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.