auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Artifact getRelatedArtifact(Artifact artifact, IRelationType relationType, RelationSide relationSide) throws OseeCoreException { List<Artifact> artifacts = getRelatedArtifactsUnSorted(artifact, relationType, relationSide); if (artifacts.isEmpty()) { <START> throw new ArtifactDoesNotExist("There is no artifact related to [(%s) %s] by a relation of type [%s]", <END> artifact.getArtId(), artifact, relationType); } if (artifacts.size() > 1) { throw new MultipleArtifactsExist( "There are %s artifacts related to (%s) \"%s\" by a relation of type \"%s\" on side %s instead of the expected 1.", artifacts.size(), artifact.getArtId(), artifact, relationType, relationSide); } return artifacts.get(0); }</code><technical_language>nit: consider artifact.toStringWithId(), name uuid in a consistent format</technical_language>

Target:
private static Artifact getRelatedArtifact(Artifact artifact, IRelationType relationType, RelationSide relationSide) throws OseeCoreException { List<Artifact> artifacts = getRelatedArtifactsUnSorted(artifact, relationType, relationSide); if (artifacts.isEmpty()) { throw new ArtifactDoesNotExist("There is no artifact related to [%s] by a relation of type [%s]", artifact.toStringWithId(), relationType); } if (artifacts.size() > 1) { throw new MultipleArtifactsExist( "There are %s artifacts related to \"%s\" by a relation of type \"%s\" on side %s instead of the expected 1.", artifacts.size(), artifact.toStringWithId(), relationType, relationSide); } return artifacts.get(0); }
Source:
<code>public Option<Command> localChangesAboutToCommit(Collection<Notification> notifications) { Command result = null; if (needsRefresh() && !disable) { boolean impactingNotification = isImpactingNotification(notifications); if (impactingNotification || !representationsToForceRefresh.isEmpty()) { Option<? extends Command> optionCommand = getRefreshOpennedRepresentationsCommand(impactingNotification); if (optionCommand.some()) { result = optionCommand.get(); } } <START> } <END> disable = false; setForceRefresh(false); representationsToForceRefresh.clear(); return Options.newSome(result); }</code><technical_language>If disabled, forceRefresh attribute representationToForceRefresh list</technical_language>

Target:
public Option<Command> localChangesAboutToCommit(Collection<Notification> notifications) { Command result = null; if (!disabled && needsRefresh()) { boolean impactingNotification = isImpactingNotification(notifications); if (impactingNotification || !representationsToForceRefresh.isEmpty()) { Option<? extends Command> optionCommand = getRefreshOpennedRepresentationsCommand(impactingNotification); if (optionCommand.some()) { result = optionCommand.get(); } } setForceRefresh(false); representationsToForceRefresh.clear(); } disabled = false; return Options.newSome(result); }
Source:
<code>public void testDeleteRecursive() throws IOException { File f1 = new File(trash, "test/test/a"); <START> assertTrue(f1.getParentFile().mkdirs()); <END> FileUtils.createNewFile(f1); File f2 = new File(trash, "test/test/b"); FileUtils.createNewFile(f2); File d = new File(trash, "test"); FileUtils.delete(d, FileUtils.RECURSIVE); assertFalse(d.exists()); try { FileUtils.delete(d, FileUtils.RECURSIVE); fail("recursive deletion of non-existing directory must fail"); } catch (IOException e) { } try { FileUtils.delete(d, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING); } catch (IOException e) { fail("recursive deletion of non-existing directory must not fail with option SKIP_MISSING"); } }</code><technical_language>previous version work? FileUtils.mkdirs</technical_language>

Target:
public void testDeleteRecursive() throws IOException { File f1 = new File(trash, "test/test/a"); FileUtils.mkdirs(f1.getParentFile()); FileUtils.createNewFile(f1); File f2 = new File(trash, "test/test/b"); FileUtils.createNewFile(f2); File d = new File(trash, "test"); FileUtils.delete(d, FileUtils.RECURSIVE); assertFalse(d.exists()); try { FileUtils.delete(d, FileUtils.RECURSIVE); fail("recursive deletion of non-existing directory must fail"); } catch (IOException e) { } try { FileUtils.delete(d, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING); } catch (IOException e) { fail("recursive deletion of non-existing directory must not fail with option SKIP_MISSING"); } }
Source:
<code>public static void analyzeFiles(Set<String> fileNames) throws ArgumentParserException, IOException { numErrors = 0; numWarnings = 0; List<File> files = fileNames.parallelStream().map(File::new).collect(Collectors.toList()); ConcurrentMap<File, Optional<CommonTokenStream>> filesToTokenStreams = files.parallelStream().collect(Collectors.toConcurrentMap(Function.identity(), Tailor::getTokenStream)); System.out.format("Analyzing %s:%n", pluralize(fileNames.size(), "file", "files")); ConcurrentMap<File, Optional<TopLevelContext>> filesToTrees = files .parallelStream() .collect(Collectors.toConcurrentMap(Function.identity(), file -> { Optional<TopLevelContext> tree = Optional.empty(); try { tree = Tailor.getParseTree(filesToTokenStreams.get(file)); System.out.print("."); } catch (ErrorListener.ParseException e) { System.out.print("S"); numSkippedFiles++; } return tree; })); System.out.format("%n"); <START> files.parallelStream().forEach( <END> file -> { try { Tailor.analyzeFile(file, filesToTokenStreams.get(file), filesToTrees.get(file)); } catch (ArgumentParserException e) { handleCliException(e); } }); printSummary(fileNames.size(), numSkippedFiles, numErrors, numWarnings); if (numErrors >= 1L) { System.exit(ExitCode.failure()); } }</code><technical_language>parallelStream() results in unordered output of violation messages a file, is fixed switching stream(). change minimal impact performance</technical_language>

