auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private long detectObjects(String imageHex, String cascadeFilePath) { long objectCount; try { byte[] imageByteArr = (byte[]) new Hex().decode(imageHex); Mat image = Highgui.imdecode(new MatOfByte(imageByteArr), Highgui.IMREAD_UNCHANGED); CascadeClassifier cClassifier = new CascadeClassifier(); cClassifier.load(cascadeFilePath); Imgproc.cvtColor(image, image, Imgproc.COLOR_RGB2GRAY); Imgproc.equalizeHist(image, image); MatOfRect imageRect = new MatOfRect(); cClassifier.detectMultiScale(image, imageRect); objectCount = ((Integer) imageRect.toList().size()).longValue(); } catch (DecoderException e) { log.error("Unable to decode the hex string of the image.", e); throw new RuntimeException("Unable to decode the hex string of the image.", e); <START> } <END> return objectCount; }</code><technical_language>Pass image file path in exception</technical_language>

Target:
private long detectObjects(String imageHex, String cascadeFilePath) { long objectCount; try { byte[] imageByteArr = (byte[]) new Hex().decode(imageHex); Mat image = Highgui.imdecode(new MatOfByte(imageByteArr), Highgui.IMREAD_UNCHANGED); CascadeClassifier cClassifier = new CascadeClassifier(); cClassifier.load(cascadeFilePath); Imgproc.cvtColor(image, image, Imgproc.COLOR_RGB2GRAY); Imgproc.equalizeHist(image, image); MatOfRect imageRect = new MatOfRect(); cClassifier.detectMultiScale(image, imageRect); objectCount = ((Integer) imageRect.toList().size()).longValue(); } catch (DecoderException e) { log.error("Unable to decode the hex string of the image. Make sure the image is not " + "corrupted.", e); throw new RuntimeException("Unable to decode the hex string of the image. Make sure " + "the image is not corrupted.", e); } return objectCount; }
Source:
<code>public void setUp() throws Exception { <START> URL resource = getClass().getResource("/projects/CSharpFileAdvancedOperations"); <END> testProjectServiceClient.importProject( workspace.getId(), Paths.get(resource.toURI()), PROJECT_NAME, DOT_NET); ide.open(workspace); projectExplorer.openItemByPath(PROJECT_NAME); projectExplorer.openItemByPath(PATH_TO_DOTNET_FILE); consoles.waitExpectedTextIntoConsole(FINISH_LANGUAGE_SERVER_INITIALIZATION_MESSAGE); projectExplorer.waitItem(PROJECT_NAME + "/obj"); projectExplorer.waitItem(PROJECT_NAME + "/bin"); }</code><technical_language>In opinion, renaming of variable "testProject" enough</technical_language>

