auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected Composite createToolTipContentArea(Event event, Composite parent) { Composite tooltipComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); tooltipComposite.setLayout(layout); for (SerieEntry entry : fEntries) { StringBuilder text = new StringBuilder().append(entry.id).append(": ").append(entry.value); Composite serieComposite = new Composite(tooltipComposite, SWT.NONE); <START> layout = new GridLayout(); <END> serieComposite.setLayout(layout); Label label = new Label(serieComposite, SWT.NONE); label.setText(text.toString()); label.setBackground(null); GridData gridData = new GridData(); gridData.horizontalIndent = 16; label.setLayoutData(gridData); serieComposite.addPaintListener(e -> { e.gc.setBackground(entry.color); e.gc.fillOval(5, 10, 10, 10); }); } return tooltipComposite; }</code><technical_language>default marginHeight is 5, 10 pixels label. Is this much</technical_language>

Target:
protected Composite createToolTipContentArea(Event event, Composite parent) { Composite tooltipComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); tooltipComposite.setLayout(layout); for (SerieEntry entry : fEntries) { Composite serieComposite = new Composite(tooltipComposite, SWT.NONE); layout = new GridLayout(); serieComposite.setLayout(layout); StringBuilder text = new StringBuilder().append(entry.id).append(": ").append(entry.value); Label label = addSerieLabel(serieComposite); label.setText(text.toString()); serieComposite.addPaintListener(e -> { e.gc.setBackground(entry.color); e.gc.fillOval(5, 10, 10, 10); }); } return tooltipComposite; }
Source:
<code>private Thread createDelayedCloseExecutor() { Thread delayedCloseExecutor = new Thread( () -> { while (!closed) { Long closeTimeNs = null; Boolean dueToShutdownRequest = null; <START> Long idleCloseTimeNs = idleCloseTimeNsHolder.get(); <END> if (idleCloseTimeNs != null) { closeTimeNs = idleCloseTimeNs; dueToShutdownRequest = false; } Long requestedShutdownTimeNs = requestedShutdownTimeNsHolder.get(); if (requestedShutdownTimeNs != null) { if (closeTimeNs == null || requestedShutdownTimeNs - closeTimeNs <= 0) { closeTimeNs = requestedShutdownTimeNs; dueToShutdownRequest = true; } } if (closeTimeNs == null) { log.error( "A bug in EventReceiverFirehose code, " + "either idleCloseTimeNs or requestedShutdownTimeNs should be non-null" ); try { Threads.sleepFor(1, TimeUnit.MINUTES); } catch (InterruptedException ignore) { } continue; } long closeTimeoutNs = closeTimeNs - System.nanoTime(); if (closeTimeoutNs <= 0) { if (dueToShutdownRequest) { log.info("Closing Firehose after a shutdown request"); } else { log.info("Firehose has been idle for %d ms, closing.", maxIdleTimeMillis); } close(); return; } else { try { Threads.sleepFor(closeTimeoutNs, TimeUnit.NANOSECONDS); } catch (InterruptedException ignore) { } } } }, "event-receiver-firehose-closer" ); this.delayedCloseExecutor = delayedCloseExecutor; delayedCloseExecutor.start(); return delayedCloseExecutor; }</code><technical_language>find rationale description for idleCloseTimeNsHolder/maxIdleTime, do issue requires introducing variable</technical_language>

Target:
private Thread createDelayedCloseExecutor() { Thread delayedCloseExecutor = new Thread( () -> { while (!closed) { if (idleCloseTimeNs == null && requestedShutdownTimeNs == null) { log.error( "Either idleCloseTimeNs or requestedShutdownTimeNs must be non-null. " + "Please file a bug at <LINK_0>" ); } if (idleCloseTimeNs != null && idleCloseTimeNs - System.nanoTime() <= 0) { log.info("Firehose has been idle for %d ms, closing.", maxIdleTimeMillis); close(); } else if (requestedShutdownTimeNs != null && requestedShutdownTimeNs - System.nanoTime() <= 0) { log.info("Closing Firehose after a shutdown request"); close(); } try { Threads.sleepFor(1, TimeUnit.SECONDS); } catch (InterruptedException ignore) { } } }, "event-receiver-firehose-closer" ); delayedCloseExecutor.setDaemon(true); this.delayedCloseExecutor = delayedCloseExecutor; delayedCloseExecutor.start(); return delayedCloseExecutor; }
Source:
<code><START> public boolean equals(Object obj) { <END> if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } FakeMetric metric = (FakeMetric) obj; return metric.getName() == getName() && metric.getValue() == getValue(); }</code><technical_language>Item 9 of _Effective Java_ (2nd Edition) Joshua Bloch, override hashCode override equals</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof FakeMetric)) return false; FakeMetric other = (FakeMetric) obj; if (metricManager == null) { if (other.metricManager != null) return false; } else if (!metricManager.equals(other.metricManager)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; }
Source:
<code>private synchronized MemoryPoolAssignmentsRequest updateAssignments(Iterable<QueryExecution> queries) { ClusterMemoryPool reservedPool = pools.get(RESERVED_POOL); ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); verify(generalPool != null, "generalPool is null"); verify(reservedPool != null, "reservedPool is null"); long version = memoryPoolAssignmentsVersion.incrementAndGet(); if (allAssignmentsHavePropagated(queries)) { if (reservedPool.getAssignedQueries() == 0 && generalPool.getBlockedNodes() > 0) { QueryExecution biggestQuery = null; long maxMemory = -1; for (QueryExecution queryExecution : queries) { if (resourceOvercommit(queryExecution.getSession())) { continue; } long bytesUsed = getQueryMemoryReservation(queryExecution); if (bytesUsed > maxMemory) { biggestQuery = queryExecution; maxMemory = bytesUsed; } } if (biggestQuery != null) { <START> log.warn("Moving query %s to the reserved pool", biggestQuery.getQueryId()); <END> biggestQuery.setMemoryPool(new VersionedMemoryPoolId(RESERVED_POOL, version)); } } } ImmutableList.Builder<MemoryPoolAssignment> assignments = ImmutableList.builder(); for (QueryExecution queryExecution : queries) { assignments.add(new MemoryPoolAssignment(queryExecution.getQueryId(), queryExecution.getMemoryPool().getId())); } return new MemoryPoolAssignmentsRequest(coordinatorId, version, assignments.build()); }</code><technical_language>info</technical_language>