Target:
private void analyzeFiles(Set<String> fileNames) throws CLIArgumentParserException, IOException { ColorSettings colorSettings = new ColorSettings(configuration.shouldColorOutput(), configuration.shouldInvertColorOutput()); Formatter formatter = configuration.getFormatter(colorSettings); Severity maxSeverity = configuration.getMaxSeverity(); ConstructLengths constructLengths = configuration.parseConstructLengths(); Set<Rules> enabledRules = configuration.getEnabledRules(); List<File> files = fileNames.parallelStream().map(File::new).collect(Collectors.toList()); formatter.printProgressInfo( String.format("Analyzing %s:%n", Formatter.pluralize(fileNames.size(), "file", "files"))); files.parallelStream().forEach( file -> { try { Optional<CommonTokenStream> tokenStream = getTokenStream(file); Optional<TopLevelContext> tree = getParseTree(tokenStream); analyzeFile(file, tokenStream, tree, formatter, maxSeverity, constructLengths, enabledRules); formatter.printProgressInfo("."); } catch (ErrorListener.ParseException e) { formatter.printProgressInfo("S"); Printer printer = new Printer(file, maxSeverity, formatter); printer.setShouldPrintParseErrorMessage(true); printersForAllFiles.add(printer); numSkippedFiles.incrementAndGet(); } catch (CLIArgumentParserException e) { handleCLIException(e, configuration); } }); formatter.printProgressInfo(String.format("%n")); printersForAllFiles.forEach(printer -> { try { printer.printAllMessages(); } catch (IOException e) { handleIOException(e); } }); formatter.displaySummary(fileNames.size(), numSkippedFiles.get(), numErrors.get(), numWarnings.get()); handleErrorViolations(formatter, numErrors.get()); }
Source:
<code>private InputStream loadFile(File file) { InputStream inputStream = null; if (!file.canWrite() && isRootExplorer) { try { cachedFile = new File(externalCacheDir, file.getName()); RootUtils.copy(file.getAbsolutePath(), cachedFile.getPath()); inputStream = new FileInputStream(cachedFile); } catch (ShellNotRunningException e) { e.printStackTrace(); inputStream = null; } catch (FileNotFoundException e) { e.printStackTrace(); inputStream = null; } } else if (file.canRead()) { try { inputStream = new FileInputStream(file.getAbsolutePath()); } catch (FileNotFoundException e) { <START> inputStream = null; <END> } } return inputStream; }</code><technical_language>Please log print stack trace</technical_language>

Target:
private InputStream loadFile(File file) { InputStream inputStream = null; if (!file.canWrite() && isRootExplorer) { try { cachedFile = new File(externalCacheDir, file.getName()); RootUtils.copy(file.getAbsolutePath(), cachedFile.getPath()); inputStream = new FileInputStream(cachedFile); } catch (ShellNotRunningException e) { e.printStackTrace(); inputStream = null; } catch (FileNotFoundException e) { e.printStackTrace(); inputStream = null; } } else if (file.canRead()) { try { inputStream = new FileInputStream(file.getAbsolutePath()); } catch (FileNotFoundException e) { Log.e(TAG, "Unable to open file [" + file.getAbsolutePath() + "] for reading", e); inputStream = null; } } return inputStream; }
Source:
<code>public String getPrintString(IAdaptable element, int flags) { String elementType = null; if(element instanceof SemanticAdapter){ Object realObject = ((SemanticAdapter) element).getAdapter(EObject.class); <START> if (realObject instanceof org.eclipse.uml2.uml.Class) { elementType = UMLUtil.getStereotypeApplication(((org.eclipse.uml2.uml.Class) realObject), ConstraintBlock.class) != null ? "constraintBlock" : "block"; } <END> } if (element instanceof EObjectAdapter) { Object realObject = ((EObjectAdapter) element).getRealObject(); if (realObject instanceof org.eclipse.uml2.uml.Class) { elementType = UMLUtil.getStereotypeApplication(((org.eclipse.uml2.uml.Class) realObject), ConstraintBlock.class) != null ? "ConstraintBlock" : "Block"; } } return "par [" + elementType + "] " + super.getPrintString(element, flags); }</code><technical_language>Duplicated code</technical_language>

Target:
public String getPrintString(IAdaptable element, int flags) { String elementType = null; if(element instanceof SemanticAdapter){ Object realObject = ((SemanticAdapter) element).getAdapter(EObject.class); if (realObject instanceof org.eclipse.uml2.uml.Class) { elementType = UMLUtil.getStereotypeApplication(((org.eclipse.uml2.uml.Class) realObject), ConstraintBlock.class) != null ? "constraintBlock" : "block"; } } return "par [" + elementType + "] " + super.getPrintString(element, flags); }
Source:
<code>public InvalidCursorException(final CursorError error, final NakadiCursor position) { <START> super(); <END> this.error = error; this.cursor = null; this.position = position; }</code><technical_language>do call this? called default</technical_language>

Target:
public InvalidCursorException(final CursorError error, final NakadiCursor position) { this.error = error; this.cursor = null; this.position = position; }
Source:
<code>public void removeBlob(String container, String name) { String objManifest = getManifestInfo(container, name); <START> String sloInfo = getSLOInfo(container, name); <END> if (objManifest == null && sloInfo == null) api.getObjectApi(regionId, container).delete(name); else if (objManifest == null && sloInfo != null) { DeleteStaticLargeObjectResponse response = api.getStaticLargeObjectApi(regionId, container).delete(name); } else if (objManifest != null && sloInfo == null) { api.getObjectApi(regionId, container).delete(name); if (!Strings.isNullOrEmpty(objManifest)) { removeObjectsWithPrefix(objManifest); } } }</code><technical_language>Previously this code issued DELETEs depending if name SLO a regular object. this commit issue issue RPCs, getWithoutBody, getWithoutBody, DELETE some flags. optimize this? this fails if object exist</technical_language>

Target:
public void removeBlob(String container, String name) { DeleteStaticLargeObjectResponse response = api.getStaticLargeObjectApi(regionId, container).delete(name); if (!response.status().equals("200 OK")) { api.getObjectApi(regionId, container).delete(name); } }
Source:
<code>public void doBeforeComposeChildren(final Component comp) throws Exception { if (comp.getPage() == null) { ((ComponentCtrl) comp).addCallback(ComponentCtrl.AFTER_PAGE_ATTACHED, new Callback() { public void call(Object data) { try { doBeforeComposeChildren(comp); } catch (Exception e) { <START> throw UiException.Aide.wrap(e, e.getMessage()); <END> } } }); return; } _viewModel = initViewModel(evalx, comp); _binder = initBinder(evalx, comp); if (!this.equals(_viewModel)) { Object vmProxy = _binder.createViewModelProxyIfEnabled(_viewModel); if (vmProxy != null) { _viewModel = vmProxy; comp.setAttribute((String) comp.getAttribute(VM_ID), vmProxy); } } ValidationMessages _vmsgs = initValidationMessages(evalx, comp, _binder); Selectors.wireVariables(comp, _viewModel, Selectors.newVariableResolvers(BindUtils.getViewModelClass(_viewModel), null)); if (_vmsgs != null) { _binder.setValidationMessages(_vmsgs); } try { BinderKeeper keeper = BinderKeeper.getInstance(comp); keeper.book(_binder, comp); _binder.init(comp, _viewModel, getViewModelInitArgs(evalx, comp)); } catch (Exception x) { throw MiscUtil.mergeExceptionInfo(x, comp); } ConventionWires.wireController(comp, this); }</code><technical_language>throw UiException.Aide.wrap(e);</technical_language>