Target:
public void setUp() throws Exception { URL resource = getClass().getResource("/projects/CSharpFileAdvancedOperations"); testProjectServiceClient.importProject( workspace.getId(), Paths.get(resource.toURI()), PROJECT_NAME, DOT_NET); ide.open(workspace); projectExplorer.openItemByPath(PROJECT_NAME); projectExplorer.openItemByPath(PATH_TO_DOT_NET_FILE); consoles.waitExpectedTextIntoConsole(FINISH_LANGUAGE_SERVER_INITIALIZATION_MESSAGE); projectExplorer.waitItem(PROJECT_NAME + "/obj"); projectExplorer.waitItem(PROJECT_NAME + "/bin"); }
Source:
<code>@NonNull public String server() { if (server.startsWith(" server = <START> "https:" + <END> server; } return server; }</code><technical_language>derive this Prefs.getMediaWikiBaseUri() require client pass in a default protocol. I I prefer avoid complicating this nice simple model type</technical_language>

Target:
@NonNull public String server() { return server; }
Source:
<code>public Workflow initializeWorkflow(String repositoryId, Workflow workflow) { try { GHRepository repository = github.getRepository(repositoryId); workflow.setOrganization(repository.getOwner().getLogin()); workflow.setRepository(repository.getName()); workflow.setSourceControl(SourceControl.GITHUB); workflow.setGitUrl(repository.getSshUrl()); workflow.setLastUpdated(new Date()); } catch (GHFileNotFoundException e) { <START> LOG.info(gitUsername + ": GitHub reports file not found: " + e.getCause().getLocalizedMessage()); <END> throw new CustomWebApplicationException("GitHub reports file not found: " + e.getCause().getLocalizedMessage(), HttpStatus.SC_BAD_REQUEST); } catch (IOException e) { LOG.info(gitUsername + ": Cannot getNewWorkflow {}"); throw new CustomWebApplicationException("Could not reach GitHub", HttpStatus.SC_SERVICE_UNAVAILABLE); } return workflow; }</code><technical_language>I feel good log exception, in handy</technical_language>

Target:
public Workflow initializeWorkflow(String repositoryId, Workflow workflow) { try { GHRepository repository = github.getRepository(repositoryId); workflow.setOrganization(repository.getOwner().getLogin()); workflow.setRepository(repository.getName()); workflow.setSourceControl(SourceControl.GITHUB); workflow.setGitUrl(repository.getSshUrl()); workflow.setLastUpdated(new Date()); } catch (GHFileNotFoundException e) { LOG.info(gitUsername + ": GitHub reports file not found: " + e.getCause().getLocalizedMessage(), e); throw new CustomWebApplicationException("GitHub reports file not found: " + e.getCause().getLocalizedMessage(), HttpStatus.SC_BAD_REQUEST); } catch (IOException e) { LOG.info(gitUsername + ": Cannot getNewWorkflow {}", e); throw new CustomWebApplicationException("Could not reach GitHub", HttpStatus.SC_SERVICE_UNAVAILABLE); } return workflow; }
Source:
<code>public void putSchemaMetadata(String schemaName, SchemaMetadata schemaMetadata) { byte[] serializedMetadata = schemaMetadata.persistToBytes(); while (!Thread.currentThread().isInterrupted()) { Optional<byte[]> existingMetadata = loadMetadataCellFromKeyValueService(schemaName); CheckAndSetRequest request = existingMetadata.map(existingData -> CheckAndSetRequest.singleCell( AtlasDbConstants.DEFAULT_SCHEMA_METADATA_TABLE, createCellForGivenSchemaName(schemaName), existingData, serializedMetadata)) .orElse(CheckAndSetRequest.newCell( AtlasDbConstants.DEFAULT_SCHEMA_METADATA_TABLE, createCellForGivenSchemaName(schemaName), serializedMetadata)); try { <START> keyValueService.checkAndSet(request); <END> return; } catch (CheckAndSetException e) { log.info("Failed to update the schema metadata: {}. Retrying.", UnsafeArg.of("attemptedUpdate", request)); } } }</code><technical_language>log success here, a lot of "Retrying" statements class confusing</technical_language>

Target:
public void putSchemaMetadata(String schemaName, SchemaMetadata schemaMetadata) { byte[] serializedMetadata = schemaMetadata.persistToBytes(); while (!Thread.currentThread().isInterrupted()) { Optional<byte[]> existingMetadata = loadMetadataCellFromKeyValueService(schemaName); CheckAndSetRequest request = existingMetadata.map(existingData -> CheckAndSetRequest.singleCell( AtlasDbConstants.DEFAULT_SCHEMA_METADATA_TABLE, createCellForGivenSchemaName(schemaName), existingData, serializedMetadata)) .orElse(CheckAndSetRequest.newCell( AtlasDbConstants.DEFAULT_SCHEMA_METADATA_TABLE, createCellForGivenSchemaName(schemaName), serializedMetadata)); try { keyValueService.checkAndSet(request); log.info("Successfully updated the schema metadata to {}.", UnsafeArg.of("committedUpdate", request)); return; } catch (CheckAndSetException e) { log.info("Failed to update the schema metadata: {}. Retrying.", UnsafeArg.of("attemptedUpdate", request)); } } }
Source:
<code>private static boolean hasSuppressed(Throwable exception) { <START> if (getSuppressed != null) { <END> try { Throwable[] suppressed = (Throwable[]) getSuppressed.invoke(exception); return suppressed.length != 0; } catch (Throwable e) { return false; } } else { return false; } }</code><technical_language>nit: I personally prefer existing out error conditions early, avoid over-intentation: if (getSuppressed == null) { return false; } try { ... } catch (Throwable e) { return false; }</technical_language>

Target:
private static boolean hasSuppressed(Throwable exception) { if (getSuppressed == null) { return false; } try { Throwable[] suppressed = (Throwable[]) getSuppressed.invoke(exception); return suppressed.length != 0; } catch (Throwable e) { return false; } }
Source:
<code>private ITransformedNetwork getFinalTransformedNetwork(ITransformedNetwork transformedNetwork, List<String> alternativeIdsForConceptList) { List<Node> searchedNodes = new ArrayList<Node>(); Set<String> statementIdSet = new HashSet<String>(); for (Node node : transformedNetwork.getNodes().values()) { for (String alternativeIdsForConcept : alternativeIdsForConceptList) { if (alternativeIdsForConcept.equals(node.getConceptId())) { searchedNodes.add(node); statementIdSet.addAll(node.getStatementIds()); break; } } } List<Link> finalLinks = new ArrayList<Link>(); Set<Link> finalLinksSet = new HashSet<Link>(); Map<String, Node> finalNodes = new HashMap<String, Node>(); Set<Node> addedNodes = new HashSet<Node>(); for (Link link : transformedNetwork.getLinks()) { if (statementIdSet.contains(link.getStatementId())) { finalLinksSet.add(link); Node subjectNode = link.getSubject(); Node objectNode = link.getObject(); if (!addedNodes.contains(subjectNode)) { finalNodes.put(subjectNode.getId(), subjectNode); addedNodes.add(subjectNode); } if (!addedNodes.contains(objectNode)) { finalNodes.put(objectNode.getId(), objectNode); addedNodes.add(objectNode); } } } for (Node node : searchedNodes) { if (!searchedNodes.contains(node)) { finalNodes.put(node.getId(), node); } } finalLinks.addAll(finalLinksSet); <START> return new TransformedNetwork(finalNodes, finalLinks); <END> }</code><technical_language>merge4 line 343 378</technical_language>

Target:
private ITransformedNetwork getFinalTransformedNetwork(ITransformedNetwork transformedNetwork, List<String> alternativeIdsForConceptList) { List<Node> searchedNodes = new ArrayList<Node>(); Set<String> statementIdSet = new HashSet<String>(); for (Node node : transformedNetwork.getNodes().values()) { for (String alternativeIdsForConcept : alternativeIdsForConceptList) { if (alternativeIdsForConcept.equals(node.getConceptId())) { searchedNodes.add(node); statementIdSet.addAll(node.getStatementIds()); break; } } } Set<Link> finalLinksSet = new HashSet<Link>(); Map<String, Node> finalNodes = new HashMap<String, Node>(); Set<Node> addedNodes = new HashSet<Node>(); for (Link link : transformedNetwork.getLinks()) { if (statementIdSet.contains(link.getStatementId())) { finalLinksSet.add(link); Node subjectNode = link.getSubject(); Node objectNode = link.getObject(); if (!addedNodes.contains(subjectNode)) { finalNodes.put(subjectNode.getId(), subjectNode); addedNodes.add(subjectNode); } if (!addedNodes.contains(objectNode)) { finalNodes.put(objectNode.getId(), objectNode); addedNodes.add(objectNode); } } } for (Node node : searchedNodes) { if (!searchedNodes.contains(node)) { finalNodes.put(node.getId(), node); } } List<Link> finalLinks = new ArrayList<Link>(finalLinksSet); return new TransformedNetwork(finalNodes, finalLinks); }
Source:
<code><START> public void setMaximumPoolSize(int newMaximumPoolSize) <END> { final int oldMaxWorkers = maxWorkers.get(); long current; int workPermits; if (newMaximumPoolSize < 0) { throw new IllegalArgumentException("Maximum number of workers must not be negative"); } int deltaWorkPermits = newMaximumPoolSize - oldMaxWorkers; if (!maxWorkers.compareAndSet(oldMaxWorkers, newMaximumPoolSize)) { throw new IllegalStateException("Maximum pool size has been changed while resizing"); } if (deltaWorkPermits == 0) return; do { current = permits.get(); workPermits = workPermits(current); } while (!permits.compareAndSet(current, updateWorkPermits(current, workPermits + deltaWorkPermits))); logger.info("Resized maximum pool size from to {}", name, oldMaxWorkers, newMaximumPoolSize); updatedMaxWorkers.onUpdateMaximumPoolSize(newMaximumPoolSize); }</code><technical_language>synchronised</technical_language>

Target:
public synchronized void setMaximumPoolSize(int newMaximumPoolSize) { final int oldMaximumPoolSize = maximumPoolSize.get(); if (newMaximumPoolSize < 0) { throw new IllegalArgumentException("Maximum number of workers must not be negative"); } int deltaWorkPermits = newMaximumPoolSize - oldMaximumPoolSize; if (!maximumPoolSize.compareAndSet(oldMaximumPoolSize, newMaximumPoolSize)) { throw new IllegalStateException("Maximum pool size has been changed while resizing"); } if (deltaWorkPermits == 0) return; permits.updateAndGet(cur -> updateWorkPermits(cur, workPermits(cur) + deltaWorkPermits)); logger.info("Resized maximum pool size from to {}", name, oldMaximumPoolSize, newMaximumPoolSize); maximumPoolSizeListener.onUpdateMaximumPoolSize(newMaximumPoolSize); }
Source:
<code>public void process(Node externsNode, Node rootNode) { if (rootNode.hasChildren()) { if (instrumentOption == InstrumentOption.BRANCH_ONLY) { NodeTraversal.traverse( compiler, rootNode, new BranchCoverageInstrumentationCallback(compiler, instrumentationData)); } else if (instrumentOption == InstrumentOption.ADVANCED) { NodeTraversal.traverse( compiler, rootNode, <START> new AdvancedCoverageInstrumentationCallback(compiler, new HashMap<>())); <END> return; } else { NodeTraversal.traverse( compiler, rootNode, new CoverageInstrumentationCallback(instrumentationData, reach)); } Node firstScript = rootNode.getFirstChild(); checkState(firstScript.isScript()); if (firstScript.hasChildren() && firstScript.getFirstChild().isModuleBody()) { firstScript = firstScript.getFirstChild(); } addHeaderCode(firstScript); } }</code><technical_language>Is passing in Map a parameter necessary? used, initialized in callback itself. If not, prefer LinkedHashMap here, deterministic iteration order</technical_language>

Target:
public void process(Node externsNode, Node rootNode) { if (rootNode.hasChildren()) { if (instrumentOption == InstrumentOption.BRANCH_ONLY) { NodeTraversal.traverse( compiler, rootNode, new BranchCoverageInstrumentationCallback(compiler, instrumentationData)); } else if (instrumentOption == InstrumentOption.PRODUCTION) { NodeTraversal.traverse( compiler, rootNode, new ProductionCoverageInstrumentationCallback(compiler)); return; } else { NodeTraversal.traverse( compiler, rootNode, new CoverageInstrumentationCallback(instrumentationData, reach)); } Node firstScript = rootNode.getFirstChild(); checkState(firstScript.isScript()); if (firstScript.hasChildren() && firstScript.getFirstChild().isModuleBody()) { firstScript = firstScript.getFirstChild(); } addHeaderCode(firstScript); } }
Source:
<code>public Task<?> expunge(final Entity entity, final boolean release) { return mgmt.getExecutionManager().submit( MutableMap.of("displayName", "expunging " + entity, "description", "REST call to expunge entity " + entity.getDisplayName() + " (" + entity + ")"), new Runnable() { @Override public void run() { if (release) <START> Entities.destroyCatching(entity); <END> mgmt.getEntityManager().unmanage(entity); } }); }</code><technical_language>I expunge(true) a jboss7 entity, I logging of: 2014-01-28 22:18:47,089 WARN brooklyn.management.internal.LocalEntityManager@2524e205 call stop management of unknown entity (already unmanaged?) JBoss7ServerImpl{id=mPXYvab1}; skipping, descendants This is Entities.destroyCatching unmanage. want if-else, do mgmt.getEntityManager().unmanage(entity) in else block</technical_language>

Target:
public Task<?> expunge(final Entity entity, final boolean release) { return mgmt.getExecutionManager().submit( MutableMap.of("displayName", "expunging " + entity, "description", "REST call to expunge entity " + entity.getDisplayName() + " (" + entity + ")"), new Runnable() { @Override public void run() { if (release) Entities.destroyCatching(entity); else mgmt.getEntityManager().unmanage(entity); } }); }
Source:
<code>public void mouseHover(MouseEvent e) { if ((getChartViewer().getWindowDuration() != 0) && (e != null)) { IAxis xAxis = getChart().getAxisSet().getXAxis(0); IAxis yAxis = getChart().getAxisSet().getYAxis(0); ISeries[] series = getChart().getSeriesSet().getSeries(); double smallestDistance = Double.MAX_VALUE; int seriesIndex = 0; int dataIndex = 0; <START> for (int k = 0; k < series.length; k++) { <END> ISeries serie = series[k]; double[] xS = serie.getXSeries(); double[] yS = serie.getYSeries(); if ((xS == null) || (yS == null)) { return; } for (int i = 0; i < xS.length; i++) { int xs = xAxis.getPixelCoordinate(xS[i]); int ys = yAxis.getPixelCoordinate(yS[i]); double currentDistance = Math.sqrt(Math.pow((e.x - xs), 2) + Math.pow((e.y - ys), 2)); if (currentDistance < smallestDistance) { smallestDistance = currentDistance; fHighlightX = xs; fHighlightY = ys; seriesIndex = k; dataIndex = i; } } } String tooltip = createToolTipText(seriesIndex, dataIndex); if (tooltip != null) { getChart().getPlotArea().setToolTipText(tooltip); fIsHighlight = true; getChart().redraw(); } } }</code><technical_language>I if this is a performance issue, if is, : 1- remove duplicate points 2- if set is X sorted, (no garanty) if X2 > min dist, ignore. do this if performance is issue</technical_language>

Target:
public void mouseHover(MouseEvent e) { if ((getChartViewer().getWindowDuration() != 0) && (e != null)) { IAxis xAxis = getChart().getAxisSet().getXAxis(0); IAxis yAxis = getChart().getAxisSet().getYAxis(0); ISeries[] series = getChart().getSeriesSet().getSeries(); double smallestDistance = Double.MAX_VALUE; Parameter param = null; for (int k = 0; k < series.length; k++) { ISeries serie = series[k]; double[] xS = serie.getXSeries(); double[] yS = serie.getYSeries(); if ((xS == null) || (yS == null)) { continue; } for (int i = 0; i < xS.length; i++) { int xs = xAxis.getPixelCoordinate(xS[i]) - e.x; int ys = yAxis.getPixelCoordinate(yS[i]) - e.y; double currentDistance = Math.sqrt(xs * xs + ys * ys); if ((currentDistance < smallestDistance) && (currentDistance < HIGHLIGHT_RADIUS)) { smallestDistance = currentDistance; fHighlightX = xs + e.x; fHighlightY = ys + e.y; if (param == null) { param = new Parameter(); } param.setSeriesIndex(k); param.setDataIndex(i); } } } String tooltip = null; if (param != null) { tooltip = createToolTipText(param); if (tooltip != null) { fIsHighlight = true; getChart().redraw(); } } getChart().getPlotArea().setToolTipText(tooltip); } }
Source:
<code>public IASTImplicitName[] getImplicitNames() { if (implicitNames == null) { IBinding ctor = CPPSemantics.findImplicitlyCalledConstructor(this); if (ctor == null) { implicitNames = IASTImplicitName.EMPTY_NAME_ARRAY; } else { CPPASTImplicitName ctorName = new CPPASTImplicitName(ctor.getNameCharArray(), this); ctorName.setBinding(ctor); IASTName id = name; <START> if (id instanceof ICPPASTQualifiedName) { <END> id = id.getLastName(); } ctorName.setOffsetAndLength((ASTNode) id); implicitNames = new IASTImplicitName[] { ctorName }; } } return implicitNames; }</code><technical_language>Redundant condition. more in other files</technical_language>

Target:
public IASTImplicitName[] getImplicitNames() { if (implicitNames == null) { IBinding ctor = CPPSemantics.findImplicitlyCalledConstructor(this); if (ctor == null) { implicitNames = IASTImplicitName.EMPTY_NAME_ARRAY; } else { CPPASTImplicitName ctorName = new CPPASTImplicitName(ctor.getNameCharArray(), this); ctorName.setBinding(ctor); IASTName id = name.getLastName(); ctorName.setOffsetAndLength((ASTNode) id); implicitNames = new IASTImplicitName[] { ctorName }; } } return implicitNames; }
Source:
<code>private boolean isConsiderSuccessful() { <START> return getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.AUTO_GENERATED_SNAPSHOT_REMOVE_END; <END> }</code><technical_language>check current of that, print audit log indicating source disk deleted - right changes method wrong</technical_language>

Target:
private boolean isConsiderSuccessful() { return getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.SOURCE_IMAGE_DELETION; }
Source:
<code>private Statement addScopeToMethodCallExpr(PreprocessPhaseResult result, Expression scope, Statement e) { if (e != null && e.isExpressionStmt()) { Expression expression = e.asExpressionStmt().getExpression(); if (expression.isMethodCallExpr()) { MethodCallExpr mcExpr = expression.asMethodCallExpr(); Expression enclosed = new EnclosedExpr(scope); mcExpr.setScope(enclosed); final String methodName = mcExpr.getName().asString(); <START> String set = methodName.replace("set", ""); <END> if (scope.isNameExpr() || scope instanceof DrlNameExpr) { result.addModifyProperties(printConstraint(scope)); } return new ExpressionStmt(mcExpr); } } return e; }</code><technical_language>if missing something, I 2 statements leftover removed</technical_language>

Target:
private Statement addScopeToMethodCallExpr(PreprocessPhaseResult result, Expression scope, Statement e) { if (e != null && e.isExpressionStmt()) { Expression expression = e.asExpressionStmt().getExpression(); if (expression.isMethodCallExpr()) { MethodCallExpr mcExpr = expression.asMethodCallExpr(); Expression enclosed = new EnclosedExpr(scope); mcExpr.setScope(enclosed); if (scope.isNameExpr() || scope instanceof DrlNameExpr) { result.addUsedBinding(printConstraint(scope)); } return new ExpressionStmt(mcExpr); } } return e; }
Source:
<code>protected Resource getInputType(Object input) { <START> if (input instanceof EditPart) { input = ((EditPart) input).getModel(); } if (input instanceof Resource) { return (Resource) input; } <END> return null; }</code><technical_language>before, simply if (input instanceof EditPart && ((EditPart) input).getModel() instanceof Resource)</technical_language>

Target:
protected Resource getInputType(Object input) { if (input instanceof EditPart && ((EditPart) input).getModel() instanceof Resource) return (Resource) input; }
Source:
<code><START> public CompletableFuture<?> readRecoveredState(ExecutorService executor, ChannelStateReader reader) throws IOException { synchronized (requestLock) { if (closeFuture.isDone()) { return FutureUtils.completedVoidFuture(); } for (InputChannel inputChannel : inputChannels.values()) { if (inputChannel instanceof RemoteRecoveredInputChannel) { ((RemoteRecoveredInputChannel) inputChannel).assignExclusiveSegments(); } } } <END> List<CompletableFuture<?>> futures = getStateConsumedFuture(); executor.submit(() -> { Collection<InputChannel> channels; synchronized (requestLock) { channels = inputChannels.values(); } internalReadRecoveredState(reader, channels); }); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); }</code><technical_language>is this change relevant fix? add some explanation commit message</technical_language>

Target:
public CompletableFuture<?> readRecoveredState(ExecutorService executor, ChannelStateReader reader) throws IOException { synchronized (requestLock) { if (closeFuture.isDone()) { return FutureUtils.completedVoidFuture(); } for (InputChannel inputChannel : inputChannels.values()) { if (inputChannel instanceof RecoveredInputChannel) { ((RecoveredInputChannel) inputChannel).assignExclusiveSegments(); } } } List<CompletableFuture<?>> futures = getStateConsumedFuture(); executor.submit(() -> { Collection<InputChannel> channels; synchronized (requestLock) { channels = inputChannels.values(); } internalReadRecoveredState(reader, channels); }); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); }
Source:
<code>void processRoads() throws IOException { DataStore dataStore = null; FeatureIterator<SimpleFeature> roads = null; try { dataStore = openShapefileDataStore(roadsFile); roads = getFeatureIerator(dataStore); while (roads.hasNext()) { SimpleFeature road = roads.next(); for (Coordinate[] points : getCoords(road.getDefaultGeometry())) { Coordinate startTowerPnt = null; List<Coordinate> pillars = new ArrayList<Coordinate>(); for (Coordinate point : points) { if (startTowerPnt == null) { startTowerPnt = point; } else { int state = coordState.get(point); if (state >= FIRST_NODE_ID) { int fromTowerNodeId = coordState.get(startTowerPnt); int toTowerNodeId = state; double distance = getWayLength(startTowerPnt, pillars, point); GHPoint estmCentre = new GHPoint(0.5 * (lat(startTowerPnt) + lat(point)), 0.5 * (lng(startTowerPnt) + lng(point))); PointList pillarNodes = new PointList(pillars.size(), false); for (Coordinate pillar : pillars) { pillarNodes.add(lat(pillar), lng(pillar)); } addEdge(fromTowerNodeId, toTowerNodeId, road, distance, estmCentre, pillarNodes); startTowerPnt = point; pillars.clear(); } else { pillars.add(point); } } } } } } catch (Exception e) { <START> LOGGER.error("Exception while processing for roads: ", e); <END> } finally { if (roads != null) { roads.close(); } if (dataStore != null) { dataStore.dispose(); } } }</code><technical_language>throw exception, e.g. throw new RuntimeException("some info", e)</technical_language>

Target:
void processRoads() { DataStore dataStore = null; FeatureIterator<SimpleFeature> roads = null; try { dataStore = openShapefileDataStore(roadsFile); roads = getFeatureIterator(dataStore); while (roads.hasNext()) { SimpleFeature road = roads.next(); for (Coordinate[] points : getCoords(road.getDefaultGeometry())) { Coordinate startTowerPnt = null; List<Coordinate> pillars = new ArrayList<Coordinate>(); for (Coordinate point : points) { if (startTowerPnt == null) { startTowerPnt = point; } else { int state = coordState.get(point); if (state >= FIRST_NODE_ID) { int fromTowerNodeId = coordState.get(startTowerPnt); int toTowerNodeId = state; double distance = getWayLength(startTowerPnt, pillars, point); GHPoint estmCentre = new GHPoint( 0.5 * (lat(startTowerPnt) + lat(point)), 0.5 * (lng(startTowerPnt) + lng(point))); PointList pillarNodes = new PointList(pillars.size(), false); for (Coordinate pillar : pillars) { pillarNodes.add(lat(pillar), lng(pillar)); } addEdge(fromTowerNodeId, toTowerNodeId, road, distance, estmCentre, pillarNodes); startTowerPnt = point; pillars.clear(); } else { pillars.add(point); } } } } } } finally { if (roads != null) { roads.close(); } if (dataStore != null) { dataStore.dispose(); } } }
Source:
<code><START> private String extractMessageRecursively(final Throwable t) { <END> if (t.getCause() == null) { return t.getMessage(); } return t.getMessage() + " Caused by: " + extractMessageRecursively(t.getCause()); }</code><technical_language>Please account t null</technical_language>

Target:
protected static String extractMessageRecursively(final Throwable t) { if (t == null) { return ""; } if (t.getCause() == null) { return t.getMessage(); } return t.getMessage() + " Caused by: " + extractMessageRecursively(t.getCause()); }
Source:
<code>public RadiologyReport createAndClaimRadiologyReport(RadiologyOrder radiologyOrder) throws IllegalArgumentException { if (radiologyOrder == null) { throw new IllegalArgumentException("radiologyOrder cannot be null"); } if (radiologyOrder.getStudy().isCompleted() == false) { throw new IllegalArgumentException("Cannot create report for uncompleted order"); } if (radiologyReportDAO.hasRadiologyOrderCompletedRadiologyReport(radiologyOrder)) { throw new UnsupportedOperationException( <START> "Cannot create a radiologyReport for this radiologyOrder because it is already " + "completed"); <END> } if (radiologyReportDAO.hasRadiologyOrderClaimedRadiologyReport(radiologyOrder)) { throw new UnsupportedOperationException( "Cannot create a radiologyReport for this radiologyOrder because it is already claimed"); } RadiologyReport radiologyReport = new RadiologyReport(radiologyOrder); radiologyReport.setCreator(Context.getAuthenticatedUser()); return radiologyReportDAO.saveRadiologyReport(radiologyReport); }</code><technical_language>remove string concatenation</technical_language>

Target:
public RadiologyReport createAndClaimRadiologyReport(RadiologyOrder radiologyOrder) throws IllegalArgumentException, UnsupportedOperationException { if (radiologyOrder == null) { throw new IllegalArgumentException("radiologyOrder cannot be null"); } if (radiologyOrder.getStudy() == null) { throw new IllegalArgumentException("study cannot be null"); } if (radiologyOrder.getStudy().isCompleted() == false) { throw new IllegalArgumentException("cannot create RadiologyReport for uncompleted radiologyOrder"); } if (radiologyReportDAO.hasRadiologyOrderCompletedRadiologyReport(radiologyOrder)) { throw new UnsupportedOperationException( "cannot create radiologyReport for this radiologyOrder because it is already completed"); } if (radiologyReportDAO.hasRadiologyOrderClaimedRadiologyReport(radiologyOrder)) { throw new UnsupportedOperationException( "cannot create radiologyReport for this radiologyOrder because it is already claimed"); } RadiologyReport radiologyReport = new RadiologyReport(radiologyOrder); radiologyReport.setCreator(Context.getAuthenticatedUser()); return radiologyReportDAO.saveRadiologyReport(radiologyReport); }
Source:
<code>public void onTaskCompleted(SonarQubeWebHook.Payload payload, String receivedSignature) { if (payload.getTaskId().equals(step.taskId)) { try { PauseAction.endCurrentPause(getContextClass(FlowNode.class)); SonarQubeWebHook.get().removeListener(this); if (step.webhookSecretId != null) { if (validateWebhook(receivedSignature, payload.getPayloadAsString())) { checkQualityGate(payload.getTaskStatus(), payload.getQGStatus()); <START> } <END> } else { checkQualityGate(payload.getTaskStatus(), payload.getQGStatus()); } } catch (IOException e) { getContext().onFailure(e); throw new IllegalStateException(e); } } }</code><technical_language>Is ok fail pipeline secret match expected? (Honest question.)</technical_language>

Target:
public void onTaskCompleted(SonarQubeWebHook.Payload payload, String receivedSignature) { if (payload.getTaskId().equals(step.taskId)) { try { PauseAction.endCurrentPause(getContextClass(FlowNode.class)); SonarQubeWebHook.get().removeListener(this); if (step.webhookSecretId != null && !step.webhookSecretId.isEmpty()) { if (validateWebhook(receivedSignature, payload.getPayloadAsString())) { checkQualityGate(payload.getTaskStatus(), payload.getQualityGateStatus()); } } else { checkQualityGate(payload.getTaskStatus(), payload.getQualityGateStatus()); } } catch (IOException e) { getContext().onFailure(e); throw new IllegalStateException(e); } } }
Source:
<code>public void testDoTransferAsAnon() { User ticketOwner = createUser(); User ticketReceiver = createUser(); Ticket ticket = createTicketForUser(ticketOwner); TicketTransferToken ttt = ticketService.setupForTransfer(ticket.getId(), ticketReceiver.getEmail()); given(). body(ttt.getToken()). when(). put(TRANSFER_ENDPOINT). then(). statusCode(HttpStatus.SC_FORBIDDEN); ttt = tttRepository.findByToken(ttt.getToken()).get(); <START> ticket = ticketRepository.findById(ticket.getId()).orElse(new Ticket()); <END> Assert.assertTrue(ttt.isValid()); Assert.assertTrue(ticket.getOwner().equals(ticketOwner)); }</code><technical_language>I is nicer do .orElseThrow(TicketNotFoundInDatabaseException::new) here. is more explicit fail-fast</technical_language>

Target:
public void testDoTransferAsAnon() { User ticketOwner = createUser(); User ticketReceiver = createUser(); Ticket ticket = createTicketForUser(ticketOwner); TicketTransferToken ttt = ticketService.setupForTransfer(ticket.getId(), ticketReceiver.getEmail()); given(). body(ttt.getToken()). when(). put(TRANSFER_ENDPOINT). then(). statusCode(HttpStatus.SC_FORBIDDEN); ttt = tttRepository.findByToken(ttt.getToken()).get(); ticket = ticketRepository.findById(ticket.getId()).orElseThrow(TicketNotFoundException::new); Assert.assertTrue(ttt.isValid()); Assert.assertEquals(ticket.getOwner(), ticketOwner); }
Source:
<code>public Collection<Ticket> getOwnedTicketsAndFromTeamMembers(User u) { if (u == null) { <START> throw new UserNotFoundException("null"); <END> } Collection<Ticket> ownedTickets = ticketRepository.findAllByOwnerUsernameIgnoreCase(u.getUsername()). stream(). filter(Ticket::isValid). collect(Collectors.toList()); Collection<Ticket> captainedTickets = getCaptainedTickets(u); Collection<Ticket> ticketsInControl = new ArrayList<>(); ticketsInControl.addAll(ownedTickets); ticketsInControl.addAll(captainedTickets); return ticketsInControl; }</code><technical_language>This is correct exception in opinion, user is unfound, is user in parameter</technical_language>

Target:
public Collection<Ticket> getOwnedTicketsAndFromTeamMembers(User u) { if (u == null) { throw new IllegalArgumentException("User can't be null"); } Collection<Ticket> ownedTickets = ticketRepository.findAllByOwnerUsernameIgnoreCase(u.getUsername()). stream(). filter(Ticket::isValid). collect(Collectors.toList()); Collection<Ticket> captainedTickets = getCaptainedTickets(u); Collection<Ticket> ticketsInControl = new ArrayList<>(); ticketsInControl.addAll(ownedTickets); ticketsInControl.addAll(captainedTickets); return ticketsInControl; }
Source:
<code>public InMemoryCircuitBreakerRegistry(CircuitBreakerConfig defaultCircuitBreakerConfig) { this.defaultCircuitBreakerConfig = Objects.requireNonNull(defaultCircuitBreakerConfig, "CircuitBreakerConfig must not be null"); this.circuitBreakers = new ConcurrentHashMap<>(); <START> this.postCreationConsumers = new ArrayList<>(); <END> this.sharedCircuitBreakerConfiguration = new ConcurrentHashMap<>(); this.sharedCircuitBreakerConfiguration.put(DEFAULT_CONFIG, defaultCircuitBreakerConfig); }</code><technical_language>Please CopyOnWriteArrayList</technical_language>

Target:
public InMemoryCircuitBreakerRegistry(CircuitBreakerConfig defaultCircuitBreakerConfig) { super(); this.defaultCircuitBreakerConfig = Objects.requireNonNull(defaultCircuitBreakerConfig, "CircuitBreakerConfig must not be null"); this.circuitBreakers = new ConcurrentHashMap<>(); this.configurations.put(DEFAULT_CONFIG, defaultCircuitBreakerConfig); }
Source:
<code>public List<InternalJob> loadJobs(final boolean fullState, final JobId... jobIds) { return executeReadOnlyTransaction(session -> { List<Long> ids = new ArrayList<>(jobIds.length); <START> for (JobId jobId : jobIds) { <END> ids.add(jobId(jobId)); } return loadInternalJobs(fullState, session, ids); }); }</code><technical_language>addAll stream</technical_language>

Target:
public List<InternalJob> loadJobs(final boolean fullState, final JobId... jobIds) { return executeReadOnlyTransaction(session -> { final List<Long> ids = Stream.of(jobIds).map(SchedulerDBManager::jobId).collect(Collectors.toList()); return loadInternalJobs(fullState, session, ids); }); }
Source:
<code>void flushStoredSession(File storedFile) { Session payload = new Session(storedFile); <START> if (payload.isV2Payload()) { END> payload.setApp(client.getAppDataCollector().generateApp()); payload.setDevice(client.getDeviceDataCollector().generateDevice()); } DeliveryStatus deliveryStatus = deliverSessionPayload(payload); switch (deliveryStatus) { case DELIVERED: sessionStore.deleteStoredFiles(Collections.singletonList(storedFile)); break; case UNDELIVERED: sessionStore.cancelQueuedFiles(Collections.singletonList(storedFile)); logger.w("Leaving session payload for future delivery"); break; case FAILURE: logger.w("Deleting invalid session tracking payload"); sessionStore.deleteStoredFiles(Collections.singletonList(storedFile)); break; default: break; } }</code><technical_language>This !isV2Payload adding missing data</technical_language>

Target:
void flushStoredSession(File storedFile) { Session payload = new Session(storedFile); if (!payload.isV2Payload()) { payload.setApp(client.getAppDataCollector().generateApp()); payload.setDevice(client.getDeviceDataCollector().generateDevice()); } DeliveryStatus deliveryStatus = deliverSessionPayload(payload); switch (deliveryStatus) { case DELIVERED: sessionStore.deleteStoredFiles(Collections.singletonList(storedFile)); break; case UNDELIVERED: sessionStore.cancelQueuedFiles(Collections.singletonList(storedFile)); logger.w("Leaving session payload for future delivery"); break; case FAILURE: logger.w("Deleting invalid session tracking payload"); sessionStore.deleteStoredFiles(Collections.singletonList(storedFile)); break; default: break; } }
Source:
<code>public void getCourseComponentFromServer(boolean showProgress) { final TaskProgressCallback progressCallback = showProgress ? new TaskProgressCallback.ProgressViewController(loadingIndicator) : null; final String courseId = courseData.getCourse().getId(); getHierarchyCall = courseApi.getCourseStructureWithoutStale(courseId); getHierarchyCall.enqueue(new CourseAPI.GetCourseStructureCallback(getActivity(), courseId, progressCallback, errorNotification, null, this) { @Override protected void onResponse(@NonNull final CourseComponent courseComponent) { courseManager.addCourseDataInAppLevelCache(courseId, courseComponent); loadData(validateCourseComponent(courseComponent)); swipeContainer.setRefreshing(false); } @Override protected void onFailure(@NonNull Throwable error) { super.onFailure(error); if (error instanceof CourseContentNotValidException) { errorNotification.showError(getContext(), error); logger.error(error, true); <START> swipeContainer.setRefreshing(false); <END> } } @Override protected void onFinish() { if (!EventBus.getDefault().isRegistered(CourseOutlineFragment.this)) { EventBus.getDefault().registerSticky(CourseOutlineFragment.this); swipeContainer.setRefreshing(false); } } }); }</code><technical_language>This line do if block out of it</technical_language>

Target:
public void getCourseComponentFromServer(boolean showProgress) { final TaskProgressCallback progressCallback = showProgress ? new TaskProgressCallback.ProgressViewController(loadingIndicator) : null; final String courseId = courseData.getCourse().getId(); getHierarchyCall = courseApi.getCourseStructureWithoutStale(courseId); getHierarchyCall.enqueue(new CourseAPI.GetCourseStructureCallback(getActivity(), courseId, progressCallback, errorNotification, null, this) { @Override protected void onResponse(@NonNull final CourseComponent courseComponent) { courseManager.addCourseDataInAppLevelCache(courseId, courseComponent); loadData(validateCourseComponent(courseComponent)); swipeContainer.setRefreshing(false); } @Override protected void onFailure(@NonNull Throwable error) { super.onFailure(error); if (error instanceof CourseContentNotValidException) { errorNotification.showError(getContext(), error); logger.error(error, true); } swipeContainer.setRefreshing(false); } @Override protected void onFinish() { if (!EventBus.getDefault().isRegistered(CourseOutlineFragment.this)) { EventBus.getDefault().registerSticky(CourseOutlineFragment.this); } swipeContainer.setRefreshing(false); } }); }
Source:
<code>public FutureResult<Warehouse> createWarehouse(Warehouse warehouse) { <START> final WarehouseTask task; <END> try { task = restTemplate.postForObject(Warehouses.URI, warehouse, WarehouseTask.class); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create Warehouse", e); } if (task == null) { throw new GoodDataException("Empty response when Warehouse POSTed to API"); } return new FutureResult<>(this, new PollHandler<WarehouseTask,Warehouse>(task.getPollLink(), WarehouseTask.class, Warehouse.class) { @Override protected boolean isFinished(ClientHttpResponse response) throws IOException { return HttpStatus.CREATED.equals(response.getStatusCode()); } @Override protected void onFinish() { if (!getResult().isEnabled()) { throw new GoodDataException("Created warehouse is not enabled!"); } } @Override protected void handlePollResult(WarehouseTask pollResult) { try { final Warehouse warehouse = restTemplate.getForObject(pollResult.getWarehouseLink(), Warehouse.class); setResult(setWarehouseConnection(warehouse)); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Warehouse creation finished, but can't get created warehouse", e); } } }); }</code><technical_language>check warhouse != null</technical_language>

