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 IMarkerResolution[] getResolutions(IMarker marker) { ArrayList<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); int position = marker.getAttribute(IMarker.CHAR_START, 0); try { if(marker.getResource() instanceof IFile){ IFile file = (IFile)marker.getResource(); if(file != null){ String preferenceKey = getPreferenceKey(marker); String preferencePageId = getPreferencePageId(marker); if(preferenceKey != null && preferencePageId != null){ resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey)); boolean enabled = marker.getAttribute(ValidationErrorManager.SUPPRESS_WARNINGS_ENABLED_ATTRIBUTE, false); int severity = marker.getAttribute(IMarker.SEVERITY, 0); if(enabled && severity == IMarker.SEVERITY_WARNING){ IJavaElement element = findJavaElement(file, position); if(element != null){ if(element instanceof IMethod){ ILocalVariable parameter = findParameter((IMethod)element, position); if(parameter != null){ resolutions.add(new AddSuppressWarningsMarkerResolution(file, parameter, preferenceKey)); } } resolutions.add(new AddSuppressWarningsMarkerResolution(file, element, preferenceKey)); } } } } } } catch (CoreException e) { CommonUIPlugin.getDefault().logError(e); } return resolutions.toArray(new IMarkerResolution[] {}); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getResolutions"
"@Override public IMarkerResolution[] getResolutions(IMarker marker) { ArrayList<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); int position = marker.getAttribute(IMarker.CHAR_START, 0); try { if(marker.getResource() instanceof IFile){ IFile file = (IFile)marker.getResource(); if(file != null){ String preferenceKey = getPreferenceKey(marker); String preferencePageId = getPreferencePageId(marker); if(preferenceKey != null && preferencePageId != null){ resolutions.add(new ConfigureProblemSeverityMarkerResolution(preferencePageId, preferenceKey)); boolean enabled = marker.getAttribute(ValidationErrorManager.SUPPRESS_WARNINGS_ENABLED_ATTRIBUTE, false); int severity = marker.getAttribute(IMarker.SEVERITY, 0); if(enabled && severity == IMarker.SEVERITY_WARNING){ IJavaElement element = findJavaElement(file, position); if(element != null){ if(element instanceof IMethod){ ILocalVariable parameter = findParameter((IMethod)element, position); if(parameter != null){ resolutions.add(new AddSuppressWarningsMarkerResolution(file, parameter, preferenceKey)); } <MASK>resolutions.add(new AddSuppressWarningsMarkerResolution(file, element, preferenceKey));</MASK> } } } } } } } catch (CoreException e) { CommonUIPlugin.getDefault().logError(e); } return resolutions.toArray(new IMarkerResolution[] {}); }"
Inversion-Mutation
megadiff
"public Constant asJava() { Type type = getType(); String txt = originalTextualRepresentation; switch (type) { case Byte: case Int: case Long: case LongString: case Short: txt = trimTrailingTypeInfo(txt); break; case UInt: case ULong: case IntegerString: txt = null; break; } switch (type) { case Long: case ULong: if (txt != null) txt += "L"; case LongString: type = Type.Long; break; case UInt: if ((getValue() instanceof Long) && ((Long)getValue()) > Integer.MAX_VALUE) txt = null; case IntegerString: type = Type.Int; break; } return new Constant(type, getValue(), txt); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "asJava"
"public Constant asJava() { Type type = getType(); String txt = originalTextualRepresentation; switch (type) { case Byte: case Int: <MASK>case IntegerString:</MASK> case Long: case LongString: case Short: txt = trimTrailingTypeInfo(txt); break; case UInt: case ULong: txt = null; break; } switch (type) { case Long: case ULong: if (txt != null) txt += "L"; case LongString: type = Type.Long; break; case UInt: if ((getValue() instanceof Long) && ((Long)getValue()) > Integer.MAX_VALUE) txt = null; <MASK>case IntegerString:</MASK> type = Type.Int; break; } return new Constant(type, getValue(), txt); }"
Inversion-Mutation
megadiff
"public void shutdown() throws CoreException { if (fDescriptorManager != null) { fDescriptorManager.shutdown(); } if (fCoreModel != null) { fCoreModel.shutdown(); } if (cdtLog != null) { cdtLog.shutdown(); } super.shutdown(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "shutdown"
"public void shutdown() throws CoreException { <MASK>super.shutdown();</MASK> if (fDescriptorManager != null) { fDescriptorManager.shutdown(); } if (fCoreModel != null) { fCoreModel.shutdown(); } if (cdtLog != null) { cdtLog.shutdown(); } }"
Inversion-Mutation
megadiff
"private void findConnectingPorts(ArcProto startArc, ArcProto endArc, StringBuffer ds) { // throw away route if it's longer than shortest good route if (specifiedRoute.size() > getShortestRouteLength()) return; if (startArc == endArc) { saveRoute(specifiedRoute); return; // don't need anything to connect between them } ds.append(" "); if (searchNumber == SEARCHLIMIT) { System.out.println("Search limit reached in VerticalRoute"); } if (searchNumber >= SEARCHLIMIT) { return; } searchNumber++; Technology tech = startArc.getTechnology(); // see if we can find a port in the current technology // that will connect the two arcs for (Iterator portsIt = tech.getPorts(); portsIt.hasNext(); ) { PrimitivePort pp = (PrimitivePort)portsIt.next(); // ignore anything whose parent is not a CONTACT if (pp.getParent().getFunction() != PrimitiveNode.Function.CONTACT) continue; if (DEBUGSEARCH) System.out.println(ds+"Checking if "+pp+" connects between "+startArc+" and "+endArc); if (pp.connectsTo(startArc) && pp.connectsTo(endArc)) { specifiedRoute.add(pp); saveRoute(specifiedRoute); return; // this connects between both arcs } } // try all contact ports as an intermediate for (Iterator portsIt = tech.getPorts(); portsIt.hasNext(); ) { PrimitivePort pp = (PrimitivePort)portsIt.next(); // ignore anything whose parent is not a CONTACT if (pp.getParent().getFunction() != PrimitiveNode.Function.CONTACT) continue; if (DEBUGSEARCH) System.out.println(ds+"Checking if "+pp+" (parent is "+pp.getParent()+") connects to "+startArc); if (pp.connectsTo(startArc)) { if (pp == startPort) continue; // ignore start port if (pp == endPort) continue; // ignore end port if (specifiedRoute.contains(pp)) continue; // ignore ones we've already hit // add to list int prePortSize = specifiedRoute.size(); specifiedRoute.add(pp); // now try to connect through all arcs that can connect to the found pp int preArcSize = specifiedRoute.size(); ArcProto [] arcs = pp.getConnections(); for (int i=0; i<arcs.length; i++) { ArcProto tryarc = arcs[i]; if (tryarc == Generic.tech.universal_arc) continue; if (tryarc == Generic.tech.invisible_arc) continue; if (tryarc == Generic.tech.unrouted_arc) continue; if (tryarc.isNotUsed()) continue; if (tryarc == startArc) continue; // already connecting through startArc if (tryarc == this.startArc) continue; // original arc connecting from if (specifiedRoute.contains(tryarc)) continue; // already used this arc specifiedRoute.add(tryarc); if (DEBUGSEARCH) System.out.println(ds+"...found intermediate node "+pp+" through "+startArc+" to "+tryarc); // recurse findConnectingPorts(tryarc, endArc, ds); // remove added arcs and port and continue search while (specifiedRoute.size() > preArcSize) { specifiedRoute.remove(specifiedRoute.size()-1); } } // that port didn't get us anywhere, clear list back to last good point while (specifiedRoute.size() > prePortSize) { specifiedRoute.remove(specifiedRoute.size()-1); } } } if (DEBUGSEARCH) System.out.println(ds+"--- Bad path ---"); return; // no valid path to endpp found }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findConnectingPorts"
"private void findConnectingPorts(ArcProto startArc, ArcProto endArc, StringBuffer ds) { // throw away route if it's longer than shortest good route if (specifiedRoute.size() > getShortestRouteLength()) return; if (startArc == endArc) { saveRoute(specifiedRoute); return; // don't need anything to connect between them } ds.append(" "); <MASK>searchNumber++;</MASK> if (searchNumber == SEARCHLIMIT) { System.out.println("Search limit reached in VerticalRoute"); } if (searchNumber >= SEARCHLIMIT) { return; } Technology tech = startArc.getTechnology(); // see if we can find a port in the current technology // that will connect the two arcs for (Iterator portsIt = tech.getPorts(); portsIt.hasNext(); ) { PrimitivePort pp = (PrimitivePort)portsIt.next(); // ignore anything whose parent is not a CONTACT if (pp.getParent().getFunction() != PrimitiveNode.Function.CONTACT) continue; if (DEBUGSEARCH) System.out.println(ds+"Checking if "+pp+" connects between "+startArc+" and "+endArc); if (pp.connectsTo(startArc) && pp.connectsTo(endArc)) { specifiedRoute.add(pp); saveRoute(specifiedRoute); return; // this connects between both arcs } } // try all contact ports as an intermediate for (Iterator portsIt = tech.getPorts(); portsIt.hasNext(); ) { PrimitivePort pp = (PrimitivePort)portsIt.next(); // ignore anything whose parent is not a CONTACT if (pp.getParent().getFunction() != PrimitiveNode.Function.CONTACT) continue; if (DEBUGSEARCH) System.out.println(ds+"Checking if "+pp+" (parent is "+pp.getParent()+") connects to "+startArc); if (pp.connectsTo(startArc)) { if (pp == startPort) continue; // ignore start port if (pp == endPort) continue; // ignore end port if (specifiedRoute.contains(pp)) continue; // ignore ones we've already hit // add to list int prePortSize = specifiedRoute.size(); specifiedRoute.add(pp); // now try to connect through all arcs that can connect to the found pp int preArcSize = specifiedRoute.size(); ArcProto [] arcs = pp.getConnections(); for (int i=0; i<arcs.length; i++) { ArcProto tryarc = arcs[i]; if (tryarc == Generic.tech.universal_arc) continue; if (tryarc == Generic.tech.invisible_arc) continue; if (tryarc == Generic.tech.unrouted_arc) continue; if (tryarc.isNotUsed()) continue; if (tryarc == startArc) continue; // already connecting through startArc if (tryarc == this.startArc) continue; // original arc connecting from if (specifiedRoute.contains(tryarc)) continue; // already used this arc specifiedRoute.add(tryarc); if (DEBUGSEARCH) System.out.println(ds+"...found intermediate node "+pp+" through "+startArc+" to "+tryarc); // recurse findConnectingPorts(tryarc, endArc, ds); // remove added arcs and port and continue search while (specifiedRoute.size() > preArcSize) { specifiedRoute.remove(specifiedRoute.size()-1); } } // that port didn't get us anywhere, clear list back to last good point while (specifiedRoute.size() > prePortSize) { specifiedRoute.remove(specifiedRoute.size()-1); } } } if (DEBUGSEARCH) System.out.println(ds+"--- Bad path ---"); return; // no valid path to endpp found }"
Inversion-Mutation
megadiff
"public void createEmbeddedForm(Element startElement) throws XFormsException { // receive all models from given element List<Element> modelElements = getModelElements(startElement); final int nrOfModels = modelElements.size(); // list containing all model of embded form ArrayList<Model> embeddedModels = new ArrayList<Model>(nrOfModels); for (int i = 0; i < nrOfModels; i++) { Element modelElement = modelElements.get(i); Model model = (Model) getElementFactory().createXFormsElement(modelElement, null); this.models.add(model); embeddedModels.add(model); } boolean isCompatible= false; for (int i = 0; i < nrOfModels; i++) { if (i == 0) { isCompatible = checkVersionCompatibility(); } Model model = embeddedModels.get(i); model.init(); if(!(isCompatible)){ return; } dispatch(model.getTarget(), XFormsEventNames.MODEL_CONSTRUCT, null); } for (Model model : embeddedModels) { dispatch(model.getTarget(), XFormsEventNames.MODEL_CONSTRUCT_DONE, null); // set up UI for specific model Initializer.initializeUIElements(model,startElement,null,null); } for (Model model: embeddedModels) { dispatch(model.getTarget(), XFormsEventNames.READY, null); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createEmbeddedForm"
"public void createEmbeddedForm(Element startElement) throws XFormsException { // receive all models from given element List<Element> modelElements = getModelElements(startElement); final int nrOfModels = modelElements.size(); // list containing all model of embded form ArrayList<Model> embeddedModels = new ArrayList<Model>(nrOfModels); for (int i = 0; i < nrOfModels; i++) { Element modelElement = modelElements.get(i); Model model = (Model) getElementFactory().createXFormsElement(modelElement, null); this.models.add(model); embeddedModels.add(model); } for (int i = 0; i < nrOfModels; i++) { <MASK>boolean isCompatible= false;</MASK> if (i == 0) { isCompatible = checkVersionCompatibility(); } Model model = embeddedModels.get(i); model.init(); if(!(isCompatible)){ return; } dispatch(model.getTarget(), XFormsEventNames.MODEL_CONSTRUCT, null); } for (Model model : embeddedModels) { dispatch(model.getTarget(), XFormsEventNames.MODEL_CONSTRUCT_DONE, null); // set up UI for specific model Initializer.initializeUIElements(model,startElement,null,null); } for (Model model: embeddedModels) { dispatch(model.getTarget(), XFormsEventNames.READY, null); } }"
Inversion-Mutation
megadiff
"private static void decodeTextSegment(BitSource bits, StringBuffer result) throws FormatException { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append(cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < 27) { if (upperShift) { result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw FormatException.getFormatInstance(); } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (upperShift) { result.append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_SHIFT3_SET_CHARS[cValue]); } shift = 0; break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "decodeTextSegment"
"private static void decodeTextSegment(BitSource bits, StringBuffer result) throws FormatException { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); <MASK>int shift = 0;</MASK> for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append(cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < 27) { if (upperShift) { result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw FormatException.getFormatInstance(); } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (upperShift) { result.append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_SHIFT3_SET_CHARS[cValue]); } shift = 0; break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); }"
Inversion-Mutation
megadiff
"Dialog createDialog() { final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null); mInput = (EditText) layout.findViewById(R.id.folder_name); AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); builder.setIcon(0); builder.setTitle(getString(R.string.rename_folder_title)); builder.setCancelable(true); builder.setOnCancelListener(new Dialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { cleanup(); } }); builder.setNegativeButton(getString(R.string.cancel_action), new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cleanup(); } } ); builder.setPositiveButton(getString(R.string.rename_action), new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { changeFolderName(); } } ); builder.setView(layout); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { public void onShow(DialogInterface dialog) { mWaitingForResult = true; mInput.requestFocus(); InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(mInput, 0); } }); return dialog; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createDialog"
"Dialog createDialog() { <MASK>mWaitingForResult = true;</MASK> final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null); mInput = (EditText) layout.findViewById(R.id.folder_name); AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); builder.setIcon(0); builder.setTitle(getString(R.string.rename_folder_title)); builder.setCancelable(true); builder.setOnCancelListener(new Dialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { cleanup(); } }); builder.setNegativeButton(getString(R.string.cancel_action), new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cleanup(); } } ); builder.setPositiveButton(getString(R.string.rename_action), new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { changeFolderName(); } } ); builder.setView(layout); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { public void onShow(DialogInterface dialog) { mInput.requestFocus(); InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(mInput, 0); } }); return dialog; }"
Inversion-Mutation
megadiff
"@Override public void init(ReceivedTransaction receivedTransaction, EntityOperation entityOperation) { view.setController(this); view.resetComponents(); model.registerObserver(view); model.setEntityAndEntityOperation(receivedTransaction, entityOperation); customerModel.registerObserver(view); view.init(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
"@Override public void init(ReceivedTransaction receivedTransaction, EntityOperation entityOperation) { view.setController(this); view.resetComponents(); <MASK>customerModel.registerObserver(view);</MASK> model.registerObserver(view); model.setEntityAndEntityOperation(receivedTransaction, entityOperation); view.init(); }"
Inversion-Mutation
megadiff
"private void loadAndBindAllApps() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { synchronized (mLock) { if (i == 0) { // This needs to happen inside the same lock block as when we // prepare the first batch for bindAllApplications. Otherwise // the package changed receiver can come in and double-add // (or miss one?). mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { mBeforeFirstLoad = false; callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadAndBindAllApps"
"private void loadAndBindAllApps() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { synchronized (mLock) { if (i == 0) { // This needs to happen inside the same lock block as when we // prepare the first batch for bindAllApplications. Otherwise // the package changed receiver can come in and double-add // (or miss one?). mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); <MASK>final Callbacks callbacks = tryGetCallbacks(oldCallbacks);</MASK> if (callbacks != null) { if (first) { mBeforeFirstLoad = false; callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } }"
Inversion-Mutation
megadiff
"public IPropertyDescriptor[] getPropertyDescriptors() { if (fDescriptors == null) { try { final List<IPropertyDescriptor> descriptors = new ArrayList<IPropertyDescriptor>(); fDescriptors = new TCFTask<IPropertyDescriptor[]>(fNode.getChannel()) { public void run() { if (fNode instanceof TCFNodeExecContext) { getExecContextDescriptors((TCFNodeExecContext) fNode); } else if (fNode instanceof TCFNodeStackFrame) { getFrameDescriptors((TCFNodeStackFrame) fNode); } else { done(descriptors.toArray(new IPropertyDescriptor[descriptors.size()])); } } private void getFrameDescriptors(TCFNodeStackFrame frameNode) { TCFDataCache<IStackTrace.StackTraceContext> ctx_cache = frameNode.getStackTraceContext(); TCFDataCache<TCFSourceRef> line_info_cache = frameNode.getLineInfo(); if (!validateAll(ctx_cache, line_info_cache)) return; IStackTrace.StackTraceContext ctx = ctx_cache.getData(); if (ctx != null) { Map<String, Object> props = ctx.getProperties(); for (String key : props.keySet()) { Object value = props.get(key); if (value instanceof Number) { value = toHexAddrString((Number) value); } addDescriptor("Context", key, value); } } TCFSourceRef sourceRef = line_info_cache.getData(); if (sourceRef != null) { if (sourceRef.area != null) { addDescriptor("Source", "Directory", sourceRef.area.directory); addDescriptor("Source", "File", sourceRef.area.file); addDescriptor("Source", "Line", sourceRef.area.start_line); } if (sourceRef.error != null) { addDescriptor("Source", "Error", sourceRef.error); } } done(descriptors.toArray(new IPropertyDescriptor[descriptors.size()])); } private void getExecContextDescriptors(TCFNodeExecContext exeNode) { TCFDataCache<IRunControl.RunControlContext> ctx_cache = exeNode.getRunContext(); TCFDataCache<TCFContextState> state_cache = exeNode.getState(); TCFDataCache<MemoryRegion[]> mem_map_cache = exeNode.getMemoryMap(); if (!validateAll(ctx_cache, state_cache, mem_map_cache)) return; IRunControl.RunControlContext ctx = ctx_cache.getData(); if (ctx != null) { Map<String, Object> props = ctx.getProperties(); for (String key : props.keySet()) { Object value = props.get(key); if (value instanceof Number) { value = toHexAddrString((Number) value); } addDescriptor("Context", key, value); } } TCFContextState state = state_cache.getData(); if (state != null) { addDescriptor("State", "Suspended", state.is_suspended); if (state.is_suspended) { addDescriptor("State", "Suspend reason", state.suspend_reason); addDescriptor("State", "PC", toHexAddrString(new BigInteger(state.suspend_pc))); } addDescriptor("State", "Active", !exeNode.isNotActive()); } MemoryRegion[] mem_map = mem_map_cache.getData(); if (mem_map != null && mem_map.length > 0) { int idx = 0; for (MemoryRegion region : mem_map) { Map<String, Object> props = region.region.getProperties(); for (String key : props.keySet()) { Object value = props.get(key); if (value instanceof Number) { value = toHexAddrString((Number) value); } addDescriptor("MemoryRegion["+idx+']', key, value); } idx++; } } done(descriptors.toArray(new IPropertyDescriptor[descriptors.size()])); } private void addDescriptor(String category, String key, Object value) { String id = category + '.' + key; PropertyDescriptor desc = new PropertyDescriptor(id, key); desc.setCategory(category); descriptors.add(desc); fProperties.put(id, value); } boolean validateAll(TCFDataCache<?> ... caches) { TCFDataCache<?> pending = null; for (TCFDataCache<?> cache : caches) { if (!cache.validate()) { pending = cache; } } if (pending != null) { pending.wait(this); return false; } return true; } }.get(5, TimeUnit.SECONDS); } catch (Exception e) { Activator.log("Error retrieving property data", e); fDescriptors = new IPropertyDescriptor[0]; } } return fDescriptors; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getPropertyDescriptors"
"public IPropertyDescriptor[] getPropertyDescriptors() { if (fDescriptors == null) { try { fDescriptors = new TCFTask<IPropertyDescriptor[]>(fNode.getChannel()) { <MASK>final List<IPropertyDescriptor> descriptors = new ArrayList<IPropertyDescriptor>();</MASK> public void run() { if (fNode instanceof TCFNodeExecContext) { getExecContextDescriptors((TCFNodeExecContext) fNode); } else if (fNode instanceof TCFNodeStackFrame) { getFrameDescriptors((TCFNodeStackFrame) fNode); } else { done(descriptors.toArray(new IPropertyDescriptor[descriptors.size()])); } } private void getFrameDescriptors(TCFNodeStackFrame frameNode) { TCFDataCache<IStackTrace.StackTraceContext> ctx_cache = frameNode.getStackTraceContext(); TCFDataCache<TCFSourceRef> line_info_cache = frameNode.getLineInfo(); if (!validateAll(ctx_cache, line_info_cache)) return; IStackTrace.StackTraceContext ctx = ctx_cache.getData(); if (ctx != null) { Map<String, Object> props = ctx.getProperties(); for (String key : props.keySet()) { Object value = props.get(key); if (value instanceof Number) { value = toHexAddrString((Number) value); } addDescriptor("Context", key, value); } } TCFSourceRef sourceRef = line_info_cache.getData(); if (sourceRef != null) { if (sourceRef.area != null) { addDescriptor("Source", "Directory", sourceRef.area.directory); addDescriptor("Source", "File", sourceRef.area.file); addDescriptor("Source", "Line", sourceRef.area.start_line); } if (sourceRef.error != null) { addDescriptor("Source", "Error", sourceRef.error); } } done(descriptors.toArray(new IPropertyDescriptor[descriptors.size()])); } private void getExecContextDescriptors(TCFNodeExecContext exeNode) { TCFDataCache<IRunControl.RunControlContext> ctx_cache = exeNode.getRunContext(); TCFDataCache<TCFContextState> state_cache = exeNode.getState(); TCFDataCache<MemoryRegion[]> mem_map_cache = exeNode.getMemoryMap(); if (!validateAll(ctx_cache, state_cache, mem_map_cache)) return; IRunControl.RunControlContext ctx = ctx_cache.getData(); if (ctx != null) { Map<String, Object> props = ctx.getProperties(); for (String key : props.keySet()) { Object value = props.get(key); if (value instanceof Number) { value = toHexAddrString((Number) value); } addDescriptor("Context", key, value); } } TCFContextState state = state_cache.getData(); if (state != null) { addDescriptor("State", "Suspended", state.is_suspended); if (state.is_suspended) { addDescriptor("State", "Suspend reason", state.suspend_reason); addDescriptor("State", "PC", toHexAddrString(new BigInteger(state.suspend_pc))); } addDescriptor("State", "Active", !exeNode.isNotActive()); } MemoryRegion[] mem_map = mem_map_cache.getData(); if (mem_map != null && mem_map.length > 0) { int idx = 0; for (MemoryRegion region : mem_map) { Map<String, Object> props = region.region.getProperties(); for (String key : props.keySet()) { Object value = props.get(key); if (value instanceof Number) { value = toHexAddrString((Number) value); } addDescriptor("MemoryRegion["+idx+']', key, value); } idx++; } } done(descriptors.toArray(new IPropertyDescriptor[descriptors.size()])); } private void addDescriptor(String category, String key, Object value) { String id = category + '.' + key; PropertyDescriptor desc = new PropertyDescriptor(id, key); desc.setCategory(category); descriptors.add(desc); fProperties.put(id, value); } boolean validateAll(TCFDataCache<?> ... caches) { TCFDataCache<?> pending = null; for (TCFDataCache<?> cache : caches) { if (!cache.validate()) { pending = cache; } } if (pending != null) { pending.wait(this); return false; } return true; } }.get(5, TimeUnit.SECONDS); } catch (Exception e) { Activator.log("Error retrieving property data", e); fDescriptors = new IPropertyDescriptor[0]; } } return fDescriptors; }"
Inversion-Mutation
megadiff
"public void leverInn() { Date innTid = new Date(); if(leietid(innTid) > Sykkel.getMAXTID()) { if(leietid(innTid) - 3 == 1 ) { setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " time for sent"); } else { setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " timer for sent"); } } sykkel = null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "leverInn"
"public void leverInn() { Date innTid = new Date(); if(leietid(innTid) > Sykkel.getMAXTID()) { if(leietid(innTid) - 3 == 1 ) { setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " time for sent"); } else { setMerknad(innTid, "Sykkel ble levert " + (leietid(innTid) - Sykkel.getMAXTID()) + " timer for sent"); } <MASK>sykkel = null;</MASK> } }"
Inversion-Mutation
megadiff
"private void processText(boolean ignorable) throws SAXException { firstCIIChunk = true; if(context.expectText() && (!ignorable || !WhiteSpaceProcessor.isWhiteSpace(buffer))) { if (!hasBase64Data) { visitor.text(buffer); } else { visitor.text(base64Data); hasBase64Data = false; } } buffer.setLength(0); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processText"
"private void processText(boolean ignorable) throws SAXException { firstCIIChunk = true; if(context.expectText() && (!ignorable || !WhiteSpaceProcessor.isWhiteSpace(buffer))) { if (!hasBase64Data) { visitor.text(buffer); <MASK>buffer.setLength(0);</MASK> } else { visitor.text(base64Data); hasBase64Data = false; } } }"
Inversion-Mutation
megadiff
"private List<StopPoint> stopPointList( Route route) { List<StopPoint> stopPoints = new ArrayList<StopPoint>(); try { for ( int i=0; i<routeStopCount; i++) { StopArea stopArea = modelFactory.createModel(StopArea.class); StopPoint stopPoint = new StopPoint(); stopPoint.setContainedInStopArea( quays.get( i%quayCount)); stopPoint.setObjectId( "T:StopPoint:"+route.objectIdSuffix()+"-"+i); stopPoint = modelFactory.createModel( stopPoint); stopPoint.setRoute(route); stopPoints.add( stopPoint); } } catch (CreateModelException ex) { Logger.getLogger(ComplexModelFactory.class.getName()).log(Level.SEVERE, null, ex); } return stopPoints; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stopPointList"
"private List<StopPoint> stopPointList( Route route) { List<StopPoint> stopPoints = new ArrayList<StopPoint>(); try { for ( int i=0; i<routeStopCount; i++) { StopArea stopArea = modelFactory.createModel(StopArea.class); StopPoint stopPoint = new StopPoint(); stopPoint.setContainedInStopArea( quays.get( i%quayCount)); stopPoint.setObjectId( "T:StopPoint:"+route.objectIdSuffix()+"-"+i); <MASK>stopPoint.setRoute(route);</MASK> stopPoint = modelFactory.createModel( stopPoint); stopPoints.add( stopPoint); } } catch (CreateModelException ex) { Logger.getLogger(ComplexModelFactory.class.getName()).log(Level.SEVERE, null, ex); } return stopPoints; }"
Inversion-Mutation
megadiff
"public void mine() throws NoSuchAlgorithmException { String startString = randomString(); String currentString; MessageDigest md = MessageDigest.getInstance("SHA-512"); StringBuffer sb; while (MainView.getStatus()) { for (int counter = 0; counter < 999999999; counter++) { MainView.updateCounter(); sb = new StringBuffer(); currentString = startString + counter; md.update(currentString.getBytes()); byte byteData[] = md.digest(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer .toString((byteData[i] & 0xff) + 0x100, 16) .substring(1)); } if (sb.toString().startsWith(difficulty)) { MainView.updateSolved(currentString); System.out.println("Success: " + currentString); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "mine"
"public void mine() throws NoSuchAlgorithmException { String startString = randomString(); String currentString; MessageDigest md = MessageDigest.getInstance("SHA-512"); StringBuffer sb; for (int counter = 0; counter < 999999999; counter++) { <MASK>while (MainView.getStatus()) {</MASK> MainView.updateCounter(); sb = new StringBuffer(); currentString = startString + counter; md.update(currentString.getBytes()); byte byteData[] = md.digest(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer .toString((byteData[i] & 0xff) + 0x100, 16) .substring(1)); } if (sb.toString().startsWith(difficulty)) { MainView.updateSolved(currentString); System.out.println("Success: " + currentString); } } } }"
Inversion-Mutation
megadiff
"public boolean schedule(long lazyTimeout) { long execution = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(lazyTimeout); if (_task == null || execution < _execution) { cancel(); _execution = execution; _task = _bayeux.schedule(this, lazyTimeout); return true; } return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "schedule"
"public boolean schedule(long lazyTimeout) { <MASK>cancel();</MASK> long execution = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(lazyTimeout); if (_task == null || execution < _execution) { _execution = execution; _task = _bayeux.schedule(this, lazyTimeout); return true; } return false; }"
Inversion-Mutation
megadiff
"public void authenticate(SVNRepositoryImpl repository) throws SVNException { SVNErrorMessage failureReason = null; Object[] items = read("[((*W)?S)]", null); List mechs = SVNReader.getList(items, 0); myRealm = SVNReader.getString(items, 1); if (mechs == null || mechs.size() == 0) { return; } ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); if (authManager != null && authManager.isAuthenticationForced() && mechs.contains("ANONYMOUS") && mechs.contains("CRAM-MD5")) { mechs.remove("ANONYMOUS"); } SVNURL location = myRepository.getLocation(); SVNPasswordAuthentication auth = null; if (repository.getExternalUserName() != null && mechs.contains("EXTERNAL")) { write("(w(s))", new Object[] { "EXTERNAL", "" }); failureReason = readAuthResponse(repository); } else if (mechs.contains("ANONYMOUS")) { write("(w())", new Object[] { "ANONYMOUS" }); failureReason = readAuthResponse(repository); } else if (mechs.contains("CRAM-MD5")) { while (true) { CramMD5 authenticator = new CramMD5(); String realm = getRealm(); if (location != null) { realm = "<" + location.getProtocol() + "://" + location.getHost() + ":" + location.getPort() + "> " + realm; } if (auth == null && authManager != null) { auth = (SVNPasswordAuthentication) authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, location); } else if (authManager != null) { authManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, failureReason, auth); auth = (SVNPasswordAuthentication) authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, location); } if (auth == null || auth.getUserName() == null || auth.getPassword() == null) { failureReason = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "Authentication is required for ''{0}''", realm); break; } write("(w())", new Object[] { "CRAM-MD5" }); while (true) { authenticator.setUserCredentials(auth); items = read("(W(?B))", null); if (SUCCESS.equals(items[0])) { if (!myIsCredentialsReceived) { Object[] creds = read("[(S?S)]", null); if (creds != null && creds.length == 2 && creds[0] != null && creds[1] != null) { SVNURL rootURL = SVNURL.parseURIEncoded((String) creds[1]); repository.updateCredentials((String) creds[0], rootURL); if (myRealm == null) { myRealm = (String) creds[0]; } } myIsCredentialsReceived = true; } authManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, auth); return; } else if (FAILURE.equals(items[0])) { failureReason = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, new String((byte[]) items[1])); break; } else if (STEP.equals(items[0])) { try { byte[] response = authenticator.buildChallengeReponse((byte[]) items[1]); getOutputStream().write(response); getOutputStream().flush(); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_SVN_IO_ERROR, e.getMessage()), e); } } } } } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_UNKNOWN_AUTH)); } if (failureReason == null) { return; } SVNErrorManager.error(failureReason); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "authenticate"
"public void authenticate(SVNRepositoryImpl repository) throws SVNException { SVNErrorMessage failureReason = null; Object[] items = read("[((*W)?S)]", null); List mechs = SVNReader.getList(items, 0); myRealm = SVNReader.getString(items, 1); if (mechs == null || mechs.size() == 0) { return; } ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); if (authManager != null && authManager.isAuthenticationForced() && mechs.contains("ANONYMOUS") && mechs.contains("CRAM-MD5")) { mechs.remove("ANONYMOUS"); } SVNURL location = myRepository.getLocation(); SVNPasswordAuthentication auth = null; if (repository.getExternalUserName() != null && mechs.contains("EXTERNAL")) { write("(w(s))", new Object[] { "EXTERNAL", "" }); failureReason = readAuthResponse(repository); } else if (mechs.contains("ANONYMOUS")) { write("(w())", new Object[] { "ANONYMOUS" }); failureReason = readAuthResponse(repository); } else if (mechs.contains("CRAM-MD5")) { while (true) { CramMD5 authenticator = new CramMD5(); String realm = getRealm(); if (location != null) { realm = "<" + location.getProtocol() + "://" + location.getHost() + ":" + location.getPort() + "> " + realm; } if (auth == null && authManager != null) { auth = (SVNPasswordAuthentication) authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, location); } else if (authManager != null) { authManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, failureReason, auth); auth = (SVNPasswordAuthentication) authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, location); } if (auth == null || auth.getUserName() == null || auth.getPassword() == null) { failureReason = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "Authentication is required for ''{0}''", realm); break; } write("(w())", new Object[] { "CRAM-MD5" }); while (true) { authenticator.setUserCredentials(auth); items = read("(W(?B))", null); if (SUCCESS.equals(items[0])) { if (!myIsCredentialsReceived) { Object[] creds = read("[(S?S)]", null); if (creds != null && creds.length == 2 && creds[0] != null && creds[1] != null) { SVNURL rootURL = SVNURL.parseURIEncoded((String) creds[1]); repository.updateCredentials((String) creds[0], rootURL); if (myRealm == null) { myRealm = (String) creds[0]; } } myIsCredentialsReceived = true; } authManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, auth); return; } else if (FAILURE.equals(items[0])) { failureReason = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, new String((byte[]) items[1])); break; } else if (STEP.equals(items[0])) { <MASK>byte[] response = authenticator.buildChallengeReponse((byte[]) items[1]);</MASK> try { getOutputStream().write(response); getOutputStream().flush(); } catch (IOException e) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_SVN_IO_ERROR, e.getMessage()), e); } } } } } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_UNKNOWN_AUTH)); } if (failureReason == null) { return; } SVNErrorManager.error(failureReason); }"
Inversion-Mutation
megadiff
"public static void config(Object target, World world) { try { Class<?> clazz = target.getClass(); do { for (Field field : clazz.getDeclaredFields()) { Mapper annotation = field.getAnnotation(Mapper.class); if (annotation != null && Mapper.class.isAssignableFrom(Mapper.class)) { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); Class componentType = (Class) genericType.getActualTypeArguments()[0]; field.setAccessible(true); field.set(target, world.getMapper(componentType)); } } clazz = clazz.getSuperclass(); } while (clazz != null); } catch (Exception e) { throw new RuntimeException("Error while setting component mappers", e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "config"
"public static void config(Object target, World world) { try { Class<?> clazz = target.getClass(); do { for (Field field : clazz.getDeclaredFields()) { Mapper annotation = field.getAnnotation(Mapper.class); if (annotation != null && Mapper.class.isAssignableFrom(Mapper.class)) { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); Class componentType = (Class) genericType.getActualTypeArguments()[0]; field.setAccessible(true); field.set(target, world.getMapper(componentType)); } <MASK>clazz = clazz.getSuperclass();</MASK> } } while (clazz != null); } catch (Exception e) { throw new RuntimeException("Error while setting component mappers", e); } }"
Inversion-Mutation
megadiff
"@Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (result == DropboxAPI.STATUS_SUCCESS) { if (m_config != null && m_config.authStatus == DropboxAPI.STATUS_SUCCESS) { m_act.setLoggedIn(true); m_act.storeKeys(m_config.accessTokenKey, m_config.accessTokenSecret); m_act.showToast("Logged into Dropbox"); } } else { if (result == DropboxAPI.STATUS_NETWORK_ERROR) { m_act.showToast("Network error: " + m_config.authDetail); } else { m_act.showToast("Unsuccessful login."); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPostExecute"
"@Override protected void onPostExecute(Integer result) { super.onPostExecute(result); if (result == DropboxAPI.STATUS_SUCCESS) { if (m_config != null && m_config.authStatus == DropboxAPI.STATUS_SUCCESS) { m_act.storeKeys(m_config.accessTokenKey, m_config.accessTokenSecret); <MASK>m_act.setLoggedIn(true);</MASK> m_act.showToast("Logged into Dropbox"); } } else { if (result == DropboxAPI.STATUS_NETWORK_ERROR) { m_act.showToast("Network error: " + m_config.authDetail); } else { m_act.showToast("Unsuccessful login."); } } }"
Inversion-Mutation
megadiff
"@Override public boolean onItemLongClick(final AdapterView<?> l, final View v, final int position, final long id) { v.setSelected(true); final SimpleLocation location = (SimpleLocation) l.getItemAtPosition(position); final String[] items = getResources().getStringArray(R.array.location_list_fragment_context_menu); final Context context = getActivity(); final AlertDialog.Builder builder = new AlertDialog.Builder(context) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); switch (which) { case 0: // edit break; case 1: // delete final AlertDialog.Builder builder = new AlertDialog.Builder(context) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); } }) .setMessage(R.string.are_you_sure_that_you_want_to_delete_this_location) .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); deleteSimpleLocation(location); } }) .setTitle(R.string.delete); builder.show(); break; } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setTitle(R.string.select_an_action); builder.show(); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onItemLongClick"
"@Override public boolean onItemLongClick(final AdapterView<?> l, final View v, final int position, final long id) { v.setSelected(true); final SimpleLocation location = (SimpleLocation) l.getItemAtPosition(position); final String[] items = getResources().getStringArray(R.array.location_list_fragment_context_menu); final Context context = getActivity(); final AlertDialog.Builder builder = new AlertDialog.Builder(context) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); switch (which) { case 0: // edit break; case 1: // delete final AlertDialog.Builder builder = new AlertDialog.Builder(context) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); } }) .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); deleteSimpleLocation(location); } }) .setTitle(R.string.delete); builder.show(); break; } } }) <MASK>.setMessage(R.string.are_you_sure_that_you_want_to_delete_this_location)</MASK> .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setTitle(R.string.select_an_action); builder.show(); return true; }"
Inversion-Mutation
megadiff
"public static void main( String[] args ) throws Exception { Commands command = new Commands(); DatabaseFormat databaseFormat; OperationMode mode; SupportedDatabase databaseType; try { Args.parse( command, args ); databaseFormat = DatabaseFormat.valueOf( command.databaseFormat ); mode = OperationMode.valueOf( command.mode ); databaseType = SupportedDatabase.valueOf( command.databaseType ); } catch ( IllegalArgumentException e ) { Args.usage( command ); System.err.println( e.getMessage() ); return; } if ( command.directory.exists() && !command.directory.isDirectory() ) { System.err.println( command.directory + " already exists and is not a directory." ); return; } if ( !command.overwrite && mode == OperationMode.EXPORT && command.directory.exists() ) { System.err.println( command.directory + " already exists and will not be overwritten unless the -overwrite flag is used." ); return; } if ( command.debug ) { BasicConfigurator.configure(); Logger.getRootLogger().setLevel( Level.DEBUG ); Logger.getLogger( "JPOX" ).setLevel( Level.DEBUG ); } DatabaseParams params = new DatabaseParams( databaseType.defaultParams ); params.setUrl( command.jdbcUrl ); DefaultPlexusContainer container = new DefaultPlexusContainer(); List<Artifact> artifacts = new ArrayList<Artifact>(); artifacts.addAll( downloadArtifact( container, params.getGroupId(), params.getArtifactId(), params.getVersion() ) ); artifacts.addAll( downloadArtifact( container, "org.apache.maven.continuum", "data-management-jdo", "1.1-SNAPSHOT" ) ); artifacts.addAll( downloadArtifact( container, "jpox", "jpox", databaseFormat.getJpoxVersion() ) ); List<File> jars = new ArrayList<File>(); // Little hack to make it work more nicely in the IDE List<String> exclusions = new ArrayList<String>(); URLClassLoader cp = (URLClassLoader) DataManagementCli.class.getClassLoader(); for ( URL url : cp.getURLs() ) { String urlEF = url.toExternalForm(); if ( urlEF.endsWith( "target/classes/" ) ) { int idEndIdx = urlEF.length() - 16; String id = urlEF.substring( urlEF.lastIndexOf( '/', idEndIdx - 1 ) + 1, idEndIdx ); // continuum-legacy included because the IDE doesn't do the proper assembly of enhanced classes and JDO metadata if ( !"data-management-api".equals( id ) && !"data-management-cli".equals( id ) && !"continuum-legacy".equals( id ) && !"continuum-model".equals( id ) ) { exclusions.add( "org.apache.maven.continuum:" + id ); jars.add( new File( url.getPath() ) ); } } // Sometimes finds its way into the IDE. Make sure it is loaded in the extra classloader too if ( urlEF.contains( "jpox-enhancer" ) ) { jars.add( new File( url.getPath() ) ); } } ArtifactFilter filter = new ExcludesArtifactFilter( exclusions ); for ( Artifact a : artifacts ) { if ( "jpox".equals( a.getGroupId() ) && "jpox".equals( a.getArtifactId() ) ) { if ( a.getVersion().equals( databaseFormat.getJpoxVersion() ) ) { jars.add( a.getFile() ); } } else if ( filter.include( a ) ) { jars.add( a.getFile() ); } } ClassRealm realm = container.createComponentRealm( "app", jars ); ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( realm ); ClassRealm oldRealm = container.setLookupRealm( realm ); DatabaseManager manager = (DatabaseManager) container.lookup( DatabaseManager.class.getName(), "jdo", realm ); manager.configure( params ); DataManagementTool tool = (DataManagementTool) container.lookup( DataManagementTool.ROLE, databaseFormat.getToolRoleHint(), realm ); if ( mode == OperationMode.EXPORT ) { tool.backupBuildDatabase( command.directory ); } else if ( mode == OperationMode.IMPORT ) { tool.eraseBuildDatabase(); tool.restoreBuildDatabase( command.directory ); } container.setLookupRealm( oldRealm ); Thread.currentThread().setContextClassLoader( oldLoader ); }"
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 Exception { Commands command = new Commands(); DatabaseFormat databaseFormat; OperationMode mode; SupportedDatabase databaseType; try { Args.parse( command, args ); databaseFormat = DatabaseFormat.valueOf( command.databaseFormat ); mode = OperationMode.valueOf( command.mode ); databaseType = SupportedDatabase.valueOf( command.databaseType ); } catch ( IllegalArgumentException e ) { Args.usage( command ); System.err.println( e.getMessage() ); return; } if ( command.directory.exists() && !command.directory.isDirectory() ) { System.err.println( command.directory + " already exists and is not a directory." ); return; } if ( !command.overwrite && mode == OperationMode.EXPORT && command.directory.exists() ) { System.err.println( command.directory + " already exists and will not be overwritten unless the -overwrite flag is used." ); return; } if ( command.debug ) { BasicConfigurator.configure(); Logger.getRootLogger().setLevel( Level.DEBUG ); Logger.getLogger( "JPOX" ).setLevel( Level.DEBUG ); } DatabaseParams params = new DatabaseParams( databaseType.defaultParams ); params.setUrl( command.jdbcUrl ); DefaultPlexusContainer container = new DefaultPlexusContainer(); List<Artifact> artifacts = new ArrayList<Artifact>(); <MASK>artifacts.addAll( downloadArtifact( container, "jpox", "jpox", databaseFormat.getJpoxVersion() ) );</MASK> artifacts.addAll( downloadArtifact( container, params.getGroupId(), params.getArtifactId(), params.getVersion() ) ); artifacts.addAll( downloadArtifact( container, "org.apache.maven.continuum", "data-management-jdo", "1.1-SNAPSHOT" ) ); List<File> jars = new ArrayList<File>(); // Little hack to make it work more nicely in the IDE List<String> exclusions = new ArrayList<String>(); URLClassLoader cp = (URLClassLoader) DataManagementCli.class.getClassLoader(); for ( URL url : cp.getURLs() ) { String urlEF = url.toExternalForm(); if ( urlEF.endsWith( "target/classes/" ) ) { int idEndIdx = urlEF.length() - 16; String id = urlEF.substring( urlEF.lastIndexOf( '/', idEndIdx - 1 ) + 1, idEndIdx ); // continuum-legacy included because the IDE doesn't do the proper assembly of enhanced classes and JDO metadata if ( !"data-management-api".equals( id ) && !"data-management-cli".equals( id ) && !"continuum-legacy".equals( id ) && !"continuum-model".equals( id ) ) { exclusions.add( "org.apache.maven.continuum:" + id ); jars.add( new File( url.getPath() ) ); } } // Sometimes finds its way into the IDE. Make sure it is loaded in the extra classloader too if ( urlEF.contains( "jpox-enhancer" ) ) { jars.add( new File( url.getPath() ) ); } } ArtifactFilter filter = new ExcludesArtifactFilter( exclusions ); for ( Artifact a : artifacts ) { if ( "jpox".equals( a.getGroupId() ) && "jpox".equals( a.getArtifactId() ) ) { if ( a.getVersion().equals( databaseFormat.getJpoxVersion() ) ) { jars.add( a.getFile() ); } } else if ( filter.include( a ) ) { jars.add( a.getFile() ); } } ClassRealm realm = container.createComponentRealm( "app", jars ); ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( realm ); ClassRealm oldRealm = container.setLookupRealm( realm ); DatabaseManager manager = (DatabaseManager) container.lookup( DatabaseManager.class.getName(), "jdo", realm ); manager.configure( params ); DataManagementTool tool = (DataManagementTool) container.lookup( DataManagementTool.ROLE, databaseFormat.getToolRoleHint(), realm ); if ( mode == OperationMode.EXPORT ) { tool.backupBuildDatabase( command.directory ); } else if ( mode == OperationMode.IMPORT ) { tool.eraseBuildDatabase(); tool.restoreBuildDatabase( command.directory ); } container.setLookupRealm( oldRealm ); Thread.currentThread().setContextClassLoader( oldLoader ); }"
Inversion-Mutation
megadiff
"@Override public void receivePath(AStarPath newPath) { if (this.waitingForPath) { this.path = newPath; if (!path.isEmpty()) { world.setNodesOccupied(occupiedNode, entity.getSize(), 0); this.occupiedNode = path.getNextNode().getNode(); world.setNodesOccupied(occupiedNode, entity.getSize(), entity.getEntityID()); } waitingForPath = false; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "receivePath"
"@Override public void receivePath(AStarPath newPath) { if (this.waitingForPath) { this.path = newPath; <MASK>world.setNodesOccupied(occupiedNode, entity.getSize(), 0);</MASK> if (!path.isEmpty()) { this.occupiedNode = path.getNextNode().getNode(); world.setNodesOccupied(occupiedNode, entity.getSize(), entity.getEntityID()); } waitingForPath = false; } }"
Inversion-Mutation
megadiff
"protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { UrlMappingsHolder holder = lookupUrlMappings(); GrailsApplication application = lookupApplication(); GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST); GrailsClass[] controllers = application.getArtefacts(ControllerArtefactHandler.TYPE); if(controllers == null || controllers.length == 0 || holder == null) { processFilterChain(request, response, filterChain); return; } if(LOG.isDebugEnabled()) { LOG.debug("Executing URL mapping filter..."); LOG.debug(holder); } String uri = urlHelper.getPathWithinApplication(request); UrlMappingInfo[] urlInfos = holder.matchAll(uri); WrappedResponseHolder.setWrappedResponse(response); boolean dispatched = false; try { for (int i = 0; i < urlInfos.length; i++) { UrlMappingInfo info = urlInfos[i]; if(info!=null) { String action = info.getActionName() == null ? "" : info.getActionName(); info.configure(webRequest); GrailsClass controller = application.getArtefactForFeature(ControllerArtefactHandler.TYPE, SLASH + info.getControllerName() + SLASH + action); if(controller == null) { continue; } dispatched = true; String forwardUrl = buildDispatchUrlForMapping(request, info); if(LOG.isDebugEnabled()) { LOG.debug("Matched URI ["+uri+"] to URL mapping ["+info+"], forwarding to ["+forwardUrl+"] with response ["+response.getClass()+"]"); } //populateParamsForMapping(info); RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl); populateWebRequestWithInfo(webRequest, info); WebUtils.exposeForwardRequestAttributes(request); dispatcher.forward(request, response); break; } } } finally { WrappedResponseHolder.setWrappedResponse(null); } if(!dispatched) { if(LOG.isDebugEnabled()) { LOG.debug("No match found, processing remaining filter chain."); } processFilterChain(request, response, filterChain); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doFilterInternal"
"protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { UrlMappingsHolder holder = lookupUrlMappings(); GrailsApplication application = lookupApplication(); GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST); GrailsClass[] controllers = application.getArtefacts(ControllerArtefactHandler.TYPE); if(controllers == null || controllers.length == 0 || holder == null) { processFilterChain(request, response, filterChain); return; } if(LOG.isDebugEnabled()) { LOG.debug("Executing URL mapping filter..."); LOG.debug(holder); } String uri = urlHelper.getPathWithinApplication(request); UrlMappingInfo[] urlInfos = holder.matchAll(uri); WrappedResponseHolder.setWrappedResponse(response); boolean dispatched = false; try { for (int i = 0; i < urlInfos.length; i++) { UrlMappingInfo info = urlInfos[i]; if(info!=null) { String action = info.getActionName() == null ? "" : info.getActionName(); GrailsClass controller = application.getArtefactForFeature(ControllerArtefactHandler.TYPE, SLASH + info.getControllerName() + SLASH + action); if(controller == null) { continue; } dispatched = true; <MASK>info.configure(webRequest);</MASK> String forwardUrl = buildDispatchUrlForMapping(request, info); if(LOG.isDebugEnabled()) { LOG.debug("Matched URI ["+uri+"] to URL mapping ["+info+"], forwarding to ["+forwardUrl+"] with response ["+response.getClass()+"]"); } //populateParamsForMapping(info); RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl); populateWebRequestWithInfo(webRequest, info); WebUtils.exposeForwardRequestAttributes(request); dispatcher.forward(request, response); break; } } } finally { WrappedResponseHolder.setWrappedResponse(null); } if(!dispatched) { if(LOG.isDebugEnabled()) { LOG.debug("No match found, processing remaining filter chain."); } processFilterChain(request, response, filterChain); } }"
Inversion-Mutation
megadiff
"private List<RelationManager> computeSelectionPath(Component source, Relation relation) { List<RelationManager> selectionPath = new ArrayList<RelationManager>(); /* * If resolve = exist or internal, only ApamMan must be called */ boolean resolveExternal = relation.getResolve() == ResolvePolicy.EXTERNAL ; if (resolveExternal) { for (RelationManager relationManager : ApamManagers.getRelationManagers()) { /* * Skip apamman and UpdateMan */ if (relationManager.getName().equals(CST.APAMMAN) || relationManager.getName().equals(CST.UPDATEMAN)) { continue; } relationManager.getSelectionPath(source, relation, selectionPath); } } ((RelationImpl)relation).computeFilters(source) ; if (!relation.isRelation()) { // It is a find logger.info("Looking for " + relation.getTargetKind() + " " + relation.getTarget().getName()); } else logger.info("Resolving " + relation); // To select first in Apam selectionPath.add(0, apam.getApamMan()); selectionPath.add(0, apam.getUpdateMan()); return selectionPath; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "computeSelectionPath"
"private List<RelationManager> computeSelectionPath(Component source, Relation relation) { List<RelationManager> selectionPath = new ArrayList<RelationManager>(); /* * If resolve = exist or internal, only ApamMan must be called */ boolean resolveExternal = relation.getResolve() == ResolvePolicy.EXTERNAL ; if (resolveExternal) { for (RelationManager relationManager : ApamManagers.getRelationManagers()) { /* * Skip apamman and UpdateMan */ if (relationManager.getName().equals(CST.APAMMAN) || relationManager.getName().equals(CST.UPDATEMAN)) { continue; } relationManager.getSelectionPath(source, relation, selectionPath); } <MASK>((RelationImpl)relation).computeFilters(source) ;</MASK> } if (!relation.isRelation()) { // It is a find logger.info("Looking for " + relation.getTargetKind() + " " + relation.getTarget().getName()); } else logger.info("Resolving " + relation); // To select first in Apam selectionPath.add(0, apam.getApamMan()); selectionPath.add(0, apam.getUpdateMan()); return selectionPath; }"
Inversion-Mutation
megadiff
"public void drop() { addCompleteCollideList(); float temp = (pc.getDirection() == Direction.LEFT ? -3f : 3f); this.setVector2D(new Vector2D(temp, -2f)); this.pc = null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "drop"
"public void drop() { <MASK>this.pc = null;</MASK> addCompleteCollideList(); float temp = (pc.getDirection() == Direction.LEFT ? -3f : 3f); this.setVector2D(new Vector2D(temp, -2f)); }"
Inversion-Mutation
megadiff
"public BaseFrame(Dimension windowSize) { this.windowSize = windowSize; add("Center", new GamePanel()); setSize(windowSize); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); c = new Controls(); addKeyListener(c); addMouseListener(c); addMouseMotionListener(c); setEnabled(true); setVisible(true); // initFrame(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "BaseFrame"
"public BaseFrame(Dimension windowSize) { this.windowSize = windowSize; add("Center", new GamePanel()); setSize(windowSize); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addKeyListener(c); addMouseListener(c); addMouseMotionListener(c); <MASK>c = new Controls();</MASK> setEnabled(true); setVisible(true); // initFrame(); }"
Inversion-Mutation
megadiff
"public Report(AssetReportCollection arc) { this.arc = arc; logger = JOVALMsg.getLogger(); requests = new HashMap<String, XccdfBenchmark>(); for (ReportRequestType req : arc.getReportRequests().getReportRequest()) { Object request = req.getContent().getAny(); if (request instanceof XccdfBenchmark) { requests.put(req.getId(), (XccdfBenchmark)request); } else { String type = request == null ? "null" : request.getClass().getName(); logger.warn(JOVALMsg.WARNING_ARF_REQUEST, req.getId(), type); } } assets = new HashMap<String, AssetType>(); for (AssetReportCollection.Assets.Asset asset : arc.getAssets().getAsset()) { assets.put(asset.getId(), asset.getAsset().getValue()); } reports = new HashMap<String, Object>(); for (ReportType report : arc.getReports().getReport()) { reports.put(report.getId(), report.getContent().getAny()); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Report"
"public Report(AssetReportCollection arc) { this.arc = arc; requests = new HashMap<String, XccdfBenchmark>(); for (ReportRequestType req : arc.getReportRequests().getReportRequest()) { Object request = req.getContent().getAny(); if (request instanceof XccdfBenchmark) { requests.put(req.getId(), (XccdfBenchmark)request); } else { String type = request == null ? "null" : request.getClass().getName(); logger.warn(JOVALMsg.WARNING_ARF_REQUEST, req.getId(), type); } } assets = new HashMap<String, AssetType>(); for (AssetReportCollection.Assets.Asset asset : arc.getAssets().getAsset()) { assets.put(asset.getId(), asset.getAsset().getValue()); } reports = new HashMap<String, Object>(); for (ReportType report : arc.getReports().getReport()) { reports.put(report.getId(), report.getContent().getAny()); } <MASK>logger = JOVALMsg.getLogger();</MASK> }"
Inversion-Mutation
megadiff
"private void init() { setContentView(R.layout.textquestion); textView = (TextView) findViewById(R.id.textquestion_questionTV); initButton(); initAnswerEditText(); initContent(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
"private void init() { setContentView(R.layout.textquestion); textView = (TextView) findViewById(R.id.textquestion_questionTV); <MASK>initAnswerEditText();</MASK> initButton(); initContent(); }"
Inversion-Mutation
megadiff
"public static double mean(int[] a) { double mean =0; int sum = 0; for (int i=0; i<a.length; i++) { sum =sum + a[i]; } mean = sum/(a.length); return mean; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "mean"
"public static double mean(int[] a) { double mean =0; int sum = 0; for (int i=0; i<a.length; i++) { sum =sum + a[i]; <MASK>mean = sum/(a.length);</MASK> } return mean; }"
Inversion-Mutation
megadiff
"private void createDisk(Properties properties) { String diskRoot = getDiskZkPath(properties.get(DiskProperties.UUID_KEY).toString()); zk.saveDiskProperties(diskRoot, properties); DiskUtils.createDisk(properties); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createDisk"
"private void createDisk(Properties properties) { String diskRoot = getDiskZkPath(properties.get(DiskProperties.UUID_KEY).toString()); <MASK>DiskUtils.createDisk(properties);</MASK> zk.saveDiskProperties(diskRoot, properties); }"
Inversion-Mutation
megadiff
"@Override public void init() { tabPane.addTab("Deer agent", new PopulationPanel()); tabPane.addTab("Grass agent", new PopulationPanel()); tabPane.addTab("Wolf agent", new PopulationPanel()); add(tabPane); pack(); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setTitle("Population settings"); setIconImage(new ImageIcon("res/Simulated ecosystem icon.png").getImage()); centerOnScreen(this, true); setVisible(true); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "init"
"@Override public void init() { tabPane.addTab("Deer agent", new PopulationPanel()); tabPane.addTab("Grass agent", new PopulationPanel()); tabPane.addTab("Wolf agent", new PopulationPanel()); add(tabPane); <MASK>setVisible(true);</MASK> pack(); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setTitle("Population settings"); setIconImage(new ImageIcon("res/Simulated ecosystem icon.png").getImage()); centerOnScreen(this, true); }"
Inversion-Mutation
megadiff
"public void setRootComponent(AComponent rootComponent) { this.contentPanel.getChildren().clear(); this.rootComponent = null; if (rootComponent != null) { this.contentPanel.getChildren().add(rootComponent); this.rootComponent = rootComponent; } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setRootComponent"
"public void setRootComponent(AComponent rootComponent) { this.contentPanel.getChildren().clear(); this.rootComponent = null; if (rootComponent != null) { this.contentPanel.getChildren().add(rootComponent); } <MASK>this.rootComponent = rootComponent;</MASK> }"
Inversion-Mutation
megadiff
"private final void attachWriter(final AtmosphereResource r) { final AtmosphereRequest request = r.getRequest(); AtmosphereResponse res = r.getResponse(); AsyncIOWriter writer = res.getAsyncIOWriter(); BlockingQueue<AtmosphereResource> queue = (BlockingQueue<AtmosphereResource>) getContextValue(request, SUSPENDED_RESPONSE); if (queue == null) { queue = new LinkedBlockingQueue<AtmosphereResource>(); request.getSession().setAttribute(SUSPENDED_RESPONSE, queue); } if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) { // WebSocket already had one. AtmosphereInterceptorWriter.class.cast(writer).interceptor(interceptor); if (r.transport() != AtmosphereResource.TRANSPORT.WEBSOCKET) { res.asyncIOWriter(new AtmosphereInterceptorWriter() { @Override protected void writeReady(AtmosphereResponse response, byte[] data) throws IOException { // We are buffering response. if (data == null) return; BlockingQueue<AtmosphereResource> queue = (BlockingQueue<AtmosphereResource>) getContextValue(request, SUSPENDED_RESPONSE); if (queue != null) { AtmosphereResource resource; try { // TODO: Should this be configurable // We stay suspended for 60 seconds resource = queue.poll(60, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.trace("", e); return; } if (resource == null) { logger.debug("No resource was suspended, resuming the second connection."); } else { logger.trace("Resuming {}", resource.uuid()); try { OutputStream o = resource.getResponse().getResponse().getOutputStream(); o.write(data); o.flush(); resource.resume(); } catch (IOException ex) { logger.warn("", ex); } } } else { logger.error("Queue was null"); } } }); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "attachWriter"
"private final void attachWriter(final AtmosphereResource r) { final AtmosphereRequest request = r.getRequest(); AtmosphereResponse res = r.getResponse(); AsyncIOWriter writer = res.getAsyncIOWriter(); BlockingQueue<AtmosphereResource> queue = (BlockingQueue<AtmosphereResource>) getContextValue(request, SUSPENDED_RESPONSE); if (queue == null) { queue = new LinkedBlockingQueue<AtmosphereResource>(); request.getSession().setAttribute(SUSPENDED_RESPONSE, queue); } if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) { // WebSocket already had one. if (r.transport() != AtmosphereResource.TRANSPORT.WEBSOCKET) { <MASK>AtmosphereInterceptorWriter.class.cast(writer).interceptor(interceptor);</MASK> res.asyncIOWriter(new AtmosphereInterceptorWriter() { @Override protected void writeReady(AtmosphereResponse response, byte[] data) throws IOException { // We are buffering response. if (data == null) return; BlockingQueue<AtmosphereResource> queue = (BlockingQueue<AtmosphereResource>) getContextValue(request, SUSPENDED_RESPONSE); if (queue != null) { AtmosphereResource resource; try { // TODO: Should this be configurable // We stay suspended for 60 seconds resource = queue.poll(60, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.trace("", e); return; } if (resource == null) { logger.debug("No resource was suspended, resuming the second connection."); } else { logger.trace("Resuming {}", resource.uuid()); try { OutputStream o = resource.getResponse().getResponse().getOutputStream(); o.write(data); o.flush(); resource.resume(); } catch (IOException ex) { logger.warn("", ex); } } } else { logger.error("Queue was null"); } } }); } } }"
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
"@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("MainActivity", "onActivityResult called with requestCode " + requestCode); if (!isMosesServiceRunning()) startAndBindService(); if (requestCode == 1) { // Login activity waitingForResult = false; switch (resultCode) { case Activity.RESULT_OK: SharedPreferences.Editor e = PreferenceManager .getDefaultSharedPreferences(this).edit(); String username = data.getStringExtra(MosesPreferences.PREF_EMAIL); String password = data.getStringExtra(MosesPreferences.PREF_PASSWORD); String deviceName = data.getStringExtra(MosesPreferences.PREF_DEVICENAME); Log.d("MoSeS.ACTIVITY", username); Log.d("MoSeS.ACTIVITY", password); e.putString(MosesPreferences.PREF_EMAIL, username); e.putString(MosesPreferences.PREF_PASSWORD, password); String deviceNameAlreadyStored = HardwareAbstraction.extractDeviceNameFromSharedPreferences(); if(deviceNameAlreadyStored == null){ // only set the deviceName sent by the server if the client does not know his name if(deviceName != null){ // the server may not know the name of the device, so check if the response contained the name e.putString(MosesPreferences.PREF_DEVICENAME, deviceName); } else{ // the server does not know the deviceName either, set the the device's model name as the device name e.putString(MosesPreferences.PREF_DEVICENAME, Build.MODEL); } } e.apply(); if (onLoginCompleteShowUserStudy != null) { // if a user study is to be displayed UserstudyNotificationManager.displayUserStudyContent( onLoginCompleteShowUserStudy, this.getApplicationContext()); onLoginCompleteShowUserStudy = null; } break; case Activity.RESULT_CANCELED: finish(); break; } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onActivityResult"
"@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("MainActivity", "onActivityResult called with requestCode " + requestCode); if (!isMosesServiceRunning()) startAndBindService(); if (requestCode == 1) { // Login activity waitingForResult = false; switch (resultCode) { case Activity.RESULT_OK: SharedPreferences.Editor e = PreferenceManager .getDefaultSharedPreferences(this).edit(); String username = data.getStringExtra(MosesPreferences.PREF_EMAIL); String password = data.getStringExtra(MosesPreferences.PREF_PASSWORD); String deviceName = data.getStringExtra(MosesPreferences.PREF_DEVICENAME); Log.d("MoSeS.ACTIVITY", username); Log.d("MoSeS.ACTIVITY", password); e.putString(MosesPreferences.PREF_EMAIL, username); e.putString(MosesPreferences.PREF_PASSWORD, password); String deviceNameAlreadyStored = HardwareAbstraction.extractDeviceNameFromSharedPreferences(); if(deviceNameAlreadyStored == null){ // only set the deviceName sent by the server if the client does not know his name if(deviceName != null){ // the server may not know the name of the device, so check if the response contained the name e.putString(MosesPreferences.PREF_DEVICENAME, deviceName); } else{ // the server does not know the deviceName either, set the the device's model name as the device name e.putString(MosesPreferences.PREF_DEVICENAME, Build.MODEL); } <MASK>e.apply();</MASK> } if (onLoginCompleteShowUserStudy != null) { // if a user study is to be displayed UserstudyNotificationManager.displayUserStudyContent( onLoginCompleteShowUserStudy, this.getApplicationContext()); onLoginCompleteShowUserStudy = null; } break; case Activity.RESULT_CANCELED: finish(); break; } } }"
Inversion-Mutation
megadiff
"@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String handle = req.getParameter("id"); UserService userService = UserServiceFactory.getUserService(); if (handle != null && userService.isUserLoggedIn()) { long taskdefHandle = Long.parseLong(handle); DataStoreTaskFactory.getInstance().deleteTaskDef(userService.getCurrentUser().getNickname(), taskdefHandle); } resp.sendRedirect("/"); }"
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 { String handle = req.getParameter("id"); UserService userService = UserServiceFactory.getUserService(); <MASK>long taskdefHandle = Long.parseLong(handle);</MASK> if (handle != null && userService.isUserLoggedIn()) { DataStoreTaskFactory.getInstance().deleteTaskDef(userService.getCurrentUser().getNickname(), taskdefHandle); } resp.sendRedirect("/"); }"
Inversion-Mutation
megadiff
"protected void tearDown() throws Exception { // Simple strategy to prevent connection leaks if (connection != null && !connection.isClosed()) { connection.close(); } connection = null; testContext = null; tester = null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "tearDown"
"protected void tearDown() throws Exception { // Simple strategy to prevent connection leaks if (connection != null && !connection.isClosed()) { connection.close(); <MASK>connection = null;</MASK> } testContext = null; tester = null; }"
Inversion-Mutation
megadiff
"public static MediaFormat payloadTypeToMediaFormat( PayloadTypePacketExtension payloadType, DynamicPayloadTypeRegistry ptRegistry) { byte pt = (byte)payloadType.getID(); boolean unknown = false; //convert params to a name:value map List<ParameterPacketExtension> params = payloadType.getParameters(); Map<String, String> paramsMap = new HashMap<String, String>(); for(ParameterPacketExtension param : params) paramsMap.put(param.getName(), param.getValue()); //now create the format. MediaFormat format = JabberActivator.getMediaService().getFormatFactory() .createMediaFormat( pt, payloadType.getName(), (double)payloadType.getClockrate(), payloadType.getChannels(), -1, paramsMap, null); //we don't seem to know anything about this format if(format == null) { unknown = true; format = JabberActivator.getMediaService().getFormatFactory() .createUnknownMediaFormat(MediaType.AUDIO); } /* * We've just created a MediaFormat for the specified payloadType * so we have to remember the mapping between the two so that we * don't, for example, map the same payloadType to a different * MediaFormat at a later time when we do automatic generation * of payloadType in DynamicPayloadTypeRegistry. */ /* * TODO What is expected to happen when the remote peer tries to * re-map a payloadType in its answer to a different MediaFormat * than the one we've specified in our offer? */ if ((pt >= MediaFormat.MIN_DYNAMIC_PAYLOAD_TYPE) && (pt <= MediaFormat.MAX_DYNAMIC_PAYLOAD_TYPE) && (ptRegistry.findFormat(pt) == null)) ptRegistry.addMapping(format, pt); return (unknown == false) ? format : null; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "payloadTypeToMediaFormat"
"public static MediaFormat payloadTypeToMediaFormat( PayloadTypePacketExtension payloadType, DynamicPayloadTypeRegistry ptRegistry) { byte pt = (byte)payloadType.getID(); boolean unknown = false; //convert params to a name:value map List<ParameterPacketExtension> params = payloadType.getParameters(); Map<String, String> paramsMap = new HashMap<String, String>(); for(ParameterPacketExtension param : params) paramsMap.put(param.getName(), param.getValue()); //now create the format. MediaFormat format = JabberActivator.getMediaService().getFormatFactory() .createMediaFormat( pt, payloadType.getName(), (double)payloadType.getClockrate(), <MASK>-1,</MASK> payloadType.getChannels(), paramsMap, null); //we don't seem to know anything about this format if(format == null) { unknown = true; format = JabberActivator.getMediaService().getFormatFactory() .createUnknownMediaFormat(MediaType.AUDIO); } /* * We've just created a MediaFormat for the specified payloadType * so we have to remember the mapping between the two so that we * don't, for example, map the same payloadType to a different * MediaFormat at a later time when we do automatic generation * of payloadType in DynamicPayloadTypeRegistry. */ /* * TODO What is expected to happen when the remote peer tries to * re-map a payloadType in its answer to a different MediaFormat * than the one we've specified in our offer? */ if ((pt >= MediaFormat.MIN_DYNAMIC_PAYLOAD_TYPE) && (pt <= MediaFormat.MAX_DYNAMIC_PAYLOAD_TYPE) && (ptRegistry.findFormat(pt) == null)) ptRegistry.addMapping(format, pt); return (unknown == false) ? format : null; }"
Inversion-Mutation
megadiff
"private void cbFindNext() { if (m_pattern == null) return; Node root = m_gameTree.getRoot(); Node node = NodeUtils.findInComments(m_currentNode, m_pattern); if (node == null) if (m_currentNode != root) if (showQuestion("End of tree reached. Continue from start?")) { node = root; if (! NodeUtils.commentContains(node, m_pattern)) node = NodeUtils.findInComments(node, m_pattern); } if (node == null) { showInfo("Not found"); m_menuBar.enableFindNext(false); } else { cbGotoNode(node); m_comment.markAll(m_pattern); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cbFindNext"
"private void cbFindNext() { if (m_pattern == null) return; Node root = m_gameTree.getRoot(); Node node = NodeUtils.findInComments(m_currentNode, m_pattern); if (node == null) if (m_currentNode != root) if (showQuestion("End of tree reached. Continue from start?")) { node = root; if (! NodeUtils.commentContains(node, m_pattern)) node = NodeUtils.findInComments(node, m_pattern); } if (node == null) { showInfo("Not found"); m_menuBar.enableFindNext(false); } else { <MASK>m_comment.markAll(m_pattern);</MASK> cbGotoNode(node); } }"
Inversion-Mutation
megadiff
"@Override public void onBackPressed() { NavUtils.navigateUpFromSameTask(this); super.onBackPressed(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBackPressed"
"@Override public void onBackPressed() { <MASK>super.onBackPressed();</MASK> NavUtils.navigateUpFromSameTask(this); }"
Inversion-Mutation
megadiff
"public void save(EncogPersistedObject obj, WriteXML out) { ActivationGaussian g = (ActivationGaussian)obj; out.beginTag(obj.getClass().getSimpleName()); out.addProperty(ATTRIBUTE_CENTER, g.getGausian().getCenter()); out.addProperty(ATTRIBUTE_PEAK, g.getGausian().getPeak()); out.addProperty(ATTRIBUTE_WIDTH, g.getGausian().getWidth()); out.endTag(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "save"
"public void save(EncogPersistedObject obj, WriteXML out) { ActivationGaussian g = (ActivationGaussian)obj; out.addProperty(ATTRIBUTE_CENTER, g.getGausian().getCenter()); out.addProperty(ATTRIBUTE_PEAK, g.getGausian().getPeak()); out.addProperty(ATTRIBUTE_WIDTH, g.getGausian().getWidth()); <MASK>out.beginTag(obj.getClass().getSimpleName());</MASK> out.endTag(); }"
Inversion-Mutation
megadiff
"public DBInterface(Connection conn, String user) throws java.sql.SQLException { this.conn = conn; userLogged = user; stmt = conn.createStatement(); String userSchema = this.getUserMetaDataSchemaName() ; String query = "SET search_path TO " + userSchema + ", cas_metadata, public;"; stmt.execute(query); logger.info("The DB interface is successfully created..."); curNBatchStatements = 0; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DBInterface"
"public DBInterface(Connection conn, String user) throws java.sql.SQLException { this.conn = conn; userLogged = user; String userSchema = this.getUserMetaDataSchemaName() ; String query = "SET search_path TO " + userSchema + ", cas_metadata, public;"; <MASK>stmt = conn.createStatement();</MASK> stmt.execute(query); logger.info("The DB interface is successfully created..."); curNBatchStatements = 0; }"
Inversion-Mutation
megadiff
"private boolean parse(final AttributedList<Path> childs, FTPFileEntryParser parser, BufferedReader reader) throws IOException { if(null == reader) { // This is an empty directory return false; } boolean success = false; String line; while((line = parser.readNextEntry(reader)) != null) { final FTPFile f = parser.parseFTPEntry(line); if(null == f) { continue; } if(f.getType() == FTPFile.SYMBOLIC_LINK_TYPE) { if(this.getAbsolute().equals(f.getName())) { // Workaround for #2434. STAT of symbolic link directory only lists the directory itself. continue; } } if(f.getName().equals(".") || f.getName().equals("..")) { continue; } success = true; // At least one entry successfully parsed final Path parsed = new FTPPath(session, this.getAbsolute(), f.getName(), Path.FILE_TYPE); parsed.setParent(this); switch(f.getType()) { case FTPFile.SYMBOLIC_LINK_TYPE: parsed.setSymbolicLinkPath(this.getAbsolute(), f.getLink()); parsed.attributes.setType(Path.SYMBOLIC_LINK_TYPE); break; case FTPFile.DIRECTORY_TYPE: parsed.attributes.setType(Path.DIRECTORY_TYPE); break; } parsed.attributes.setSize(f.getSize()); parsed.attributes.setOwner(f.getUser()); parsed.attributes.setGroup(f.getGroup()); if(session.isPermissionSupported(parser)) { parsed.attributes.setPermission(new Permission( new boolean[][]{ {f.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION), f.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION), f.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) }, {f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION), f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION), f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION) }, {f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION), f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION), f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION) } } )); } final Calendar timestamp = f.getTimestamp(); if(timestamp != null) { parsed.attributes.setModificationDate(timestamp.getTimeInMillis()); } childs.add(parsed); } return success; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parse"
"private boolean parse(final AttributedList<Path> childs, FTPFileEntryParser parser, BufferedReader reader) throws IOException { if(null == reader) { // This is an empty directory return false; } boolean success = false; String line; while((line = parser.readNextEntry(reader)) != null) { final FTPFile f = parser.parseFTPEntry(line); if(null == f) { continue; } if(f.getType() == FTPFile.SYMBOLIC_LINK_TYPE) { if(this.getAbsolute().equals(f.getName())) { // Workaround for #2434. STAT of symbolic link directory only lists the directory itself. continue; } } <MASK>success = true; // At least one entry successfully parsed</MASK> if(f.getName().equals(".") || f.getName().equals("..")) { continue; } final Path parsed = new FTPPath(session, this.getAbsolute(), f.getName(), Path.FILE_TYPE); parsed.setParent(this); switch(f.getType()) { case FTPFile.SYMBOLIC_LINK_TYPE: parsed.setSymbolicLinkPath(this.getAbsolute(), f.getLink()); parsed.attributes.setType(Path.SYMBOLIC_LINK_TYPE); break; case FTPFile.DIRECTORY_TYPE: parsed.attributes.setType(Path.DIRECTORY_TYPE); break; } parsed.attributes.setSize(f.getSize()); parsed.attributes.setOwner(f.getUser()); parsed.attributes.setGroup(f.getGroup()); if(session.isPermissionSupported(parser)) { parsed.attributes.setPermission(new Permission( new boolean[][]{ {f.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION), f.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION), f.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) }, {f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION), f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION), f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION) }, {f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION), f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION), f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION) } } )); } final Calendar timestamp = f.getTimestamp(); if(timestamp != null) { parsed.attributes.setModificationDate(timestamp.getTimeInMillis()); } childs.add(parsed); } return success; }"
Inversion-Mutation
megadiff
"private void addOrder(final Map<String, String> values) { long startDate = System.currentTimeMillis(); long endDate = startDate; long millsInHour = 3600000; long millsInMinute = 60000; if (!values.get("scheduled_start_date").isEmpty()) { try { startDate = FORMATTER.parse(values.get("scheduled_start_date")).getTime(); } catch (ParseException e) { LOG.warn(e.getMessage(), e); } } if ("000001".equals(values.get(L_ORDER_NR))) { endDate = startDate + MILLIS_IN_DAY + 1 * millsInHour + 45 * millsInMinute; } else if ("000002".equals(values.get(L_ORDER_NR))) { startDate -= 2 * MILLIS_IN_DAY; endDate = startDate + MILLIS_IN_DAY + 3 * millsInHour + 40 * millsInMinute; } else if ("000003".equals(values.get(L_ORDER_NR))) { startDate += 2 * MILLIS_IN_DAY; endDate = startDate + 6 * millsInHour + 50 * millsInMinute; } if (!values.get("scheduled_end_date").isEmpty()) { try { endDate = FORMATTER.parse(values.get("scheduled_end_date")).getTime(); } catch (ParseException e) { LOG.warn(e.getMessage(), e); } } Entity order = dataDefinitionService.get(ORDERS_PLUGIN_IDENTIFIER, ORDERS_MODEL_ORDER).create(); order.setField(L_DATE_FROM, new Date(startDate)); order.setField(L_DATE_TO, new Date(endDate)); order.setField("externalSynchronized", true); order.setField(TECHNOLOGY_MODEL_TECHNOLOGY, getTechnologyByNumber(values.get("tech_nr"))); order.setField(L_NAME, (values.get(L_NAME).isEmpty() || values.get(L_NAME) == null) ? values.get(L_ORDER_NR) : values.get(L_NAME)); order.setField(L_NUMBER, values.get(L_ORDER_NR)); order.setField(L_PLANNED_QUANTITY, values.get("quantity_scheduled").isEmpty() ? new BigDecimal( 100 * RANDOM.nextDouble() + 1) : new BigDecimal(values.get("quantity_scheduled"))); order.setField(L_ORDER_STATE, values.get("status")); Entity product = getProductByNumber(values.get(L_PRODUCT_NR)); if (isEnabled(L_PRODUCTION_COUNTING)) { order.setField("typeOfProductionRecording", values.get("type_of_production_recording")); order.setField("registerQuantityInProduct", values.get("register_quantity_in_product")); order.setField("registerQuantityOutProduct", values.get("register_quantity_out_product")); order.setField("registerProductionTime", values.get("register_production_time")); order.setField("justOne", values.get("just_one")); order.setField("allowToClose", values.get("allow_to_close")); order.setField("autoCloseOrder", values.get("auto_close_order")); } if (isEnabled(L_ADVANCED_GENEALOGY_FOR_ORDERS)) { order.setField("trackingRecordTreatment", "01duringProduction"); order.setField("trackingRecordForOrderTreatment", values.get("tracking_record_for_order_treatment")); } order.setField(BASIC_MODEL_PRODUCT, product); if (order.getField(TECHNOLOGY_MODEL_TECHNOLOGY) == null) { order.setField(TECHNOLOGY_MODEL_TECHNOLOGY, getDefaultTechnologyForProduct(product)); } if (LOG.isDebugEnabled()) { LOG.debug("Add test order {id=" + order.getId() + ", name=" + order.getField(L_NAME) + ", " + L_NUMBER + "=" + order.getField(L_NUMBER) + ", product=" + (order.getField(BASIC_MODEL_PRODUCT) == null ? null : ((Entity) order.getField(BASIC_MODEL_PRODUCT)) .getField(L_NUMBER)) + ", technology=" + (order.getField(TECHNOLOGY_MODEL_TECHNOLOGY) == null ? null : ((Entity) order .getField(TECHNOLOGY_MODEL_TECHNOLOGY)).getField(L_NUMBER)) + ", dateFrom=" + order.getField(L_DATE_FROM) + ", dateTo=" + order.getField(L_DATE_TO) + ", effectiveDateFrom=" + order.getField("effectiveDateFrom") + ", effectiveDateTo=" + order.getField("effectiveDateTo") + ", doneQuantity=" + order.getField("doneQuantity") + ", plannedQuantity=" + order.getField(L_PLANNED_QUANTITY) + ", trackingRecordTreatment=" + order.getField("trackingRecordTreatment") + ", state=" + order.getField(L_ORDER_STATE) + "}"); } order = dataDefinitionService.get(ORDERS_PLUGIN_IDENTIFIER, ORDERS_MODEL_ORDER).save(order); validateEntity(order); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addOrder"
"private void addOrder(final Map<String, String> values) { long startDate = System.currentTimeMillis(); long endDate = startDate; long millsInHour = 3600000; long millsInMinute = 60000; if (!values.get("scheduled_start_date").isEmpty()) { try { startDate = FORMATTER.parse(values.get("scheduled_start_date")).getTime(); } catch (ParseException e) { LOG.warn(e.getMessage(), e); } } if ("000001".equals(values.get(L_ORDER_NR))) { endDate = startDate + MILLIS_IN_DAY + 1 * millsInHour + 45 * millsInMinute; } else if ("000002".equals(values.get(L_ORDER_NR))) { startDate -= 2 * MILLIS_IN_DAY; endDate = startDate + MILLIS_IN_DAY + 3 * millsInHour + 40 * millsInMinute; } else if ("000003".equals(values.get(L_ORDER_NR))) { startDate += 2 * MILLIS_IN_DAY; endDate = startDate + 6 * millsInHour + 50 * millsInMinute; } if (!values.get("scheduled_end_date").isEmpty()) { try { endDate = FORMATTER.parse(values.get("scheduled_end_date")).getTime(); } catch (ParseException e) { LOG.warn(e.getMessage(), e); } } Entity order = dataDefinitionService.get(ORDERS_PLUGIN_IDENTIFIER, ORDERS_MODEL_ORDER).create(); order.setField(L_DATE_FROM, new Date(startDate)); order.setField(L_DATE_TO, new Date(endDate)); order.setField("externalSynchronized", true); order.setField(TECHNOLOGY_MODEL_TECHNOLOGY, getTechnologyByNumber(values.get("tech_nr"))); order.setField(L_NAME, (values.get(L_NAME).isEmpty() || values.get(L_NAME) == null) ? values.get(L_ORDER_NR) : values.get(L_NAME)); order.setField(L_NUMBER, values.get(L_ORDER_NR)); order.setField(L_PLANNED_QUANTITY, values.get("quantity_scheduled").isEmpty() ? new BigDecimal( 100 * RANDOM.nextDouble() + 1) : new BigDecimal(values.get("quantity_scheduled"))); <MASK>order.setField("trackingRecordTreatment", "01duringProduction");</MASK> order.setField(L_ORDER_STATE, values.get("status")); Entity product = getProductByNumber(values.get(L_PRODUCT_NR)); if (isEnabled(L_PRODUCTION_COUNTING)) { order.setField("typeOfProductionRecording", values.get("type_of_production_recording")); order.setField("registerQuantityInProduct", values.get("register_quantity_in_product")); order.setField("registerQuantityOutProduct", values.get("register_quantity_out_product")); order.setField("registerProductionTime", values.get("register_production_time")); order.setField("justOne", values.get("just_one")); order.setField("allowToClose", values.get("allow_to_close")); order.setField("autoCloseOrder", values.get("auto_close_order")); } if (isEnabled(L_ADVANCED_GENEALOGY_FOR_ORDERS)) { order.setField("trackingRecordForOrderTreatment", values.get("tracking_record_for_order_treatment")); } order.setField(BASIC_MODEL_PRODUCT, product); if (order.getField(TECHNOLOGY_MODEL_TECHNOLOGY) == null) { order.setField(TECHNOLOGY_MODEL_TECHNOLOGY, getDefaultTechnologyForProduct(product)); } if (LOG.isDebugEnabled()) { LOG.debug("Add test order {id=" + order.getId() + ", name=" + order.getField(L_NAME) + ", " + L_NUMBER + "=" + order.getField(L_NUMBER) + ", product=" + (order.getField(BASIC_MODEL_PRODUCT) == null ? null : ((Entity) order.getField(BASIC_MODEL_PRODUCT)) .getField(L_NUMBER)) + ", technology=" + (order.getField(TECHNOLOGY_MODEL_TECHNOLOGY) == null ? null : ((Entity) order .getField(TECHNOLOGY_MODEL_TECHNOLOGY)).getField(L_NUMBER)) + ", dateFrom=" + order.getField(L_DATE_FROM) + ", dateTo=" + order.getField(L_DATE_TO) + ", effectiveDateFrom=" + order.getField("effectiveDateFrom") + ", effectiveDateTo=" + order.getField("effectiveDateTo") + ", doneQuantity=" + order.getField("doneQuantity") + ", plannedQuantity=" + order.getField(L_PLANNED_QUANTITY) + ", trackingRecordTreatment=" + order.getField("trackingRecordTreatment") + ", state=" + order.getField(L_ORDER_STATE) + "}"); } order = dataDefinitionService.get(ORDERS_PLUGIN_IDENTIFIER, ORDERS_MODEL_ORDER).save(order); validateEntity(order); }"
Inversion-Mutation
megadiff
"@Override public void remove() { if (!mEntryValid) { throw new IllegalStateException(); } colRemoveAt(mIndex); mIndex--; mEnd--; mEntryValid = false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "remove"
"@Override public void remove() { if (!mEntryValid) { throw new IllegalStateException(); } mIndex--; mEnd--; mEntryValid = false; <MASK>colRemoveAt(mIndex);</MASK> }"
Inversion-Mutation
megadiff
"private boolean parseReg(String regRecord, long orgId) { Case currentCase = Case.getCurrentCase(); // get the most updated case SleuthkitCase tempDb = currentCase.getSleuthkitCase(); try { File regfile = new File(regRecord); BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(regfile))); String regString = new Scanner(input).useDelimiter("\\Z").next(); regfile.delete(); String startdoc = "<document>"; String result = regString.replaceAll("----------------------------------------",""); String enddoc = "</document>"; String stringdoc = startdoc + result + enddoc; SAXBuilder sb = new SAXBuilder(); Document document = sb.build(new StringReader(stringdoc)); Element root = document.getRootElement(); List types = root.getChildren(); Iterator iterator = types.iterator(); //for(int i = 0; i < types.size(); i++) //for(Element tempnode : types) while (iterator.hasNext()) { String time = ""; String context = ""; Element tempnode = (Element) iterator.next(); // Element tempnode = types.get(i); context = tempnode.getName(); Element timenode = tempnode.getChild("time"); time = timenode.getTextTrim(); Element artroot = tempnode.getChild("artifacts"); List artlist = artroot.getChildren(); String winver = ""; String installdate = ""; if(artlist.isEmpty()){ } else{ Iterator aiterator = artlist.iterator(); while (aiterator.hasNext()) { Element artnode = (Element) aiterator.next(); String name = artnode.getAttributeValue("name"); String value = artnode.getTextTrim(); Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); if("recentdocs".equals(context)){ BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_RECENT_OBJECT); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "RecentActivity", context, time)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "RecentActivity", context, name)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), "RecentActivity", context, value)); bbart.addAttributes(bbattributes); } else if("runMRU".equals(context)){ BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_RECENT_OBJECT); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "RecentActivity", context, time)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "RecentActivity", context, name)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), "RecentActivity", context, value)); bbart.addAttributes(bbattributes); } else if("uninstall".equals(context)){ bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "RecentActivity", context, time)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "RecentActivity", context, value)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "RecentActivity", context, name)); BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_INSTALLED_PROG); bbart.addAttributes(bbattributes); } else if("WinVersion".equals(context)){ if(name.contains("ProductName")) { winver = value; } if(name.contains("CSDVersion")){ winver = winver + " " + value; } if(name.contains("InstallDate")) { installdate = value; bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "RecentActivity", context, winver)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "RecentActivity", context, installdate)); BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_INSTALLED_PROG); bbart.addAttributes(bbattributes); } } else { BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(sysid); bbart.addAttributes(bbattributes); } } } } } catch (Exception ex) { logger.log(Level.WARNING, "Error while trying to read into a registry file." + ex); } return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseReg"
"private boolean parseReg(String regRecord, long orgId) { Case currentCase = Case.getCurrentCase(); // get the most updated case SleuthkitCase tempDb = currentCase.getSleuthkitCase(); try { File regfile = new File(regRecord); BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(regfile))); <MASK>regfile.delete();</MASK> String regString = new Scanner(input).useDelimiter("\\Z").next(); String startdoc = "<document>"; String result = regString.replaceAll("----------------------------------------",""); String enddoc = "</document>"; String stringdoc = startdoc + result + enddoc; SAXBuilder sb = new SAXBuilder(); Document document = sb.build(new StringReader(stringdoc)); Element root = document.getRootElement(); List types = root.getChildren(); Iterator iterator = types.iterator(); //for(int i = 0; i < types.size(); i++) //for(Element tempnode : types) while (iterator.hasNext()) { String time = ""; String context = ""; Element tempnode = (Element) iterator.next(); // Element tempnode = types.get(i); context = tempnode.getName(); Element timenode = tempnode.getChild("time"); time = timenode.getTextTrim(); Element artroot = tempnode.getChild("artifacts"); List artlist = artroot.getChildren(); String winver = ""; String installdate = ""; if(artlist.isEmpty()){ } else{ Iterator aiterator = artlist.iterator(); while (aiterator.hasNext()) { Element artnode = (Element) aiterator.next(); String name = artnode.getAttributeValue("name"); String value = artnode.getTextTrim(); Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); if("recentdocs".equals(context)){ BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_RECENT_OBJECT); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "RecentActivity", context, time)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "RecentActivity", context, name)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), "RecentActivity", context, value)); bbart.addAttributes(bbattributes); } else if("runMRU".equals(context)){ BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_RECENT_OBJECT); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "RecentActivity", context, time)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "RecentActivity", context, name)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), "RecentActivity", context, value)); bbart.addAttributes(bbattributes); } else if("uninstall".equals(context)){ bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "RecentActivity", context, time)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "RecentActivity", context, value)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "RecentActivity", context, name)); BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_INSTALLED_PROG); bbart.addAttributes(bbattributes); } else if("WinVersion".equals(context)){ if(name.contains("ProductName")) { winver = value; } if(name.contains("CSDVersion")){ winver = winver + " " + value; } if(name.contains("InstallDate")) { installdate = value; bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "RecentActivity", context, winver)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "RecentActivity", context, installdate)); BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(ARTIFACT_TYPE.TSK_INSTALLED_PROG); bbart.addAttributes(bbattributes); } } else { BlackboardArtifact bbart = tempDb.getContentById(orgId).newArtifact(sysid); bbart.addAttributes(bbattributes); } } } } } catch (Exception ex) { logger.log(Level.WARNING, "Error while trying to read into a registry file." + ex); } return true; }"
Inversion-Mutation
megadiff
"private void insert(OwnIdentity identity) throws IOException { Bucket tempB = mTBF.makeBucket(64 * 1024); /* FIXME: Tweak */ OutputStream os = null; try { os = tempB.getOutputStream(); mWoT.getXMLTransformer().exportOwnIdentity(identity, os); os.close(); os = null; tempB.setReadOnly(); long edition = identity.getEdition(); if(identity.getLastInsertDate().after(new Date(0))) ++edition; InsertBlock ib = new InsertBlock(tempB, null, identity.getInsertURI().setSuggestedEdition(edition)); InsertContext ictx = mClient.getInsertContext(true); ClientPutter pu = mClient.insert(ib, false, null, false, ictx, this); pu.setPriorityClass(RequestStarter.IMMEDIATE_SPLITFILE_PRIORITY_CLASS, mClientContext, null); addInsert(pu); tempB = null; Logger.debug(this, "Started insert of identity '" + identity.getNickname() + "'"); } catch(Exception e) { Logger.error(this, "Error during insert of identity '" + identity.getNickname() + "'", e); } finally { Closer.close(os); Closer.close(tempB); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "insert"
"private void insert(OwnIdentity identity) throws IOException { Bucket tempB = mTBF.makeBucket(64 * 1024); /* FIXME: Tweak */ OutputStream os = null; try { os = tempB.getOutputStream(); mWoT.getXMLTransformer().exportOwnIdentity(identity, os); os.close(); os = null; tempB.setReadOnly(); long edition = identity.getEdition(); if(identity.getLastInsertDate().after(new Date(0))) ++edition; InsertBlock ib = new InsertBlock(tempB, null, identity.getInsertURI().setSuggestedEdition(edition)); InsertContext ictx = mClient.getInsertContext(true); ClientPutter pu = mClient.insert(ib, false, null, false, ictx, this); pu.setPriorityClass(RequestStarter.IMMEDIATE_SPLITFILE_PRIORITY_CLASS, mClientContext, null); addInsert(pu); tempB = null; Logger.debug(this, "Started insert of identity '" + identity.getNickname() + "'"); } catch(Exception e) { Logger.error(this, "Error during insert of identity '" + identity.getNickname() + "'", e); } finally { <MASK>Closer.close(tempB);</MASK> Closer.close(os); } }"
Inversion-Mutation
megadiff
"private List<String> addUsersRealm( boolean notify) { // return the list of user eids for successfully added user List<String> addedUserEIds = new Vector<String>(); if (userRoleEntries != null && !userRoleEntries.isEmpty()) { if (site != null) { // get realm object String realmId = site.getReference(); try { AuthzGroup realmEdit = authzGroupService.getAuthzGroup(realmId); for (UserRoleEntry entry: userRoleEntries) { String eId = entry.userEId; String role =entry.role; try { User user = UserDirectoryService.getUserByEid(eId); if (authzGroupService.allowUpdate(realmId) || siteService.allowUpdateSiteMembership(site.getId())) { realmEdit.addMember(user.getId(), role, true, false); addedUserEIds.add(eId); // send notification if (notify) { // send notification email notiProvider.notifyAddedParticipant(!isOfficialAccount(eId), user, site.getTitle()); } } } catch (UserNotDefinedException e) { targettedMessageList.addMessage(new TargettedMessage("java.account", new Object[] { eId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: cannot find user with eid= " + eId); } // try } // for try { // post event about adding participant EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); authzGroupService.save(realmEdit); } catch (GroupNotDefinedException ee) { targettedMessageList.addMessage(new TargettedMessage("java.realm",new Object[] { realmId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: cannot find realm for" + realmId); } catch (AuthzPermissionException ee) { targettedMessageList.addMessage(new TargettedMessage("java.permeditsite",new Object[] { realmId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: don't have permission to edit realm " + realmId); } } catch (GroupNotDefinedException eee) { targettedMessageList.addMessage(new TargettedMessage("java.realm",new Object[] { realmId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: cannot find realm for " + realmId); } catch (Exception eee) { M_log.warn(this + ".addUsersRealm: " + eee.getMessage() + " realmId=" + realmId); } } } return addedUserEIds; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addUsersRealm"
"private List<String> addUsersRealm( boolean notify) { // return the list of user eids for successfully added user List<String> addedUserEIds = new Vector<String>(); if (userRoleEntries != null && !userRoleEntries.isEmpty()) { if (site != null) { // get realm object String realmId = site.getReference(); try { AuthzGroup realmEdit = authzGroupService.getAuthzGroup(realmId); for (UserRoleEntry entry: userRoleEntries) { String eId = entry.userEId; String role =entry.role; try { User user = UserDirectoryService.getUserByEid(eId); if (authzGroupService.allowUpdate(realmId) || siteService.allowUpdateSiteMembership(site.getId())) { realmEdit.addMember(user.getId(), role, true, false); addedUserEIds.add(eId); // send notification if (notify) { // send notification email notiProvider.notifyAddedParticipant(!isOfficialAccount(eId), user, site.getTitle()); } } } catch (UserNotDefinedException e) { targettedMessageList.addMessage(new TargettedMessage("java.account", new Object[] { eId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: cannot find user with eid= " + eId); } // try } // for try { <MASK>authzGroupService.save(realmEdit);</MASK> // post event about adding participant EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); } catch (GroupNotDefinedException ee) { targettedMessageList.addMessage(new TargettedMessage("java.realm",new Object[] { realmId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: cannot find realm for" + realmId); } catch (AuthzPermissionException ee) { targettedMessageList.addMessage(new TargettedMessage("java.permeditsite",new Object[] { realmId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: don't have permission to edit realm " + realmId); } } catch (GroupNotDefinedException eee) { targettedMessageList.addMessage(new TargettedMessage("java.realm",new Object[] { realmId }, TargettedMessage.SEVERITY_INFO)); M_log.warn(this + ".addUsersRealm: cannot find realm for " + realmId); } catch (Exception eee) { M_log.warn(this + ".addUsersRealm: " + eee.getMessage() + " realmId=" + realmId); } } } return addedUserEIds; }"
Inversion-Mutation
megadiff
"public void hidePlaceholder() { if (super.getTextBox().getText().equals(this.getPlaceholderText())) { super.getTextBox().setText(""); } super.getTextBox().removeStyleName(this.getPlaceholderStyleName()); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "hidePlaceholder"
"public void hidePlaceholder() { if (super.getTextBox().getText().equals(this.getPlaceholderText())) { super.getTextBox().setText(""); <MASK>super.getTextBox().removeStyleName(this.getPlaceholderStyleName());</MASK> } }"
Inversion-Mutation
megadiff
"public void run() { try { int width = Display.getDisplayMode().getWidth(); int height = Display.getDisplayMode().getHeight(); Display.create(); // Display.setDisplayMode(new DisplayMode(width, height)); Display.setFullscreen(true); Display.setVSyncEnabled(true); // First "image" contains the header configuration configure(config); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, width, height); glMatrixMode(GL11.GL_MODELVIEW); glMatrixMode(GL11.GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, height, 0, 1, -1); glMatrixMode(GL11.GL_MODELVIEW); // init resources Texture[] textures = new Texture[images.size()]; Point[] points = new Point[images.size()]; Region[] regions = new Region[images.size() + 4]; // 4 is for walls for (int i = 0; i < images.size(); i++) { InputStream in = new FileInputStream(new File(scriptFile.getParent(), images.get(i) .get("image"))); textures[i] = TextureLoader.getTexture("PNG", in); regions[i] = Region.createRegion(textures[i]); points[i] = new Point(Integer.parseInt(images.get(i).get("x")), Integer.parseInt( images.get(i).get("y"))); } setRegionPositions(regions, points); // Define the wall regions[images.size() + 0] = Region.createBlock(width, 1, 0, -1); regions[images.size() + 1] = Region.createBlock(1, height, width, 0); regions[images.size() + 2] = Region.createBlock(width, 1, 0, height); regions[images.size() + 3] = Region.createBlock(1, height, -1, 0); boolean quit = false; while (!Display.isCloseRequested() && !quit) { MouseEvent mouseEvent = mousePoller.poll(); MouseEvent mouseDelta = deltaMouseEventFilter.apply(mouseEvent); Display.sync(60); if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { quit = true; } if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { setRegionPositions(regions, points); } if (mouseEvent.isButtonDown() && !mouseDelta.isButtonDown()) { int x = mouseEvent.getX(); int y = height - mouseEvent.getY(); int dx = mouseDelta.getX(); int dy = mouseDelta.getY(); for (int i = 0; i < regions.length; i++) { if (regions[i].contains(x, y)) { regions[i].setDxDy(dx, -dy); displacement.apply(regions[i], dx, -dy, regions); i = regions.length; } } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); StringBuilder s = new StringBuilder("Regions ({}): "); // Move regions for (int i = 0; i < textures.length; i++) { int x = regions[i].getX(); int y = regions[i].getY(); s.append(x).append(",").append(y); if (i != (textures.length - 1)) { s.append(","); } renderImage(textures[i], x, y); } log.info(s.toString(), textures.length); Display.update(); throw new RuntimeException("Soemthing"); } } catch (ScriptException e) { UI.confirm("Script file contains errors:\n" + e.getMessage()); } catch (Exception e) { log.error(e.getMessage(), e); } finally { Display.destroy(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { try { int width = Display.getDisplayMode().getWidth(); int height = Display.getDisplayMode().getHeight(); Display.create(); // Display.setDisplayMode(new DisplayMode(width, height)); Display.setFullscreen(true); Display.setVSyncEnabled(true); // First "image" contains the header configuration configure(config); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, width, height); glMatrixMode(GL11.GL_MODELVIEW); glMatrixMode(GL11.GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, height, 0, 1, -1); glMatrixMode(GL11.GL_MODELVIEW); // init resources Texture[] textures = new Texture[images.size()]; Point[] points = new Point[images.size()]; Region[] regions = new Region[images.size() + 4]; // 4 is for walls for (int i = 0; i < images.size(); i++) { InputStream in = new FileInputStream(new File(scriptFile.getParent(), images.get(i) .get("image"))); textures[i] = TextureLoader.getTexture("PNG", in); regions[i] = Region.createRegion(textures[i]); points[i] = new Point(Integer.parseInt(images.get(i).get("x")), Integer.parseInt( images.get(i).get("y"))); } setRegionPositions(regions, points); // Define the wall regions[images.size() + 0] = Region.createBlock(width, 1, 0, -1); regions[images.size() + 1] = Region.createBlock(1, height, width, 0); regions[images.size() + 2] = Region.createBlock(width, 1, 0, height); regions[images.size() + 3] = Region.createBlock(1, height, -1, 0); boolean quit = false; while (!Display.isCloseRequested() && !quit) { MouseEvent mouseEvent = mousePoller.poll(); MouseEvent mouseDelta = deltaMouseEventFilter.apply(mouseEvent); Display.sync(60); if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { quit = true; } if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { setRegionPositions(regions, points); } if (mouseEvent.isButtonDown() && !mouseDelta.isButtonDown()) { int x = mouseEvent.getX(); int y = height - mouseEvent.getY(); int dx = mouseDelta.getX(); int dy = mouseDelta.getY(); for (int i = 0; i < regions.length; i++) { if (regions[i].contains(x, y)) { regions[i].setDxDy(dx, -dy); displacement.apply(regions[i], dx, -dy, regions); i = regions.length; } } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); StringBuilder s = new StringBuilder("Regions ({}): "); // Move regions for (int i = 0; i < textures.length; i++) { int x = regions[i].getX(); int y = regions[i].getY(); s.append(x).append(",").append(y); if (i != (textures.length - 1)) { s.append(","); } renderImage(textures[i], x, y); } log.info(s.toString(), textures.length); <MASK>throw new RuntimeException("Soemthing");</MASK> Display.update(); } } catch (ScriptException e) { UI.confirm("Script file contains errors:\n" + e.getMessage()); } catch (Exception e) { log.error(e.getMessage(), e); } finally { Display.destroy(); } }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") @Override public void handleMessage(Message msgP) { final Activity a = SynodroidFragment.this.getActivity(); if (a != null){ final SynoServer server = ((Synodroid) a.getApplication()).getServer(); Synodroid app = (Synodroid) a.getApplication(); Style msg_style = null; // According to the message switch (msgP.what) { case ResponseHandler.MSG_CONNECT_WITH_ACTION: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received connect with action message."); }catch (Exception ex){/*DO NOTHING*/} ((BaseActivity)a).showDialogToConnect(true, (List<SynoAction>) msgP.obj, true); break; case ResponseHandler.MSG_ERROR: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received error message."); }catch (Exception ex){/*DO NOTHING*/} // Change the title ((BaseActivity)a).updateSMServer(null); // Show the error // Save the last error inside the server to surive UI rotation and // pause/resume. if (server != null) { server.setLastError((String) msgP.obj); android.view.View.OnClickListener ocl = new android.view.View.OnClickListener() { @Override public void onClick(View v) { if (server != null) { if (!server.isConnected()) { ((BaseActivity) a).showDialogToConnect(false, null, false); } } Crouton.cancelAllCroutons(); } }; Crouton.makeText(getActivity(), server.getLastError()+ "\n\n" + getText(R.string.click_dismiss), Synodroid.CROUTON_ERROR).setOnClickListener(ocl).show(); } break; case ResponseHandler.MSG_OTP_REQUESTED: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received OTP Request message."); }catch (Exception ex){/*DO NOTHING*/} postOTPActions = (List<SynoAction>)msgP.obj; // Show the connection dialog try { ((BaseActivity)a).showDialog(BaseActivity.OTP_REQUEST_DIALOG_ID); } catch (Exception e) {/* Unable to show dialog probably because intent has been closed. Ignoring...*/} break; case ResponseHandler.MSG_CONNECTED: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message."); }catch (Exception ex){/*DO NOTHING*/} ((BaseActivity)a).updateSMServer(server); break; case ResponseHandler.MSG_CONNECTING: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message."); }catch (Exception ex){/*DO NOTHING*/} ((BaseActivity)a).updateSMServer(null); break; case MSG_OPERATION_PENDING: if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received operation pending message."); if (a instanceof HomeActivity){ ((HomeActivity) a).updateRefreshStatus(true); } else if (a instanceof DetailActivity){ ((DetailActivity) a).updateRefreshStatus(true); } else if (a instanceof SearchActivity){ ((SearchActivity) a).updateRefreshStatus(true); } else if (a instanceof FileActivity){ ((FileActivity) a).updateRefreshStatus(true); } else if (a instanceof BrowserActivity){ ((BrowserActivity) a).updateRefreshStatus(true); } break; case MSG_INFO: if (msg_style == null) msg_style = Synodroid.CROUTON_INFO; case MSG_ALERT: if (msg_style == null) msg_style = Synodroid.CROUTON_ALERT; case MSG_ERR: if (msg_style == null) msg_style = Synodroid.CROUTON_ERROR; case MSG_CONFIRM: if (msg_style == null) msg_style = Synodroid.CROUTON_CONFIRM; if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received toast message."); final String text = (String) msgP.obj; Runnable runnable = new Runnable() { public void run() { Crouton.makeText(a, text, Synodroid.CROUTON_CONFIRM).show(); } }; a.runOnUiThread(runnable); break; default: if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received default message."); if (a instanceof HomeActivity){ ((HomeActivity) a).updateRefreshStatus(false); } else if (a instanceof DetailActivity){ ((DetailActivity) a).updateRefreshStatus(false); } else if (a instanceof SearchActivity){ ((SearchActivity) a).updateRefreshStatus(false); } else if (a instanceof FileActivity){ ((FileActivity) a).updateRefreshStatus(false); } else if (a instanceof BrowserActivity){ ((BrowserActivity) a).updateRefreshStatus(false); } break; } // Delegate to the sub class in case it have something to do SynodroidFragment.this.handleMessage(msgP); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleMessage"
"@SuppressWarnings("unchecked") @Override public void handleMessage(Message msgP) { final Activity a = SynodroidFragment.this.getActivity(); <MASK>final SynoServer server = ((Synodroid) a.getApplication()).getServer();</MASK> if (a != null){ Synodroid app = (Synodroid) a.getApplication(); Style msg_style = null; // According to the message switch (msgP.what) { case ResponseHandler.MSG_CONNECT_WITH_ACTION: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received connect with action message."); }catch (Exception ex){/*DO NOTHING*/} ((BaseActivity)a).showDialogToConnect(true, (List<SynoAction>) msgP.obj, true); break; case ResponseHandler.MSG_ERROR: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.w(Synodroid.DS_TAG,"SynodroidFragment: Received error message."); }catch (Exception ex){/*DO NOTHING*/} // Change the title ((BaseActivity)a).updateSMServer(null); // Show the error // Save the last error inside the server to surive UI rotation and // pause/resume. if (server != null) { server.setLastError((String) msgP.obj); android.view.View.OnClickListener ocl = new android.view.View.OnClickListener() { @Override public void onClick(View v) { if (server != null) { if (!server.isConnected()) { ((BaseActivity) a).showDialogToConnect(false, null, false); } } Crouton.cancelAllCroutons(); } }; Crouton.makeText(getActivity(), server.getLastError()+ "\n\n" + getText(R.string.click_dismiss), Synodroid.CROUTON_ERROR).setOnClickListener(ocl).show(); } break; case ResponseHandler.MSG_OTP_REQUESTED: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received OTP Request message."); }catch (Exception ex){/*DO NOTHING*/} postOTPActions = (List<SynoAction>)msgP.obj; // Show the connection dialog try { ((BaseActivity)a).showDialog(BaseActivity.OTP_REQUEST_DIALOG_ID); } catch (Exception e) {/* Unable to show dialog probably because intent has been closed. Ignoring...*/} break; case ResponseHandler.MSG_CONNECTED: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message."); }catch (Exception ex){/*DO NOTHING*/} ((BaseActivity)a).updateSMServer(server); break; case ResponseHandler.MSG_CONNECTING: try{ if (((Synodroid)a.getApplication()).DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received connected to server message."); }catch (Exception ex){/*DO NOTHING*/} ((BaseActivity)a).updateSMServer(null); break; case MSG_OPERATION_PENDING: if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received operation pending message."); if (a instanceof HomeActivity){ ((HomeActivity) a).updateRefreshStatus(true); } else if (a instanceof DetailActivity){ ((DetailActivity) a).updateRefreshStatus(true); } else if (a instanceof SearchActivity){ ((SearchActivity) a).updateRefreshStatus(true); } else if (a instanceof FileActivity){ ((FileActivity) a).updateRefreshStatus(true); } else if (a instanceof BrowserActivity){ ((BrowserActivity) a).updateRefreshStatus(true); } break; case MSG_INFO: if (msg_style == null) msg_style = Synodroid.CROUTON_INFO; case MSG_ALERT: if (msg_style == null) msg_style = Synodroid.CROUTON_ALERT; case MSG_ERR: if (msg_style == null) msg_style = Synodroid.CROUTON_ERROR; case MSG_CONFIRM: if (msg_style == null) msg_style = Synodroid.CROUTON_CONFIRM; if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received toast message."); final String text = (String) msgP.obj; Runnable runnable = new Runnable() { public void run() { Crouton.makeText(a, text, Synodroid.CROUTON_CONFIRM).show(); } }; a.runOnUiThread(runnable); break; default: if (app != null && app.DEBUG) Log.v(Synodroid.DS_TAG,"SynodroidFragment: Received default message."); if (a instanceof HomeActivity){ ((HomeActivity) a).updateRefreshStatus(false); } else if (a instanceof DetailActivity){ ((DetailActivity) a).updateRefreshStatus(false); } else if (a instanceof SearchActivity){ ((SearchActivity) a).updateRefreshStatus(false); } else if (a instanceof FileActivity){ ((FileActivity) a).updateRefreshStatus(false); } else if (a instanceof BrowserActivity){ ((BrowserActivity) a).updateRefreshStatus(false); } break; } // Delegate to the sub class in case it have something to do SynodroidFragment.this.handleMessage(msgP); } }"
Inversion-Mutation
megadiff
"private ByteArrayOutputStream encodeToBytes() throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new GZIPOutputStream(buf)); oos.writeObject(this); } finally { IOUtils.closeQuietly(oos); } ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); DataOutputStream dos = null; try { dos = new DataOutputStream(new Base64OutputStream(buf2, true, -1, null)); buf2.write(PREAMBLE); dos.writeInt(buf.size()); buf.writeTo(dos); } finally { IOUtils.closeQuietly(dos); buf2.write(POSTAMBLE); } return buf2; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "encodeToBytes"
"private ByteArrayOutputStream encodeToBytes() throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new GZIPOutputStream(buf)); oos.writeObject(this); } finally { IOUtils.closeQuietly(oos); } ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); DataOutputStream dos = null; try { dos = new DataOutputStream(new Base64OutputStream(buf2, true, -1, null)); buf2.write(PREAMBLE); dos.writeInt(buf.size()); buf.writeTo(dos); <MASK>buf2.write(POSTAMBLE);</MASK> } finally { IOUtils.closeQuietly(dos); } return buf2; }"
Inversion-Mutation
megadiff
"protected void processStaleIndexEntries(TitanType type, boolean repair) throws RepairException { if (!type.isPropertyKey()) { throw new RepairException("the given type is not a property key"); } //begin graph and store transactions InternalTitanTransaction itx = (InternalTitanTransaction) graph.newTransaction(); StoreTransaction stx = ((BackendTransaction) itx.getTxHandle()).getStoreTransactionHandle(); //get the key TitanKey titanKey = itx.getPropertyKey(type.getName()); if (!titanKey.hasIndex()) { throw new RepairException("the given key is not an index"); } Backend backend = getBackend(); KeyColumnValueStore indexStore = backend.getVertexIndexStore(); int keyCount = 0; int deletedVertexCount = 0; int repairedPropertyCount = 0; try { //we need to iterate over all keys in the index RecordIterator<ByteBuffer> keys = indexStore.getKeys(stx); while (keys.hasNext()) { ByteBuffer key = keys.next(); byte[] keyArray = getByteArray(key); List<ByteBuffer> deletions = new ArrayList<ByteBuffer>(); List<TitanProperty> additions = new ArrayList<TitanProperty>(); ByteBuffer startCol = VariableLong.positiveByteBuffer(titanKey.getID()); List<Entry> columns = indexStore.getSlice( key, startCol, ByteBufferUtil.nextBiggerBuffer(startCol), stx ); for (Entry entry : columns) { long eid = VariableLong.readPositive(entry.getValue()); TitanVertex v = (TitanVertex) graph.getVertex(eid); if (v == null) { deletions.add(entry.getColumn()); System.out.println("deleted vertex found in index"); deletedVertexCount++; } else { //verify that the given property matches Iterator<TitanProperty> properties = v.getProperties(titanKey.getName()).iterator(); assert properties.hasNext(); TitanProperty property = properties.next(); assert !properties.hasNext(); Object value = property.getAttribute(); ByteBuffer indexKey = getIndexKey(value); byte[] valueArray = getByteArray(indexKey); if (!Arrays.equals(keyArray, valueArray)) { deletions.add(entry.getColumn()); additions.add(property); System.out.println("value mismatch found in index"); repairedPropertyCount++; } } } if (repair) { InternalTitanTransaction tx = (InternalTitanTransaction) graph.newTransaction(); if (deletions.size() > 0 || additions.size() > 0) { BackendMutator mutator = new BackendMutator(backend, tx.getTxHandle()); if (deletions.size() > 0) { indexStore.mutate(key, null, deletions, stx); } for (TitanProperty property: additions) { addIndexEntry(property, mutator); } tx.commit(); } } keyCount++; } } catch (StorageException e) { throw new RepairException(e); } finally { //cleanup itx.commit(); } System.out.println("[" + type.getName() + "] repair completed"); System.out.println(" > " + keyCount + " keys examined"); System.out.println(" > " + deletedVertexCount + " references to deleted vertices " + (repair?"removed":"detected")); System.out.println(" > " + repairedPropertyCount + " incorrectly indexed vertex properties " + (repair?"repaired":"detected")); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processStaleIndexEntries"
"protected void processStaleIndexEntries(TitanType type, boolean repair) throws RepairException { if (!type.isPropertyKey()) { throw new RepairException("the given type is not a property key"); } //begin graph and store transactions InternalTitanTransaction itx = (InternalTitanTransaction) graph.newTransaction(); StoreTransaction stx = ((BackendTransaction) itx.getTxHandle()).getStoreTransactionHandle(); //get the key TitanKey titanKey = itx.getPropertyKey(type.getName()); if (!titanKey.hasIndex()) { throw new RepairException("the given key is not an index"); } Backend backend = getBackend(); KeyColumnValueStore indexStore = backend.getVertexIndexStore(); int keyCount = 0; int deletedVertexCount = 0; int repairedPropertyCount = 0; try { //we need to iterate over all keys in the index RecordIterator<ByteBuffer> keys = indexStore.getKeys(stx); while (keys.hasNext()) { ByteBuffer key = keys.next(); byte[] keyArray = getByteArray(key); List<ByteBuffer> deletions = new ArrayList<ByteBuffer>(); List<TitanProperty> additions = new ArrayList<TitanProperty>(); ByteBuffer startCol = VariableLong.positiveByteBuffer(titanKey.getID()); List<Entry> columns = indexStore.getSlice( key, startCol, ByteBufferUtil.nextBiggerBuffer(startCol), stx ); for (Entry entry : columns) { long eid = VariableLong.readPositive(entry.getValue()); TitanVertex v = (TitanVertex) graph.getVertex(eid); if (v == null) { deletions.add(entry.getColumn()); System.out.println("deleted vertex found in index"); deletedVertexCount++; } else { //verify that the given property matches Iterator<TitanProperty> properties = v.getProperties(titanKey.getName()).iterator(); assert properties.hasNext(); TitanProperty property = properties.next(); assert !properties.hasNext(); Object value = property.getAttribute(); ByteBuffer indexKey = getIndexKey(value); byte[] valueArray = getByteArray(indexKey); if (!Arrays.equals(keyArray, valueArray)) { deletions.add(entry.getColumn()); additions.add(property); System.out.println("value mismatch found in index"); } <MASK>repairedPropertyCount++;</MASK> } } if (repair) { InternalTitanTransaction tx = (InternalTitanTransaction) graph.newTransaction(); if (deletions.size() > 0 || additions.size() > 0) { BackendMutator mutator = new BackendMutator(backend, tx.getTxHandle()); if (deletions.size() > 0) { indexStore.mutate(key, null, deletions, stx); } for (TitanProperty property: additions) { addIndexEntry(property, mutator); } tx.commit(); } } keyCount++; } } catch (StorageException e) { throw new RepairException(e); } finally { //cleanup itx.commit(); } System.out.println("[" + type.getName() + "] repair completed"); System.out.println(" > " + keyCount + " keys examined"); System.out.println(" > " + deletedVertexCount + " references to deleted vertices " + (repair?"removed":"detected")); System.out.println(" > " + repairedPropertyCount + " incorrectly indexed vertex properties " + (repair?"repaired":"detected")); }"
Inversion-Mutation
megadiff
"@Deprecated @Override public boolean newMap(URL url) throws FileNotFoundException, XMLParseException, IOException, URISyntaxException { final IMapViewManager mapViewManager = Controller.getCurrentController().getMapViewManager(); if (mapViewManager.tryToChangeToMapView(url)) return false; if (AddOnsController.getController().installIfAppropriate(url)) return false; URL alternativeURL = null; try { final File file = Compat.urlToFile(url); if(file == null){ alternativeURL = url; } else{ if(file.exists()){ final MFileManager fileManager = MFileManager.getController(getMModeController()); File alternativeFile = fileManager.getAlternativeFile(file, AlternativeFileMode.AUTOSAVE); if(alternativeFile != null){ alternativeURL = Compat.fileToUrl(alternativeFile); } else return false; } else{ alternativeURL = url; } } } catch (MalformedURLException e) { } catch (URISyntaxException e) { } if(alternativeURL == null) return false; Controller.getCurrentController().getViewController().setWaitingCursor(true); try{ final MapModel newModel = new MMapModel(); final MFileManager fileManager = MFileManager.getController(getMModeController()); fileManager.loadAndLock(alternativeURL, newModel); newModel.setURL(url); newModel.setSaved(alternativeURL.equals(url)); fireMapCreated(newModel); newMapView(newModel); return true; } finally { Controller.getCurrentController().getViewController().setWaitingCursor(false); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "newMap"
"@Deprecated @Override public boolean newMap(URL url) throws FileNotFoundException, XMLParseException, IOException, URISyntaxException { final IMapViewManager mapViewManager = Controller.getCurrentController().getMapViewManager(); if (mapViewManager.tryToChangeToMapView(url)) return false; if (AddOnsController.getController().installIfAppropriate(url)) return false; <MASK>Controller.getCurrentController().getViewController().setWaitingCursor(true);</MASK> URL alternativeURL = null; try { final File file = Compat.urlToFile(url); if(file == null){ alternativeURL = url; } else{ if(file.exists()){ final MFileManager fileManager = MFileManager.getController(getMModeController()); File alternativeFile = fileManager.getAlternativeFile(file, AlternativeFileMode.AUTOSAVE); if(alternativeFile != null){ alternativeURL = Compat.fileToUrl(alternativeFile); } else return false; } else{ alternativeURL = url; } } } catch (MalformedURLException e) { } catch (URISyntaxException e) { } if(alternativeURL == null) return false; try{ final MapModel newModel = new MMapModel(); final MFileManager fileManager = MFileManager.getController(getMModeController()); fileManager.loadAndLock(alternativeURL, newModel); newModel.setURL(url); newModel.setSaved(alternativeURL.equals(url)); fireMapCreated(newModel); newMapView(newModel); return true; } finally { Controller.getCurrentController().getViewController().setWaitingCursor(false); } }"
Inversion-Mutation
megadiff
"protected void handleCompareInputChange() { // before setting the new input we have to save the old Object input = getInput(); if (!isSaving() && (isLeftDirty() || isRightDirty())) { if (Utilities.RUNNING_TESTS) { if (Utilities.TESTING_FLUSH_ON_COMPARE_INPUT_CHANGE) { flushContent(input, null); } } else { // post alert Shell shell= fComposite.getShell(); MessageDialog dialog= new MessageDialog(shell, CompareMessages.ContentMergeViewer_resource_changed_title, null, // accept the default window icon CompareMessages.ContentMergeViewer_resource_changed_description, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, // 0 IDialogConstants.NO_LABEL, // 1 }, 0); // default button index switch (dialog.open()) { // open returns index of pressed button case 0: flushContent(input, null); break; case 1: setLeftDirty(false); setRightDirty(false); break; } } } refresh(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleCompareInputChange"
"protected void handleCompareInputChange() { // before setting the new input we have to save the old Object input = getInput(); if (!isSaving() && (isLeftDirty() || isRightDirty())) { if (Utilities.RUNNING_TESTS) { if (Utilities.TESTING_FLUSH_ON_COMPARE_INPUT_CHANGE) { flushContent(input, null); } } else { // post alert Shell shell= fComposite.getShell(); MessageDialog dialog= new MessageDialog(shell, CompareMessages.ContentMergeViewer_resource_changed_title, null, // accept the default window icon CompareMessages.ContentMergeViewer_resource_changed_description, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, // 0 IDialogConstants.NO_LABEL, // 1 }, 0); // default button index switch (dialog.open()) { // open returns index of pressed button case 0: flushContent(input, null); break; case 1: setLeftDirty(false); setRightDirty(false); break; } } <MASK>refresh();</MASK> } }"
Inversion-Mutation
megadiff
"public void handlePageException(Throwable e) throws ServletException, IOException { if (e instanceof SkipPageException) return; HttpServletRequest request = getCauchoRequest(); request.setAttribute("javax.servlet.jsp.jspException", e); CauchoResponse response = getCauchoResponse(); response.setForbidForward(false); response.setResponseStream(_responseStream); response.killCache(); response.setNoCache(true); _hasException = true; if (e instanceof ClientDisconnectException) throw (ClientDisconnectException) e; if (! (_servlet instanceof Page)) { } else if (getApplication() == null || getApplication().getJsp() == null || ! getApplication().getJsp().isRecompileOnError()) { } else if (e instanceof OutOfMemoryError) { } else if (e instanceof Error) { try { Path workDir = getApplication().getAppDir().lookup("WEB-INF/work"); String className = _servlet.getClass().getName(); Path path = workDir.lookup(className.replace('.', '/') + ".class"); log.warning("Removing " + path + " due to " + e); path.remove(); } catch (Exception e1) { } Page page = (Page) _servlet; page._caucho_unload(); if (! page.isDead()) { page.setDead(); page.destroy(); } } _topOut.clearBuffer(); if (_errorPage != null) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, e.toString(), e); } else if (e instanceof DisplayableException) { log.warning(e.getMessage()); } else { log.log(Level.WARNING, e.toString(), e); } getCauchoRequest().setAttribute(EXCEPTION, e); getCauchoRequest().setAttribute("javax.servlet.error.exception", e); getCauchoRequest().setAttribute("javax.servlet.error.exception_type", e); getCauchoRequest().setAttribute("javax.servlet.error.request_uri", getCauchoRequest().getRequestURI()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); try { RequestDispatcher rd = getCauchoRequest().getRequestDispatcher(_errorPage); if (rd instanceof RequestDispatcherImpl) { getCauchoResponse().setHasError(true); ((RequestDispatcherImpl) rd).error(getCauchoRequest(), getCauchoResponse()); } else { if (rd != null) { getCauchoResponse().killCache(); getCauchoResponse().setNoCache(true); rd.forward(getCauchoRequest(), getCauchoResponse()); } else { log.log(Level.FINE, e.toString(), e); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } } } catch (FileNotFoundException e2) { log.log(Level.WARNING, e.toString(), e2); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } catch (IOException e2) { log.log(Level.FINE, e.toString(), e2); } return; } /* if (_servlet instanceof Page && ! (e instanceof LineMapException)) { LineMap lineMap = ((Page) _servlet)._caucho_getLineMap(); if (lineMap != null) e = new JspLineException(e, lineMap); } */ if (e instanceof ServletException) { throw (ServletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new ServletException(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handlePageException"
"public void handlePageException(Throwable e) throws ServletException, IOException { if (e instanceof SkipPageException) return; HttpServletRequest request = getCauchoRequest(); request.setAttribute("javax.servlet.jsp.jspException", e); CauchoResponse response = getCauchoResponse(); response.setForbidForward(false); response.setResponseStream(_responseStream); response.killCache(); response.setNoCache(true); <MASK>response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);</MASK> _hasException = true; if (e instanceof ClientDisconnectException) throw (ClientDisconnectException) e; if (! (_servlet instanceof Page)) { } else if (getApplication() == null || getApplication().getJsp() == null || ! getApplication().getJsp().isRecompileOnError()) { } else if (e instanceof OutOfMemoryError) { } else if (e instanceof Error) { try { Path workDir = getApplication().getAppDir().lookup("WEB-INF/work"); String className = _servlet.getClass().getName(); Path path = workDir.lookup(className.replace('.', '/') + ".class"); log.warning("Removing " + path + " due to " + e); path.remove(); } catch (Exception e1) { } Page page = (Page) _servlet; page._caucho_unload(); if (! page.isDead()) { page.setDead(); page.destroy(); } } _topOut.clearBuffer(); if (_errorPage != null) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, e.toString(), e); } else if (e instanceof DisplayableException) { log.warning(e.getMessage()); } else { log.log(Level.WARNING, e.toString(), e); } getCauchoRequest().setAttribute(EXCEPTION, e); getCauchoRequest().setAttribute("javax.servlet.error.exception", e); getCauchoRequest().setAttribute("javax.servlet.error.exception_type", e); getCauchoRequest().setAttribute("javax.servlet.error.request_uri", getCauchoRequest().getRequestURI()); try { RequestDispatcher rd = getCauchoRequest().getRequestDispatcher(_errorPage); if (rd instanceof RequestDispatcherImpl) { getCauchoResponse().setHasError(true); ((RequestDispatcherImpl) rd).error(getCauchoRequest(), getCauchoResponse()); } else { if (rd != null) { getCauchoResponse().killCache(); getCauchoResponse().setNoCache(true); rd.forward(getCauchoRequest(), getCauchoResponse()); } else { log.log(Level.FINE, e.toString(), e); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } } } catch (FileNotFoundException e2) { log.log(Level.WARNING, e.toString(), e2); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } catch (IOException e2) { log.log(Level.FINE, e.toString(), e2); } return; } /* if (_servlet instanceof Page && ! (e instanceof LineMapException)) { LineMap lineMap = ((Page) _servlet)._caucho_getLineMap(); if (lineMap != null) e = new JspLineException(e, lineMap); } */ if (e instanceof ServletException) { throw (ServletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new ServletException(e); } }"
Inversion-Mutation
megadiff
"public boolean removeSyncBytes(IResource resource, int depth) throws TeamException { if (resource.exists() || resource.isPhantom()) { try { if (depth != IResource.DEPTH_ZERO || internalGetSyncBytes(resource) != null) { getSynchronizer().flushSyncInfo(getSyncName(), resource, depth); return true; } } catch (CoreException e) { throw TeamException.asTeamException(e); } } return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "removeSyncBytes"
"public boolean removeSyncBytes(IResource resource, int depth) throws TeamException { if (resource.exists() || resource.isPhantom()) { try { if (depth != IResource.DEPTH_ZERO || internalGetSyncBytes(resource) != null) { getSynchronizer().flushSyncInfo(getSyncName(), resource, depth); } <MASK>return true;</MASK> } catch (CoreException e) { throw TeamException.asTeamException(e); } } return false; }"
Inversion-Mutation
megadiff
"private void traverseShortestPaths() { Collection<IAtom> canonicalizeAtoms = new SimpleAtomCanonicalisation().canonicalizeAtoms(atomContainer); for (IAtom sourceAtom : canonicalizeAtoms) { StringBuffer sb = new StringBuffer(); if (sourceAtom instanceof IPseudoAtom) { if (!pseudoAtoms.contains(sourceAtom.getSymbol())) { pseudoAtoms.add(pseduoAtomCounter, sourceAtom.getSymbol()); pseduoAtomCounter += 1; } sb.append((char) (PeriodicTable.getElementCount() + pseudoAtoms.indexOf(sourceAtom.getSymbol()) + 1)); } else { Integer atnum = PeriodicTable.getAtomicNumber(sourceAtom.getSymbol()); if (atnum != null) { sb.append(toAtomPattern(sourceAtom)); } else { sb.append((char) PeriodicTable.getElementCount() + 1); } } if (!allPaths.contains(sb)) { allPaths.add(sb); } for (IAtom sinkAtom : canonicalizeAtoms) { sb = new StringBuffer(); if (sourceAtom == sinkAtom) { continue; } List<IAtom> shortestPath = PathTools.getShortestPath(atomContainer, sourceAtom, sinkAtom); if (shortestPath == null || shortestPath.isEmpty() || shortestPath.size() < 2) { continue; } //System.out.println("Path length " + shortestPath.size()); IAtom atomCurrent = shortestPath.get(0); for (int i = 1; i < shortestPath.size(); i++) { IAtom atomNext = shortestPath.get(i); if (atomCurrent instanceof IPseudoAtom) { if (!pseudoAtoms.contains(atomCurrent.getSymbol())) { pseudoAtoms.add(pseduoAtomCounter, atomCurrent.getSymbol()); pseduoAtomCounter += 1; } sb.append((char) (PeriodicTable.getElementCount() + pseudoAtoms.indexOf(atomCurrent.getSymbol()) + 1)); } else { Integer atnum = PeriodicTable.getAtomicNumber(atomCurrent.getSymbol()); if (atnum != null) { sb.append(toAtomPattern(atomCurrent)); } else { sb.append((char) PeriodicTable.getElementCount() + 1); } } sb.append(getBondSymbol(atomContainer.getBond(atomCurrent, atomNext))); atomCurrent = atomNext; } allPaths.add(sb); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "traverseShortestPaths"
"private void traverseShortestPaths() { Collection<IAtom> canonicalizeAtoms = new SimpleAtomCanonicalisation().canonicalizeAtoms(atomContainer); for (IAtom sourceAtom : canonicalizeAtoms) { StringBuffer <MASK>sb = new StringBuffer();</MASK> if (sourceAtom instanceof IPseudoAtom) { if (!pseudoAtoms.contains(sourceAtom.getSymbol())) { pseudoAtoms.add(pseduoAtomCounter, sourceAtom.getSymbol()); pseduoAtomCounter += 1; } sb.append((char) (PeriodicTable.getElementCount() + pseudoAtoms.indexOf(sourceAtom.getSymbol()) + 1)); } else { Integer atnum = PeriodicTable.getAtomicNumber(sourceAtom.getSymbol()); if (atnum != null) { sb.append(toAtomPattern(sourceAtom)); } else { sb.append((char) PeriodicTable.getElementCount() + 1); } } if (!allPaths.contains(sb)) { allPaths.add(sb); } for (IAtom sinkAtom : canonicalizeAtoms) { if (sourceAtom == sinkAtom) { continue; } List<IAtom> shortestPath = PathTools.getShortestPath(atomContainer, sourceAtom, sinkAtom); if (shortestPath == null || shortestPath.isEmpty() || shortestPath.size() < 2) { continue; } //System.out.println("Path length " + shortestPath.size()); IAtom atomCurrent = shortestPath.get(0); for (int i = 1; i < shortestPath.size(); i++) { IAtom atomNext = shortestPath.get(i); <MASK>sb = new StringBuffer();</MASK> if (atomCurrent instanceof IPseudoAtom) { if (!pseudoAtoms.contains(atomCurrent.getSymbol())) { pseudoAtoms.add(pseduoAtomCounter, atomCurrent.getSymbol()); pseduoAtomCounter += 1; } sb.append((char) (PeriodicTable.getElementCount() + pseudoAtoms.indexOf(atomCurrent.getSymbol()) + 1)); } else { Integer atnum = PeriodicTable.getAtomicNumber(atomCurrent.getSymbol()); if (atnum != null) { sb.append(toAtomPattern(atomCurrent)); } else { sb.append((char) PeriodicTable.getElementCount() + 1); } } sb.append(getBondSymbol(atomContainer.getBond(atomCurrent, atomNext))); atomCurrent = atomNext; } allPaths.add(sb); } } }"
Inversion-Mutation
megadiff
"public NodeUpdateService(final Node node) { this.node = node; nodeSyncService = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()) { @Override protected void afterExecute(final Runnable r, final Throwable t) { node.setDegraded(getQueue().isEmpty()); timerEnabled.set(getQueue().isEmpty()); } }; nodeLogger = new NodeLogger(node); dataUpdateTimer = new Timer(); dataUpdateTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { // If there is connection and the timer can work. if (timerEnabled.get() && node.getChannel() != null && node.getChannel().isConnected()) { // The copy of the signals to send must be isolated final Set<Signal> signalsCopy = new HashSet<>(); synchronized (node.getToDistributeSignals()) { signalsCopy.addAll(node.getToDistributeSignals()); } if (signalsCopy.size() > 0) { // TODO: DRY this references if possible List<Address> allMembersButMyself = Lists .newArrayList(node.getAliveNodes()); allMembersButMyself.remove(node.getAddress()); // TODO: Take this out. Multimap<Address, Signal> copyOfBackupSignals = null; synchronized (node.getBackupSignals()) { copyOfBackupSignals = HashMultimap.create(); } nodeLogger.log("Updating my new nodes..."); // This synchronized might be a bit too much. synchronized (node) { syncMembers( Lists.newArrayList(allMembersButMyself), Lists.newArrayList(node.getAliveNodes()), signalsCopy, copyOfBackupSignals); node.getToDistributeSignals().clear(); } if (node.getToDistributeSignals().isEmpty() && node.getListener() != null) { node.getListener().onNodeSyncDone(); } } } } catch (Exception e) { e.printStackTrace(); } } }, 0, 1000); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "NodeUpdateService"
"public NodeUpdateService(final Node node) { this.node = node; nodeSyncService = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()) { @Override protected void afterExecute(final Runnable r, final Throwable t) { node.setDegraded(getQueue().isEmpty()); timerEnabled.set(getQueue().isEmpty()); } }; nodeLogger = new NodeLogger(node); dataUpdateTimer = new Timer(); dataUpdateTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { // If there is connection and the timer can work. if (timerEnabled.get() && node.getChannel() != null && node.getChannel().isConnected()) { // The copy of the signals to send must be isolated final Set<Signal> signalsCopy = new HashSet<>(); synchronized (node.getToDistributeSignals()) { signalsCopy.addAll(node.getToDistributeSignals()); <MASK>node.getToDistributeSignals().clear();</MASK> } if (signalsCopy.size() > 0) { // TODO: DRY this references if possible List<Address> allMembersButMyself = Lists .newArrayList(node.getAliveNodes()); allMembersButMyself.remove(node.getAddress()); // TODO: Take this out. Multimap<Address, Signal> copyOfBackupSignals = null; synchronized (node.getBackupSignals()) { copyOfBackupSignals = HashMultimap.create(); } nodeLogger.log("Updating my new nodes..."); // This synchronized might be a bit too much. synchronized (node) { syncMembers( Lists.newArrayList(allMembersButMyself), Lists.newArrayList(node.getAliveNodes()), signalsCopy, copyOfBackupSignals); } if (node.getToDistributeSignals().isEmpty() && node.getListener() != null) { node.getListener().onNodeSyncDone(); } } } } catch (Exception e) { e.printStackTrace(); } } }, 0, 1000); }"
Inversion-Mutation
megadiff
"@Override public void run() { try { // If there is connection and the timer can work. if (timerEnabled.get() && node.getChannel() != null && node.getChannel().isConnected()) { // The copy of the signals to send must be isolated final Set<Signal> signalsCopy = new HashSet<>(); synchronized (node.getToDistributeSignals()) { signalsCopy.addAll(node.getToDistributeSignals()); } if (signalsCopy.size() > 0) { // TODO: DRY this references if possible List<Address> allMembersButMyself = Lists .newArrayList(node.getAliveNodes()); allMembersButMyself.remove(node.getAddress()); // TODO: Take this out. Multimap<Address, Signal> copyOfBackupSignals = null; synchronized (node.getBackupSignals()) { copyOfBackupSignals = HashMultimap.create(); } nodeLogger.log("Updating my new nodes..."); // This synchronized might be a bit too much. synchronized (node) { syncMembers( Lists.newArrayList(allMembersButMyself), Lists.newArrayList(node.getAliveNodes()), signalsCopy, copyOfBackupSignals); node.getToDistributeSignals().clear(); } if (node.getToDistributeSignals().isEmpty() && node.getListener() != null) { node.getListener().onNodeSyncDone(); } } } } catch (Exception e) { e.printStackTrace(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"@Override public void run() { try { // If there is connection and the timer can work. if (timerEnabled.get() && node.getChannel() != null && node.getChannel().isConnected()) { // The copy of the signals to send must be isolated final Set<Signal> signalsCopy = new HashSet<>(); synchronized (node.getToDistributeSignals()) { signalsCopy.addAll(node.getToDistributeSignals()); <MASK>node.getToDistributeSignals().clear();</MASK> } if (signalsCopy.size() > 0) { // TODO: DRY this references if possible List<Address> allMembersButMyself = Lists .newArrayList(node.getAliveNodes()); allMembersButMyself.remove(node.getAddress()); // TODO: Take this out. Multimap<Address, Signal> copyOfBackupSignals = null; synchronized (node.getBackupSignals()) { copyOfBackupSignals = HashMultimap.create(); } nodeLogger.log("Updating my new nodes..."); // This synchronized might be a bit too much. synchronized (node) { syncMembers( Lists.newArrayList(allMembersButMyself), Lists.newArrayList(node.getAliveNodes()), signalsCopy, copyOfBackupSignals); } if (node.getToDistributeSignals().isEmpty() && node.getListener() != null) { node.getListener().onNodeSyncDone(); } } } } catch (Exception e) { e.printStackTrace(); } }"
Inversion-Mutation
megadiff
"protected void doCopyToCimi(final CimiContext context, final Credentials dataService, final CimiCredentials dataCimi) { this.fill(context, dataService, dataCimi); if (true == context.mustBeExpanded(dataCimi)) { dataCimi.setUserName(dataService.getUserName()); dataCimi.setKey(dataService.getPublicKey()); // Next write only if (true == context.isConvertedWriteOnly()) { dataCimi.setPassword(dataService.getPassword()); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doCopyToCimi"
"protected void doCopyToCimi(final CimiContext context, final Credentials dataService, final CimiCredentials dataCimi) { this.fill(context, dataService, dataCimi); if (true == context.mustBeExpanded(dataCimi)) { dataCimi.setUserName(dataService.getUserName()); // Next write only if (true == context.isConvertedWriteOnly()) { <MASK>dataCimi.setKey(dataService.getPublicKey());</MASK> dataCimi.setPassword(dataService.getPassword()); } } }"
Inversion-Mutation
megadiff
"public void draw(SpriteBatch batch, FringeLayer layer, float delta) { layer.begin(); for (ClientEntity e : entities) { layer.renderTill(batch, e.getEntity().getY()); e.getView().draw(batch, e, delta); } layer.end(batch); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "draw"
"public void draw(SpriteBatch batch, FringeLayer layer, float delta) { layer.begin(); for (ClientEntity e : entities) { <MASK>e.getView().draw(batch, e, delta);</MASK> layer.renderTill(batch, e.getEntity().getY()); } layer.end(batch); }"
Inversion-Mutation
megadiff
"public boolean addAccount(SipProfile profile) throws SameThreadException { int status = pjsuaConstants.PJ_FALSE; if (!created) { Log.e(THIS_FILE, "PJSIP is not started here, nothing can be done"); return status == pjsuaConstants.PJ_SUCCESS; } PjSipAccount account = new PjSipAccount(profile); account.applyExtraParams(service); // Force the use of a transport /* * switch (account.transport) { case SipProfile.TRANSPORT_UDP: if * (udpTranportId != null) { * //account.cfg.setTransport_id(udpTranportId); } break; case * SipProfile.TRANSPORT_TCP: if (tcpTranportId != null) { // * account.cfg.setTransport_id(tcpTranportId); } break; case * SipProfile.TRANSPORT_TLS: if (tlsTransportId != null) { // * account.cfg.setTransport_id(tlsTransportId); } break; default: break; * } */ SipProfileState currentAccountStatus = getProfileState(profile); account.cfg.setRegister_on_acc_add(pjsuaConstants.PJ_FALSE); if (currentAccountStatus.isAddedToStack()) { pjsua.csipsimple_set_acc_user_data(currentAccountStatus.getPjsuaId(), account.css_cfg); status = pjsua.acc_modify(currentAccountStatus.getPjsuaId(), account.cfg); beforeAccountRegistration(currentAccountStatus.getPjsuaId(), profile); ContentValues cv = new ContentValues(); cv.put(SipProfileState.ADDED_STATUS, status); service.getContentResolver().update( ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, profile.id), cv, null, null); if (!account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) { // Re register if (status == pjsuaConstants.PJ_SUCCESS) { status = pjsua.acc_set_registration(currentAccountStatus.getPjsuaId(), 1); if (status == pjsuaConstants.PJ_SUCCESS) { pjsua.acc_set_online_status(currentAccountStatus.getPjsuaId(), 1); } } } } else { int[] accId = new int[1]; if (account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) { // We already have local account by default // For now consider we are talking about UDP one // In the future local account should be set per transport switch (account.transport) { case SipProfile.TRANSPORT_UDP: accId[0] = prefsWrapper.useIPv6() ? localUdp6AccPjId : localUdpAccPjId; break; case SipProfile.TRANSPORT_TCP: accId[0] = prefsWrapper.useIPv6() ? localTcp6AccPjId : localTcpAccPjId; break; case SipProfile.TRANSPORT_TLS: accId[0] = prefsWrapper.useIPv6() ? localTls6AccPjId : localTlsAccPjId; break; default: // By default use UDP accId[0] = localUdpAccPjId; break; } pjsua.csipsimple_set_acc_user_data(accId[0], account.css_cfg); // TODO : use video cfg here // nCfg.setVid_in_auto_show(pjsuaConstants.PJ_TRUE); // nCfg.setVid_out_auto_transmit(pjsuaConstants.PJ_TRUE); // status = pjsua.acc_modify(accId[0], nCfg); } else { // Cause of standard account different from local account :) status = pjsua.acc_add(account.cfg, pjsuaConstants.PJ_FALSE, accId); pjsua.csipsimple_set_acc_user_data(accId[0], account.css_cfg); beforeAccountRegistration(accId[0], profile); pjsua.acc_set_registration(accId[0], 1); } if (status == pjsuaConstants.PJ_SUCCESS) { SipProfileState ps = new SipProfileState(profile); ps.setAddedStatus(status); ps.setPjsuaId(accId[0]); service.getContentResolver().insert( ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, account.id), ps.getAsContentValue()); pjsua.acc_set_online_status(accId[0], 1); } } return status == pjsuaConstants.PJ_SUCCESS; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addAccount"
"public boolean addAccount(SipProfile profile) throws SameThreadException { int status = pjsuaConstants.PJ_FALSE; if (!created) { Log.e(THIS_FILE, "PJSIP is not started here, nothing can be done"); return status == pjsuaConstants.PJ_SUCCESS; } PjSipAccount account = new PjSipAccount(profile); account.applyExtraParams(service); // Force the use of a transport /* * switch (account.transport) { case SipProfile.TRANSPORT_UDP: if * (udpTranportId != null) { * //account.cfg.setTransport_id(udpTranportId); } break; case * SipProfile.TRANSPORT_TCP: if (tcpTranportId != null) { // * account.cfg.setTransport_id(tcpTranportId); } break; case * SipProfile.TRANSPORT_TLS: if (tlsTransportId != null) { // * account.cfg.setTransport_id(tlsTransportId); } break; default: break; * } */ SipProfileState currentAccountStatus = getProfileState(profile); account.cfg.setRegister_on_acc_add(pjsuaConstants.PJ_FALSE); if (currentAccountStatus.isAddedToStack()) { pjsua.csipsimple_set_acc_user_data(currentAccountStatus.getPjsuaId(), account.css_cfg); status = pjsua.acc_modify(currentAccountStatus.getPjsuaId(), account.cfg); beforeAccountRegistration(currentAccountStatus.getPjsuaId(), profile); ContentValues cv = new ContentValues(); cv.put(SipProfileState.ADDED_STATUS, status); service.getContentResolver().update( ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, profile.id), cv, null, null); if (!account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) { // Re register if (status == pjsuaConstants.PJ_SUCCESS) { status = pjsua.acc_set_registration(currentAccountStatus.getPjsuaId(), 1); if (status == pjsuaConstants.PJ_SUCCESS) { pjsua.acc_set_online_status(currentAccountStatus.getPjsuaId(), 1); } } } } else { int[] accId = new int[1]; if (account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) { // We already have local account by default // For now consider we are talking about UDP one // In the future local account should be set per transport switch (account.transport) { case SipProfile.TRANSPORT_UDP: accId[0] = prefsWrapper.useIPv6() ? localUdp6AccPjId : localUdpAccPjId; break; case SipProfile.TRANSPORT_TCP: accId[0] = prefsWrapper.useIPv6() ? localTcp6AccPjId : localTcpAccPjId; break; case SipProfile.TRANSPORT_TLS: accId[0] = prefsWrapper.useIPv6() ? localTls6AccPjId : localTlsAccPjId; break; default: // By default use UDP accId[0] = localUdpAccPjId; break; } <MASK>pjsua.csipsimple_set_acc_user_data(accId[0], account.css_cfg);</MASK> // TODO : use video cfg here // nCfg.setVid_in_auto_show(pjsuaConstants.PJ_TRUE); // nCfg.setVid_out_auto_transmit(pjsuaConstants.PJ_TRUE); // status = pjsua.acc_modify(accId[0], nCfg); } else { // Cause of standard account different from local account :) <MASK>pjsua.csipsimple_set_acc_user_data(accId[0], account.css_cfg);</MASK> status = pjsua.acc_add(account.cfg, pjsuaConstants.PJ_FALSE, accId); beforeAccountRegistration(accId[0], profile); pjsua.acc_set_registration(accId[0], 1); } if (status == pjsuaConstants.PJ_SUCCESS) { SipProfileState ps = new SipProfileState(profile); ps.setAddedStatus(status); ps.setPjsuaId(accId[0]); service.getContentResolver().insert( ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, account.id), ps.getAsContentValue()); pjsua.acc_set_online_status(accId[0], 1); } } return status == pjsuaConstants.PJ_SUCCESS; }"
Inversion-Mutation
megadiff
"@Override public void synchronizeActiveTasks(final boolean manual, final SyncResultCallback callback) { callback.started(); callback.incrementMax(100); gtasksPreferenceService.recordSyncStart(); new Thread(new Runnable() { public void run() { callback.incrementProgress(50); String authToken = getValidatedAuthToken(); final GtasksInvoker invoker = new GtasksInvoker(authToken); try { gtasksListService.updateLists(invoker.allGtaskLists()); } catch (GoogleTasksException e) { handler.handleException("gtasks-sync=io", e, e.getType()); //$NON-NLS-1$ } catch (IOException e) { handler.handleException("gtasks-sync=io", e, e.toString()); //$NON-NLS-1$ } StoreObject[] lists = gtasksListService.getLists(); if (lists.length == 0) { finishSync(callback); return; } callback.incrementMax(25 * lists.length); final AtomicInteger finisher = new AtomicInteger(lists.length); for (final StoreObject list : lists) { new Thread(new Runnable() { @Override public void run() { synchronizeListHelper(list, invoker, manual, handler, callback); callback.incrementProgress(25); if (finisher.decrementAndGet() == 0) { pushUpdated(invoker, callback); finishSync(callback); } } }).start(); } } }).start(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "synchronizeActiveTasks"
"@Override public void synchronizeActiveTasks(final boolean manual, final SyncResultCallback callback) { callback.started(); callback.incrementMax(100); gtasksPreferenceService.recordSyncStart(); new Thread(new Runnable() { public void run() { callback.incrementProgress(50); String authToken = getValidatedAuthToken(); final GtasksInvoker invoker = new GtasksInvoker(authToken); try { gtasksListService.updateLists(invoker.allGtaskLists()); } catch (GoogleTasksException e) { handler.handleException("gtasks-sync=io", e, e.getType()); //$NON-NLS-1$ } catch (IOException e) { handler.handleException("gtasks-sync=io", e, e.toString()); //$NON-NLS-1$ } StoreObject[] lists = gtasksListService.getLists(); if (lists.length == 0) { finishSync(callback); return; } callback.incrementMax(25 * lists.length); final AtomicInteger finisher = new AtomicInteger(lists.length); for (final StoreObject list : lists) { new Thread(new Runnable() { @Override public void run() { synchronizeListHelper(list, invoker, manual, handler, callback); callback.incrementProgress(25); if (finisher.decrementAndGet() == 0) { finishSync(callback); } } }).start(); } <MASK>pushUpdated(invoker, callback);</MASK> } }).start(); }"
Inversion-Mutation
megadiff
"public void run() { callback.incrementProgress(50); String authToken = getValidatedAuthToken(); final GtasksInvoker invoker = new GtasksInvoker(authToken); try { gtasksListService.updateLists(invoker.allGtaskLists()); } catch (GoogleTasksException e) { handler.handleException("gtasks-sync=io", e, e.getType()); //$NON-NLS-1$ } catch (IOException e) { handler.handleException("gtasks-sync=io", e, e.toString()); //$NON-NLS-1$ } StoreObject[] lists = gtasksListService.getLists(); if (lists.length == 0) { finishSync(callback); return; } callback.incrementMax(25 * lists.length); final AtomicInteger finisher = new AtomicInteger(lists.length); for (final StoreObject list : lists) { new Thread(new Runnable() { @Override public void run() { synchronizeListHelper(list, invoker, manual, handler, callback); callback.incrementProgress(25); if (finisher.decrementAndGet() == 0) { pushUpdated(invoker, callback); finishSync(callback); } } }).start(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { callback.incrementProgress(50); String authToken = getValidatedAuthToken(); final GtasksInvoker invoker = new GtasksInvoker(authToken); try { gtasksListService.updateLists(invoker.allGtaskLists()); } catch (GoogleTasksException e) { handler.handleException("gtasks-sync=io", e, e.getType()); //$NON-NLS-1$ } catch (IOException e) { handler.handleException("gtasks-sync=io", e, e.toString()); //$NON-NLS-1$ } StoreObject[] lists = gtasksListService.getLists(); if (lists.length == 0) { finishSync(callback); return; } callback.incrementMax(25 * lists.length); final AtomicInteger finisher = new AtomicInteger(lists.length); for (final StoreObject list : lists) { new Thread(new Runnable() { @Override public void run() { synchronizeListHelper(list, invoker, manual, handler, callback); callback.incrementProgress(25); if (finisher.decrementAndGet() == 0) { finishSync(callback); } } }).start(); } <MASK>pushUpdated(invoker, callback);</MASK> }"
Inversion-Mutation
megadiff
"public void doAssignedWork() { logger.finest("Entering method doAssignedWork."); if (workLeft > 0) { if (state == UnitState.IMPROVING) { // Has the improvement been completed already? Do nothing. if (getWorkImprovement().isComplete()) { setState(UnitState.ACTIVE); return; } // Otherwise do work int amountOfWork = unitType.hasAbility("model.ability.expertPioneer") ? 2 : 1; workLeft = getWorkImprovement().doWork(amountOfWork); // Make sure that a hardy pioneer will finish if the workLeft is // less than he can do in a turn if (0 < workLeft && workLeft < amountOfWork){ workLeft = getWorkImprovement().doWork(workLeft); } } else { workLeft--; } // Shorter travel time to America for the REF: if (state == UnitState.TO_AMERICA && getOwner().isREF()) { workLeft = 0; } if (workLeft == 0) { workLeft = -1; UnitState state = getState(); switch (state) { case TO_EUROPE: // trade unit arrives in Europe if(this.getTradeRoute() != null){ setMovesLeft(0); setState(UnitState.ACTIVE); return; } addModelMessage(getOwner().getEurope(), ModelMessage.MessageType.DEFAULT, this, "model.unit.arriveInEurope", "%europe%", getOwner().getEurope().getName()); setState(UnitState.ACTIVE); ArrayList<Unit> unitList = new ArrayList<Unit>(getUnitList()); for (Unit u : unitList) { if (u.canCarryTreasure()) { u.cashInTreasureTrain(); } } break; case TO_AMERICA: getGame().getModelController().setToVacantEntryLocation(this); setState(UnitState.ACTIVE); break; case FORTIFYING: setState(UnitState.FORTIFIED); break; case IMPROVING: expendEquipment(getWorkImprovement().getExpendedEquipmentType(), getWorkImprovement().getExpendedAmount()); // Deliver Goods if any GoodsType deliverType = getWorkImprovement().getDeliverGoodsType(); if (deliverType != null) { int deliverAmount = getTile().potential(deliverType) * getWorkImprovement().getDeliverAmount(); if (unitType.hasAbility("model.ability.expertPioneer")) { deliverAmount *= 2; } if (getColony() != null && getColony().getOwner().equals(getOwner())) { getColony().addGoods(deliverType, deliverAmount); } else { List<Tile> surroundingTiles = getTile().getMap().getSurroundingTiles(getTile(), 1); List<Settlement> adjacentColonies = new ArrayList<Settlement>(); for (int i = 0; i < surroundingTiles.size(); i++) { Tile t = surroundingTiles.get(i); if (t.getColony() != null && t.getColony().getOwner().equals(getOwner())) { adjacentColonies.add(t.getColony()); } } if (adjacentColonies.size() > 0) { int deliverPerCity = (deliverAmount / adjacentColonies.size()); for (int i = 0; i < adjacentColonies.size(); i++) { Colony c = (Colony) adjacentColonies.get(i); // Make sure the lumber lost is being added // again to the first adjacent colony: if (i == 0) { c.addGoods(deliverType, deliverPerCity + (deliverAmount % adjacentColonies.size())); } else { c.addGoods(deliverType, deliverPerCity); } } } } } // Perform TileType change if any TileType changeType = getWorkImprovement().getChange(getTile().getType()); if (changeType != null) { getTile().setType(changeType); } // Finish up setState(UnitState.ACTIVE); setMovesLeft(0); break; default: logger.warning("Unknown work completed. State: " + state); setState(UnitState.ACTIVE); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doAssignedWork"
"public void doAssignedWork() { logger.finest("Entering method doAssignedWork."); if (workLeft > 0) { if (state == UnitState.IMPROVING) { // Has the improvement been completed already? Do nothing. if (getWorkImprovement().isComplete()) { <MASK>setState(UnitState.ACTIVE);</MASK> return; } // Otherwise do work int amountOfWork = unitType.hasAbility("model.ability.expertPioneer") ? 2 : 1; workLeft = getWorkImprovement().doWork(amountOfWork); // Make sure that a hardy pioneer will finish if the workLeft is // less than he can do in a turn if (0 < workLeft && workLeft < amountOfWork){ workLeft = getWorkImprovement().doWork(workLeft); } } else { workLeft--; } // Shorter travel time to America for the REF: if (state == UnitState.TO_AMERICA && getOwner().isREF()) { workLeft = 0; } if (workLeft == 0) { workLeft = -1; UnitState state = getState(); switch (state) { case TO_EUROPE: // trade unit arrives in Europe if(this.getTradeRoute() != null){ setMovesLeft(0); <MASK>setState(UnitState.ACTIVE);</MASK> return; } addModelMessage(getOwner().getEurope(), ModelMessage.MessageType.DEFAULT, this, "model.unit.arriveInEurope", "%europe%", getOwner().getEurope().getName()); ArrayList<Unit> unitList = new ArrayList<Unit>(getUnitList()); for (Unit u : unitList) { if (u.canCarryTreasure()) { u.cashInTreasureTrain(); } } <MASK>setState(UnitState.ACTIVE);</MASK> break; case TO_AMERICA: getGame().getModelController().setToVacantEntryLocation(this); <MASK>setState(UnitState.ACTIVE);</MASK> break; case FORTIFYING: setState(UnitState.FORTIFIED); break; case IMPROVING: expendEquipment(getWorkImprovement().getExpendedEquipmentType(), getWorkImprovement().getExpendedAmount()); // Deliver Goods if any GoodsType deliverType = getWorkImprovement().getDeliverGoodsType(); if (deliverType != null) { int deliverAmount = getTile().potential(deliverType) * getWorkImprovement().getDeliverAmount(); if (unitType.hasAbility("model.ability.expertPioneer")) { deliverAmount *= 2; } if (getColony() != null && getColony().getOwner().equals(getOwner())) { getColony().addGoods(deliverType, deliverAmount); } else { List<Tile> surroundingTiles = getTile().getMap().getSurroundingTiles(getTile(), 1); List<Settlement> adjacentColonies = new ArrayList<Settlement>(); for (int i = 0; i < surroundingTiles.size(); i++) { Tile t = surroundingTiles.get(i); if (t.getColony() != null && t.getColony().getOwner().equals(getOwner())) { adjacentColonies.add(t.getColony()); } } if (adjacentColonies.size() > 0) { int deliverPerCity = (deliverAmount / adjacentColonies.size()); for (int i = 0; i < adjacentColonies.size(); i++) { Colony c = (Colony) adjacentColonies.get(i); // Make sure the lumber lost is being added // again to the first adjacent colony: if (i == 0) { c.addGoods(deliverType, deliverPerCity + (deliverAmount % adjacentColonies.size())); } else { c.addGoods(deliverType, deliverPerCity); } } } } } // Perform TileType change if any TileType changeType = getWorkImprovement().getChange(getTile().getType()); if (changeType != null) { getTile().setType(changeType); } // Finish up <MASK>setState(UnitState.ACTIVE);</MASK> setMovesLeft(0); break; default: logger.warning("Unknown work completed. State: " + state); <MASK>setState(UnitState.ACTIVE);</MASK> } } } }"
Inversion-Mutation
megadiff
"public void indexFile(SourceFile squidFile, File sonarFile) { if (canIndexFiles) { LOG.debug("C# BRIDGE is indexing {}:", squidFile.getKey()); indexChildren(squidFile.getChildren(), sonarFile); } else { throw new IllegalStateException( "The CSharpResourcesBridge has been locked to prevent future modifications. It is impossible to index new files."); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "indexFile"
"public void indexFile(SourceFile squidFile, File sonarFile) { <MASK>LOG.debug("C# BRIDGE is indexing {}:", squidFile.getKey());</MASK> if (canIndexFiles) { indexChildren(squidFile.getChildren(), sonarFile); } else { throw new IllegalStateException( "The CSharpResourcesBridge has been locked to prevent future modifications. It is impossible to index new files."); } }"
Inversion-Mutation
megadiff
"@SuppressWarnings("unchecked") public PacketHandler() { try { final List<ClassInfo> classes = new ArrayList<ClassInfo>(ClassPath .from(this.getClass().getClassLoader()).getTopLevelClasses( "logisticspipes.network.packets")); Collections.sort(classes, new Comparator<ClassInfo>() { @Override public int compare(ClassInfo o1, ClassInfo o2) { return o1.getSimpleName().compareTo(o2.getSimpleName()); } }); packetlist = new ArrayList<ModernPacket>(classes.size()); packetmap = new HashMap<Class<? extends ModernPacket>, ModernPacket>( classes.size()); int currentid = 200;// TODO: Only 200 until all packets get // converted System.out.println("Loading " + classes.size() + " Packets"); for (ClassInfo c : classes) { try { final Class<?> cls = c.load(); final ModernPacket instance = (ModernPacket) cls .getConstructors()[0].newInstance(currentid); packetlist.add(instance); packetmap .put((Class<? extends ModernPacket>) cls, instance); System.out.println("Packet: " + c.getSimpleName() + " loaded"); } catch (NoClassDefFoundError e) { System.out.println("Not loading packet " + c.getSimpleName() + " (it is probably a client-side packet)"); packetlist.add(null); } currentid++; } } catch (Throwable e) { throw new RuntimeException(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "PacketHandler"
"@SuppressWarnings("unchecked") public PacketHandler() { try { final List<ClassInfo> classes = new ArrayList<ClassInfo>(ClassPath .from(this.getClass().getClassLoader()).getTopLevelClasses( "logisticspipes.network.packets")); Collections.sort(classes, new Comparator<ClassInfo>() { @Override public int compare(ClassInfo o1, ClassInfo o2) { return o1.getSimpleName().compareTo(o2.getSimpleName()); } }); packetlist = new ArrayList<ModernPacket>(classes.size()); packetmap = new HashMap<Class<? extends ModernPacket>, ModernPacket>( classes.size()); int currentid = 200;// TODO: Only 200 until all packets get // converted System.out.println("Loading " + classes.size() + " Packets"); for (ClassInfo c : classes) { <MASK>currentid++;</MASK> try { final Class<?> cls = c.load(); final ModernPacket instance = (ModernPacket) cls .getConstructors()[0].newInstance(currentid); packetlist.add(instance); packetmap .put((Class<? extends ModernPacket>) cls, instance); System.out.println("Packet: " + c.getSimpleName() + " loaded"); } catch (NoClassDefFoundError e) { System.out.println("Not loading packet " + c.getSimpleName() + " (it is probably a client-side packet)"); packetlist.add(null); } } } catch (Throwable e) { throw new RuntimeException(e); } }"
Inversion-Mutation
megadiff
"public static void exportConfig(String url) { try { FileConnection con = (FileConnection)Connector.open(url); if (!con.exists()) { con.create(); } Configuration.serialise(con.openOutputStream()); String name = con.getName(); con.close(); GpsMid.getInstance().alert(Locale.get("generic.Info")/*Info*/, Locale.get("guidiscover.CfgExported", name)/*Configuration exported to '<file>'*/, 3000); } catch (Exception e) { logger.exception(Locale.get("guidiscover.CouldNotSaveCfg")/*Could not save configuration*/ + ": " + e.getMessage(), e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "exportConfig"
"public static void exportConfig(String url) { try { FileConnection con = (FileConnection)Connector.open(url); if (!con.exists()) { con.create(); } Configuration.serialise(con.openOutputStream()); <MASK>con.close();</MASK> String name = con.getName(); GpsMid.getInstance().alert(Locale.get("generic.Info")/*Info*/, Locale.get("guidiscover.CfgExported", name)/*Configuration exported to '<file>'*/, 3000); } catch (Exception e) { logger.exception(Locale.get("guidiscover.CouldNotSaveCfg")/*Could not save configuration*/ + ": " + e.getMessage(), e); } }"
Inversion-Mutation
megadiff
"@Override protected View onCreateDialogView() { LinearLayout.LayoutParams params; LinearLayout layout = new LinearLayout(mContext); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(6, 6, 6, 6); mValueText = new TextView(mContext); mValueText.setGravity(Gravity.CENTER_HORIZONTAL); mValueText.setTextSize(32); params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layout.addView(mValueText, params); mSeekBar = new SeekBar(mContext); mSeekBar.setOnSeekBarChangeListener(this); layout.addView(mSeekBar, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); if (shouldPersist()) { mValue = getPersistedInt(mDefault); } mSeekBar.setProgress((int) ((mValue - mMin) / mInterval)); mSeekBar.setMax((int) ((mMax - mMin) / mInterval)); String t = String.valueOf(mValue); mValueText.setText(mSuffix == null ? t : t.concat(mSuffix)); return layout; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreateDialogView"
"@Override protected View onCreateDialogView() { LinearLayout.LayoutParams params; LinearLayout layout = new LinearLayout(mContext); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(6, 6, 6, 6); mValueText = new TextView(mContext); mValueText.setGravity(Gravity.CENTER_HORIZONTAL); mValueText.setTextSize(32); params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layout.addView(mValueText, params); mSeekBar = new SeekBar(mContext); mSeekBar.setOnSeekBarChangeListener(this); layout.addView(mSeekBar, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); if (shouldPersist()) { mValue = getPersistedInt(mDefault); } <MASK>mSeekBar.setMax((int) ((mMax - mMin) / mInterval));</MASK> mSeekBar.setProgress((int) ((mValue - mMin) / mInterval)); String t = String.valueOf(mValue); mValueText.setText(mSuffix == null ? t : t.concat(mSuffix)); return layout; }"
Inversion-Mutation
megadiff
"@Override public void remove() { if (!mEntryValid) { throw new IllegalStateException(); } colRemoveAt(mIndex); mIndex--; mEnd--; mEntryValid = false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "remove"
"@Override public void remove() { if (!mEntryValid) { throw new IllegalStateException(); } mIndex--; mEnd--; mEntryValid = false; <MASK>colRemoveAt(mIndex);</MASK> }"
Inversion-Mutation
megadiff
"private void createCoverMenu() { coverMenu = new JPopupMenu(); JMenuItem replaceCoverItem = new JMenuItem("Add/Replace Cover..."); replaceCoverItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MP3File mp3 = getSelectedMP3(); if(mp3 != null){ JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(new AllImagesFileFilter()); if(fileChooser.showOpenDialog(ID3View.this) == JFileChooser.APPROVE_OPTION){ File file = fileChooser.getSelectedFile(); ID3Parser.readCoverFromFile(mp3, file); coverContainer.setIcon(new ImageIcon(mp3.getCover())); coverContainer.setText(""); } } } }); JMenuItem deleteCoverItem = new JMenuItem("Delete Cover"); deleteCoverItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MP3File mp3 = getSelectedMP3(); if(mp3 != null){ mp3.deleteCover(); updateDetailForm(); } } }); coverMenu.add(replaceCoverItem); coverMenu.add(deleteCoverItem); coverContainer.setComponentPopupMenu(coverMenu); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createCoverMenu"
"private void createCoverMenu() { coverMenu = new JPopupMenu(); JMenuItem replaceCoverItem = new JMenuItem("Add/Replace Cover..."); replaceCoverItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MP3File mp3 = getSelectedMP3(); if(mp3 != null){ JFileChooser fileChooser = new JFileChooser(); <MASK>fileChooser.setFileFilter(new AllImagesFileFilter());</MASK> fileChooser.setAcceptAllFileFilterUsed(false); if(fileChooser.showOpenDialog(ID3View.this) == JFileChooser.APPROVE_OPTION){ File file = fileChooser.getSelectedFile(); ID3Parser.readCoverFromFile(mp3, file); coverContainer.setIcon(new ImageIcon(mp3.getCover())); coverContainer.setText(""); } } } }); JMenuItem deleteCoverItem = new JMenuItem("Delete Cover"); deleteCoverItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MP3File mp3 = getSelectedMP3(); if(mp3 != null){ mp3.deleteCover(); updateDetailForm(); } } }); coverMenu.add(replaceCoverItem); coverMenu.add(deleteCoverItem); coverContainer.setComponentPopupMenu(coverMenu); }"
Inversion-Mutation
megadiff
"@Override public void actionPerformed(ActionEvent e) { MP3File mp3 = getSelectedMP3(); if(mp3 != null){ JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(new AllImagesFileFilter()); if(fileChooser.showOpenDialog(ID3View.this) == JFileChooser.APPROVE_OPTION){ File file = fileChooser.getSelectedFile(); ID3Parser.readCoverFromFile(mp3, file); coverContainer.setIcon(new ImageIcon(mp3.getCover())); coverContainer.setText(""); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed"
"@Override public void actionPerformed(ActionEvent e) { MP3File mp3 = getSelectedMP3(); if(mp3 != null){ JFileChooser fileChooser = new JFileChooser(); <MASK>fileChooser.setFileFilter(new AllImagesFileFilter());</MASK> fileChooser.setAcceptAllFileFilterUsed(false); if(fileChooser.showOpenDialog(ID3View.this) == JFileChooser.APPROVE_OPTION){ File file = fileChooser.getSelectedFile(); ID3Parser.readCoverFromFile(mp3, file); coverContainer.setIcon(new ImageIcon(mp3.getCover())); coverContainer.setText(""); } } }"
Inversion-Mutation
megadiff
"public boolean performItemClick(View view, int position, long id) { if (mOnItemClickListener != null) { if (view != null) { view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); } mOnItemClickListener.onItemClick(this, view, position, id); playSoundEffect(SoundEffectConstants.CLICK); return true; } return false; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performItemClick"
"public boolean performItemClick(View view, int position, long id) { if (mOnItemClickListener != null) { <MASK>playSoundEffect(SoundEffectConstants.CLICK);</MASK> if (view != null) { view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); } mOnItemClickListener.onItemClick(this, view, position, id); return true; } return false; }"
Inversion-Mutation
megadiff
"private void call(String procUri, CallMeta resultMeta, Object... arguments) { WampMessage.Call call = new WampMessage.Call(newId(), procUri, arguments.length); for (int i = 0; i < arguments.length; ++i) { call.mArgs[i] = arguments[i]; } mCalls.put(call.mCallId, resultMeta); mWriter.forward(call); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "call"
"private void call(String procUri, CallMeta resultMeta, Object... arguments) { WampMessage.Call call = new WampMessage.Call(newId(), procUri, arguments.length); for (int i = 0; i < arguments.length; ++i) { call.mArgs[i] = arguments[i]; } <MASK>mWriter.forward(call);</MASK> mCalls.put(call.mCallId, resultMeta); }"
Inversion-Mutation
megadiff
"public AnyViewParameters handle() { try { final String actionmethod = PostDecoder.decodeAction(normalizedmap); // Do this FIRST in case it discovers any scopelocks required presmanager.scopeRestore(); // invoke all state-altering operations within the runnable wrapper. postwrapper.invokeRunnable(new Runnable() { public void run() { if (viewparams.flowtoken != null) { presmanager.restore(viewparams.flowtoken, viewparams.endflow != null); } Exception exception = null; try { rsvcapplier.applyValues(requestrsvc); // many errors possible here. } catch (Exception e) { exception = e; } Object newcode = handleError(actionresult, exception); exception = null; if ((newcode == null && !messages.isError()) || newcode instanceof String) { // only proceed to actually invoke action if no ARIResult already // note all this odd two-step procedure is only required to be able // to pass AES error returns and make them "appear" to be the // returns of the first action method in a Flow. try { if (actionmethod != null) { actionresult = rsvcapplier.invokeAction(actionmethod, (String) newcode); } } catch (Exception e) { exception = e; } newcode = handleError(actionresult, exception); } if (newcode != null) actionresult = newcode; // must interpret ARI INSIDE the wrapper, since it may need it // on closure. if (actionresult instanceof ARIResult) { ariresult = (ARIResult) actionresult; } else { ActionResultInterpreter ari = ariresolver .getActionResultInterpreter(); ariresult = ari.interpretActionResult(viewparams, actionresult); } arinterceptor.interceptActionResult(ariresult, viewparams, actionresult); } }); presmanager.scopePreserve(); flowstatemanager.inferFlowState(viewparams, ariresult); // moved inside since this may itself cause an error! String submitting = PostDecoder.decodeSubmittingControl(normalizedmap); errorstatemanager.globaltargetid = submitting; } catch (Throwable e) { // avoid masking errors from the finally block Logger.log.error("Error invoking action", e); // ThreadErrorState.addError(new TargettedMessage( // CoreMessages.GENERAL_ACTION_ERROR)); // Detect failure to fill out arires properly. if (ariresult == null || ariresult.resultingView == null || e instanceof IllegalStateException) { ariresult = new ARIResult(); ariresult.propagateBeans = ARIResult.FLOW_END; ViewParameters defaultparameters = viewparams.copyBase(); ariresult.resultingView = defaultparameters; } } finally { String errortoken = errorstatemanager.requestComplete(); if (ariresult.resultingView instanceof ViewParameters) { ((ViewParameters) ariresult.resultingView).errortoken = errortoken; } } return ariresult.resultingView; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handle"
"public AnyViewParameters handle() { <MASK>final String actionmethod = PostDecoder.decodeAction(normalizedmap);</MASK> try { // Do this FIRST in case it discovers any scopelocks required presmanager.scopeRestore(); // invoke all state-altering operations within the runnable wrapper. postwrapper.invokeRunnable(new Runnable() { public void run() { if (viewparams.flowtoken != null) { presmanager.restore(viewparams.flowtoken, viewparams.endflow != null); } Exception exception = null; try { rsvcapplier.applyValues(requestrsvc); // many errors possible here. } catch (Exception e) { exception = e; } Object newcode = handleError(actionresult, exception); exception = null; if ((newcode == null && !messages.isError()) || newcode instanceof String) { // only proceed to actually invoke action if no ARIResult already // note all this odd two-step procedure is only required to be able // to pass AES error returns and make them "appear" to be the // returns of the first action method in a Flow. try { if (actionmethod != null) { actionresult = rsvcapplier.invokeAction(actionmethod, (String) newcode); } } catch (Exception e) { exception = e; } newcode = handleError(actionresult, exception); } if (newcode != null) actionresult = newcode; // must interpret ARI INSIDE the wrapper, since it may need it // on closure. if (actionresult instanceof ARIResult) { ariresult = (ARIResult) actionresult; } else { ActionResultInterpreter ari = ariresolver .getActionResultInterpreter(); ariresult = ari.interpretActionResult(viewparams, actionresult); } arinterceptor.interceptActionResult(ariresult, viewparams, actionresult); } }); presmanager.scopePreserve(); flowstatemanager.inferFlowState(viewparams, ariresult); // moved inside since this may itself cause an error! String submitting = PostDecoder.decodeSubmittingControl(normalizedmap); errorstatemanager.globaltargetid = submitting; } catch (Throwable e) { // avoid masking errors from the finally block Logger.log.error("Error invoking action", e); // ThreadErrorState.addError(new TargettedMessage( // CoreMessages.GENERAL_ACTION_ERROR)); // Detect failure to fill out arires properly. if (ariresult == null || ariresult.resultingView == null || e instanceof IllegalStateException) { ariresult = new ARIResult(); ariresult.propagateBeans = ARIResult.FLOW_END; ViewParameters defaultparameters = viewparams.copyBase(); ariresult.resultingView = defaultparameters; } } finally { String errortoken = errorstatemanager.requestComplete(); if (ariresult.resultingView instanceof ViewParameters) { ((ViewParameters) ariresult.resultingView).errortoken = errortoken; } } return ariresult.resultingView; }"
Inversion-Mutation
megadiff
"private void stop() { mLibVLC.stop(); mEventManager.removeHandler(mEventHandler); setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED); mCurrentMedia = null; mMediaList.clear(); mPrevious.clear(); mHandler.removeMessages(SHOW_PROGRESS); hideNotification(); executeUpdate(); changeAudioFocus(false); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stop"
"private void stop() { <MASK>mEventManager.removeHandler(mEventHandler);</MASK> mLibVLC.stop(); setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED); mCurrentMedia = null; mMediaList.clear(); mPrevious.clear(); mHandler.removeMessages(SHOW_PROGRESS); hideNotification(); executeUpdate(); changeAudioFocus(false); }"
Inversion-Mutation
megadiff
"final public void argument(ProcedureType procedureType) throws ParseException { String s = null; ArgumentType argumentType = null; DatabaseType argumentDataType = null; ArgumentTypeDirection argDirection = ArgumentTypeDirection.IN; // by default, arguments are IN String direction = null; boolean defaultAssignment = false; s = OracleObjectName(); if (jj_2_7(2)) { direction = direction(); } else { ; } if (jj_2_8(2)) { jj_consume_token(K_NOCOPY); } else { ; } argumentDataType = typeSpec(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case O_ASSIGN: case R_DEFAULT: defaultAssignment = argumentDefaultAssignment(); break; default: ; } argumentType = new ArgumentType(s); argumentType.setEnclosedType(argumentDataType); if (argumentDataType instanceof UnresolvedType) { ((UnresolvedType)argumentDataType).setOwningType(argumentType); } if (direction != null) { if ("OUT".equals(direction)) { argDirection = ArgumentTypeDirection.OUT; } else if ("IN OUT".equals(direction)) { argDirection = ArgumentTypeDirection.INOUT; } } argumentType.setDirection(argDirection); if (defaultAssignment) { argumentType.setOptional(); } procedureType.addArgument(argumentType); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "argument"
"final public void argument(ProcedureType procedureType) throws ParseException { String s = null; ArgumentType argumentType = null; DatabaseType argumentDataType = null; ArgumentTypeDirection argDirection = ArgumentTypeDirection.IN; // by default, arguments are IN String direction = null; boolean defaultAssignment = false; s = OracleObjectName(); if (jj_2_7(2)) { direction = direction(); } else { ; } if (jj_2_8(2)) { jj_consume_token(K_NOCOPY); } else { ; } argumentDataType = typeSpec(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case O_ASSIGN: case R_DEFAULT: defaultAssignment = argumentDefaultAssignment(); break; default: ; } argumentType = new ArgumentType(s); argumentType.setEnclosedType(argumentDataType); if (argumentDataType instanceof UnresolvedType) { ((UnresolvedType)argumentDataType).setOwningType(argumentType); } if (direction != null) { if ("OUT".equals(direction)) { argDirection = ArgumentTypeDirection.OUT; } else if ("IN OUT".equals(direction)) { argDirection = ArgumentTypeDirection.INOUT; } <MASK>argumentType.setDirection(argDirection);</MASK> } if (defaultAssignment) { argumentType.setOptional(); } procedureType.addArgument(argumentType); }"
Inversion-Mutation
megadiff
"public void run() { while (refresh) { world.explore(); try { Thread.sleep(ttr * 1000); } catch (InterruptedException e) { /* Do nothing */ System.out.println( "Ic2d exploring thread has been interupted."); } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { while (refresh) { try { <MASK>world.explore();</MASK> Thread.sleep(ttr * 1000); } catch (InterruptedException e) { /* Do nothing */ System.out.println( "Ic2d exploring thread has been interupted."); } } }"
Inversion-Mutation
megadiff
"public void publish(HttpServletRequest request, HttpServletResponse response, Map<String, String> parameters) throws ServletException, IOException { try { // Retrieve the application responsible for the request List<ColumnOrSuperColumn> application = getApplication(parameters.get("id")); tr.open(); // Reconstruct the API List<Map<String, String>> keyList = null; List<Map<String, String>> valueList = null; for (ColumnOrSuperColumn label : application) { Column column = label.column; String jsonName = new String(column.name, "UTF8"); String jsonValue = new String(column.value, "UTF8"); if (jsonName.contains("keys")) { keyList = new Gson().fromJson( jsonValue, new TypeToken<List<Map<String, String>>>() { }.getType()); } else if (jsonName.contains("values")) { valueList = new Gson().fromJson( jsonValue, new TypeToken<List<Map<String, String>>>() { }.getType()); } } // Get the request parameters and format the values Map<String, String> keys = new HashMap<String, String>(); List<Map<String, String>> values = new ArrayList<Map<String,String>>(); if(keyList != null && valueList != null){ for(Map<String, String> key : keyList){ String name = key.get("name"); keys.put(name, parameters.get(name)); } for(Map<String, String> value : valueList){ String name = value.get("name"); value.put(name, parameters.get(name)); values.add(value); } } // Execute the publish request for(String key : keys.keySet()){ System.out.println(new Gson().toJson(values)); } } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); // } catch (InvalidRequestException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (UnavailableException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (TimedOutException e) { // // TODO Auto-generated catch block // e.printStackTrace(); } finally { tr.close(); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "publish"
"public void publish(HttpServletRequest request, HttpServletResponse response, Map<String, String> parameters) throws ServletException, IOException { try { <MASK>tr.open();</MASK> // Retrieve the application responsible for the request List<ColumnOrSuperColumn> application = getApplication(parameters.get("id")); // Reconstruct the API List<Map<String, String>> keyList = null; List<Map<String, String>> valueList = null; for (ColumnOrSuperColumn label : application) { Column column = label.column; String jsonName = new String(column.name, "UTF8"); String jsonValue = new String(column.value, "UTF8"); if (jsonName.contains("keys")) { keyList = new Gson().fromJson( jsonValue, new TypeToken<List<Map<String, String>>>() { }.getType()); } else if (jsonName.contains("values")) { valueList = new Gson().fromJson( jsonValue, new TypeToken<List<Map<String, String>>>() { }.getType()); } } // Get the request parameters and format the values Map<String, String> keys = new HashMap<String, String>(); List<Map<String, String>> values = new ArrayList<Map<String,String>>(); if(keyList != null && valueList != null){ for(Map<String, String> key : keyList){ String name = key.get("name"); keys.put(name, parameters.get(name)); } for(Map<String, String> value : valueList){ String name = value.get("name"); value.put(name, parameters.get(name)); values.add(value); } } // Execute the publish request for(String key : keys.keySet()){ System.out.println(new Gson().toJson(values)); } } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); // } catch (InvalidRequestException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (UnavailableException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (TimedOutException e) { // // TODO Auto-generated catch block // e.printStackTrace(); } finally { tr.close(); } }"
Inversion-Mutation
megadiff
"@Override public boolean toHTML(StringBuilder sb){ // if(title != null && !title.isEmpty())DocGen.HTML.title(sb,title); if(glm_model == null){ sb.append("No model yet..."); return true; } DocGen.HTML.paragraph(sb,"Model Key: "+glm_model._selfKey); if(glm_model.submodels != null) DocGen.HTML.paragraph(sb,water.api.Predict.link(glm_model._selfKey,"Predict!")); String succ = (glm_model.warnings == null || glm_model.warnings.length == 0)?"alert-success":"alert-warning"; sb.append("<div class='alert " + succ + "'>"); pprintTime(sb.append(glm_model.iteration() + " iterations computed in "),glm_model.run_time); if(glm_model.warnings != null && glm_model.warnings.length > 0){ sb.append("<b>Warnings:</b><ul>"); for(String w:glm_model.warnings)sb.append("<li>" + w + "</li>"); sb.append("</ul>"); } sb.append("</div>"); sb.append("<h4>Parameters</h4>"); parm(sb,"family",glm_model.glm.family); parm(sb,"link",glm_model.glm.link); parm(sb,"&epsilon;<sub>&beta;</sub>",glm_model.beta_eps); parm(sb,"&alpha;",glm_model.alpha); parm(sb,"&lambda;",DFORMAT2.format(lambda)); if(glm_model.submodels.length > 1){ sb.append("\n<table class='table table-bordered table-condensed'>\n"); StringBuilder firstRow = new StringBuilder("\t<tr><th>&lambda;</th>\n"); StringBuilder secondRow = new StringBuilder("\t<tr><th>nonzeros</th>\n"); StringBuilder thirdRow = new StringBuilder("\t<tr><th>Deviance Explained</th>\n"); StringBuilder fourthRow = new StringBuilder("\t<tr><th>" + (glm_model.glm.family == Family.binomial?"AUC":"AIC") + "</th>\n"); for(int i = 0; i < glm_model.submodels.length; ++i){ final Submodel sm = glm_model.submodels[i]; if(sm.validation == null)break; if(glm_model.lambdas[i] == lambda)firstRow.append("\t\t<td><b>" + DFORMAT2.format(glm_model.lambdas[i]) + "</b></td>\n"); else firstRow.append("\t\t<td>" + link(DFORMAT2.format(glm_model.lambdas[i]),glm_model._selfKey,glm_model.lambdas[i]) + "</td>\n"); secondRow.append("\t\t<td>" + (sm.rank-1) + "</td>\n"); thirdRow.append("\t\t<td>" + DFORMAT.format(1-sm.validation.residual_deviance/sm.validation.null_deviance) + "</td>\n"); fourthRow.append("\t\t<td>" + DFORMAT.format(glm_model.glm.family==Family.binomial?sm.validation.auc:sm.validation.aic) + "</td>\n"); } sb.append(firstRow.append("\t</tr>\n")); sb.append(secondRow.append("\t</tr>\n")); sb.append(thirdRow.append("\t</tr>\n")); sb.append(fourthRow.append("\t</tr>\n")); sb.append("</table>\n"); } Submodel sm = glm_model.submodels[glm_model.best_lambda_idx]; if(!Double.isNaN(lambda) && glm_model.lambdas[glm_model.best_lambda_idx] != lambda){ int ii = 0; sm = glm_model.submodels[0]; while(glm_model.lambdas[ii] != lambda && ++ii < glm_model.submodels.length) sm = glm_model.submodels[ii]; if(ii == glm_model.submodels.length)throw new IllegalArgumentException("Unexpected value of lambda '" + lambda + "'"); } if(glm_model.beta() != null) coefs2html(sm,sb); GLMValidation val = sm.validation; if(val != null)val2HTML(sm,val, sb); return true; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "toHTML"
"@Override public boolean toHTML(StringBuilder sb){ // if(title != null && !title.isEmpty())DocGen.HTML.title(sb,title); <MASK>DocGen.HTML.paragraph(sb,"Model Key: "+glm_model._selfKey);</MASK> if(glm_model == null){ sb.append("No model yet..."); return true; } if(glm_model.submodels != null) DocGen.HTML.paragraph(sb,water.api.Predict.link(glm_model._selfKey,"Predict!")); String succ = (glm_model.warnings == null || glm_model.warnings.length == 0)?"alert-success":"alert-warning"; sb.append("<div class='alert " + succ + "'>"); pprintTime(sb.append(glm_model.iteration() + " iterations computed in "),glm_model.run_time); if(glm_model.warnings != null && glm_model.warnings.length > 0){ sb.append("<b>Warnings:</b><ul>"); for(String w:glm_model.warnings)sb.append("<li>" + w + "</li>"); sb.append("</ul>"); } sb.append("</div>"); sb.append("<h4>Parameters</h4>"); parm(sb,"family",glm_model.glm.family); parm(sb,"link",glm_model.glm.link); parm(sb,"&epsilon;<sub>&beta;</sub>",glm_model.beta_eps); parm(sb,"&alpha;",glm_model.alpha); parm(sb,"&lambda;",DFORMAT2.format(lambda)); if(glm_model.submodels.length > 1){ sb.append("\n<table class='table table-bordered table-condensed'>\n"); StringBuilder firstRow = new StringBuilder("\t<tr><th>&lambda;</th>\n"); StringBuilder secondRow = new StringBuilder("\t<tr><th>nonzeros</th>\n"); StringBuilder thirdRow = new StringBuilder("\t<tr><th>Deviance Explained</th>\n"); StringBuilder fourthRow = new StringBuilder("\t<tr><th>" + (glm_model.glm.family == Family.binomial?"AUC":"AIC") + "</th>\n"); for(int i = 0; i < glm_model.submodels.length; ++i){ final Submodel sm = glm_model.submodels[i]; if(sm.validation == null)break; if(glm_model.lambdas[i] == lambda)firstRow.append("\t\t<td><b>" + DFORMAT2.format(glm_model.lambdas[i]) + "</b></td>\n"); else firstRow.append("\t\t<td>" + link(DFORMAT2.format(glm_model.lambdas[i]),glm_model._selfKey,glm_model.lambdas[i]) + "</td>\n"); secondRow.append("\t\t<td>" + (sm.rank-1) + "</td>\n"); thirdRow.append("\t\t<td>" + DFORMAT.format(1-sm.validation.residual_deviance/sm.validation.null_deviance) + "</td>\n"); fourthRow.append("\t\t<td>" + DFORMAT.format(glm_model.glm.family==Family.binomial?sm.validation.auc:sm.validation.aic) + "</td>\n"); } sb.append(firstRow.append("\t</tr>\n")); sb.append(secondRow.append("\t</tr>\n")); sb.append(thirdRow.append("\t</tr>\n")); sb.append(fourthRow.append("\t</tr>\n")); sb.append("</table>\n"); } Submodel sm = glm_model.submodels[glm_model.best_lambda_idx]; if(!Double.isNaN(lambda) && glm_model.lambdas[glm_model.best_lambda_idx] != lambda){ int ii = 0; sm = glm_model.submodels[0]; while(glm_model.lambdas[ii] != lambda && ++ii < glm_model.submodels.length) sm = glm_model.submodels[ii]; if(ii == glm_model.submodels.length)throw new IllegalArgumentException("Unexpected value of lambda '" + lambda + "'"); } if(glm_model.beta() != null) coefs2html(sm,sb); GLMValidation val = sm.validation; if(val != null)val2HTML(sm,val, sb); return true; }"
Inversion-Mutation
megadiff
"@Override public void actionPerformed(ActionEvent actionEvent) { listModel.setMessage("Loading list of data sets... just a moment"); cultureHubClient.fetchDataSetList(new CultureHubClient.ListReceiveListener() { @Override public void listReceived(final List<CultureHubClient.DataSetEntry> entries) { Exec.swing(new Runnable() { @Override public void run() { if (entries == null || entries.isEmpty()) { listModel.setMessage("No data sets available yet. Create them on the Culture Hub first."); } else { listModel.setEntries(entries); } downloadDialog.setVisible(true); } }); } @Override public void failed(Exception e) { LOG.warn("Fetching list failed", e); sipModel.getFeedback().alert("Failed to receive data set list"); Exec.swing(new Runnable() { @Override public void run() { downloadDialog.setVisible(false); } }); } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "actionPerformed"
"@Override public void actionPerformed(ActionEvent actionEvent) { listModel.setMessage("Loading list of data sets... just a moment"); cultureHubClient.fetchDataSetList(new CultureHubClient.ListReceiveListener() { @Override public void listReceived(final List<CultureHubClient.DataSetEntry> entries) { Exec.swing(new Runnable() { @Override public void run() { if (entries == null || entries.isEmpty()) { listModel.setMessage("No data sets available yet. Create them on the Culture Hub first."); } else { listModel.setEntries(entries); } downloadDialog.setVisible(true); } }); } @Override public void failed(Exception e) { LOG.warn("Fetching list failed", e); Exec.swing(new Runnable() { @Override public void run() { <MASK>sipModel.getFeedback().alert("Failed to receive data set list");</MASK> downloadDialog.setVisible(false); } }); } }); }"
Inversion-Mutation
megadiff
"@Override public void failed(Exception e) { LOG.warn("Fetching list failed", e); sipModel.getFeedback().alert("Failed to receive data set list"); Exec.swing(new Runnable() { @Override public void run() { downloadDialog.setVisible(false); } }); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "failed"
"@Override public void failed(Exception e) { LOG.warn("Fetching list failed", e); Exec.swing(new Runnable() { @Override public void run() { <MASK>sipModel.getFeedback().alert("Failed to receive data set list");</MASK> downloadDialog.setVisible(false); } }); }"
Inversion-Mutation
megadiff
"@Override public void configure(JobConf jobConf) { if (parameters == null) { ParameteredGeneralizations.configureParameters(this, jobConf); } try { if (weightsFile.get() != null) { FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf); Vector weights = (Vector) vectorClass.get().newInstance(); if (!fs.exists(weightsFile.get())) { throw new FileNotFoundException(weightsFile.get().toString()); } DataInputStream in = fs.open(weightsFile.get()); try { weights.readFields(in); } finally { in.close(); } this.weights = weights; } } catch (IOException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configure"
"@Override public void configure(JobConf jobConf) { if (parameters == null) { ParameteredGeneralizations.configureParameters(this, jobConf); } try { <MASK>FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf);</MASK> if (weightsFile.get() != null) { Vector weights = (Vector) vectorClass.get().newInstance(); if (!fs.exists(weightsFile.get())) { throw new FileNotFoundException(weightsFile.get().toString()); } DataInputStream in = fs.open(weightsFile.get()); try { weights.readFields(in); } finally { in.close(); } this.weights = weights; } } catch (IOException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } }"
Inversion-Mutation
megadiff
"protected void installUsingP2( final String repositoryURL, final String installIU, final String destination, final Map<String, String> extraEnv ) throws Exception { FileUtils.deleteDirectory( destination ); final File basedir = ResourceExtractor.simpleExtractResources( getClass(), "/run-p2" ); final Map<String, String> env = new HashMap<String, String>(); env.put( "org.eclipse.ecf.provider.filetransfer.retrieve.readTimeout", "30000" ); env.put( "p2.installIU", installIU ); env.put( "p2.destination", destination ); env.put( "p2.metadataRepository", repositoryURL ); env.put( "p2.artifactRepository", repositoryURL ); env.put( "p2.profile", getTestId() ); if ( extraEnv != null ) { env.putAll( extraEnv ); } final Verifier verifier = new Verifier( basedir.getAbsolutePath() ); verifier.setLogFileName( getTestId() + "-maven-output.log" ); verifier.addCliOption( "-X" ); verifier.executeGoals( Arrays.asList( "verify" ), env ); verifier.verifyErrorFreeLog(); verifier.resetStreams(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "installUsingP2"
"protected void installUsingP2( final String repositoryURL, final String installIU, final String destination, final Map<String, String> extraEnv ) throws Exception { FileUtils.deleteDirectory( destination ); final File basedir = ResourceExtractor.simpleExtractResources( getClass(), "/run-p2" ); final Map<String, String> env = new HashMap<String, String>(); env.put( "org.eclipse.ecf.provider.filetransfer.retrieve.readTimeout", "30000" ); env.put( "p2.installIU", installIU ); env.put( "p2.destination", destination ); env.put( "p2.metadataRepository", repositoryURL ); env.put( "p2.artifactRepository", repositoryURL ); env.put( "p2.profile", getTestId() ); if ( extraEnv != null ) { env.putAll( extraEnv ); } final Verifier verifier = new Verifier( basedir.getAbsolutePath() ); verifier.setLogFileName( getTestId() + "-maven-output.log" ); verifier.executeGoals( Arrays.asList( "verify" ), env ); verifier.verifyErrorFreeLog(); verifier.resetStreams(); <MASK>verifier.addCliOption( "-X" );</MASK> }"
Inversion-Mutation
megadiff
"public FitSphere(final Vector3D[] points) { Vector3D mean = Vector3D.ZERO; for(Vector3D point : points) mean = mean.add(point.scalarMultiply(1D/(double)points.length)); ReportingUtils.logMessage("MEAN: " + mean.toString()); final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ()); double[] params = new double[PARAMLEN]; params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm(); Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS])); params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ(); double[] steps = new double[PARAMLEN]; steps[XC] = steps[YC] = steps[ZC] = 0.001; steps[RADIUS] = 0.00001; ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps)); MultivariateRealFunction MRF = new MultivariateRealFunction() { @Override public double value(double[] params) { Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]); double err = 0; for(Vector3D point : points) err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D); // ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err); return err; } }; SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1); NelderMeadSimplex nm = new NelderMeadSimplex(steps); opt.setSimplex(nm); double[] result = null; try { result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint(); error = Math.sqrt(MRF.value(result)); } catch(Throwable t) { ReportingUtils.logError(t, "Optimization failed!"); } ReportingUtils.logMessage("Fit: " + Arrays.toString(result)); center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean); radius = result[RADIUS]; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "FitSphere"
"public FitSphere(final Vector3D[] points) { Vector3D mean = Vector3D.ZERO; for(Vector3D point : points) mean = mean.add(point.scalarMultiply(1D/(double)points.length)); ReportingUtils.logMessage("MEAN: " + mean.toString()); final Vector3D endMean = new Vector3D(mean.getX(), mean.getY(), mean.getZ()); double[] params = new double[PARAMLEN]; params[RADIUS] = 0.5*points[0].subtract(points[points.length-1]).getNorm(); Vector3D centerGuess = points[points.length/2].subtract(mean).add(mean.subtract(points[points.length/2]).normalize().scalarMultiply(params[RADIUS])); params[XC] = centerGuess.getX(); params[YC] = centerGuess.getY(); params[ZC] = centerGuess.getZ(); double[] steps = new double[PARAMLEN]; steps[XC] = steps[YC] = steps[ZC] = 0.001; steps[RADIUS] = 0.00001; ReportingUtils.logMessage("Initial parameters: " + Arrays.toString(params) + ", steps: " + Arrays.toString(steps)); MultivariateRealFunction MRF = new MultivariateRealFunction() { @Override public double value(double[] params) { Vector3D center = new Vector3D(params[XC], params[YC], params[ZC]); double err = 0; for(Vector3D point : points) err += Math.pow(point.subtract(endMean).subtract(center).getNorm() - params[RADIUS], 2D); // ReportingUtils.logMessage("value(" + Arrays.toString(params) + "): endMean=" + endMean.toString() + ", err=" + err); return err; } }; SimplexOptimizer opt = new SimplexOptimizer(1e-6, -1); NelderMeadSimplex nm = new NelderMeadSimplex(steps); opt.setSimplex(nm); double[] result = null; try { result = opt.optimize(5000000, MRF, GoalType.MINIMIZE, params).getPoint(); } catch(Throwable t) { ReportingUtils.logError(t, "Optimization failed!"); } ReportingUtils.logMessage("Fit: " + Arrays.toString(result)); center = new Vector3D(result[XC], result[YC], result[ZC]).add(mean); radius = result[RADIUS]; <MASK>error = Math.sqrt(MRF.value(result));</MASK> }"
Inversion-Mutation
megadiff
"protected void initialize(IParseController controller, Language language) { // (Thrown exceptions are shown directly in the editor view.) this.language = language; if (controller instanceof DynamicParseController) this.parseController = (SGLRParseController) ((DynamicParseController) controller).getWrapped(); if (getWrapped() == null) // (trigger descriptor init) throw new RuntimeException("Failed to initialize language " + language.getName()); if (!this.language.getName().equals(language.getName())) throw new RuntimeException("Failed to initialize language " + this.language.getName() + ": language name in plugin.xml (" + language.getName() + ") does not correspond to name in editor service descriptors (" + language.getName() + ")"); Descriptor descriptor = Environment.getDescriptor(language); if (descriptor == null) throw new RuntimeException("No definition for language '" + language.getName() + "'; try re-opening the editor"); descriptor.addActiveService(this); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "initialize"
"protected void initialize(IParseController controller, Language language) { // (Thrown exceptions are shown directly in the editor view.) if (controller instanceof DynamicParseController) this.parseController = (SGLRParseController) ((DynamicParseController) controller).getWrapped(); <MASK>this.language = language;</MASK> if (getWrapped() == null) // (trigger descriptor init) throw new RuntimeException("Failed to initialize language " + language.getName()); if (!this.language.getName().equals(language.getName())) throw new RuntimeException("Failed to initialize language " + this.language.getName() + ": language name in plugin.xml (" + language.getName() + ") does not correspond to name in editor service descriptors (" + language.getName() + ")"); Descriptor descriptor = Environment.getDescriptor(language); if (descriptor == null) throw new RuntimeException("No definition for language '" + language.getName() + "'; try re-opening the editor"); descriptor.addActiveService(this); }"
Inversion-Mutation
megadiff
"private void processPushBundle(boolean isPushPluginActive) { Bundle extras = getIntent().getExtras(); if (extras != null) { Bundle originalExtras = extras.getBundle("pushBundle"); if (!isPushPluginActive) { originalExtras.putBoolean("coldstart", true); } PushPlugin.setForeground(true); PushPlugin.sendExtras(originalExtras); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processPushBundle"
"private void processPushBundle(boolean isPushPluginActive) { Bundle extras = getIntent().getExtras(); if (extras != null) { Bundle originalExtras = extras.getBundle("pushBundle"); if (!isPushPluginActive) { originalExtras.putBoolean("coldstart", true); <MASK>PushPlugin.sendExtras(originalExtras);</MASK> } PushPlugin.setForeground(true); } }"
Inversion-Mutation
megadiff
"void scheduleSync(Account account, boolean uploadChangesOnly, String url) { Bundle extras = new Bundle(); if (uploadChangesOnly) { extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, uploadChangesOnly); } if (url != null) { extras.putString("feed", url); } extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(account, Calendars.CONTENT_URI.getAuthority(), extras); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "scheduleSync"
"void scheduleSync(Account account, boolean uploadChangesOnly, String url) { Bundle extras = new Bundle(); if (uploadChangesOnly) { extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, uploadChangesOnly); } if (url != null) { extras.putString("feed", url); <MASK>extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);</MASK> } ContentResolver.requestSync(account, Calendars.CONTENT_URI.getAuthority(), extras); }"
Inversion-Mutation
megadiff
"private static ProgramPathDisabler createProgramPathsChain(Configuration configuration) { return new ProgramPathDisabler( new ConfigurationProgramPaths(configuration, new WindowsRegistryProgramPaths( new PlatformSpecificDefaultPathsFactory().get()))); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createProgramPathsChain"
"private static ProgramPathDisabler createProgramPathsChain(Configuration configuration) { return new ProgramPathDisabler( <MASK>new WindowsRegistryProgramPaths(</MASK> new ConfigurationProgramPaths(configuration, new PlatformSpecificDefaultPathsFactory().get()))); }"
Inversion-Mutation
megadiff
"@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setIntegerProperty("loadUrlTimeoutValue", 60000); super.setIntegerProperty("splashscreen", R.drawable.splash); super.loadUrl("file:///android_asset/www/index.html", 60000); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate"
"@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setIntegerProperty("splashscreen", R.drawable.splash); super.loadUrl("file:///android_asset/www/index.html", 60000); <MASK>super.setIntegerProperty("loadUrlTimeoutValue", 60000);</MASK> }"
Inversion-Mutation
megadiff
"@Override public void write(Cluster cluster) throws IOException { StringBuilder line = new StringBuilder(); line.append(createNode(String.valueOf(cluster.getId()))); List<WeightedVectorWritable> points = getClusterIdToPoints().get(cluster.getId()); if (points != null) { for (WeightedVectorWritable point : points) { Vector theVec = point.getVector(); String vecStr; if (theVec instanceof NamedVector) { vecStr = ((NamedVector) theVec).getName(); line.append(createNode(vecStr)); } else { vecStr = theVec.asFormatString(); //do some basic manipulations for display vecStr = VEC_PATTERN.matcher(vecStr).replaceAll("_"); line.append(createNode(vecStr)); } line.append(createEdge(String.valueOf(cluster.getId()), vecStr)); } } getWriter().append(line).append("\n"); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "write"
"@Override public void write(Cluster cluster) throws IOException { StringBuilder line = new StringBuilder(); line.append(createNode(String.valueOf(cluster.getId()))); List<WeightedVectorWritable> points = getClusterIdToPoints().get(cluster.getId()); if (points != null) { for (WeightedVectorWritable point : points) { Vector theVec = point.getVector(); String vecStr; if (theVec instanceof NamedVector) { vecStr = ((NamedVector) theVec).getName(); line.append(createNode(vecStr)); } else { vecStr = theVec.asFormatString(); //do some basic manipulations for display vecStr = VEC_PATTERN.matcher(vecStr).replaceAll("_"); line.append(createNode(vecStr)); } line.append(createEdge(String.valueOf(cluster.getId()), vecStr)); } <MASK>getWriter().append(line).append("\n");</MASK> } }"
Inversion-Mutation
megadiff
"public AssemblyInfo getAssemblyInfo() { String basedir = mavenProject.getBasedir().toString(); AssemblyInfo assemblyInfo = new AssemblyInfo(); String description = mavenProject.getDescription(); String version = mavenProject.getVersion(); String name = mavenProject.getName(); Organization org = mavenProject.getOrganization(); String company = ( org != null ) ? org.getName() : ""; String copyright = null; String informationalVersion = ""; String configuration = ""; File file = new File( basedir + "/COPYRIGHT.txt" ); if ( file.exists() ) { logger.debug( "NMAVEN-020-000: Found Copyright: " + file.getAbsolutePath() ); FileInputStream fis = null; try { fis = new FileInputStream( file ); copyright = IOUtil.toString( fis ).replace( "\r", " " ).replace( "\n", " " ).replace( "\"", "'" ); } catch ( IOException e ) { logger.info( "NMAVEN-020-001: Could not get copyright: File = " + file.getAbsolutePath(), e ); } finally { if ( fis != null ) { IOUtil.close( fis ); } } } informationalVersion = version; if ( version.contains( "-" ) ) { version = version.split( "-" )[0]; } assemblyInfo.setCompany( company ); assemblyInfo.setCopyright( copyright ); assemblyInfo.setCulture( "" ); assemblyInfo.setDescription( description ); assemblyInfo.setProduct( company + "-" + name ); assemblyInfo.setTitle( name ); assemblyInfo.setTrademark( "" ); assemblyInfo.setInformationalVersion( informationalVersion ); assemblyInfo.setVersion( version ); assemblyInfo.setConfiguration( configuration ); return assemblyInfo; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getAssemblyInfo"
"public AssemblyInfo getAssemblyInfo() { String basedir = mavenProject.getBasedir().toString(); AssemblyInfo assemblyInfo = new AssemblyInfo(); String description = mavenProject.getDescription(); String version = mavenProject.getVersion(); String name = mavenProject.getName(); Organization org = mavenProject.getOrganization(); String company = ( org != null ) ? org.getName() : ""; String copyright = null; String informationalVersion = ""; String configuration = ""; File file = new File( basedir + "/COPYRIGHT.txt" ); if ( file.exists() ) { logger.debug( "NMAVEN-020-000: Found Copyright: " + file.getAbsolutePath() ); FileInputStream fis = null; try { fis = new FileInputStream( file ); copyright = IOUtil.toString( fis ).replace( "\r", " " ).replace( "\n", " " ).replace( "\"", "'" ); } catch ( IOException e ) { logger.info( "NMAVEN-020-001: Could not get copyright: File = " + file.getAbsolutePath(), e ); } finally { if ( fis != null ) { IOUtil.close( fis ); } } } if ( version.contains( "-" ) ) { <MASK>informationalVersion = version;</MASK> version = version.split( "-" )[0]; } assemblyInfo.setCompany( company ); assemblyInfo.setCopyright( copyright ); assemblyInfo.setCulture( "" ); assemblyInfo.setDescription( description ); assemblyInfo.setProduct( company + "-" + name ); assemblyInfo.setTitle( name ); assemblyInfo.setTrademark( "" ); assemblyInfo.setInformationalVersion( informationalVersion ); assemblyInfo.setVersion( version ); assemblyInfo.setConfiguration( configuration ); return assemblyInfo; }"
Inversion-Mutation
megadiff
"public void stop() throws JMSException { toConnection.stop(); fromConnection.stop(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "stop"
"public void stop() throws JMSException { fromConnection.stop(); <MASK>toConnection.stop();</MASK> }"
Inversion-Mutation
megadiff
"public static Collection<String> getGuestAccountsToDelete(int limit) { List<String> uids = new ArrayList<String>(); try { int excess = guestUserCount() - limit; Base64Counter count = new Base64Counter(); while (excess-- > 0) { // Deletes oldest ones first String uid; do { uid = GUEST_UID_PREFIX + count.toString(); count.increment(); } while (!exists(uid)); uids.add(uid); } } catch (BackingStoreException e) { LogHelper.log(e); } return uids; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getGuestAccountsToDelete"
"public static Collection<String> getGuestAccountsToDelete(int limit) { List<String> uids = new ArrayList<String>(); try { int excess = guestUserCount() - limit; while (excess-- > 0) { // Deletes oldest ones first <MASK>Base64Counter count = new Base64Counter();</MASK> String uid; do { uid = GUEST_UID_PREFIX + count.toString(); count.increment(); } while (!exists(uid)); uids.add(uid); } } catch (BackingStoreException e) { LogHelper.log(e); } return uids; }"
Inversion-Mutation
megadiff
"private void loadAndBindAllApps() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { synchronized (mLock) { if (i == 0) { // This needs to happen inside the same lock block as when we // prepare the first batch for bindAllApplications. Otherwise // the package changed receiver can come in and double-add // (or miss one?). mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { mBeforeFirstLoad = false; callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "loadAndBindAllApps"
"private void loadAndBindAllApps() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { synchronized (mLock) { if (i == 0) { // This needs to happen inside the same lock block as when we // prepare the first batch for bindAllApplications. Otherwise // the package changed receiver can come in and double-add // (or miss one?). mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new ResolveInfo.DisplayNameComparator(packageManager)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); i++; } final boolean first = i <= batchSize; final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); <MASK>final Callbacks callbacks = tryGetCallbacks(oldCallbacks);</MASK> if (callbacks != null) { if (first) { mBeforeFirstLoad = false; callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } }"
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 List<GlobalSilverContent> transformSilverContentsToGlobalSilverContents( List<SilverContentInterface> silverContentTempo, String instanceId, PdcSearchSessionController pdcSC) throws Exception { List<GlobalSilverContent> alSilverContents = new ArrayList<GlobalSilverContent>(); SilverContentInterface sci = null; UserDetail creatorDetail = null; GlobalSilverContent gsc = null; for (int i = 0; i < silverContentTempo.size(); i++) { sci = silverContentTempo.get(i); creatorDetail = pdcSC.getOrganizationController().getUserDetail(sci.getCreatorId()); if (creatorDetail != null) gsc = new GlobalSilverContent(sci, getLocation(instanceId, pdcSC), creatorDetail .getFirstName(), creatorDetail.getLastName()); else gsc = new GlobalSilverContent(sci, getLocation(instanceId, pdcSC), null, null); // Special "Gallery" case if (instanceId.startsWith("gallery")) { String galleryDirectory = null; if (galleryDirectory == null) { ResourceLocator gallerySettings = new ResourceLocator("com.silverpeas.gallery.settings.gallerySettings", ""); galleryDirectory = gallerySettings.getString("imagesSubDirectory"); } /* * TODO à reprendre pour être indépendant de Gallery String directory = * galleryDirectory+sci.getId(); PhotoDetail photo = (PhotoDetail) sci; * gsc.setThumbnailURL(FileServerUtils.getUrl(null, instanceId, photo.getImageName(), * photo.getImageMimeType(), directory)); String[] widthAndHeight = {"60", "45"}; try { * widthAndHeight = ImageHelper.getWidthAndHeight(instanceId, directory, * photo.getImageName(), 60); } catch (IOException e) { SilverTrace.info("pdcPeas", * "PdcSearchRequestRouter.transformSilverContentsToGlobalSilverContents", * "root.MSG_GEN_PARAM_VALUE", "Error during processing size !"); } * gsc.setThumbnailWidth(widthAndHeight[0]); gsc.setThumbnailHeight(widthAndHeight[1]); } */ } alSilverContents.add(gsc); } return alSilverContents; }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "transformSilverContentsToGlobalSilverContents"
"private List<GlobalSilverContent> transformSilverContentsToGlobalSilverContents( List<SilverContentInterface> silverContentTempo, String instanceId, PdcSearchSessionController pdcSC) throws Exception { List<GlobalSilverContent> alSilverContents = new ArrayList<GlobalSilverContent>(); SilverContentInterface sci = null; UserDetail creatorDetail = null; GlobalSilverContent gsc = null; for (int i = 0; i < silverContentTempo.size(); i++) { sci = silverContentTempo.get(i); creatorDetail = pdcSC.getOrganizationController().getUserDetail(sci.getCreatorId()); if (creatorDetail != null) gsc = new GlobalSilverContent(sci, getLocation(instanceId, pdcSC), creatorDetail .getFirstName(), creatorDetail.getLastName()); else gsc = new GlobalSilverContent(sci, getLocation(instanceId, pdcSC), null, null); // Special "Gallery" case if (instanceId.startsWith("gallery")) { String galleryDirectory = null; if (galleryDirectory == null) { ResourceLocator gallerySettings = new ResourceLocator("com.silverpeas.gallery.settings.gallerySettings", ""); galleryDirectory = gallerySettings.getString("imagesSubDirectory"); } /* * TODO à reprendre pour être indépendant de Gallery String directory = * galleryDirectory+sci.getId(); PhotoDetail photo = (PhotoDetail) sci; * gsc.setThumbnailURL(FileServerUtils.getUrl(null, instanceId, photo.getImageName(), * photo.getImageMimeType(), directory)); String[] widthAndHeight = {"60", "45"}; try { * widthAndHeight = ImageHelper.getWidthAndHeight(instanceId, directory, * photo.getImageName(), 60); } catch (IOException e) { SilverTrace.info("pdcPeas", * "PdcSearchRequestRouter.transformSilverContentsToGlobalSilverContents", * "root.MSG_GEN_PARAM_VALUE", "Error during processing size !"); } * gsc.setThumbnailWidth(widthAndHeight[0]); gsc.setThumbnailHeight(widthAndHeight[1]); } */ <MASK>alSilverContents.add(gsc);</MASK> } } return alSilverContents; }"
Inversion-Mutation
megadiff
"private void storeHistory(ConnectionResource conn, History history, Repository repository) throws SQLException { Integer reposId = null; Map<String, Integer> authors = null; Map<String, Integer> files = null; PreparedStatement addChangeset = null; PreparedStatement addFilechange = null; for (int i = 0;; i++) { try { if (reposId == null) { reposId = getRepositoryId(conn, repository); conn.commit(); } if (authors == null) { authors = getAuthors(conn, history, reposId); conn.commit(); } if (files == null) { files = getFiles(conn, history, reposId); conn.commit(); } if (addChangeset == null) { addChangeset = conn.getStatement(ADD_CHANGESET); } if (addFilechange == null) { addFilechange = conn.getStatement(ADD_FILECHANGE); } // Success! Break out of the loop. break; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } addChangeset.setInt(1, reposId); // getHistoryEntries() returns the entries in reverse chronological // order, but we want to insert them in chronological order so that // their auto-generated identity column can be used as a chronological // ordering column. Otherwise, incremental updates will make the // identity column unusable for chronological ordering. So therefore // we walk the list backwards. List<HistoryEntry> entries = history.getHistoryEntries(); for (ListIterator<HistoryEntry> it = entries.listIterator(entries.size()); it.hasPrevious();) { HistoryEntry entry = it.previous(); retry: for (int i = 0;; i++) { try { addChangeset.setString(2, entry.getRevision()); addChangeset.setInt(3, authors.get(entry.getAuthor())); addChangeset.setTimestamp(4, new Timestamp(entry.getDate().getTime())); addChangeset.setString(5, entry.getMessage()); addChangeset.executeUpdate(); int changesetId = getGeneratedIntKey(addChangeset); addFilechange.setInt(1, changesetId); for (String file : entry.getFiles()) { int fileId = files.get(toUnixPath(file)); addFilechange.setInt(2, fileId); addFilechange.executeUpdate(); } conn.commit(); // Successfully added the entry. Break out of retry loop. break retry; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } } }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "storeHistory"
"private void storeHistory(ConnectionResource conn, History history, Repository repository) throws SQLException { Integer reposId = null; Map<String, Integer> authors = null; Map<String, Integer> files = null; PreparedStatement addChangeset = null; PreparedStatement addFilechange = null; for (int i = 0;; i++) { try { if (reposId == null) { reposId = getRepositoryId(conn, repository); conn.commit(); } if (authors == null) { authors = getAuthors(conn, history, reposId); conn.commit(); } if (files == null) { files = getFiles(conn, history, reposId); conn.commit(); } if (addChangeset == null) { addChangeset = conn.getStatement(ADD_CHANGESET); } if (addFilechange == null) { addFilechange = conn.getStatement(ADD_FILECHANGE); } // Success! Break out of the loop. break; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } addChangeset.setInt(1, reposId); // getHistoryEntries() returns the entries in reverse chronological // order, but we want to insert them in chronological order so that // their auto-generated identity column can be used as a chronological // ordering column. Otherwise, incremental updates will make the // identity column unusable for chronological ordering. So therefore // we walk the list backwards. List<HistoryEntry> entries = history.getHistoryEntries(); for (ListIterator<HistoryEntry> it = entries.listIterator(entries.size()); it.hasPrevious();) { retry: for (int i = 0;; i++) { try { <MASK>HistoryEntry entry = it.previous();</MASK> addChangeset.setString(2, entry.getRevision()); addChangeset.setInt(3, authors.get(entry.getAuthor())); addChangeset.setTimestamp(4, new Timestamp(entry.getDate().getTime())); addChangeset.setString(5, entry.getMessage()); addChangeset.executeUpdate(); int changesetId = getGeneratedIntKey(addChangeset); addFilechange.setInt(1, changesetId); for (String file : entry.getFiles()) { int fileId = files.get(toUnixPath(file)); addFilechange.setInt(2, fileId); addFilechange.executeUpdate(); } conn.commit(); // Successfully added the entry. Break out of retry loop. break retry; } catch (SQLException sqle) { handleSQLException(sqle, i); conn.rollback(); } } } }"
Inversion-Mutation
megadiff
"public void run() { FileConnection file = null; InputStream is = null; Image capturedImage = null; try { file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE); is = file.openInputStream(); capturedImage = Image.createImage(is); } catch (IOException e) { Log.error("Problem creating image: " + e); removeProgressBar(); invalidate(); showMessage("An error occured processing the image."); return; } finally { try { if (is != null) { is.close(); } if (file != null && file.exists()) { if (file.isOpen()) { file.delete(); file.close(); } Log.info("Deleted image file."); } } catch (IOException ioe) { Log.error("Error while closing file: " + ioe); } } if (capturedImage != null) { Log.info("Got image..."); LuminanceSource source = new LCDUIImageLuminanceSource(capturedImage); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Result result; ReasonableTimer decodingTimer = null; try { decodingTimer = new ReasonableTimer(); Log.info("Attempting to decode image..."); result = reader.decode(bitmap, readerHints); decodingTimer.finished(); } catch (ReaderException e) { Log.error("Could not decode image: " + e); decodingTimer.finished(); removeProgressBar(); invalidate(); boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue(); if (showResolutionMsg) { showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } else { showMessage("A QR Code was not found in the image."); } return; } if (result != null) { String resultText = result.getText(); Log.info("result: " + resultText); if (isURI(resultText)) { resultText = URLDecoder.decode(resultText); removeProgressBar(); invalidate(); if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) { showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText)); invokeBrowser(resultText); return; } } else { removeProgressBar(); invalidate(); showMessage("A QR Code was not found in the image."); return; } } removeProgressBar(); invalidate(); }"
You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run"
"public void run() { FileConnection file = null; InputStream is = null; Image capturedImage = null; try { file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE); is = file.openInputStream(); capturedImage = Image.createImage(is); } catch (IOException e) { Log.error("Problem creating image: " + e); removeProgressBar(); invalidate(); showMessage("An error occured processing the image."); return; } finally { try { if (is != null) { is.close(); } if (file != null && file.exists()) { if (file.isOpen()) { file.close(); } <MASK>file.delete();</MASK> Log.info("Deleted image file."); } } catch (IOException ioe) { Log.error("Error while closing file: " + ioe); } } if (capturedImage != null) { Log.info("Got image..."); LuminanceSource source = new LCDUIImageLuminanceSource(capturedImage); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Result result; ReasonableTimer decodingTimer = null; try { decodingTimer = new ReasonableTimer(); Log.info("Attempting to decode image..."); result = reader.decode(bitmap, readerHints); decodingTimer.finished(); } catch (ReaderException e) { Log.error("Could not decode image: " + e); decodingTimer.finished(); removeProgressBar(); invalidate(); boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue(); if (showResolutionMsg) { showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } else { showMessage("A QR Code was not found in the image."); } return; } if (result != null) { String resultText = result.getText(); Log.info("result: " + resultText); if (isURI(resultText)) { resultText = URLDecoder.decode(resultText); removeProgressBar(); invalidate(); if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) { showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText)); invokeBrowser(resultText); return; } } else { removeProgressBar(); invalidate(); showMessage("A QR Code was not found in the image."); return; } } removeProgressBar(); invalidate(); }"