auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Long migrate(final HaWorkVO work) { long vmId = work.getInstanceId(); long srcHostId = work.getHostId(); VMInstanceVO vm = _instanceDao.findById(vmId); if (vm == null) { return null; } <START> s_logger.info("Migration attempt: for VM " + vm.getUuid() + "from host id " + srcHostId + <END> ". Retry count: " + work.getTimesTried() + "/" + _maxRetries + " times."); try { work.setStep(Step.Migrating); _haDao.update(work.getId(), work); _itMgr.migrateAway(vm.getUuid(), srcHostId); return null; } catch (InsufficientServerCapacityException e) { s_logger.warn("Migration attempt: Insufficient capacity for migrating a VM " + vm.getUuid() + " from source host id " + srcHostId + ". Exception: " + e.getMessage()); _resourceMgr.maintenanceFailed(srcHostId); return (System.currentTimeMillis() >> 10) + _migrateRetryInterval; } catch (Exception e) { s_logger.warn("Migration attempt: Unexpected exception occurred when attempting migration of " + vm.getUuid() + e.getMessage()); throw e; } }</code><technical_language>Log a debug/trace statement VM for migration skipping migrate()</technical_language>

Target:
public Long migrate(final HaWorkVO work) { long vmId = work.getInstanceId(); long srcHostId = work.getHostId(); VMInstanceVO vm = _instanceDao.findById(vmId); if (vm == null) { s_logger.info("Unable to find vm: " + vmId + ", skipping migrate."); return null; } s_logger.info("Migration attempt: for VM " + vm.getUuid() + "from host id " + srcHostId + ". Starting attempt: " + (1 + work.getTimesTried()) + "/" + _maxRetries + " times."); try { work.setStep(Step.Migrating); _haDao.update(work.getId(), work); _itMgr.migrateAway(vm.getUuid(), srcHostId); return null; } catch (InsufficientServerCapacityException e) { s_logger.warn("Migration attempt: Insufficient capacity for migrating a VM " + vm.getUuid() + " from source host id " + srcHostId + ". Exception: " + e.getMessage()); _resourceMgr.migrateAwayFailed(srcHostId, vmId); return (System.currentTimeMillis() >> 10) + _migrateRetryInterval; } catch (Exception e) { s_logger.warn("Migration attempt: Unexpected exception occurred when attempting migration of " + vm.getUuid() + e.getMessage()); throw e; } }
Source:
<code>public void testConfigWrite() throws Exception { StoredConfig dbconfig = db.getConfig(); RemoteConfig remoteConfig = new RemoteConfig(dbconfig, "origin"); remoteConfig.addURI( new URIish("<LINK_0>android")); remoteConfig.addFetchRefSpec( new RefSpec("+refs/heads }, output); PubSubConfig config = SubscribeDaemon.getConfig(); assertEquals(1, config.getPublishers().size()); Publisher pub = config.getPublisher("<LINK_0>"); assertTrue(pub != null); assertEquals( <START> new URIish("<LINK_0>"), pub.getUri()); <END> assertEquals(1, pub.getSubscribers().size()); Subscriber sub = pub.getSubscribers().iterator().next(); assertEquals("android", sub.getName()); assertEquals("origin", sub.getRemote()); assertEquals(1, sub.getSubscribeSpecs().size()); RefSpec spec = sub.getSubscribeSpecs().get(0); assertEquals("refs/heads/*", spec.getSource()); }</code><technical_language>compiler warning: Potential null pointer access: variable pub null this location</technical_language>

Target:
public void testConfigWrite() throws Exception { setupURIFetchConfig(); String[] output = execute("git subscribe origin"); assertArrayEquals("expected successful subscribe", new String[] { MessageFormat.format( CLIText.get().didSubscribe, "origin", "<LINK_0>"), "" }, output); PubSubConfig config = SubscribeDaemon.getConfig(); assertEquals(1, config.getPublishers().size()); Publisher pub = config.getPublisher("<LINK_0>"); assertTrue(pub != null); assertEquals( new URIish("<LINK_0>"), pub.getUri()); assertEquals(1, pub.getSubscribers().size()); Subscriber sub = pub.getSubscribers().iterator().next(); assertEquals("android", sub.getName()); assertEquals("origin", sub.getRemote()); assertEquals(1, sub.getSubscribeSpecs().size()); RefSpec spec = sub.getSubscribeSpecs().get(0); assertEquals("refs/heads/*", spec.getSource()); }
Source:
<code>public void testDefault() throws Exception { final String[] expected = { "42:40: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, ","), "71:30: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, ","), }; <START> verify(checkConfig, getPath("InputWhitespaceAfterSimple.java"), <END> expected); }</code><technical_language>InputWhitespaceAfterDefaultConfig</technical_language>

Target:
public void testDefault() throws Exception { final String[] expected = { "42:40: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, ","), "71:30: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, ","), }; verify(checkConfig, getPath("InputWhitespaceAfterDefaultConfig.java"), expected); }
Source:
<code>public void publish(LogRecord record) { Iterator<ExtensionProxy> iter = getExtensions().iterator(); <START> while (iter.hasNext()) { <END> ExtensionProxy extension = iter.next(); extension.invoke(new ExtMap() .mput(Base.InvokeKeys.COMMAND, Logger.InvokeCommands.PUBLISH) .mput(Logger.InvokeKeys.LOG_RECORD, record)); } }</code><technical_language>for</technical_language>

Target:
public void publish(LogRecord record) { initRefreshThread(); for (ExtensionProxy extension : getExtensions()) { extension.invoke(new ExtMap() .mput(Base.InvokeKeys.COMMAND, Logger.InvokeCommands.PUBLISH) .mput(Logger.InvokeKeys.LOG_RECORD, record)); } }
Source:
<code>public void checkHoveringFeature() { editor.moveCursorToText("Greeter"); editor.waitTextInHoverPopUpEqualsTo( <START> "class Greeter", "Known permanent failure: i<LINK_0>"); <END> }</code><technical_language>Typo ihttps. Also, ":" redundant here</technical_language>

Target:
public void checkHoveringFeature() { editor.moveCursorToText("Greeter"); try { editor.waitHoverPopupAppearance(); } catch (TimeoutException ex) { fail("Known permanent failure <LINK_0>"); } }
Source:
<code>protected void remoteGetBeforeWrite(InvocationContext ctx, WriteCommand command, RecipientGenerator keygen) throws Throwable { if ((isNeedReliableReturnValues(command) || command.isConditional()) && !command.isIgnorePreviousValue()) { for (Object k : keygen.getKeys()) { <START> if (!ctx.isInTxScope() && !cdl.localNodeIsPrimaryOwner(k)) { <END> continue; } Object returnValue = remoteGetBeforeWrite(ctx, command, k); if (returnValue == null && cdl.localNodeIsPrimaryOwner(k)) { localGetCacheEntry(ctx, k, true, command); } } } }</code><technical_language>ctx.isInTxScope() is false, cache is non-transactional. if local node is primary owner, key is local, remoteGetBeforeWrite is needed</technical_language>

Target:
protected void remoteGetBeforeWrite(InvocationContext ctx, WriteCommand command, RecipientGenerator keygen) throws Throwable { if ((isNeedReliableReturnValues(command) || command.isConditional()) && !command.isIgnorePreviousValue()) { for (Object k : keygen.getKeys()) { if (cdl.localNodeIsPrimaryOwner(k)) { localGetCacheEntry(ctx, k, true, command); } } } }
Source:
<code>void createTableDuplicateName() { String tableName = testResourceNamer.randomName("test", 20); TableProperties tableProperties = new TableProperties().setTableName(tableName); createTable(tableName); String requestId = testResourceNamer.randomUuid(); StepVerifier.create(azureTable.getTables().createWithResponseAsync(tableProperties, requestId, ResponseFormat.RETURN_CONTENT, null, Context.NONE)) <START> .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) <END> .verify(); }</code><technical_language>If import this, need fully qualified</technical_language>

Target:
void createTableDuplicateName() { String tableName = testResourceNamer.randomName("test", 20); TableProperties tableProperties = new TableProperties().setTableName(tableName); createTable(tableName); String requestId = testResourceNamer.randomUuid(); StepVerifier.create(azureTable.getTables().createWithResponseAsync(tableProperties, requestId, ResponseFormat.RETURN_CONTENT, null, Context.NONE)) .expectError(TableServiceErrorException.class) .verify(); }
Source:
<code>public void testGetRootsWithGenerics() throws IOException { final GenericsMatchInputData mockModel = new GenericsMatchInputData(); final Resource leftResource = mockModel.getLeft(); final Resource rightResource = mockModel.getRight(); assertNotNull(leftResource); assertNotNull(rightResource); final Iterator<EObject> leftContent = EcoreUtil.getAllProperContents(leftResource, false); <START> final Iterator<EObject> rightContent = EcoreUtil.getAllProperContents(leftResource, false); <END> final Iterator<EObject> originContent = EcoreUtil.getAllProperContents(leftResource, false); while (leftContent.hasNext() && rightContent.hasNext() && originContent.hasNext()) { final EObject left = leftContent.next(); final EObject right = rightContent.next(); final EObject origin = originContent.next(); final IComparisonScope eObjectScope = new DefaultComparisonScope(left, right, origin); assertSame(left, eObjectScope.getLeft()); assertSame(right, eObjectScope.getRight()); assertSame(origin, eObjectScope.getOrigin()); } final IComparisonScope resourceScope = new DefaultComparisonScope(leftResource, rightResource, null); assertSame(leftResource, resourceScope.getLeft()); assertSame(rightResource, resourceScope.getRight()); final ResourceSet leftRS = newResourceSet(leftResource); final ResourceSet rightRS = newResourceSet(rightResource); final IComparisonScope resourceSetScope = new DefaultComparisonScope(leftRS, rightRS, null); assertSame(leftRS, resourceSetScope.getLeft()); assertSame(rightRS, resourceSetScope.getRight()); }</code><technical_language>rightResource instead of leftResource</technical_language>

Target:
public void testGetRootsWithGenerics() throws IOException { final GenericsMatchInputData mockModel = new GenericsMatchInputData(); final Resource leftResource = mockModel.getLeft(); final Resource rightResource = mockModel.getRight(); assertNotNull(leftResource); assertNotNull(rightResource); final Iterator<EObject> leftContent = EcoreUtil.getAllProperContents(leftResource, false); final Iterator<EObject> rightContent = EcoreUtil.getAllProperContents(rightResource, false); while (leftContent.hasNext() && rightContent.hasNext()) { final EObject left = leftContent.next(); final EObject right = rightContent.next(); final IComparisonScope eObjectScope = new DefaultComparisonScope(left, right, null); assertSame(left, eObjectScope.getLeft()); assertSame(right, eObjectScope.getRight()); } final IComparisonScope resourceScope = new DefaultComparisonScope(leftResource, rightResource, null); assertSame(leftResource, resourceScope.getLeft()); assertSame(rightResource, resourceScope.getRight()); final ResourceSet leftRS = newResourceSet(leftResource); final ResourceSet rightRS = newResourceSet(rightResource); final IComparisonScope resourceSetScope = new DefaultComparisonScope(leftRS, rightRS, null); assertSame(leftRS, resourceSetScope.getLeft()); assertSame(rightRS, resourceSetScope.getRight()); }
Source:
<code><START> public ByteBuffer getPoolableBuffer(ByteBuffer buffer) { <END> ByteBuffer result = buffer; Class clazz = buffer.getClass(); try { Method method = clazz.getMethod("attachment"); method.setAccessible(true); Object attachment = method.invoke(buffer); if (attachment instanceof ByteBuffer) { result = (ByteBuffer) attachment; } else if (attachment != null) { throw new InternalGemFireException( "direct byte buffer attachment was not a byte buffer but a " + attachment.getClass().getName()); } } catch (Exception e) { throw new InternalGemFireException("unable to retrieve underlying byte buffer", e); } return result; }</code><technical_language>is awful this method reflect single returned ByteBuffer. impose overhead for define hierarchy abstract class do work (polymorphically) of returning buffer pool? I realize entail classes. I if small (in lines-of-code). eliminate possibility of InternalGemFireException valuable</technical_language>

Target:
public ByteBuffer getPoolableBuffer(ByteBuffer buffer) { ByteBuffer result = buffer; if (parentOfSliceMethod == null) { Class clazz = buffer.getClass(); try { Method method = clazz.getMethod("attachment"); method.setAccessible(true); parentOfSliceMethod = method; } catch (Exception e) { throw new InternalGemFireException("unable to retrieve underlying byte buffer", e); } } try { Object attachment = parentOfSliceMethod.invoke(buffer); if (attachment instanceof ByteBuffer) { result = (ByteBuffer) attachment; } else if (attachment != null) { throw new InternalGemFireException( "direct byte buffer attachment was not a byte buffer but a " + attachment.getClass().getName()); } } catch (Exception e) { throw new InternalGemFireException("unable to retrieve underlying byte buffer", e); } return result; }
Source:
<code>public DefaultRequirementsCollector(Configuration configuration) { this.collectors = ImmutableList.of( new RequirementsFromAnnotationCollector(configuration), <START> new CommandRequirementsCollector(configuration)); <END> }</code><technical_language>name for this CommandRequirementsFromConfigurationCollector</technical_language>

Target:
public DefaultRequirementsCollector(Configuration configuration) { this.collectors = ImmutableList.of( new RequirementsFromAnnotationCollector(configuration), new CommandRequirementsFromConfigurationCollector(configuration)); }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("RassXmlDocumentWrapper: [ extractDate:").append(extractDate); if (CollectionUtils.isNotEmpty(awards)) { for (RassXmlAgencyEntry agency : agencies) { sb.append(KFSConstants.SQUARE_BRACKET_LEFT).append(awards.toString()).append(KFSConstants.SQUARE_BRACKET_RIGHT); } } else { <START> sb.append(KFSConstants.SQUARE_BRACKET_LEFT).append("NO AWAWRDS").append(KFSConstants.SQUARE_BRACKET_RIGHT); <END> } if (CollectionUtils.isNotEmpty(agencies)) { for (RassXmlAgencyEntry agency : agencies) { sb.append(KFSConstants.SQUARE_BRACKET_LEFT).append(agency.toString()).append(KFSConstants.SQUARE_BRACKET_RIGHT); } } else { sb.append(KFSConstants.SQUARE_BRACKET_LEFT).append("NO AGENCIES").append(KFSConstants.SQUARE_BRACKET_RIGHT); } sb.append(KFSConstants.SQUARE_BRACKET_RIGHT); return sb.toString(); }</code><technical_language>Please fix typo in appended message</technical_language>

Target:
public String toString() { return ToStringBuilder.reflectionToString(this); }
Source:
<code><START> public void afterSuite() { <END> driver.quit(); }</code><technical_language>Please change name of afterSuit</technical_language>

Target:
public void afterSuite() { loginPage.CloseWindow(); }
Source:
<code>public void shouldFailWithoutClientJaasEntry() throws Exception { final Cluster cluster = TestClientFactory.build().protocol(kdcServer.serverPrincipalName) .addContactPoint(kdcServer.hostname).create(); final Client client = cluster.connect(); try { client.submit("1+1").all().get(); fail("This should not succeed as the client config does not contain a JaasEntry"); } catch(Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); <START> assertTrue(root instanceof TimeoutException); <END> } finally { cluster.close(); } }</code><technical_language>things: 1. reason for checking ResponseException GSSException is in environments (mac os, linux, travis, etc) tend exceptions thrown. is a ton of unexpected test failures started checking both. then, Gremlin Server integration tests solid. do ensure get TimeoutException. 2. TimeoutException right exception thrown (or in test below). a bad client configuration - of other exceptions previously thrown TimeoutException - thoughts</technical_language>

Target:
public void shouldFailWithoutClientJaasEntry() throws Exception { final Cluster cluster = TestClientFactory.build().protocol(kdcServer.serverPrincipalName) .addContactPoint(kdcServer.hostname).create(); final Client client = cluster.connect(); try { client.submit("1+1").all().get(); fail("This should not succeed as the client config does not contain a JaasEntry"); } catch(Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertTrue(root instanceof ResponseException || root instanceof NoHostAvailableException); } finally { cluster.close(); } }
Source:
<code>public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> offers) { offers.forEach(offer -> { final String offerId = offer.getId().getValue(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Received offerId={}: {}", offerId, flattenProtobufString(offer.toString())); } final OfferStrategy.OfferResult result = offerStrategy.evaluate(clusterState, offer); if (result.acceptable()) { LOGGER.info("Accepting offer offerId={}", offerId); TaskInfo taskInfo = taskInfoBuilder.buildTask(offer); schedulerDriver.launchTasks( singletonList(offer.getId()), singletonList(taskInfo)); clusterState.addTask(taskInfo); } else { <START> LOGGER.info("Declined offer: " + flattenProtobufString(offer.toString()) + "\n complaints: " + result.complaints.stream().collect(Collectors.joining("; "))); <END> schedulerDriver.declineOffer(offer.getId()); } }); }</code><technical_language>Please key=value logging style, <LINK_0></technical_language>

Target:
public void resourceOffers(SchedulerDriver schedulerDriver, List<Offer> offers) { offers.forEach(offer -> { final String offerId = offer.getId().getValue(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Received offerId={}: {}", offerId, flattenProtobufString(offer.toString())); } final OfferStrategy.OfferResult result = offerStrategy.evaluate(clusterState, offer); if (result.acceptable()) { LOGGER.info("Accepting offer offerId={}", offerId); TaskInfo taskInfo = taskInfoBuilder.buildTask(offer); schedulerDriver.launchTasks( singletonList(offer.getId()), singletonList(taskInfo)); clusterState.addTask(taskInfo); } else { LOGGER.debug("Declined offer offerId={} because: " + result.complaints.stream().collect(Collectors.joining("; "))); schedulerDriver.declineOffer(offer.getId()); } }); }
Source:
<code>private void processServerError(ReplicaId replica, ServerErrorCode serverErrorCode) { <START> if (replica != null && serverErrorCode != null) { <END> switch (serverErrorCode) { case No_Error: logger.trace("The delete request was successful."); operationTracker.onResponse(replica, true); break; case Blob_Deleted: logger.trace("Blob has already been deleted."); operationTracker.onResponse(replica, true); break; case Blob_Not_Found: resolveRouterError(RouterErrorCode.BlobDoesNotExist); operationTracker.onResponse(replica, false); break; case Blob_Expired: updateOperationStatus(replica, RouterErrorCode.BlobExpired); break; case Disk_Unavailable: updateOperationStatus(replica, RouterErrorCode.AmbryUnavailable); break; case IO_Error: updateOperationStatus(replica, RouterErrorCode.UnexpectedInternalError); break; case Partition_Unknown: updateOperationStatus(replica, RouterErrorCode.BlobDoesNotExist); break; case Partition_ReadOnly: updateOperationStatus(replica, RouterErrorCode.UnexpectedInternalError); break; default: logger.trace("Server returned an error: ", serverErrorCode); updateOperationStatus(replica, RouterErrorCode.UnexpectedInternalError); break; } } else { logger.error("Both Replica and ServerErrorCode cannot be null to handle."); updateOperationStatus(replica, RouterErrorCode.UnexpectedInternalError); } }</code><technical_language>Avoid checks, add noise code. is for this method called a null replica a null serverErrorCode</technical_language>

Target:
private void processServerError(ReplicaId replica, ServerErrorCode serverErrorCode) { switch (serverErrorCode) { case No_Error: logger.trace("The delete request was successful."); operationTracker.onResponse(replica, true); break; case Blob_Deleted: logger.trace("Blob has already been deleted."); operationTracker.onResponse(replica, true); break; case Blob_Expired: updateOperationState(replica, RouterErrorCode.BlobExpired); break; case Blob_Not_Found: case Partition_Unknown: updateOperationState(replica, RouterErrorCode.BlobDoesNotExist); break; case Disk_Unavailable: updateOperationState(replica, RouterErrorCode.AmbryUnavailable); break; default: logger.trace("Server returned an error: ", serverErrorCode); updateOperationState(replica, RouterErrorCode.UnexpectedInternalError); break; } }
Source:
<code>public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); if (path.charAt(0)=='/') path = path.substring(1); if(!allowedResources.containsKey(path)) { if(!allowResourceToBeServed(path)) { rsp.sendError(SC_FORBIDDEN); return; } <START> allowedResources.putIfAbsent(path,path); <END> } URL res = classLoader.getResource(path); if(res==null) { throw HttpResponses.error(SC_NOT_FOUND,new IllegalArgumentException("No such adjunct found: "+path)); } else { long expires = MetaClass.NO_CACHE ? 0 : expiration; rsp.serveFile(req,res,expires); } }</code><technical_language>Why? checked !allowedResources.containsKey(path). Cleaner ConcurrentSkipListSet java if (allowedResources.add(path)) { // body }</technical_language>

Target:
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); if (path.charAt(0)=='/') path = path.substring(1); if(!allowedResources.contains(path)) { if(!allowResourceToBeServed(path)) { rsp.sendError(SC_FORBIDDEN); return; } allowedResources.add(path); } URL res = classLoader.getResource(path); if(res==null) { throw HttpResponses.error(SC_NOT_FOUND,new IllegalArgumentException("No such adjunct found: "+path)); } else { long expires = MetaClass.NO_CACHE ? 0 : expiration; rsp.serveFile(req,res,expires); } }
Source:
<code>public Boolean evaluate(final EObject source, final IParameterValueList2 parameterValues, final IFacetManager facetManager, final DerivedTypedElement feature) throws DerivedTypedElementException { boolean result = false; if (parameterValues.size() == 0) { throw new DerivedTypedElementException( "parameterValues must not be empty"); } final Object paramValue = parameterValues.get(0).getValue(); if (paramValue instanceof EStructuralFeature) { final EStructuralFeature eStructFeature = (EStructuralFeature) paramValue; result = !eStructFeature.isDerived(); } else if (paramValue == null) { result = true; } else { final String message = String .format("Unexpected parameter type (%s instead of EStructuralFeature)", paramValue.getClass().getName()); throw new DerivedTypedElementException(message); } if (result) { try { result <START> &= facetManager.getSuperValueOf(feature, <END> source, parameterValues, Boolean.class).booleanValue(); } catch (FacetManagerException e) { throw new DerivedTypedElementException(e); } catch (SuperInvokeException e) { throw new DerivedTypedElementException(e); } } return Boolean.valueOf(result); }</code><technical_language>""" boolean superValue = ??????; result = result && superValue; """ more readable</technical_language>

Target:
public Boolean evaluate(final EObject source, final IParameterValueList2 parameterValues, final IFacetManager facetManager, final DerivedTypedElement feature) throws DerivedTypedElementException { boolean result = false; if (parameterValues.size() == 0) { throw new DerivedTypedElementException( "parameterValues must not be empty"); } final Object paramValue = parameterValues.get(0).getValue(); if (paramValue instanceof EStructuralFeature) { final EStructuralFeature eStructFeature = (EStructuralFeature) paramValue; result = !eStructFeature.isDerived(); } else if (paramValue == null) { result = true; } else { final String message = String .format("Unexpected parameter type (%s instead of EStructuralFeature)", paramValue.getClass().getName()); throw new DerivedTypedElementException(message); } if (result) { try { result = result && facetManager.getSuperValueOf(feature, source, parameterValues, Boolean.class).booleanValue(); } catch (Exception e) { throw new DerivedTypedElementException(e); } } return Boolean.valueOf(result); }
Source:
<code>public RowExpression rewriteSpecialForm(SpecialFormExpression node, Boolean isRoot, RowExpressionTreeRewriter<Boolean> treeRewriter) { <START> if (BooleanType.BOOLEAN.equals(node.getType()) && isConjunctiveDisjunctive(node.getForm())) { <END> return rewriteBooleanExpression(node, isRoot); } if (isRoot) { return treeRewriter.rewrite(node, false); } return null; }</code><technical_language>BooleanType.BOOLEAN.equals(node.getType()) assertion instead of a condition. Put a checkState</technical_language>

Target:
public RowExpression rewriteSpecialForm(SpecialFormExpression node, Boolean isRoot, RowExpressionTreeRewriter<Boolean> treeRewriter) { if (isConjunctiveDisjunctive(node.getForm())) { checkState(BooleanType.BOOLEAN.equals(node.getType()), "AND/OR must be boolean function"); return rewriteBooleanExpression(node, isRoot); } if (isRoot) { return treeRewriter.rewrite(node, false); } return null; }
Source:
<code>public void addListToArguments(String variablesToAdd, String flag) { if (variablesToAdd == null) { return; } <START> String[] splittedVariabledToAdd = variablesToAdd.split(","); <END> addListToArguments(new ArrayList<String>(Arrays.asList(splittedVariabledToAdd)), flag); }</code><technical_language>nit: I meant splitVariablesToAdd? suggestion String[] splitVariablesToAdd = variablesToAdd.split(",");</technical_language>

Target:
public void addListToArguments(String variablesToAdd, String flag) { if (variablesToAdd == null) { return; } String[] splittedVariablesToAdd = variablesToAdd.split(","); addListToArguments(new ArrayList<String>(Arrays.asList(splittedVariablesToAdd)), flag); }
Source:
<code>public void startElement(TagNode node) { if ((isImgTag(node) && !node.hasProperty("ALT")) || <START> ((isImageInput(node) || isAreaTag(node)) && (!node.hasProperty("ALT") || StringUtils.trim(node.getPropertyValue("ALT")).isEmpty()))) { <END> createViolation(node.getStartLinePosition(), "Add an \"alt\" attribute to this image."); } }</code><technical_language>if-condition is a bit hard read, conditions broken refactored helper functions improve readability</technical_language>

Target:
public void startElement(TagNode node) { if ((isImgTag(node) && !hasAltAttribute(node)) || ((isImageInput(node) || isAreaTag(node)) && hasInvalidAltAttribute(node))) { createViolation(node.getStartLinePosition(), "Add an \"alt\" attribute to this image."); } }
Source:
<code>public Plan(TableFilter[] filters, int count, Expression condition) { this.filters = new TableFilter[count]; System.arraycopy(filters, 0, this.filters, 0, count); final ArrayList<Expression> allCond = new ArrayList<>(count/2); <START> final ArrayList<TableFilter> all = new ArrayList<>(count); <END> if (condition != null) { allCond.add(condition); } for (int i = 0; i < count; i++) { TableFilter f = filters[i]; f.visit(new TableFilterVisitor() { @Override public void accept(TableFilter f) { all.add(f); if (f.getJoinCondition() != null) { allCond.add(f.getJoinCondition()); } } }); } allConditions = allCond.toArray(new Expression[0]); allFilters = all.toArray(new TableFilter[0]); }</code><technical_language>size assumptions incorrect. small in 43% of cases TestAll. plain new ArrayList<>() default initial capacity of 10 is reasonable choice here</technical_language>

Target:
public Plan(TableFilter[] filters, int count, Expression condition) { this.filters = new TableFilter[count]; System.arraycopy(filters, 0, this.filters, 0, count); final ArrayList<Expression> allCond = new ArrayList<>(); final ArrayList<TableFilter> all = new ArrayList<>(); if (condition != null) { allCond.add(condition); } for (int i = 0; i < count; i++) { TableFilter f = filters[i]; f.visit(new TableFilterVisitor() { @Override public void accept(TableFilter f) { all.add(f); if (f.getJoinCondition() != null) { allCond.add(f.getJoinCondition()); } } }); } allConditions = allCond.toArray(new Expression[0]); allFilters = all.toArray(new TableFilter[0]); }
Source:
<code>public void whenLightStatsOnNotInitializedSubscriptionThenCorrectResponse() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventType(et); <START> final Response response = when().get("/subscriptions?show_status=true").thenReturn(); <END> final ItemsWrapper<Subscription> subsItems = MAPPER.readValue(response.print(), new TypeReference<ItemsWrapper<Subscription>>(){}); for (final Subscription subscription: subsItems.getItems()) { if (subscription.getId().equals(s.getId())) { Assert.assertNotNull(subscription.getStats()); Assert.assertEquals("unassigned", subscription.getStats().get(0).getPartitions().get(0).getState()); Assert.assertEquals("", subscription.getStats().get(0).getPartitions().get(0).getStreamId()); return; } } Assert.assertTrue(false); }</code><technical_language>acceptance test, if other subscriptions created other tests? I differ subscription created (e.g. owning_application)</technical_language>

Target:
public void whenLightStatsOnNotInitializedSubscriptionThenCorrectResponse() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventType(et); final String owningApplication = s.getOwningApplication(); final Response response = when() .get("/subscriptions?show_status=true&owning_application=" + owningApplication) .thenReturn(); final ItemsWrapper<Subscription> subsItems = MAPPER.readValue(response.print(), new TypeReference<ItemsWrapper<Subscription>>(){}); for (final Subscription subscription: subsItems.getItems()) { if (subscription.getId().equals(s.getId())) { Assert.assertNotNull(subscription.getStatus()); Assert.assertEquals("unassigned", subscription.getStatus().get(0).getPartitions().get(0).getState()); Assert.assertEquals("", subscription.getStatus().get(0).getPartitions().get(0).getStreamId()); return; } } Assert.assertTrue(false); }
Source:
<code>public void noMessageSentWhenSecondConflictWithinConflictInterval() { mockExistingActivity(gamblingGoal, nowInAmsterdam()); Set<String> conflictCategories = new HashSet<>(Arrays.asList("lotto")); service.analyze(userAnonId, new NetworkActivityDto(conflictCategories, "http://localhost/test1", Optional.empty())); <START> ArgumentCaptor<MessageDestination> messageDestination = ArgumentCaptor.forClass(MessageDestination.class); <END> verify(mockMessageService, never()).sendMessage(any(), messageDestination.capture()); }</code><technical_language>extract a method verifyNoGoalConflictMessageSent too</technical_language>

Target:
public void noMessageSentWhenSecondConflictWithinConflictInterval() { mockExistingActivity(gamblingGoal, nowInAmsterdam()); Set<String> conflictCategories = new HashSet<>(Arrays.asList("lotto")); service.analyze(userAnonId, new NetworkActivityDto(conflictCategories, "http://localhost/test1", Optional.empty())); verifyNoMessagesCreated(); }
Source:
<code>public void testFinishInitializeWhenFromCatroidThenRemoveSaveNavigationItems() { when(model.isOpenedFromCatroid()).thenReturn(true); presenter.removeMoreOptionsItems(menu); <START> verify(topBarViewHolder).removeItem(R.id.pocketpaint_nav_save_image); <END> verify(topBarViewHolder).removeItem(R.id.pocketpaint_nav_save_duplicate); }</code><technical_language>This call removeCatroidMenuItems()</technical_language>

Target:
public void testFinishInitializeWhenFromCatroidThenRemoveSaveNavigationItems() { when(model.isOpenedFromCatroid()).thenReturn(true); presenter.removeMoreOptionsItems(menu); verify(topBarViewHolder).removeStandaloneMenuItems(menu); }
Source:
<code>public DomainCommandBuilder addHostControllerJavaOption(final String arg) { if (arg != null) { hostControllerJavaOpts.add(arg); } <START> return this; <END> }</code><technical_language>This method needs processing in addJavaOption</technical_language>

Target:
public DomainCommandBuilder addHostControllerJavaOption(final String arg) { if (arg != null && !arg.trim().isEmpty()) { final Argument argument = Arguments.parse(arg); if (argument.getKey().equals(DOMAIN_BASE_DIR)) { if (argument.getValue() != null) { setBaseDirectory(argument.getValue()); } } else if (argument.getKey().equals(DOMAIN_CONFIG_DIR)) { if (argument.getValue() != null) { setConfigurationDirectory(argument.getValue()); } } else if (argument.getKey().equals(DOMAIN_LOG_DIR)) { if (argument.getValue() != null) { setLogDirectory(argument.getValue()); } } else { hostControllerJavaOpts.add(argument); } } return this; }
Source:
<code>long caretProc (long clientData) { caretId = 0; if (currentCaret == null) { return 0; } if (currentCaret.blinkCaret()) { int blinkRate = currentCaret.blinkRate; if (blinkRate == 0) return 0; <START> currentCaret.getParent().setBlink(true); <END> caretId = OS.g_timeout_add (blinkRate, caretProc, 0); } else { currentCaret = null; } return 0; }</code><technical_language>Again, currentCaret.getParent().blink = true fine</technical_language>

Target:
long caretProc (long clientData) { caretId = 0; if (currentCaret == null) { return 0; } if (currentCaret.blinkCaret()) { int blinkRate = currentCaret.blinkRate; if (blinkRate == 0) return 0; currentCaret.getParent().blink = true; caretId = OS.g_timeout_add (blinkRate, caretProc, 0); } else { currentCaret = null; } return 0; }
Source:
<code>private boolean isFeedbackPathParticipantAnInstructor(String participant) { int instructorParticipantTypeIndex = getInstructorParticipantTypeIndex(participant); <START> return FEEDBACK_PARTICIPANT_TYPE_INSTRUCTOR.equals( <END> participant.substring(instructorParticipantTypeIndex)); }</code><technical_language>Try String endsWith method if</technical_language>

Target:
private boolean isFeedbackPathParticipantAnInstructor(String participant) { return participant.endsWith(FEEDBACK_PARTICIPANT_TYPE_INSTRUCTOR); }
Source:
<code>public void writeBytes(byte[] data, int off, int len) throws IOException { <START> user.writeBytes(data, off, len); <END> }</code><technical_language>currentWriter.writeBytes</technical_language>

Target:
public void writeBytes(byte[] data, int off, int len) throws IOException { currentWriter.writeBytes(data, off, len); }
Source:
<code>protected void init() { super.init(); casper.setEthereum(ethereum); <START> if (Boolean.TRUE.equals(((CasperProperties) config).getCasperValidatorEnabled())) { <END> casperValidatorService.start(); } }</code><technical_language>add @Autowired public void setConfig(SystemProperties config) { ... } method CasperValidatorService done in other similar places</technical_language>

Target:
protected void init() { super.init(); casper.setEthereum(ethereum); casperValidatorService.init(); }
Source:
<code>public static <E> PCollection<E> partition(PCollection<E> collection, View<E> view, int numWriters, int numPartitionWriters) { <START> int writers = Math.max(numPartitionWriters, numWriters); <END> DatasetDescriptor descriptor = view.getDataset().getDescriptor(); if (descriptor.isPartitioned()) { GetStorageKey<E> getKey = new GetStorageKey<E>(view, numPartitionWriters > 0 ? numPartitionWriters : 1); PTable<Pair<GenericData.Record, Integer>, E> table = collection .by(getKey, Avros.pairs(Avros.generics(getKey.schema()), Avros.ints())); PGroupedTable<Pair<GenericData.Record, Integer>, E> grouped = writers > 0 ? table.groupByKey(writers) : table.groupByKey(); return grouped.ungroup().values(); } else { return partition(collection, numWriters); } }</code><technical_language>I separate configuration settings dataset is unpartitioned. fine max of for case, writers numWriters. in isPartitioned block, I numWriters, writers in else block. Another alternative is allow numPartitionWriters override numWriters keys writer random number behavior is both</technical_language>

Target:
public static <E> PCollection<E> partition(PCollection<E> collection, View<E> view, int numWriters, int numPartitionWriters) { DatasetDescriptor descriptor = view.getDataset().getDescriptor(); if (descriptor.isPartitioned()) { GetStorageKey<E> getKey = new GetStorageKey<E>(view, numPartitionWriters > 0 ? numPartitionWriters : 1); PTable<Pair<GenericData.Record, Integer>, E> table = collection .by(getKey, Avros.pairs(Avros.generics(getKey.schema()), Avros.ints())); PGroupedTable<Pair<GenericData.Record, Integer>, E> grouped = numWriters > 0 ? table.groupByKey(numWriters) : table.groupByKey(); return grouped.ungroup().values(); } else { return partition(collection, numWriters); } }
Source:
<code><START> private static void dataTableHeaderMayOnlyContainVariableNames(ASTNode stat) throws InvalidSpecCompileException { <END> throw new InvalidSpecCompileException(stat, "Header of data table may only contain variable names"); }</code><technical_language>return exception exits in code throw dataTableHeaderMayOnlyContainVariableNames(column.get(0));</technical_language>

Target:
private static InvalidSpecCompileException dataTableHeaderMayOnlyContainVariableNames(ASTNode stat) { return new InvalidSpecCompileException(stat, "Header of data table may only contain variable names"); }
Source:
<code>protected void contextualizeTooltip() { if (this.selectedDifferences.size() > 1) { setMultipleTooltip(this.selectedMode); } else if (this.selectedDifferences.isEmpty()) { initToolTipAndImage(this.selectedMode); } else { Diff diff = this.selectedDifferences.get(0); <START> Adapter tooltipAdapter = EcoreUtil.getAdapter(diff.eAdapters(), ITooltipLabelProvider.class); <END> if (tooltipAdapter == null) { tooltipAdapter = adapterFactory.adapt(diff, ITooltipLabelProvider.class); } if (tooltipAdapter instanceof ITooltipLabelProvider) { String tooltip = ((ITooltipLabelProvider)tooltipAdapter).getTooltip(this.selectedMode); setToolTipText(tooltip); } else { initToolTipAndImage(this.selectedMode); } } }</code><technical_language>This change is useless. tooltip providers correctly implement isAdapterForType(...), adapterFactory.adapt(ITooltiplabelProvider.class) check a relevant adapter is registered diff reuse if exists</technical_language>

Target:
protected void contextualizeTooltip() { if (this.selectedDifferences.size() > 1) { setMultipleTooltip(this.selectedMode); } else if (this.selectedDifferences.isEmpty()) { initToolTipAndImage(this.selectedMode); } else { Diff diff = this.selectedDifferences.get(0); Object adapter = adapterFactory.adapt(diff, ITooltipLabelProvider.class); if (adapter instanceof ITooltipLabelProvider) { String tooltip = ((ITooltipLabelProvider)adapter).getTooltip(this.selectedMode); setToolTipText(tooltip); } else { initToolTipAndImage(this.selectedMode); } } }
Source:
<code>private Page processPageSource() { <START> while (!finishing && !currentOutput.hasNext() && pageSource.isBlocked().isDone()) { <END> Page page = pageSource.getNextPage(); finishing = pageSource.isFinished(); pageSourceMemoryContext.setBytes(pageSource.getSystemMemoryUsage()); if (page != null) { long endCompletedBytes = pageSource.getCompletedBytes(); long endReadTimeNanos = pageSource.getReadTimeNanos(); operatorContext.recordGeneratedInput(endCompletedBytes - completedBytes, page.getPositionCount(), endReadTimeNanos - readTimeNanos); completedBytes = endCompletedBytes; readTimeNanos = endReadTimeNanos; PageProcessorOutput output = pageProcessor.process(operatorContext.getSession().toConnectorSession(), page); currentOutput.accept(output); } if (finishing) { currentOutput.flush(); } pageBuilderMemoryContext.setBytes(currentOutput.getRetainedSizeInBytes()); if (page == null) { break; } } Page result = null; if (currentOutput.hasNext()) { result = currentOutput.next(); pageBuilderMemoryContext.setBytes(currentOutput.getRetainedSizeInBytes()); } return result; }</code><technical_language>do need && pageSource.isBlocked().isDone(</technical_language>

Target:
private Page processPageSource() { DriverYieldSignal yieldSignal = operatorContext.getDriverContext().getYieldSignal(); if (!finishing && mergingOutput.needsInput() && !yieldSignal.isSet()) { Page page = pageSource.getNextPage(); finishing = pageSource.isFinished(); pageSourceMemoryContext.setBytes(pageSource.getSystemMemoryUsage()); if (page != null) { long endCompletedBytes = pageSource.getCompletedBytes(); long endReadTimeNanos = pageSource.getReadTimeNanos(); operatorContext.recordGeneratedInput(endCompletedBytes - completedBytes, page.getPositionCount(), endReadTimeNanos - readTimeNanos); completedBytes = endCompletedBytes; readTimeNanos = endReadTimeNanos; PageProcessorOutput output = pageProcessor.process(operatorContext.getSession().toConnectorSession(), yieldSignal, page); mergingOutput.addInput(output); } if (finishing) { mergingOutput.finish(); } } Page result = mergingOutput.getOutput(); pageBuilderMemoryContext.setBytes(mergingOutput.getRetainedSizeInBytes()); return result; }
Source:
<code>private void notifyNeighbors() { <START> getWorld().notifyBlockOfStateChange(getPos(), RailcraftBlocks.getBlockTrack()); <END> getWorld().notifyBlockOfStateChange(getPos().down(), RailcraftBlocks.getBlockTrack()); sendUpdateToClient(); }</code><technical_language>this is correct replacement function</technical_language>

Target:
private void notifyNeighbors() { getWorld().notifyNeighborsOfStateChange(getPos(), RailcraftBlocks.getBlockTrack()); getWorld().notifyNeighborsOfStateChange(getPos().down(), RailcraftBlocks.getBlockTrack()); sendUpdateToClient(); }
Source:
<code>private void afterResponseSent(CacheRpcCommand command, Response resp) { if (command instanceof TotalOrderCommitCommand || command instanceof TotalOrderVersionedCommitCommand || command instanceof TotalOrderRollbackCommand || (command instanceof TotalOrderPrepareCommand && (((PrepareCommand) command).isOnePhaseCommit() || resp instanceof ExceptionResponse))) { totalOrderExecutorService.checkForReadyTasks(); <START> remoteCommandsExecutor.checkForReadyTasks(); <END> } }</code><technical_language>I sense checkForReadyTasks() in remoteCommandsExecutor. checkForReadyTasks() invoked state changes tasks unblocked (in case, receive (or increase) topology id). Also, total order commands change state..</technical_language>

Target:
private void afterResponseSent(CacheRpcCommand command, Response resp) { if (command instanceof TotalOrderCommitCommand || command instanceof TotalOrderVersionedCommitCommand || command instanceof TotalOrderRollbackCommand || (command instanceof TotalOrderPrepareCommand && (((PrepareCommand) command).isOnePhaseCommit() || resp instanceof ExceptionResponse))) { totalOrderExecutorService.checkForReadyTasks(); } }
Source:
<code>public <M, R> R toRest(M modelObject, Projection projection) { M transformedModel = projection.transformModel(modelObject); DSpaceConverter<M, R> converter = requireConverter(modelObject.getClass()); R restObject = converter.convert(transformedModel, projection); if (restObject instanceof BaseObjectRest) { if (!dSpacePermissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), restObject, "READ")) { <START> log.info("Access denied on " + restObject.getClass()); <END> return null; } } if (restObject instanceof RestModel) { return (R) projection.transformRest((RestModel) restObject); } return restObject; }</code><technical_language>this log message. Do want info message for access denied object? Also, this print out class name (like "ItemRest") instead of useful info. I enhance message here, consider removing it</technical_language>

Target:
public <M, R> R toRest(M modelObject, Projection projection) { M transformedModel = projection.transformModel(modelObject); DSpaceConverter<M, R> converter = requireConverter(modelObject.getClass()); R restObject = converter.convert(transformedModel, projection); if (restObject instanceof BaseObjectRest) { if (!dSpacePermissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), restObject, "READ")) { log.debug("Access denied on " + restObject.getClass() + " with id: " + ((BaseObjectRest) restObject).getId()); return null; } } if (restObject instanceof RestModel) { return (R) projection.transformRest((RestModel) restObject); } return restObject; }
Source:
<code>public void initialize(final String endPointId) { this.localEndPointId = endPointId; this.evalPrefix = endPointId.split("-")[0]; LOG.log(Level.INFO, "Initialize router with localEndPointId: {0}", localEndPointId); for (int partitionId = 0; partitionId < numPartitions; partitionId++) { <START> final int initialEvalId = partitionId % numInitialEvals; <END> partitionIdToEvalId[partitionId] = initialEvalId; } }</code><technical_language>initialEvalId is confusing me. change evalId</technical_language>

Target:
public void initialize(final String endPointId) { this.localEndPointId = endPointId; this.evalPrefix = endPointId.split("-")[0]; LOG.log(Level.INFO, "Initialize router with localEndPointId: {0}", localEndPointId); for (int partitionId = 0; partitionId < numPartitions; partitionId++) { final int evalId = partitionId % numInitialEvals; partitionIdToEvalId[partitionId] = evalId; } }
Source:
<code>private void logServerWarnings(List<String> warnings) { <START> if (!Boolean.getBoolean(RequestHandler.DISABLE_QUERY_WARNING_LOGS)) { <END> StringBuilder warningString = new StringBuilder(); for (String warning : warnings) { warningString.append(warning).append(", "); } final String queryString = statement.toString(); logger.warn( "Query '{}' generated server side warning(s): {}", queryString.subSequence(0, Math.min(queryString.length(), MAX_QUERY_LOG_LENGTH)), warningString.substring(0, warningString.length() - ", ".length())); } }</code><technical_language>guarded call this method a conditional checks above, suggest add this if block too</technical_language>

Target:
private void logServerWarnings(List<String> warnings) { final String queryString = QUERY_LOGGER.statementAsString(statement); for (String warning : warnings) { logger.warn("Query '{}' generated server side warning(s): {}", queryString, warning); } }
Source:
<code>public Map<String, String> getMetaDataQualifiedNames() { <START> return metaDataQualifiedNames; <END> }</code><technical_language>Please Collections.unmodifiableMap(metaDataQualifiedNames) here</technical_language>

Target:
public Map<String, String> getMetaDataQualifiedNames() { return Collections.unmodifiableMap(metaDataQualifiedNames); }
Source:
<code><START> public final void removeGraph(final String graphName) { <END> graphs.remove(graphName); }</code><technical_language>this signature here, I mimic Map.remove(k) return Graph in: java public final Graph removeGraph(final String graphName) a caller do: java manager.removeGraph("graph").close(); do dynamically added graph</technical_language>

Target:
public final Graph removeGraph(final String graphName) throws Exception { Graph graph = graphs.remove(graphName); graph.close(); return graph; }
Source:
<code>protected abstract Password engineGeneratePassword(String algorithm, KeySpec keySpec) throws InvalidKeySpecException; protected abstract <S extends KeySpec> S engineGetKeySpec(String algorithm, Password password, Class<S> keySpecType) throws InvalidKeySpecException; protected abstract boolean engineIsTranslatablePassword(final String algorithm, final Password password); protected abstract Password engineTranslatePassword(String algorithm, Password password) throws InvalidKeyException; protected abstract boolean engineVerify(String algorithm, Password password, final char[] guess) throws InvalidKeyException; protected boolean engineVerify(String algorithm, Password password, final char[] guess, Charset hashCharset) throws InvalidKeyException { <START> throw new InvalidKeyException(); <END> }</code><technical_language>This throw new UnsupportedOperationException() @throws added: @throws UnsupportedOperationException if this method is supported password factory</technical_language>

Target:
protected abstract Password engineGeneratePassword(String algorithm, KeySpec keySpec) throws InvalidKeySpecException; protected abstract <S extends KeySpec> S engineGetKeySpec(String algorithm, Password password, Class<S> keySpecType) throws InvalidKeySpecException; protected abstract boolean engineIsTranslatablePassword(final String algorithm, final Password password); protected abstract Password engineTranslatePassword(String algorithm, Password password) throws InvalidKeyException; protected abstract boolean engineVerify(String algorithm, Password password, final char[] guess) throws InvalidKeyException; protected boolean engineVerify(String algorithm, Password password, final char[] guess, Charset hashCharset) throws InvalidKeyException{ throw new UnsupportedOperationException(); }