Target:
public FutureResult<Warehouse> createWarehouse(Warehouse warehouse) { notNull(warehouse, "warehouse"); final WarehouseTask task; try { task = restTemplate.postForObject(Warehouses.URI, warehouse, WarehouseTask.class); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create Warehouse", e); } if (task == null) { throw new GoodDataException("Empty response when Warehouse POSTed to API"); } return new FutureResult<>(this, new PollHandler<WarehouseTask,Warehouse>(task.getPollLink(), WarehouseTask.class, Warehouse.class) { @Override protected boolean isFinished(ClientHttpResponse response) throws IOException { return HttpStatus.CREATED.equals(response.getStatusCode()); } @Override protected void onFinish() { if (!getResult().isEnabled()) { throw new GoodDataException("Created warehouse, uri: " + getResult().getSelfLink() + " is not enabled!"); } } @Override protected void handlePollResult(WarehouseTask pollResult) { try { final Warehouse warehouse = restTemplate.getForObject(pollResult.getWarehouseLink(), Warehouse.class); setResult(setWarehouseConnection(warehouse)); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Warehouse creation finished, but can't get created warehouse, uri: " + pollResult.getWarehouseLink(), e); } } }); }
Source:
<code>public String exportPipeline(Request req, Response res) { PipelineConfig pipelineConfig = pipelineConfigFromRequest(req); String pluginId = requiredQueryParam(req, "pluginId"); String groupName = requiredQueryParam(req, "groupName"); if (!crPluginService.supportsPipelineExport(pluginId)) { throw haltBecauseOfReason("Plugin `%s` does not support pipeline config export or is not a config-repo plugin.", pluginId); } <START> ConfigRepoPlugin repoPlugin = crPlugin(pluginId); <END> String etag = repoPlugin.etagForExport(pipelineConfig, groupName); if (fresh(req, etag)) { return notModified(res); } else { setEtagHeader(res, etag); ExportedConfig export = repoPlugin.pipelineExport(pipelineConfig, groupName); res.header("Content-Type", export.getContentType()); res.header("Content-Disposition", format("attachment; filename=\"%s\"", export.getFilename())); return export.getContent(); } }</code><technical_language>Split checks provide a response message for check - 1. plugin cd.go.foo is a config repo plugin 2. plugin cd.go.bar support pipeline export</technical_language>