Target:
public void doBeforeComposeChildren(final Component comp) throws Exception { if (comp.getPage() == null) { ((ComponentCtrl) comp).addCallback(ComponentCtrl.AFTER_PAGE_ATTACHED, new Callback() { public void call(Object data) { try { doBeforeComposeChildren(comp); } catch (Exception e) { throw UiException.Aide.wrap(e); } } }); return; } _viewModel = initViewModel(evalx, comp); _binder = initBinder(evalx, comp); if (!this.equals(_viewModel)) { Object vmProxy = _binder.createViewModelProxyIfEnabled(_viewModel); if (vmProxy != null) { _viewModel = vmProxy; comp.setAttribute((String) comp.getAttribute(VM_ID), vmProxy); } } ValidationMessages _vmsgs = initValidationMessages(evalx, comp, _binder); Selectors.wireVariables(comp, _viewModel, Selectors.newVariableResolvers(BindUtils.getViewModelClass(_viewModel), null)); if (_vmsgs != null) { _binder.setValidationMessages(_vmsgs); } try { BinderKeeper keeper = BinderKeeper.getInstance(comp); keeper.book(_binder, comp); _binder.init(comp, _viewModel, getViewModelInitArgs(evalx, comp)); } catch (Exception x) { throw MiscUtil.mergeExceptionInfo(x, comp); } ConventionWires.wireController(comp, this); }
Source:
<code>public static final void setPreferenceNodeId (String id) { if (fgPreferenceNodeId == null || id == null) { fgPreferenceNodeId= id; } else { <START> Assert.isTrue(false, <END> "Preference node already set"); } }</code><technical_language>#isLegal sends IllegalArgumentException. Also, is more elegant check argument execute code. rid of 'if'</technical_language>

Target:
public static final void setPreferenceNodeId (String id) { Assert.isLegal(fgPreferenceNodeId == null || id == null, "Preference node already set"); fgPreferenceNodeId= id; }
Source:
<code><START> public void disconnect(){ <END> }</code><technical_language>here, destroy() call disconnect() move code over. Otherwise, breaking things. Also, a missing space ){. Please enable automatic code formatting in commit dialog fix 3 occurrences in this PR</technical_language>

Target:
public void disconnect() { if (fafConnectionTask != null) { fafConnectionTask.cancel(true); } }
Source:
<code>private void createGrid() { <START> GridOperator.traverseGrid((i, j) -> <END> { gridGroup.getChildren().add(createCell(i, j)); return 0; }); gridGroup.getStyleClass().add("game-grid"); hBottom.getStyleClass().add("game-backGrid"); gridGroup.setManaged(false); gridGroup.setLayoutX(BORDER_WIDTH); gridGroup.setLayoutY(BORDER_WIDTH); hBottom.setMinSize(GRID_WIDTH, GRID_WIDTH); hBottom.setPrefSize(GRID_WIDTH, GRID_WIDTH); hBottom.setMaxSize(GRID_WIDTH, GRID_WIDTH); Rectangle rect = new Rectangle(GRID_WIDTH, GRID_WIDTH); hBottom.setClip(rect); hBottom.getChildren().add(gridGroup); vGame.getChildren().add(hBottom); getChildren().add(0, vGame); }</code><technical_language>i j coordinates of position, they? If yes, named xPos</technical_language>

Target:
private void createGrid() { GridOperator.traverseGrid((xPosition, yPosition) -> { gridGroup.getChildren().add(createCell(xPosition, yPosition)); return 0; }); gridGroup.getStyleClass().add("game-grid"); hBottom.getStyleClass().add("game-backGrid"); gridGroup.setManaged(false); gridGroup.setLayoutX(BORDER_WIDTH); gridGroup.setLayoutY(BORDER_WIDTH); hBottom.setMinSize(GRID_WIDTH, GRID_WIDTH); hBottom.setPrefSize(GRID_WIDTH, GRID_WIDTH); hBottom.setMaxSize(GRID_WIDTH, GRID_WIDTH); Rectangle rect = new Rectangle(GRID_WIDTH, GRID_WIDTH); hBottom.setClip(rect); hBottom.getChildren().add(gridGroup); vGame.getChildren().add(hBottom); getChildren().add(0, vGame); }
Source:
<code>public static LimitPlanNode toPlanNode(RexNode limit, RexNode offset) { LimitPlanNode lpn = new LimitPlanNode(); if (limit != null) { if (limit instanceof RexDynamicParam) { lpn.setLimit(-1); lpn.setLimitParameterIndex(RexConverter.getParameterIndex()); <START> RexConverter.setParameterIndex(RexConverter.getParameterIndex() + 1); <END> } else { lpn.setLimit(RexLiteral.intValue(limit)); } } if (offset != null) { if (offset instanceof RexDynamicParam) { lpn.setOffset(0); lpn.setOffsetParameterIndex(RexConverter.getParameterIndex()); RexConverter.setParameterIndex(RexConverter.getParameterIndex() + 1); } else { lpn.setOffset(RexLiteral.intValue(offset)); } } return lpn; }</code><technical_language>provide a RexConverter.getAndIncrementParameterIndex() method RexConverter.getParameterIndex() RexConverter.setParameterIndex(RexConverter.getParameterIndex() + 1); atomic operation? Also, a method RexConverter.getIntValue(RexNode node) return -1 if a RexDynamicParam actual in other places (VoltPhysicalTableScan) convert limit / offset int values</technical_language>

Target:
public static LimitPlanNode toPlanNode(RexNode limit, RexNode offset) { LimitPlanNode lpn = new LimitPlanNode(); if (limit != null) { if (limit instanceof RexDynamicParam) { lpn.setLimit(-1); lpn.setLimitParameterIndex(RexConverter.getAndIncrementParameterIndex()); } else { lpn.setLimit(RexLiteral.intValue(limit)); } } if (offset != null) { if (offset instanceof RexDynamicParam) { lpn.setOffset(0); lpn.setOffsetParameterIndex(RexConverter.getAndIncrementParameterIndex()); } else { lpn.setOffset(RexLiteral.intValue(offset)); } } return lpn; }
Source:
<code>public void verifySwapVideo() { <START> this.waitForElementByElement(swapCount); <END> int initialCount = Integer.parseInt(swapCount.getText()); this.waitForElementByElement(firstSwapButton); firstSwapButton.click(); this.waitForTextToBePresentInElementByElement(swapCount, String.valueOf(initialCount-1)); PageObjectLogging.log("verifyClickSwap", "Swap button has been clicked", true); }</code><technical_language>please remove 'this' in other waiting for elements methods</technical_language>

Target:
public void verifySwapVideo() { waitForElementByElement(swapCount); int initialCount = Integer.parseInt(swapCount.getText()); waitForElementByElement(firstSwapButton); scrollAndClick(firstSwapButton); waitForTextToBePresentInElementByElement(swapCount, String.valueOf(initialCount-1)); PageObjectLogging.log("verifyClickSwap", "Swap button has been clicked", true); }
Source:
<code>public Response getDatabaseSegments( @Context final HttpServletRequest req, @QueryParam("datasources") final Set<String> datasources ) { Collection<ImmutableDruidDataSource> druidDataSources = metadataSegmentManager.getDataSources(); if (datasources != null && !datasources.isEmpty()) { druidDataSources = druidDataSources.stream() .filter(src -> datasources.contains(src.getName())) <START> .collect(Collectors.toList()); <END> } final Stream<DataSegment> metadataSegments = druidDataSources .stream() .flatMap(t -> t.getSegments().stream()); final Function<DataSegment, Iterable<ResourceAction>> raGenerator = segment -> Collections.singletonList( AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSource())); final Iterable<DataSegment> authorizedSegments = AuthorizationUtils.filterAuthorizedResources(req, metadataSegments::iterator, raGenerator, authorizerMapper); final StreamingOutput stream = outputStream -> { final JsonFactory jsonFactory = jsonMapper.getFactory(); try (final JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream)) { jsonGenerator.writeStartArray(); for (DataSegment ds : authorizedSegments) { jsonGenerator.writeObject(ds); jsonGenerator.flush(); } jsonGenerator.writeEndArray(); } }; Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.entity(stream).build(); }</code><technical_language>if collect all? return a Stream jackson handle lazy array materialization? I avoid odd output stream json factory stuff if jackson supports a thing</technical_language>