Target:
private synchronized MemoryPoolAssignmentsRequest updateAssignments(Iterable<QueryExecution> queries) { ClusterMemoryPool reservedPool = pools.get(RESERVED_POOL); ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); verify(generalPool != null, "generalPool is null"); verify(reservedPool != null, "reservedPool is null"); long version = memoryPoolAssignmentsVersion.incrementAndGet(); if (allAssignmentsHavePropagated(queries)) { if (reservedPool.getAssignedQueries() == 0 && generalPool.getBlockedNodes() > 0) { QueryExecution biggestQuery = null; long maxMemory = -1; for (QueryExecution queryExecution : queries) { if (resourceOvercommit(queryExecution.getSession())) { continue; } long bytesUsed = getQueryMemoryReservation(queryExecution); if (bytesUsed > maxMemory) { biggestQuery = queryExecution; maxMemory = bytesUsed; } } if (biggestQuery != null) { log.info("Moving query %s to the reserved pool", biggestQuery.getQueryId()); biggestQuery.setMemoryPool(new VersionedMemoryPoolId(RESERVED_POOL, version)); } } } ImmutableList.Builder<MemoryPoolAssignment> assignments = ImmutableList.builder(); for (QueryExecution queryExecution : queries) { assignments.add(new MemoryPoolAssignment(queryExecution.getQueryId(), queryExecution.getMemoryPool().getId())); } return new MemoryPoolAssignmentsRequest(coordinatorId, version, assignments.build()); }
Source:
<code><START> private static void putBlobPropertiesToBufferV1(ByteBuffer outputBuffer, BlobProperties properties) { <END> outputBuffer.putShort(Version1); outputBuffer.putLong(properties.getTimeToLiveInSeconds()); outputBuffer.put(properties.isPrivate() ? (byte) 1 : (byte) 0); outputBuffer.putLong(properties.getCreationTimeInMs()); outputBuffer.putLong(properties.getBlobSize()); Utils.serializeNullableString(outputBuffer, properties.getContentType()); Utils.serializeNullableString(outputBuffer, properties.getOwnerId()); Utils.serializeNullableString(outputBuffer, properties.getServiceId()); }</code><technical_language>Is a put test for v2</technical_language>

Target:
private static void putBlobPropertiesToBufferV1(ByteBuffer outputBuffer, BlobProperties properties) { outputBuffer.putShort(VERSION_1); outputBuffer.putLong(properties.getTimeToLiveInSeconds()); outputBuffer.put(properties.isPrivate() ? (byte) 1 : (byte) 0); outputBuffer.putLong(properties.getCreationTimeInMs()); outputBuffer.putLong(properties.getBlobSize()); Utils.serializeNullableString(outputBuffer, properties.getContentType()); Utils.serializeNullableString(outputBuffer, properties.getOwnerId()); Utils.serializeNullableString(outputBuffer, properties.getServiceId()); }
Source:
<code>public void handle(HttpExchange exchange) throws IOException { StringBuilder body = new StringBuilder(); try (InputStreamReader reader = new InputStreamReader(exchange.getRequestBody())) { <START> char[] buffer = new char[256]; <END> int read; while ((read = reader.read(buffer)) != -1) { body.append(buffer, 0, read); } } String[] delayArray = body.toString().split("="); int delay = Integer.parseInt(delayArray[1]); setAnimationDelay(delay); exchange.sendResponseHeaders(200, 0); OutputStream os = exchange.getResponseBody(); os.close(); }</code><technical_language>Is this InputStream String conversion? If yes, I recommend more intuitive, e.g. String body = new BufferedReader(reader).lines().collect(Collectors.joining("\n"))</technical_language>

Target:
public void handle(HttpExchange exchange) throws IOException { Headers headers = exchange.getResponseHeaders(); headers.add("Content-type", "application/json"); headers.add("Access-Control-Allow-Origin", "*"); String body = ""; String response = ""; if ("POST".equals(exchange.getRequestMethod())) { try (InputStreamReader reader = new InputStreamReader(exchange.getRequestBody())) { body = new BufferedReader(reader).lines().collect(Collectors.joining("\n")); } String[] animationDelayArray = body.split("="); int animationDelay = Integer.parseInt(animationDelayArray[1]); setAnimationDelay(animationDelay); } else { response = "{\"animationDelay\":\"" + diagnosticsPlugin.getAnimationDelay() + "\"}"; } exchange.sendResponseHeaders(200, response.length()); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); }
Source:
<code>void processBatch(Collection<Metric> metrics) throws InterruptedException { OpenTsdbClient client = null; boolean flushed = false; try { long processed = 0; client = getOpenTsdbClient(); if (client != null) { int errs = clientPool.clearErrorCount(); if (errs > 0) { metricsQueue.incrementError(errs); } if ( clientPool.hasCollision()) { eventBus.post(Control.highCollision()); throw new NoSuchElementException("Collision detected"); } try { for (Metric m : metrics) { <START> final String clientId = m.removeTag(TsdbMetricsQueue.CLIENT_TAG); <END> try { final String message = convert(m); client.put(message); processed++; } catch (Exception e) { log.warn("Caught (and rethrowing) exception while processing metric: {}", e.getMessage()); throw e; } finally { m.addTag(TsdbMetricsQueue.CLIENT_TAG, clientId); } } client.flush(); flushed = true; metricsQueue.incrementProcessed(processed); } catch (IOException e) { log.warn("Caught exception while processing messages: {}", e.getMessage()); if (null != client) { client.close(); } } } else { log.warn("Unable to get client to process metrics."); } } finally { if (!flushed) { try { metricsQueue.reAddAll(metrics); } catch (Exception e) { log.error("We were unable to add metrics back to the queue. Eating exception to prevent thread death.", e); } } if (client != null) { try { clientPool.returnObject(client); } catch (Exception returnException) { log.warn("Failed to return TSDB client to connection pool", returnException); } } lastWorkTime = System.currentTimeMillis(); } }</code><technical_language>copy of metric avoid confusion in future re-add tags failure modes</technical_language>