Target:
public String exportPipeline(Request req, Response res) { PipelineConfig pipelineConfig = pipelineConfigFromRequest(req); String pluginId = requiredQueryParam(req, "pluginId"); String groupName = requiredQueryParam(req, "groupName"); if (pipelineConfig.hasTemplate()) { throw haltBecauseOfReason("Pipeline `%s` cannot be exported because pipelines defined by templates are not yet supported by config-repo plugins.", pipelineConfig.name()); } if (!crPluginService.isConfigRepoPlugin(pluginId)) { throw haltBecauseOfReason("Plugin `%s` is not a config-repo plugin.", pluginId); } if (!crPluginService.supportsPipelineExport(pluginId)) { throw haltBecauseOfReason("Plugin `%s` does not support pipeline config export.", pluginId); } ConfigRepoPlugin repoPlugin = crPlugin(pluginId); String etag = repoPlugin.etagForExport(pipelineConfig, groupName); if (fresh(req, etag)) { return notModified(res); } else { setEtagHeader(res, etag); ExportedConfig export = repoPlugin.pipelineExport(pipelineConfig, groupName); res.header("Content-Type", export.getContentType()); res.header("Content-Disposition", format("attachment; filename=\"%s\"", export.getFilename())); return export.getContent(); } }
Source:
<code><START> private void confirmRemovePerson() { <END> if (mSelectedPerson == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Calypso_AlertDialog); builder.setTitle(getString(R.string.person_remove_confirmation_title, mSelectedPerson.getDisplayName())); builder.setMessage(getString(R.string.person_remove_confirmation_message, mSelectedPerson.getDisplayName())); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.remove, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeSelectedPerson(); } }); builder.show(); }</code><technical_language>checking for current user removing. allowed? If not, put out a message explaining done, more simply remove "remove" button completely. Cheers</technical_language>