Target:
public Response getDatabaseSegments( @Context final HttpServletRequest req, @QueryParam("datasources") final Set<String> datasources ) { Collection<ImmutableDruidDataSource> druidDataSources = Optional.ofNullable(metadataSegmentManager.getDataSources()) .orElse(Collections.emptyList()); Stream<ImmutableDruidDataSource> dataSourceStream = druidDataSources.stream(); if (datasources != null && !datasources.isEmpty()) { dataSourceStream = dataSourceStream.filter(src -> datasources.contains(src.getName())); } final Stream<DataSegment> metadataSegments = dataSourceStream.flatMap(t -> t.getSegments().stream()); final Function<DataSegment, Iterable<ResourceAction>> raGenerator = segment -> Collections.singletonList( AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSource())); final Iterable<DataSegment> authorizedSegments = AuthorizationUtils.filterAuthorizedResources(req, metadataSegments::iterator, raGenerator, authorizerMapper); final Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.entity(authorizedSegments).build(); }
Source:
<code>public void testAlwaysMeteredVpnWithNonNullUnderlyingNetwork() throws Exception { if (!supportedHardware()) { return; } <START> Network wifi = <END> ensureWifiConnected(); assertEquals(wifi, mCM.getActiveNetwork()); ArrayList<Network> underlyingNetworks = new ArrayList<>(1); underlyingNetworks.add(wifi); String allowedApps = mPackageName; boolean isAlwaysMetered = true; startVpn( new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"}, new String[] {"0.0.0.0/0", "::/0"}, allowedApps, "", null, underlyingNetworks, isAlwaysMetered); assertEquals(mNetwork, mCM.getActiveNetwork()); ensureVpnTransportContains(NetworkCapabilities.TRANSPORT_WIFI); assertTrue(isNetworkMetered(mNetwork)); assertTrue(mCM.isActiveNetworkMetered()); }</code><technical_language>Nit: define final</technical_language>

Target:
public void testAlwaysMeteredVpnWithNonNullUnderlyingNetwork() throws Exception { if (!supportedHardware()) { return; } Network wifi = getWifiNetwork(); assertEquals(wifi, mCM.getActiveNetwork()); ArrayList<Network> underlyingNetworks = new ArrayList<>(1); underlyingNetworks.add(wifi); String allowedApps = mPackageName; boolean isAlwaysMetered = true; startVpn( new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"}, new String[] {"0.0.0.0/0", "::/0"}, allowedApps, "", null, underlyingNetworks, isAlwaysMetered); assertEquals(mNetwork, mCM.getActiveNetwork()); ensureVpnTransportContains(NetworkCapabilities.TRANSPORT_WIFI); assertTrue(isNetworkMetered(mNetwork)); assertTrue(mCM.isActiveNetworkMetered()); }
Source:
<code>private File getNextLogFile(String logDir, Long currentTime, boolean fromSaveState, File currFile) { File[] dirFiles = new File(logDir).listFiles(new LogFilter(logFileName, rotationPattern)); Comparator logfileComparator = new Comparator<LogFileTime>() { @Override public int compare(LogFileTime o1, LogFileTime o2) { int res = o1.getModificationTime().compareTo(o2.getModificationTime()); if (res != 0) { return res; } else { res = o2.getFileName().length() - o1.getFileName().length(); } return (res != 0) ? res : o2.getFileName().compareTo(o1.getFileName()); } }; TreeMap<LogFileTime, File> logFilesTimesMap = new TreeMap<LogFileTime, File>(logfileComparator); for (File f : dirFiles) { logFilesTimesMap.put(new LogFileTime(f.lastModified(), f.getName()), f); } if (currentTime == 0 && logFilesTimesMap.size() > 0) { return logFilesTimesMap.firstEntry().getValue(); } if (fromSaveState && logFilesTimesMap.containsKey(new LogFileTime(currentTime, currFile.getName()))) { return logFilesTimesMap.get(new LogFileTime(currentTime, currFile.getName())); <START> } else { <END> boolean currentFileChanged = true; for (LogFileTime logFileTime : logFilesTimesMap.keySet()) { if (logFileTime.getModificationTime().equals(currentTime)) { currentFileChanged = false; break; } } if (currentFileChanged && logFilesTimesMap.higherKey(new LogFileTime(currentTime, currFile.getName())) == null) { return null; } LogFileTime key = logFilesTimesMap.higherKey(new LogFileTime(currentTime, currFile.getName())); return key == null ? null : logFilesTimesMap.get(key); } }</code><technical_language>need else if clause return</technical_language>

Target:
private File getNextLogFile(String logDir, Long currentTime, boolean fromSaveState, File currFile) { File[] dirFiles = new File(logDir).listFiles(new LogFilter(logFileName, rotationPattern)); TreeMap<LogFileTime, File> logFilesTimesMap = new TreeMap<LogFileTime, File>(logFileComparator); for (File f : dirFiles) { logFilesTimesMap.put(new LogFileTime(f.lastModified(), f.getName()), f); } if (currentTime == 0 && logFilesTimesMap.size() > 0) { return logFilesTimesMap.firstEntry().getValue(); } if (fromSaveState && logFilesTimesMap.containsKey(new LogFileTime(currentTime, currFile.getName()))) { return logFilesTimesMap.get(new LogFileTime(currentTime, currFile.getName())); } boolean currentFileChanged = true; for (LogFileTime logFileTime : logFilesTimesMap.keySet()) { if (logFileTime.getModificationTime().equals(currentTime)) { currentFileChanged = false; break; } } if (currentFileChanged && logFilesTimesMap.higherKey(new LogFileTime(currentTime, currFile.getName())) == null) { return null; } LogFileTime key = logFilesTimesMap.higherKey(new LogFileTime(currentTime, currFile.getName())); return key == null ? null : logFilesTimesMap.get(key); }
Source:
<code>public ImmutableValue<Boolean> sneaking() { <START> return new ImmutableSpongeValue<Boolean>(Keys.IS_SNEAKING, false, this.value); <END> }</code><technical_language>ImmutableDataCachingUtil.getValue(ImmutableSpongeValue.class, Keys.IS_SNEAKING, this.value, false); instead cached</technical_language>

Target:
public ImmutableValue<Boolean> sneaking() { return ImmutableDataCachingUtil.getValue(ImmutableSpongeValue.class, Keys.IS_SNEAKING, this.value, false); }
Source:
<code>public void changeEvent(int type) { String currUri = null; int currIndex = 0; IDockerConnection[] connections = DockerConnectionManager.getInstance() .getConnections(); if (connection != null) { currUri = connection.getUri(); } int index = 0; for (int i = 0; i < connections.length; ++i) { <START> if (currUri.equals(connections[i].getUri())) { <END> index = i; } } if (type == IDockerConnectionManagerListener.RENAME_EVENT) { index = currIndex; } if (connections.length > 0 && type != IDockerConnectionManagerListener.REMOVE_EVENT) { setConnection(connections[index]); } else { setConnection(null); } }</code><technical_language>reversed expression is a problem currUri null. I restore originally</technical_language>

Target:
public void changeEvent(int type) { String currUri = null; int currIndex = 0; IDockerConnection[] connections = DockerConnectionManager.getInstance() .getConnections(); if (connection != null) { currUri = connection.getUri(); } int index = 0; for (int i = 0; i < connections.length; ++i) { if (connections[i].getUri() != null && connections[i].getUri().equals(currUri)) { index = i; } } if (type == IDockerConnectionManagerListener.RENAME_EVENT) { index = currIndex; } if (connections.length > 0 && type != IDockerConnectionManagerListener.REMOVE_EVENT) { setConnection(connections[index]); } else { setConnection(null); } }
Source:
<code><START> public void shouldNotDeleteEncounterTypeWhenEncounterTypesAreLocked() throws Exception { <END> executeDataSet("org/openmrs/web/encounter/include/EncounterTypeFormControllerTest.xml"); EncounterService es = Context.getEncounterService(); EncounterTypeFormController controller = (EncounterTypeFormController) applicationContext .getBean("encounterTypeForm"); controller.setApplicationContext(applicationContext); controller.setSuccessView("index.htm"); controller.setFormView("EncounterType.form"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/encounters/encounterType.form?encounterTypeId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.setMethod("POST"); request.addParameter("action", "Delete EncounterType"); ModelAndView mav = controller.handleRequest(request, response); Assert.assertNotSame("The purge attempt should have failed!", "index.htm", mav.getViewName()); Assert.assertNotNull(es.getEncounterType(1)); }</code><technical_language>moving mocks, good mocks instead of extending BaseWebContextSensitiveTest</technical_language>

Target:
public void shouldNotDeleteEncounterTypeWhenEncounterTypesAreLocked() throws Exception { executeDataSet("org/openmrs/web/encounter/include/EncounterTypeFormControllerTest.xml"); EncounterService es = Context.getEncounterService(); EncounterTypeFormController controller = (EncounterTypeFormController) applicationContext .getBean("encounterTypeForm"); controller.setApplicationContext(applicationContext); controller.setSuccessView("index.htm"); controller.setFormView("EncounterType.form"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/encounters/encounterType.form?encounterTypeId=1"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); request.setMethod("POST"); request.addParameter("action", "Delete EncounterType"); ModelAndView mav = controller.handleRequest(request, response); Assert.assertEquals("The purge attempt should have failed!", "EncounterType.form", mav.getViewName()); Assert.assertSame(controller.getFormView(), mav.getViewName()); Assert.assertNotNull(es.getEncounterType(1)); }
Source:
<code>public static String imageRef(IBuild build) { final String kind = build.getOutputKind(); if (ResourceKind.IMAGE_STREAM_TAG.equals(kind) || IMAGE_STREAM_IMAGE_KIND.equals(kind)) { return build.getOutputTo().getNameAndTag(); } <START> if (DOCKER_IMAGE_KIND.equals(kind)) { <END> return build.getOutputTo().getNameAndTag().toString(); } return ""; }</code><technical_language>if statements merged</technical_language>

Target:
public static String imageRef(IBuild build) { if(build != null) { switch(build.getOutputKind()) { case ResourceKind.IMAGE_STREAM_TAG: case IMAGE_STREAM_IMAGE_KIND: case DOCKER_IMAGE_KIND: return build.getOutputTo().getNameAndTag(); } } return ""; }
Source:
<code>public void stringsDifferWithUserMessage() { try { assertEquals("not equal", "one", "two"); <START> } catch (AssertionError exception) { <END> assertEquals("not equal expected:<[one]> but was:<[two]>", exception.getMessage()); return; } failAssertionErrorExpected(); }</code><technical_language>change this catch ComparisonFailure instead (in case, perfectly fine call fail() in try block)</technical_language>

Target:
public void stringsDifferWithUserMessage() { try { assertEquals("not equal", "one", "two"); } catch (ComparisonFailure exception) { assertEquals("not equal expected:<[one]> but was:<[two]>", exception.getMessage()); return; } throw new AssertionError(ASSERTION_ERROR_EXPECTED); }
Source:
<code>public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType) throws IOException { String hostPortString = address.getHostString() + address.getPort(); Integer count = connectionIdToCount.get(hostPortString); if (count != null) { count++; } else { count = 1; } connectionIdToCount.put(hostPortString, count); <START> String connectionId = hostPortString + index++; <END> connections.add(connectionId); return connectionId; }</code><technical_language>u count instead of index</technical_language>

Target:
public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType) throws IOException { String hostPortString = address.getHostString() + address.getPort(); Integer count = connectionIdToCount.get(hostPortString); if (count != null) { count++; } else { count = 1; } connectionIdToCount.put(hostPortString, count); String connectionId = hostPortString + count; connections.add(connectionId); return connectionId; }
Source:
<code>public void setup(OperatorContext context) { super.setup(context); try { if (getFieldInfos() == null) { <START> LOG.info("Assuming direct mapping between POJO fields and DB columns"); <END> populateColumnDataTypes(null); } else { StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (int i = 0; i < getFieldInfos().size(); i++) { columns.append(getFieldInfos().get(i).getColumnName()); values.append("?"); if (i < getFieldInfos().size() - 1) { columns.append(","); values.append(","); } } populateColumnDataTypes(columns.toString()); } } catch (SQLException e) { throw new RuntimeException(e); } }</code><technical_language>Improve log message include explicit message missing field info</technical_language>

Target:
public void setup(OperatorContext context) { super.setup(context); try { if (getFieldInfos() == null) { LOG.info("FieldInfo missing. Assuming direct mapping between POJO fields and DB columns"); populateColumnDataTypes(null); } else { StringBuilder columns = new StringBuilder(); StringBuilder values = new StringBuilder(); for (int i = 0; i < getFieldInfos().size(); i++) { columns.append(getFieldInfos().get(i).getColumnName()); values.append("?"); if (i < getFieldInfos().size() - 1) { columns.append(","); values.append(","); } } populateColumnDataTypes(columns.toString()); } } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>private Optional<FloatingIP> allocateFloatingIPForNode(FloatingIPApi floatingIpApi, Optional<Set<String>> poolNames, String nodeID) { FloatingIP ip = null; if (poolNames.isPresent()){ for (String poolName : poolNames.get()){ try { logger.debug(">> allocating floating IP from pool %s for node(%s)", poolName, nodeID); ip = floatingIpApi.allocateFromPool(poolName); <START> if (ip != null){ <END> break; } } catch (InsufficientResourcesException ire){ logger.trace("<< [%s] failed to allocate floating IP from pool %s for node(%s)", ire.getMessage(), poolName, nodeID); } } } if (ip == null){ try { logger.debug(">> creating floating IP for node(%s)", nodeID); ip = floatingIpApi.create(); } catch (InsufficientResourcesException ire){ logger.trace("<< [%s] failed to create floating IP for node(%s)", ire.getMessage(), nodeID); } } if (ip == null){ logger.trace(">> searching for existing, unassigned floating IP for node(%s)", nodeID); List<FloatingIP> unassignedIps = Lists.newArrayList(Iterables.filter(floatingIpApi.list(), new Predicate<FloatingIP>() { @Override public boolean apply(FloatingIP arg0) { return arg0.getFixedIp() == null; } })); Collections.shuffle(unassignedIps); ip = Iterables.getLast(unassignedIps); } return Optional.fromNullable(ip); }</code><technical_language>return avoid "if" statements? Code cleaner</technical_language>

Target:
private Optional<FloatingIP> allocateFloatingIPForNode(FloatingIPApi floatingIpApi, Optional<Set<String>> poolNames, String nodeID) { FloatingIP ip = null; if (poolNames.isPresent()) { for (String poolName : poolNames.get()){ try { logger.debug(">> allocating floating IP from pool %s for node(%s)", poolName, nodeID); ip = floatingIpApi.allocateFromPool(poolName); if (ip != null) return Optional.of(ip); } catch (InsufficientResourcesException ire){ logger.trace("<< [%s] failed to allocate floating IP from pool %s for node(%s)", ire.getMessage(), poolName, nodeID); } } } try { logger.debug(">> creating floating IP for node(%s)", nodeID); ip = floatingIpApi.create(); if(ip != null) return Optional.of(ip); } catch (InsufficientResourcesException ire){ logger.trace("<< [%s] failed to create floating IP for node(%s)", ire.getMessage(), nodeID); } logger.trace(">> searching for existing, unassigned floating IP for node(%s)", nodeID); List<FloatingIP> unassignedIps = Lists.newArrayList(Iterables.filter(floatingIpApi.list(), new Predicate<FloatingIP>() { @Override public boolean apply(FloatingIP arg0) { return arg0.getFixedIp() == null; } })); Collections.shuffle(unassignedIps); ip = Iterables.getLast(unassignedIps); return Optional.fromNullable(ip); }
Source:
<code>public void evict(WrappedBytes key) { Lock lock = locks.getLock(key).writeLock(); lock.lock(); try { checkDeallocation(); long address = memoryLookup.getMemoryAddress(key); if (address != 0) { InternalCacheEntry<WrappedBytes, WrappedBytes> ice = performGet(address, key); <START> passivator.passivate(ice); <END> performRemove(address, key); } } finally { lock.unlock(); } }</code><technical_language>add if check for ice do this line next if is null. Prevents another loop linked list if exists</technical_language>

Target:
public void evict(WrappedBytes key) { Lock lock = locks.getLock(key).writeLock(); lock.lock(); try { checkDeallocation(); long address = memoryLookup.getMemoryAddress(key); if (address != 0) { InternalCacheEntry<WrappedBytes, WrappedBytes> ice = performGet(address, key); if (ice != null) { passivator.passivate(ice); performRemove(address, key); } } } finally { lock.unlock(); } }
Source:
<code>protected void executeCommand() { setCommandStatus(CommandStatus.ACTIVE_ASYNC); Guid taskId = persistAsyncTaskPlaceHolder(VdcActionType.DestroyImage); VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.DestroyImage, createVDSParameters()); if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getParameters().setVdsmTaskIds(new ArrayList<Guid>()); Guid result = createTask(taskId, vdsReturnValue.getCreationInfo(), VdcActionType.DestroyImage, VdcObjectType.Storage, getParameters().getStorageDomainId()); getReturnValue().getInternalVdsmTaskIdList().add(result); getReturnValue().getVdsmTaskIdList().add(result); getParameters().getVdsmTaskIds().add(result); setSucceeded(vdsReturnValue.getSucceeded()); <START> setCommandStatus(CommandStatus.ACTIVE_ASYNC_EXECUTED); <END> persistCommandWithContext(getParameters().getParentCommand(), true); log.info("Successfully started task to remove orphaned volumes resulting from live merge"); } else { setSucceeded(false); setCommandStatus(CommandStatus.FAILED); } }</code><technical_language>print log.info declare success</technical_language>

Target:
protected void executeCommand() { setCommandStatus(CommandStatus.ACTIVE_ASYNC); Guid taskId = persistAsyncTaskPlaceHolder(VdcActionType.DestroyImage); VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.DestroyImage, createVDSParameters()); if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getParameters().setVdsmTaskIds(new ArrayList<Guid>()); Guid result = createTask(taskId, vdsReturnValue.getCreationInfo(), VdcActionType.DestroyImage, VdcObjectType.Storage, getParameters().getStorageDomainId()); getReturnValue().getInternalVdsmTaskIdList().add(result); getReturnValue().getVdsmTaskIdList().add(result); getParameters().getVdsmTaskIds().add(result); setSucceeded(vdsReturnValue.getSucceeded()); persistCommandWithContext(getParameters().getParentCommand(), true); log.info("Successfully started task to remove orphaned volumes resulting from live merge"); } else { setSucceeded(false); setCommandStatus(CommandStatus.FAILED); } }
Source:
<code>public UserBasedBlacklist(Path source, CoreNode core, MutablePointers mutable, ContentAddressedStorage dht) { this.source = source; this.core = core; this.mutable = mutable; this.dht = dht; <START> pool.submit(() -> { <END> while (true) { updateBlackList(); try { Thread.sleep(5000); } catch (InterruptedException e) } }); }</code><technical_language>suggest making this more resilient failures: while (true) { try { updateBlackList(); } catch (Throwable t) { //log t } try { Thread.sleep(5000); } catch (InterruptedException e) }</technical_language>

Target:
public UserBasedBlacklist(Path source, CoreNode core, MutablePointers mutable, ContentAddressedStorage dht) { this.source = source; this.core = core; this.mutable = mutable; this.dht = dht; pool.submit(() -> { while (true) { try { updateBlackList(); } catch (Throwable t) { t.printStackTrace(); } try { Thread.sleep(5000); } catch (InterruptedException e) } }); }
Source:
<code><START> public void onGetSmeltingResult(ItemStack stack, CallbackInfoReturnable<ItemStack> cir) { <END> ItemStackSnapshot ingredient = ItemStackUtil.snapshotOf(stack); Optional<SmeltingResult> result = getCustomResult(ingredient); if (result.isPresent()) { ItemStack nativeResult = ItemStackUtil.fromSnapshotToNative(result.get().getResult()); cir.setReturnValue(nativeResult); } }</code><technical_language>is need this public</technical_language>

Target:
private void onGetSmeltingResult(ItemStack stack, CallbackInfoReturnable<ItemStack> cir) { ItemStackSnapshot ingredient = ItemStackUtil.snapshotOf(stack); Optional<SmeltingResult> result = getCustomResult(ingredient); if (result.isPresent()) { ItemStack nativeResult = ItemStackUtil.fromSnapshotToNative(result.get().getResult()); cir.setReturnValue(nativeResult); } }
Source:
<code>Optional<DataType> lookupAbsoluteParent(final DataType reference) { final Optional<DataType> optionalParent = Optional.ofNullable(parent(reference)); if (optionalParent.isPresent()) { final DataType parent = optionalParent.get(); <START> if (parent.getType().equals(dataTypeManager.structure())) { <END> return Optional.of(parent); } else { return dataTypeStore .getTopLevelDataTypes() .stream() .filter(dataType -> dataType.getName().equals(parent.getType())) .findFirst(); } } return Optional.empty(); }</code><technical_language>please Objects.equals</technical_language>

Target:
Optional<DataType> lookupAbsoluteParent(final DataType reference) { final Optional<DataType> optionalParent = Optional.ofNullable(parent(reference)); if (optionalParent.isPresent()) { return fetchTopLevelDataType(optionalParent.get()); } return Optional.empty(); }
Source:
<code><START> private boolean isEmptyCollection(Expression expr) { <END> return (expr instanceof ListExpression && ((ListExpression) expr).getExpressions().size() == 0) || (expr instanceof MapExpression && ((MapExpression) expr).getMapEntryExpressions().size() == 0); }</code><technical_language>static</technical_language>

Target:
private static boolean isEmptyCollection(Expression expr) { return (expr instanceof ListExpression && ((ListExpression) expr).getExpressions().size() == 0) || (expr instanceof MapExpression && ((MapExpression) expr).getMapEntryExpressions().size() == 0); }
Source:
<code>static void readMappingFile(VolumeManager fs, ImportedTableInfo tableInfo, String importDir, Map<String,String> fileNameMappings) throws Exception { try (BufferedReader in = new BufferedReader( new InputStreamReader(fs.open(new Path(importDir, "mappings.txt")), UTF_8))) { String line, prev; while ((line = in.readLine()) != null) { <START> String[] sa = line.split(":", 2); <END> prev = fileNameMappings.put(sa[0], importDir + "/" + sa[1]); if (prev != null) { String msg = "File exists in multiple import directories: '" + sa[0] + "'"; log.warn(msg); throw new AcceptableThriftTableOperationException(tableInfo.tableId.canonical(), tableInfo.tableName, TableOperation.IMPORT, TableOperationExceptionType.OTHER, msg); } } } }</code><technical_language>importDir + "/" + sa[1] repeatedly potential a lot more memory sa[1]. this issue for large imports. This addressed a object points importDir. fileNameMappings.put(sa[0], new Pair<>(importDir, sa[1]))</technical_language>

Target:
static void readMappingFile(VolumeManager fs, ImportedTableInfo tableInfo, String importDir, Map<String,String> fileNameMappings) throws Exception { try (BufferedReader in = new BufferedReader( new InputStreamReader(fs.open(new Path(importDir, "mappings.txt")), UTF_8))) { String line, prev; while ((line = in.readLine()) != null) { String[] sa = line.split(":", 2); prev = fileNameMappings.put(sa[0], importDir + "/" + sa[1]); if (prev != null) { String msg = "File exists in multiple import directories: '" + sa[0].replaceAll("[\r\n]", "") + "'"; log.warn(msg); throw new AcceptableThriftTableOperationException(tableInfo.tableId.canonical(), tableInfo.tableName, TableOperation.IMPORT, TableOperationExceptionType.OTHER, msg); } } } }
Source:
<code>public void openEmailClient() { if (WPActivityUtils.isEmailClientAvailable(this)) { <START> AnalyticsTracker.track(AnalyticsTracker.Stat.LOGIN_MAGIC_LINK_OPEN_EMAIL_CLIENT_VIEWED); <END> WPActivityUtils.openEmailClient(this); } else { ToastUtils.showToast(this, R.string.login_email_client_not_found); } }</code><technical_language>This stat tracking LoginMagicLinkSentFragment is viewed, user attempts open email client. I realize naming a bit unclear</technical_language>

Target:
public void openEmailClient() { if (WPActivityUtils.isEmailClientAvailable(this)) { AnalyticsTracker.track(AnalyticsTracker.Stat.LOGIN_MAGIC_LINK_OPEN_EMAIL_CLIENT_CLICKED); WPActivityUtils.openEmailClient(this); } else { ToastUtils.showToast(this, R.string.login_email_client_not_found); } }
Source:
<code>public ModelAndView showNewCodeReviewPage(@RequestParam(BRANCH_ID) Long branchId) throws NotFoundException { TopicDto dto; <START> TopicDraft draft = topicDraftService.getDraft(); <END> if (draft != null) { dto = new TopicDto(draft); } else { Topic topic = new Topic(); topic.setPoll(new Poll()); dto = new TopicDto(topic); } Branch branch = branchService.get(branchId); dto.getTopic().setBranch(branch); return new ModelAndView(CODE_REVIEW_VIEW) .addObject(TOPIC_DTO, dto) .addObject(BRANCH_ID, branchId) .addObject(SUBMIT_URL, "/reviews/new?branchId=" + branchId) .addObject(BREADCRUMB_LIST, breadcrumbBuilder.getNewTopicBreadcrumb(branch)); }</code><technical_language>ObjectUtils.defaultIfNull() well</technical_language>

Target:
public ModelAndView showNewCodeReviewPage(@RequestParam(BRANCH_ID) Long branchId) throws NotFoundException { TopicDraft draft = ObjectUtils.defaultIfNull( topicDraftService.getDraft(), new TopicDraft()); TopicDto dto = new TopicDto(draft); Branch branch = branchService.get(branchId); dto.getTopic().setBranch(branch); return new ModelAndView(CODE_REVIEW_VIEW) .addObject(TOPIC_DTO, dto) .addObject(BRANCH_ID, branchId) .addObject(SUBMIT_URL, "/reviews/new?branchId=" + branchId) .addObject(BREADCRUMB_LIST, breadcrumbBuilder.getNewTopicBreadcrumb(branch)); }
Source:
<code>protected Resource getSelectedResource(final ISelection currentSelection) { Resource resource = null; <START> if (currentSelection instanceof StructuredSelection && ((StructuredSelection) currentSelection).size() == 1) { <END> final Object selectedElement = ((StructuredSelection) currentSelection).getFirstElement(); if (selectedElement instanceof File && NattableConfigurationConstants.NATTABLE_CONFIGURATION_EXTENSION_FILE.equals(((File) selectedElement).getFileExtension())) { INattableModelManager manager = null; final IEditorPart currentPart = getActivePart().getSite().getPage().getActiveEditor(); if (null != currentPart) { manager = (INattableModelManager) currentPart.getAdapter(INattableModelManager.class); } if (null != manager) { resource = TableEditingDomainUtils.getTableEditingDomain(manager.getTable()).getResourceSet().getResource(URI.createFileURI(((File) selectedElement).getLocation().toString()), true); } } } return resource; }</code><technical_language>invert</technical_language>

Target:
protected Resource getSelectedResource(final ISelection currentSelection) { Resource resource = null; if (currentSelection instanceof StructuredSelection && 1 == ((StructuredSelection) currentSelection).size()) { final Object selectedElement = ((StructuredSelection) currentSelection).getFirstElement(); if (selectedElement instanceof File && NattableConfigurationConstants.NATTABLE_CONFIGURATION_EXTENSION_FILE.equals(((File) selectedElement).getFileExtension())) { INattableModelManager manager = null; final IEditorPart currentPart = getActivePart().getSite().getPage().getActiveEditor(); if (null != currentPart) { manager = (INattableModelManager) currentPart.getAdapter(INattableModelManager.class); } if (null != manager) { resource = TableEditingDomainUtils.getTableEditingDomain(manager.getTable()).getResourceSet().getResource(URI.createFileURI(((File) selectedElement).getLocation().toString()), true); } } } return resource; }