Target:
void processBatch(Collection<Metric> metrics) throws InterruptedException { OpenTsdbClient client = null; boolean flushed = false; try { long processed = 0; client = getOpenTsdbClient(); if (client != null) { int errs = clientPool.clearErrorCount(); if (errs > 0) { metricsQueue.incrementError(errs); } if ( clientPool.hasCollision()) { eventBus.post(Control.highCollision()); throw new NoSuchElementException("Collision detected"); } try { for (Metric m : metrics) { Metric workingCopy = new Metric(m); workingCopy.removeTag(TsdbMetricsQueue.CLIENT_TAG); try { final String message = convert(workingCopy); client.put(message); processed++; } catch (IOException e) { log.warn("Caught (and rethrowing) IOException while processing metric: {}", e.getMessage()); throw e; } } client.flush(); flushed = true; metricsQueue.incrementProcessed(processed); } catch (IOException e) { log.warn("Caught exception while processing messages: {}", e.getMessage()); if (null != client) { client.close(); } } } else { log.warn("Unable to get client to process metrics."); } } finally { if (!flushed) { try { metricsQueue.reAddAll(metrics); } catch (IllegalStateException e) { log.error("We were unable to add metrics back to the queue. Eating exception to prevent thread death.", e); } } if (client != null) { try { clientPool.returnObject(client); } catch (Exception returnException) { log.warn("Failed to return TSDB client to connection pool", returnException); } } lastWorkTime = System.currentTimeMillis(); } }
Source:
<code>private static <T> BiFunction<Set<T>, Set<T>, Set<T>> mergeSetsAccountingForSingletons() { return (newValue, oldValue) -> { if (oldValue.size() == 1) { <START> Set<T> newMutableSet = new HashSet<>(); <END> newMutableSet.addAll(oldValue); newMutableSet.addAll(newValue); return newMutableSet; } else { oldValue.addAll(newValue); return oldValue; } }; }</code><technical_language>replace entire if statement with: java final Set<T> newMutableSet = oldValue.size() == 1 ? new HashSet<>() : oldValue; newMutableSet.addAll(oldValue); newMutableSet.addAll(newValue); return newMutableSet;</technical_language>

Target:
private static <T> BiFunction<Set<T>, Set<T>, Set<T>> mergeSetsAccountingForSingletons() { return (newValue, oldValue) -> { final Set<T> mutableSet = oldValue.size() == 1 ? new HashSet<>() : oldValue; mutableSet.addAll(oldValue); mutableSet.addAll(newValue); return mutableSet; }; }
Source:
<code>private List<JavaFileScannerContext.Location> learnedConstraintFlow(LearnedConstraint learnedConstraint, ExplodedGraph.Edge edge) { Constraint constraint = learnedConstraint.constraint(); if (constraint == null || !addToFlow.test(constraint)) { return ImmutableList.of(); } ExplodedGraph.Node parent = edge.parent; Tree nodeTree = parent.programPoint.syntaxTree(); if (isMethodInvocationNode(parent)) { return methodInvocationFlow(constraint, edge); } if (nodeTree.is(Tree.Kind.NEW_CLASS)) { return ImmutableList.of(location(parent, String.format("Constructor implies '%s'.", constraint.valueAsString()))); } String msg; <START> Tree reportTree = parent.programPoint.syntaxTree(); <END> Symbol finalField = learnedConstraintOnFinalField(reportTree); if (finalField != null) { msg = String.format(IMPLIES_IS_MSG, finalField.name(), constraint.valueAsString()); reportTree = ((VariableTree) finalField.declaration()).initializer(); } else { String name = SyntaxTreeNameFinder.getName(nodeTree); if (name == null) { return ImmutableList.of(); } if (ObjectConstraint.NULL == constraint && isNullCheck(nodeTree)) { msg = String.format(IMPLIES_CAN_BE_NULL_MSG, name); } else { msg = String.format(IMPLIES_IS_MSG, name, constraint.valueAsString()); } } return ImmutableList.of(new JavaFileScannerContext.Location(msg, reportTree)); }</code><technical_language>This variable nodeTree present. I test if tree is final field tree return instead of nesting if-else constructs, bit messy</technical_language>

Target:
private List<JavaFileScannerContext.Location> learnedConstraintFlow(LearnedConstraint learnedConstraint, ExplodedGraph.Edge edge) { Constraint constraint = learnedConstraint.constraint(); if (constraint == null || !addToFlow.test(constraint)) { return ImmutableList.of(); } ExplodedGraph.Node parent = edge.parent; Tree nodeTree = parent.programPoint.syntaxTree(); if (isMethodInvocationNode(parent)) { return methodInvocationFlow(constraint, edge); } if (nodeTree.is(Tree.Kind.NEW_CLASS)) { return ImmutableList.of(location(parent, String.format("Constructor implies '%s'.", constraint.valueAsString()))); } Symbol finalField = learnedConstraintOnFinalField(nodeTree); if (finalField != null) { String msg = String.format(IMPLIES_IS_MSG, finalField.name(), constraint.valueAsString()); return ImmutableList.of(new JavaFileScannerContext.Location(msg, ((VariableTree) finalField.declaration()).initializer())); } String name = SyntaxTreeNameFinder.getName(nodeTree); if (name == null) { return ImmutableList.of(); } String msg; if (ObjectConstraint.NULL == constraint && isNullCheck(nodeTree)) { msg = String.format(IMPLIES_CAN_BE_NULL_MSG, name); } else { msg = String.format(IMPLIES_IS_MSG, name, constraint.valueAsString()); } return ImmutableList.of(location(parent, msg)); }
Source:
<code>@Test public void runWebTests() throws Exception { List<String> tests = new ArrayList<>(); <START> ATDRunner parallelThread = new ATDRunner(); <END> tests.add("LoginFailureTest"); boolean hasFailures = parallelThread.runner("com.appium.webtest",tests); }</code><technical_language>object names renamed</technical_language>