Target:
private void confirmRemovePerson() { Person person = getCurrentPerson(); if (person == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Calypso_AlertDialog); builder.setTitle(getString(R.string.person_remove_confirmation_title, person.getDisplayName())); builder.setMessage(getString(R.string.person_remove_confirmation_message, person.getDisplayName())); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.remove, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeSelectedPerson(); } }); builder.show(); }
Source:
<code>public <T extends Message> MessageCodec<T> find(Class<T> clazz) { <START> for(MessageCodec<?> codec : getCodecs()) { <END> if (codec.getType().equals(clazz)) { return (MessageCodec<T>) codec; } } return null; }</code><technical_language>honest, I this. trading a map lookup small amount of memory storing for iterating find. If this method called, this a reasonable trade-off (I might, not). But, this method is call a LOT, increase in call time scales. I vote for this part</technical_language>

Target:
public <T extends Message> MessageCodec<T> find(Class<T> clazz) { return (MessageCodec<T>) classTable.get(clazz); }
Source:
<code>protected boolean mergeTrees(AbstractTreeIterator baseTree, RevTree headTree, RevTree mergeTree, boolean ignoreConflicts) throws IOException { builder = dircache.builder(); DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder); <START> tw = new NameConflictTreeWalk(db, reader); <END> tw.addTree(baseTree); tw.addTree(headTree); tw.addTree(mergeTree); tw.addTree(buildIt); if (workingTreeIterator != null) { tw.addTree(workingTreeIterator); } else { tw.setFilter(TreeFilter.ANY_DIFF); } if (!mergeTreeWalk(tw, ignoreConflicts)) { return false; } if (!inCore) { checkout(); if (!builder.commit()) { cleanUp(); throw new IndexWriteException(); } builder = null; } else { builder.finish(); builder = null; } if (getUnmergedPaths().isEmpty() && !failed()) { resultTree = dircache.writeTree(getObjectInserter()); return true; } else { resultTree = null; return false; } }</code><technical_language>If is workingTreeIterator in game need db here? workingTree -> attributes, or</technical_language>

Target:
protected boolean mergeTrees(AbstractTreeIterator baseTree, RevTree headTree, RevTree mergeTree, boolean ignoreConflicts) throws IOException { builder = dircache.builder(); DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder); tw = new NameConflictTreeWalk(reader); tw.addTree(baseTree); tw.addTree(headTree); tw.addTree(mergeTree); tw.addTree(buildIt); if (workingTreeIterator != null) { tw.addTree(workingTreeIterator); } else { tw.setFilter(TreeFilter.ANY_DIFF); } if (!mergeTreeWalk(tw, ignoreConflicts)) { return false; } if (!inCore) { checkout(); if (!builder.commit()) { cleanUp(); throw new IndexWriteException(); } builder = null; } else { builder.finish(); builder = null; } if (getUnmergedPaths().isEmpty() && !failed()) { resultTree = dircache.writeTree(getObjectInserter()); return true; } else { resultTree = null; return false; } }