Target:
@Test public void runWebTests() throws Exception { List<String> tests = new ArrayList<>(); ATDRunner atdRunner = new ATDRunner(); tests.add("LoginFailureTest"); boolean hasFailures = atdRunner.runner("com.appium.webtest",tests); }
Source:
<code>public String toString() { <START> return "CallStackEvent start=" + fTime + " end=" + (fTime + fDuration) + " duration=" + fDuration + " value=" + fValue; END> }</code><technical_language>a big deal, getClass().getSimpleName() instead of hard-coding class's name. sub-classes add fields reuse it</technical_language>

Target:
public String toString() { return getClass().getSimpleName() + " start=" + fTime + " end=" + (fTime + fDuration) + " duration=" + fDuration + " value=" + fValue; }
Source:
<code>public void testCanContribute() { <START> assertTrue(processor.canContribute(mock(IStatus.class))); <END> }</code><technical_language>hamcrest matchers</technical_language>

Target:
public void testCanContribute() { assertThat(processor.canContribute(mock(IStatus.class)),is(true)); }
Source:
<code>protected BatchWriter getHistoryWriterFromElementType(Element element) { <START> if (element instanceof Vertex) { <END> return getHistoryVerticesWriter(); } else if (element instanceof Edge) { return getHistoryEdgesWriter(); } else { throw new VertexiumException("Unexpected element type: " + element.getClass().getName()); } }</code><technical_language>This if/else replaced with: getHistoryWriterFromElementType(ElementType.getTypeFromElement(element));</technical_language>

Target:
public BatchWriter getHistoryWriterFromElementType(Element element) { return getHistoryWriterFromElementType(ElementType.getTypeFromElement(element)); }
Source:
<code>public void testMergeEmptyBranches() throws IOException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); git.commit().setMessage("initial commit").call(); RefUpdate r = db.updateRef("refs/heads/side"); r.setNewObjectId(db.resolve(Constants.HEAD)); assertEquals(r.forceUpdate(), RefUpdate.Result.NEW); git.commit().setMessage("second commit").setCommitter(committer).call(); db.updateRef(Constants.HEAD).link("refs/heads/side"); git.commit().setMessage("first side commit").setAuthor(author).call(); FileWriter wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_HEAD)); wr.write(ObjectId.toString(db.resolve("refs/heads/master"))); wr.close(); wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_MSG)); wr.write("merging"); wr.close(); <START> git.commit().call(); <END> }</code><technical_language>Please add assert verify parent order is as-expected. In this case is side, master merged master branch current branch, is side</technical_language>

Target:
public void testMergeEmptyBranches() throws IOException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); git.commit().setMessage("initial commit").call(); RefUpdate r = db.updateRef("refs/heads/side"); r.setNewObjectId(db.resolve(Constants.HEAD)); assertEquals(r.forceUpdate(), RefUpdate.Result.NEW); RevCommit second = git.commit().setMessage("second commit").setCommitter(committer).call(); db.updateRef(Constants.HEAD).link("refs/heads/side"); RevCommit firstSide = git.commit().setMessage("first side commit").setAuthor(author).call(); FileWriter wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_HEAD)); wr.write(ObjectId.toString(db.resolve("refs/heads/master"))); wr.close(); wr = new FileWriter(new File(db.getDirectory(), Constants.MERGE_MSG)); wr.write("merging"); wr.close(); RevCommit commit = git.commit().call(); RevCommit[] parents = commit.getParents(); assertEquals(parents[0], firstSide); assertEquals(parents[1], second); assertTrue(parents.length==2); }
Source:
<code>public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); <START> } <END> Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); List<AttributeDescriptor> attributes = metacard .getMetacardType() .getAttributeDescriptors() .stream() .filter(Objects::nonNull) .collect(Collectors.toList()); Appendable appendable = writeMetacardsToCsv(Collections.singletonList(metacard), attributes, aliases); return createResponse(appendable); }</code><technical_language>Do want support arguments QueryResponseTransformer supports? ![image](<LINK_0></technical_language>

Target:
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { if (metacard == null) { LOGGER.debug("Attempted to transform null metacard"); throw new CatalogTransformerException("Unable to transform null metacard"); } Map<String, String> aliases = (Map<String, String>) arguments.getOrDefault("aliases", new HashMap<>()); Appendable appendable = writeMetacardsToCsv( Collections.singletonList(metacard), new ArrayList<>(metacard.getMetacardType().getAttributeDescriptors()), aliases); return createResponse(appendable); }
Source:
<code>public void whenPromptDoesNotHaveAnswer_buttonShouldLaunchCorrectIntent() { GeoPointWidget widget = createWidget(promptWithAnswer(null)); <START> stubAllRuntimePermissionsGranted(widget, true); <END> widget.startGeoButton.performClick(); Intent startedIntent = shadowOf(widgetTestActivity()).getNextStartedActivity(); Bundle bundle = startedIntent.getExtras(); assertThat(startedIntent.getComponent(), equalTo(new ComponentName(widgetTestActivity(), GeoPointActivity.class))); assertBundleArgumentEquals(bundle, null, DEFAULT_LOCATION_ACCURACY, false, true); }</code><technical_language>This method called stubLocationPermissions. good a test checks location permissions denied</technical_language>

Target:
public void whenPromptDoesNotHaveAnswer_buttonShouldLaunchCorrectIntent() { GeoPointWidget widget = createWidget(promptWithAnswer(null)); stubLocationPermissions(widget, true); widget.binding.simpleButton.performClick(); Intent startedIntent = shadowOf(widgetTestActivity()).getNextStartedActivity(); Bundle bundle = startedIntent.getExtras(); assertThat(startedIntent.getComponent(), equalTo(new ComponentName(widgetTestActivity(), GeoPointActivity.class))); assertBundleArgumentEquals(bundle, null, DEFAULT_LOCATION_ACCURACY); }
Source:
<code>public Image(Device device, ImageDataProvider imageDataProvider) { super(device); this.imageDataProvider = imageDataProvider; currentDeviceZoom = getDeviceZoom (); boolean[] found = new boolean[1]; ImageData data = DPIUtil.validateAndGetImageDataAtZoom(imageDataProvider, currentDeviceZoom, found); <START> if (!found[0]) { <END> float scaleFactor = currentDeviceZoom / 100; ImageData resizedData = data.scaledTo((int)(data.width * scaleFactor), (int)(data.height * scaleFactor)); init (resizedData); } else { init (data); } init (); }</code><technical_language>reverse branches reads in previous constructor, i.e if(found{0])</technical_language>

Target:
public Image(Device device, ImageDataProvider imageDataProvider) { super(device); this.imageDataProvider = imageDataProvider; currentDeviceZoom = getDeviceZoom (); boolean[] found = new boolean[1]; ImageData data = DPIUtil.validateAndGetImageDataAtZoom(imageDataProvider, currentDeviceZoom, found); if (found[0]) { init (data); } else { float scaleFactor = currentDeviceZoom / 100; ImageData resizedData = data.scaledTo((int)(data.width * scaleFactor), (int)(data.height * scaleFactor)); init (resizedData); } init (); }
Source:
<code>public void setup() { mockSystemProducer = new MockCoordinatorStreamSystemFactory.MockSystemProducer("source"); ScheduledExecutorService mockExecutorService = Mockito.mock(ScheduledExecutorService.class); <START> Mockito.when(mockExecutorService.scheduleWithFixedDelay(Mockito.argThat(new ArgumentMatcher<Runnable>() { <END> @Override public boolean matches(Object argument) { Runnable runnable = (Runnable) argument; try { runnable.run(); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } return true; } }), Mockito.anyLong(), Mockito.anyLong(), Mockito.eq(TimeUnit.SECONDS))) .thenReturn(Mockito.mock(ScheduledFuture.class)); this.diagnosticsManager = new DiagnosticsManager(jobName, jobId, containerModels, containerMb, containerNumCores, numStoresWithChangelog, "0", executionEnvContainerId, taskClassVersion, samzaVersion, hostname, diagnosticsSystemStream, mockSystemProducer, Duration.ofSeconds(1), mockExecutorService); }</code><technical_language>thenAnswer instead of a matcher execute arbitrary logic</technical_language>

Target:
public void setup() { mockSystemProducer = new MockSystemProducer(); ScheduledExecutorService mockExecutorService = Mockito.mock(ScheduledExecutorService.class); Mockito.when(mockExecutorService.scheduleWithFixedDelay(Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.eq(TimeUnit.SECONDS))).thenAnswer(invocation -> { ((Runnable) invocation.getArguments()[0]).run(); return Mockito.mock(ScheduledFuture.class); }); this.diagnosticsManager = new DiagnosticsManager(jobName, jobId, containerModels, containerMb, containerNumCores, numStoresWithChangelog, "0", executionEnvContainerId, taskClassVersion, samzaVersion, hostname, diagnosticsSystemStream, mockSystemProducer, Duration.ofSeconds(1), mockExecutorService); exceptionEventList.forEach( diagnosticsExceptionEvent -> this.diagnosticsManager.addExceptionEvent(diagnosticsExceptionEvent)); this.diagnosticsManager.addProcessorStopEvent("0", executionEnvContainerId, hostname, 101); }
Source:
<code>public void dispose() { if (fTableViewer != null) { <START> fTableViewer.getTable().dispose(); <END> } if (fTablePopupMenuManager != null) { fTablePopupMenuManager.dispose(); } super.dispose(); }</code><technical_language>more correct do if viewer implemented, in practice method implementations identical in TableViewer return control</technical_language>

Target:
public void dispose() { if (fTableViewer != null) { fTableViewer.getControl().dispose(); } if (fTablePopupMenuManager != null) { fTablePopupMenuManager.dispose(); } super.dispose(); }
Source:
<code>public Tenant getTenantByDomain(String domain) throws TenantMgtException { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); Tenant tenant; try { int tenantID = tenantManager.getTenantId(domain); tenant = (Tenant) tenantManager.getTenant(tenantID); if (tenant == null) { throw new TenantManagementClientException(ERROR_CODE_DOMAIN_NOT_FOUND.getCode(), String.format(ERROR_CODE_DOMAIN_NOT_FOUND.getMessage(), domain)); } } catch (org.wso2.carbon.user.api.UserStoreException e) { <START> throw new TenantManagementServerException("Error while getting the tenant.", e); <END> } return tenant; }</code><technical_language>good tenant ID printed ? domain idea for tenant issue caused</technical_language>

Target:
public Tenant getTenantByDomain(String domain) throws TenantMgtException { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); Tenant tenant; try { int tenantID = tenantManager.getTenantId(domain); tenant = (Tenant) tenantManager.getTenant(tenantID); if (tenant == null) { throw new TenantManagementClientException(ERROR_CODE_DOMAIN_NOT_FOUND.getCode(), String.format(ERROR_CODE_DOMAIN_NOT_FOUND.getMessage(), domain)); } } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new TenantManagementServerException("Error while getting the tenant - " + domain, e); } return tenant; }
Source:
<code>public void headers() throws Exception { WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); r.getInstance().setSlaveAgentPort(-1); Page p = wc.goTo("tcpSlaveAgentListener"); <START> assertThat(p.getWebResponse().getStatusCode(), equalTo(404)); <END> r.getInstance().setSlaveAgentPort(0); p = wc.goTo("tcpSlaveAgentListener", "text/plain"); assertThat(p.getWebResponse().getStatusCode(), equalTo(200)); assertThat(p.getWebResponse().getResponseHeaderValue("X-Instance-Identity"), notNullValue()); }</code><technical_language>assertFails</technical_language>

Target:
public void headers() throws Exception { WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); r.getInstance().setSlaveAgentPort(-1); wc.assertFails("tcpSlaveAgentListener", HttpURLConnection.HTTP_NOT_FOUND); r.getInstance().setSlaveAgentPort(0); Page p = wc.goTo("tcpSlaveAgentListener", "text/plain"); assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode()); assertThat(p.getWebResponse().getResponseHeaderValue("X-Instance-Identity"), notNullValue()); }
Source:
<code>private String loadVersion() { String version = "unknown"; try { Class clz = getClass(); String className = clz.getSimpleName() + ".class"; String classPath = clz.getResource(className).toString(); if (classPath.startsWith("jar")) { String manifestPath = classPath.substring(0, classPath.lastIndexOf('!') + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attributes = manifest.getMainAttributes(); String value = attributes.getValue("Implementation-Version"); if (StringUtils.hasText(value)) { <START> version = value; <END> } } } catch (Exception e) { System.out.println("Could not determine version of Spring XD via manifest"); e.printStackTrace(); } return version; }</code><technical_language>Suggest: version = value.replaceAll("BUILD-SNAPSHOT", "SNAP").replaceAll("-RELEASE", "");</technical_language>

Target:
private String loadVersion() { String version = "unknown"; try { Class clz = getClass(); String className = clz.getSimpleName() + ".class"; String classPath = clz.getResource(className).toString(); if (classPath.startsWith("jar")) { String manifestPath = classPath.substring(0, classPath.lastIndexOf('!') + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attributes = manifest.getMainAttributes(); String value = attributes.getValue("Implementation-Version"); if (StringUtils.hasText(value)) { version = value.replaceAll("BUILD-SNAPSHOT", "SNAP").replaceAll("-RELEASE", ""); } } } catch (Exception e) { System.out.println("Could not determine version of Spring XD via manifest"); e.printStackTrace(); } return version; }
Source:
<code><START> wbFromDMN(final String description) { <END> if (description == null) { return new Description(""); } else { return new Description(description); } }</code><technical_language>Please restore original formatting</technical_language>

Target:
public static Description wbFromDMN(final String description) { if (description == null) { return new Description(""); } else { return new Description(description); } }
Source:
<code>private static Iterable<HivePartitionMetadata> createPartitionMetadataWithOfflinePartitions() throws RuntimeException { <START> return new Iterable<HivePartitionMetadata>() <END> { @Override public Iterator<HivePartitionMetadata> iterator() { return new AbstractIterator<HivePartitionMetadata>() { private int position; private List<HivePartitionMetadata> hivePartitionMetadatas = ImmutableList.of( new HivePartitionMetadata( new HivePartition(new SchemaTableName("testSchema", "table_name"), ImmutableList.of()), Optional.empty(), ImmutableMap.of()), new HivePartitionMetadata( new HivePartition(new SchemaTableName("schemaWithOfflinePartitions", "table_name"), ImmutableList.of()), Optional.empty(), ImmutableMap.of())); protected HivePartitionMetadata computeNext() { if (hivePartitionMetadatas.get(position).getHivePartition().getTableName().getSchemaName().equalsIgnoreCase("schemaWithOfflinePartitions")) { throw new RuntimeException("OFFLINE"); } position++; if (position < hivePartitionMetadatas.size()) { return hivePartitionMetadatas.get(position); } return endOfData(); } }; } }; }</code><technical_language>I guess a lambda</technical_language>

Target:
private static Iterable<HivePartitionMetadata> createPartitionMetadataWithOfflinePartitions() throws RuntimeException { return () -> new AbstractIterator<HivePartitionMetadata>() { private int position = -1; @Override protected HivePartitionMetadata computeNext() { position++; switch (position) { case 0: return new HivePartitionMetadata( new HivePartition(new SchemaTableName("testSchema", "table_name"), ImmutableList.of()), Optional.empty(), ImmutableMap.of()); case 1: throw new RuntimeException("OFFLINE"); default: return endOfData(); } } }; }
Source:
<code>private boolean containsAnyParent(TreeItem item, Collection<TreeItem> items) { TreeItem parent = item.getParentItem(); <START> while (parent != null) { <END> if (items.contains(parent)) { return true; } parent = item.getParentItem(); } return false; }</code><technical_language>This cycle is endless if !items.contains(parent)</technical_language>

Target:
private boolean containsAnyParent(TreeItem item, Collection<TreeItem> items) { TreeItem parent = item.getParentItem(); while (parent != null) { if (items.contains(parent)) { return true; } parent = parent.getParentItem(); } return false; }
Source:
<code>public static void setRegion(final String region) { <START> Twilio.region = region; <END> }</code><technical_language>Changing region invalidate client above</technical_language>

Target:
public static void setRegion(final String region) { if (!region.equals(Twilio.region)) { Twilio.invalidate(); } Twilio.region = region; }
Source:
<code>private Tag next() throws LimitExceededException{ if (iterator != null) { while (iterator.hasNext()) { final Tag tag = iterator.next(); if (Verbs.isVerb(tag)) { if (current != null && current.hasChildren()) { final List<Tag> children = current.children(); if (children.contains(tag)) { continue; } } <START> if (tag.name().equals("Gather") && tag.hasAttribute(GatherAttributes.ATTRIBUTE_HINTS) && !StringUtils.isEmpty(tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value())) { <END> String hotWords = tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value(); List<String> hintList = Arrays.asList(hotWords.split(",")); if (hintList.size() > 50) { throw new LimitExceededException("HotWords limit exceeded. There are more than 50 phrases"); } for (String hint : hintList) { if (hint.length() > 100) { throw new LimitExceededException("HotWords limit exceeded. Hint with more than 100 characters found"); } } } current = tag; return current; } } } else { if(logger.isInfoEnabled()){ logger.info("iterator is null"); } } return null; }</code><technical_language>Please Verbs.gather instead of "Gather"</technical_language>

Target:
private Tag next() throws LimitExceededException{ if (iterator != null) { while (iterator.hasNext()) { final Tag tag = iterator.next(); if (Verbs.isVerb(tag)) { if (current != null && current.hasChildren()) { final List<Tag> children = current.children(); if (children.contains(tag)) { continue; } } if (tag.name().equals(Verbs.gather) && tag.hasAttribute(GatherAttributes.ATTRIBUTE_HINTS) && !StringUtils.isEmpty(tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value())) { String hotWords = tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value(); List<String> hintList = Arrays.asList(hotWords.split(",")); if (hintList.size() > 50) { throw new LimitExceededException("HotWords limit exceeded. There are more than 50 phrases"); } for (String hint : hintList) { if (hint.length() > 100) { throw new LimitExceededException("HotWords limit exceeded. Hint with more than 100 characters found"); } } } current = tag; return current; } } } else { if(logger.isInfoEnabled()){ logger.info("iterator is null"); } } return null; }
Source:
<code>public ModelAndView newStudy(ModelMap model) throws IOException { <START> User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); <END> Study study = new StudyImpl(user); authorizationManager.throwIfNotWritable(study); return setupForm(study, user, "New Study", model); }</code><technical_language>I transition long securityManager calls authorizationManager.getCurrentUser(); @djcooke confirm? (I a lot of residual securityManager calls in Edit*Controller files!)</technical_language>

Target:
public ModelAndView newStudy(ModelMap model) throws IOException { User user = authorizationManager.getCurrentUser(); Study study = new StudyImpl(user); authorizationManager.throwIfNotWritable(study); return setupForm(study, user, "New Study", model); }
Source:
<code>public void stop(BundleContext context_p) throws Exception { __plugin = null; if(_adapterFactory != null) <START> _adapterFactory.dispose(); <END> super.stop(context_p); }</code><technical_language>set _adaterFactory null dispose</technical_language>

Target:
public void stop(BundleContext context_p) throws Exception { __plugin = null; if(_adapterFactory != null){ _adapterFactory.dispose(); _adapterFactory = null; } super.stop(context_p); }
Source:
<code>public String getPropertiesAsJson(String namespace) { Map<String, String> props = getProperties(namespace); <START> List<String> sortedKeys = props.keySet().stream().sorted().collect(Collectors.toList()); <END> StringBuilder sb = new StringBuilder("{\n"); for (int i = 0; i < sortedKeys.size(); i++) { String key = sortedKeys.get(i); sb.append('\t').append('"').append(key).append("\": \"").append(props.get(key)).append('"'); if (i < sortedKeys.size() - 1) { sb.append(','); } sb.append('\n'); } sb.append('}'); return sb.toString(); }</code><technical_language>point of sorting keys here</technical_language>

Target:
public String getPropertiesAsJson(String namespace) throws IOException { return mapper.writeValueAsString(getProperties(namespace)); }
Source:
<code>private IStorageModel preparePosixStorageForEdit(StorageDomain storage) { final PosixStorageModel model = getPosixModelByStorage(storage); model.setRole(storage.getStorageDomainType()); boolean isPathEditable = isPathEditable(storage); model.getPath().setIsChangable(isPathEditable); <START> if (model.getType().equals(StorageType.POSIXFS)) { <END> model.getVfsType().setIsChangable(isPathEditable); } else { model.getVfsType().setIsChangable(false); } model.getMountOptions().setIsChangable(isPathEditable); AsyncDataProvider.getInstance().getStorageConnectionById(new AsyncQuery(null, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { StorageServerConnections connection = (StorageServerConnections) returnValue; model.getPath().setEntity(connection.getconnection()); model.getVfsType().setEntity(connection.getVfsType()); model.getMountOptions().setEntity(connection.getMountOptions()); } }), storage.getStorage(), true); return model; }</code><technical_language>worth moving this logic gluster/posix models instead of checking type</technical_language>

Target:
private IStorageModel preparePosixStorageForEdit(StorageDomain storage) { final PosixStorageModel model = getPosixModelByStorage(storage); model.setRole(storage.getStorageDomainType()); boolean isPathEditable = isPathEditable(storage); model.getPath().setIsChangable(isPathEditable); model.setVfsChangeability(isPathEditable); model.getMountOptions().setIsChangable(isPathEditable); AsyncDataProvider.getInstance().getStorageConnectionById(new AsyncQuery(null, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { StorageServerConnections connection = (StorageServerConnections) returnValue; model.getPath().setEntity(connection.getconnection()); model.getVfsType().setEntity(connection.getVfsType()); model.getMountOptions().setEntity(connection.getMountOptions()); } }), storage.getStorage(), true); return model; }
Source:
<code>void resumeCompaction() throws InterruptedException, IOException, StoreException { if (srcIndex == null) { throw new IllegalStateException("Compactor has not been started"); } else if (compactionLog == null) { throw new IllegalStateException("There is no compaction to resume"); } runningLatch = new CountDownLatch(1); <START> while (isActive && !compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { <END> CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case PREPARE: compactionLog.markCopyStart(); case COPY: copy(); if (isActive) { compactionLog.markCommitStart(); commit(false); compactionLog.markCleanupStart(); waitTillRefCountZero(); cleanup(false); compactionLog.markCycleComplete(); } break; default: throw new IllegalStateException("Illegal compaction phase: " + phase); } } endCompaction(); runningLatch.countDown(); }</code><technical_language>if is same, move DONE case switch-case? a bit more readable</technical_language>

Target:
void resumeCompaction() throws StoreException { if (srcIndex == null) { throw new IllegalStateException("Compactor has not been initialized"); } else if (compactionLog == null) { throw new IllegalStateException("There is no compaction to resume"); } runningLatch = new CountDownLatch(1); try { while (isActive && !compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case PREPARE: compactionLog.markCopyStart(); case COPY: copy(); if (isActive) { compactionLog.markCommitStart(); commit(false); compactionLog.markCleanupStart(); waitTillRefCountZero(); cleanup(false); compactionLog.markCycleComplete(); } break; default: throw new IllegalStateException("Illegal compaction phase: " + phase); } } endCompaction(); } catch (InterruptedException | IOException e) { throw new StoreException("Exception during compaction", e, StoreErrorCodes.Unknown_Error); } finally { runningLatch.countDown(); } }
Source:
<code><START> public static Block mask(Block sourceBlock, int[] ids) <END> { if (sourceBlock instanceof DictionaryBlock) { DictionaryBlock dictionaryBlock = (DictionaryBlock) sourceBlock; int[] directIds = new int[ids.length]; for (int i = 0; i < ids.length; i++) { directIds[i] = dictionaryBlock.getId(ids[i]); } ids = directIds; sourceBlock = dictionaryBlock.getDictionary(); } return new DictionaryBlock(ids.length, sourceBlock, ids); }</code><technical_language>_positions_ ids array _visible_ _masked_ in returned Block</technical_language>

Target:
public static Block mask(Block sourceBlock, int[] ids) { if (sourceBlock instanceof DictionaryBlock) { DictionaryBlock dictionaryBlock = (DictionaryBlock) sourceBlock; int[] directIds = new int[ids.length]; for (int i = 0; i < ids.length; i++) { directIds[i] = dictionaryBlock.getId(ids[i]); } return new DictionaryBlock(directIds.length, dictionaryBlock.getDictionary(), directIds); } return new DictionaryBlock(ids.length, sourceBlock, ids); }
Source:
<code>protected boolean set(final VanishableBridge dataHolder, final Map<Key<?>, Object> keyValues) { if (dataHolder instanceof Entity && ((Entity) dataHolder).world.isRemote) { return false; } final boolean invis = (Boolean) keyValues.get(Keys.INVISIBLE); final boolean collision = (Boolean) keyValues.get(Keys.VANISH_IGNORES_COLLISION); final boolean untargetable = (Boolean) keyValues.get(Keys.VANISH_PREVENTS_TARGETING); final boolean vanish = (Boolean) keyValues.get(Keys.VANISH); dataHolder.bridge$setInvisible(invis); dataHolder.bridge$setVanished(vanish); <START> dataHolder.bridge$setUncollideable(collision); <END> dataHolder.bridge$setUntargetable(untargetable); return true; }</code><technical_language>So... is this right? vanish is false, entity in question unquestionably collidable. a worried a spiderweb a bridge method named key named other. school of thought is setting VANISH_IGNORES_COLLISION VANISH_PREVENTS_TARGETING true cleared setting VANISH false. feels largely expected I err side of agreeing that. this change myself, need other changes insulate other issues. However, I this is in impl, bridge$setUncollideable bridge$setUntargetable named vanish only. representive is methods renamed similarly include a vanish check bodies. check method for collisions, tacking a vanish check obvious needs happen. If want/need separate non-vanish uncollidable/targetting states need more, need this work vanish based states</technical_language>

Target:
protected boolean set(final VanishableBridge dataHolder, final Map<Key<?>, Object> keyValues) { if (dataHolder instanceof Entity && ((Entity) dataHolder).world.isRemote) { return false; } final boolean invis = (Boolean) keyValues.get(Keys.INVISIBLE); final boolean collision = (Boolean) keyValues.get(Keys.VANISH_IGNORES_COLLISION); final boolean untargetable = (Boolean) keyValues.get(Keys.VANISH_PREVENTS_TARGETING); final boolean vanish = (Boolean) keyValues.get(Keys.VANISH); dataHolder.bridge$setInvisible(invis); dataHolder.bridge$setVanished(vanish); dataHolder.bridge$setUncollideable(vanish && collision); dataHolder.bridge$setUntargetable(vanish && untargetable); return true; }
Source:
<code>public void close() { try { <START> mCompressedStream.close(); <END> } catch (IOException ioe) { throw(new RuntimeIOException("Close error in CSI compressed stream: " + ioe)); } }</code><technical_language>this check for null incase constructor failed</technical_language>

Target:
public void close() { if (mCompressedStream == null) { throw new SAMException("Null input stream."); } try { mCompressedStream.close(); } catch (IOException ioe) { throw(new RuntimeIOException("Close error in CSI compressed stream: " + ioe)); } }
Source:
<code>private boolean isJsonLdMIME(Request request) { String accept = request.getHttpRequest().getHeader(HttpHeaders.ACCEPT); <START> if (accept != null && accept.contains(JSONLDGetFeatureResponse.MIME)) return true; <END> else if (request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME)) return true; else return false; }</code><technical_language>Upside down, "f" override accepts, tested first</technical_language>

Target:
private boolean isJsonLdMIME(Request request) { String accept = request.getHttpRequest().getHeader(HttpHeaders.ACCEPT); if (request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME)) return true; else if (accept != null && accept.contains(JSONLDGetFeatureResponse.MIME)) return true; else return false; }