auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<Integer, String> getCrossExpansions(final Set<Integer> gids, final Integer level, final CrossExpansionProperties crossExpansionProperties) { if (gids.size() > 5000) { throw new IllegalArgumentException( "Max set size has to be less than 5000." + " Any thing about this might casue caching and performace issues."); } final Monitor monitor = MonitorFactory.start( "org.generationcp.middleware.service.pedigree.PedigreeServiceImpl.getCrossExpansion(List<Integer>, Integer, CrossExpansionProperties)"); final Map<Integer, String> pedigreeStrings = new HashMap<>(); try { final int numberOfLevelsToTraverse = level == null ? crossExpansionProperties.getCropGenerationLevel(this.getCropName()) : level; final GermplasmCache germplasmAncestryCache = new GermplasmCache(germplasmDataManager, getNumberOfLevelsToTraverseInDb(numberOfLevelsToTraverse)); <START> germplasmAncestryCache.initialisesCache(this.getCropName(), gids, getNumberOfLevelsToTraverseInDb(numberOfLevelsToTraverse)); <END> for (Integer gid : gids) { pedigreeStrings.put(gid, buildPeidgreeString(gid, level, crossExpansionProperties, germplasmAncestryCache, numberOfLevelsToTraverse)); } return pedigreeStrings; } finally { monitor.stop(); } }</code><technical_language>please change method name 'initialiseCache'</technical_language>

Target:
public Map<Integer, String> getCrossExpansions(final Set<Integer> gids, final Integer level, final CrossExpansionProperties crossExpansionProperties) { if (gids.size() > 5000) { throw new IllegalArgumentException( "Max set size has to be less than 5000." + " Any thing about this might casue caching and performace issues."); } final Monitor monitor = MonitorFactory.start( "org.generationcp.middleware.service.pedigree.PedigreeServiceImpl.getCrossExpansion(List<Integer>, Integer, CrossExpansionProperties)"); final Map<Integer, String> pedigreeStrings = new HashMap<>(); try { final int numberOfLevelsToTraverse = level == null ? crossExpansionProperties.getCropGenerationLevel(this.getCropName()) : level; final GermplasmCache germplasmAncestryCache = new GermplasmCache(germplasmDataManager, getNumberOfLevelsToTraverseInDb(numberOfLevelsToTraverse)); germplasmAncestryCache.initialiseCache(this.getCropName(), gids, getNumberOfLevelsToTraverseInDb(numberOfLevelsToTraverse)); for (final Integer gid : gids) { pedigreeStrings.put(gid, buildPedigreeString(gid, level, crossExpansionProperties, germplasmAncestryCache, numberOfLevelsToTraverse)); } return pedigreeStrings; } finally { monitor.stop(); } }
Source:
<code>public void testRefundWithSplit() throws Throwable { transaction = transactionFactory.createCreditCardTransactionWithoutPinMode(); transaction.setCapture(true); transaction.setAmount(10000); Collection<SplitRule> splitRules = new ArrayList<SplitRule>(); Recipient recipient1 = recipientFactory.create(); recipient1.save(); SplitRule splitRule = new SplitRule(); splitRule.setRecipientId(recipient1.getId()); splitRule.setPercentage(50); splitRule.setLiable(true); splitRule.setChargeProcessingFee(true); splitRules.add(splitRule); Recipient recipient2 = recipientFactory.create(); SplitRule splitRule2 = new SplitRule(); recipient2.save(); splitRule2.setRecipientId(recipient2.getId()); splitRule2.setPercentage(50); splitRule2.setLiable(true); splitRule2.setChargeProcessingFee(true); splitRules.add(splitRule2); transaction.setSplitRules(splitRules); transaction.save(); Transaction foundTransaction = new Transaction().find(transaction.getId()); List<SplitRule> foundSplitRules = (List<SplitRule>) foundTransaction.getSplitRules(); foundSplitRules.get(0).setAmount(2000); foundSplitRules.get(1).setAmount(2000); Integer refundedAmount = 4000; foundTransaction.refundWithSplit(refundedAmount, foundSplitRules); assertEquals(refundedAmount, foundTransaction.getRefundedAmount()); List<Payable> payables = (List<Payable>) foundTransaction.payables(); <START> Integer payableExcpetedAmount = -2000; <END> assertEquals(payables.get(0).getAmount(), payableExcpetedAmount); assertEquals(payables.get(1).getAmount(), payableExcpetedAmount); }</code><technical_language>typo Excpeted</technical_language>

Target:
public void testRefundWithSplit() throws Throwable { transaction = transactionFactory.createCreditCardTransactionWithoutPinMode(); transaction.setCapture(true); transaction.setAmount(10000); Collection<SplitRule> splitRules = new ArrayList<SplitRule>(); Recipient recipient1 = recipientFactory.create(); recipient1.save(); SplitRule splitRule = new SplitRule(); splitRule.setRecipientId(recipient1.getId()); splitRule.setPercentage(50); splitRule.setLiable(true); splitRule.setChargeProcessingFee(true); splitRules.add(splitRule); Recipient recipient2 = recipientFactory.create(); SplitRule splitRule2 = new SplitRule(); recipient2.save(); splitRule2.setRecipientId(recipient2.getId()); splitRule2.setPercentage(50); splitRule2.setLiable(true); splitRule2.setChargeProcessingFee(true); splitRules.add(splitRule2); transaction.setSplitRules(splitRules); transaction.save(); Transaction foundTransaction = new Transaction().find(transaction.getId()); List<SplitRule> foundSplitRules = (List<SplitRule>) foundTransaction.getSplitRules(); foundSplitRules.get(0).setAmount(2000); foundSplitRules.get(1).setAmount(2000); Integer refundedAmount = 4000; foundTransaction.refundWithSplit(refundedAmount, foundSplitRules); assertEquals(refundedAmount, foundTransaction.getRefundedAmount()); List<Payable> payables = (List<Payable>) foundTransaction.payables(); Integer payableExpectedAmount = -2000; assertEquals(payables.get(0).getAmount(), payableExpectedAmount); assertEquals(payables.get(1).getAmount(), payableExpectedAmount); }
Source:
<code><START> public AccessResultCode writeUpdatedAlarmNotifications(final DlmsConnectionHolder conn, <END> final long alarmFilterLongValue) throws IOException, TimeoutException { final AttributeAddress alarmFilterValue = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final DataObject value = DataObject.newUInteger32Data(alarmFilterLongValue); final SetParameter setParameter = new SetParameter(alarmFilterValue, value); if (conn.hasDlmsMessageListener()) { conn.getDlmsMessageListener().setDescription("SetAlarmNotifications write updated value " + alarmFilterLongValue + ", set attribute: " + this.describeAttributes(alarmFilterValue)); } return conn.getConnection().set(setParameter); }</code><technical_language>![MAJOR](<LINK_1> Refactor this method throw checked exception instead of: java.io.IOException, java.util.concurrent.TimeoutException [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public AccessResultCode writeUpdatedAlarmNotifications(final DlmsConnectionHolder conn, final long alarmFilterLongValue) throws IOException, TimeoutException { final AttributeAddress alarmFilterValue = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final DataObject value = DataObject.newUInteger32Data(alarmFilterLongValue); final SetParameter setParameter = new SetParameter(alarmFilterValue, value); conn.getDlmsMessageListener().setDescription("SetAlarmNotifications write updated value " + alarmFilterLongValue + ", set attribute: " + JdlmsObjectToStringUtil.describeAttributes(alarmFilterValue)); return conn.getConnection().set(setParameter); }
Source:
<code>public void testExceededContentLengthLimit() throws Exception { String container = "test-container"; String blobName = "test-blob"; AzureBlobClient client = createMock(AzureBlobClient.class); <START> PayloadSlicer slicer = createMock(PayloadSlicer.class); <END> MutableBlobMetadata metadata = new MutableBlobMetadataImpl(); MutableContentMetadata contentMetadata = new BaseMutableContentMetadata(); contentMetadata.setContentLength(MultipartUploadStrategy.MAX_BLOCK_SIZE * MultipartUploadStrategy.MAX_NUMBER_OF_BLOCKS + 1); metadata.setName(blobName); metadata.setContentMetadata(contentMetadata); Blob blob = new BlobImpl(metadata); Payload payload = new StringPayload("ABCD"); payload.setContentMetadata(contentMetadata); blob.setPayload(payload); AzureBlobBlockUploadStrategy strat = new AzureBlobBlockUploadStrategy(client, slicer); strat.execute(container, blob); }</code><technical_language>need call replay mocks? And, expecting behaviour, create nice mocks instead</technical_language>

Target:
public void testExceededContentLengthLimit() throws Exception { String container = "test-container"; String blobName = "test-blob"; AzureBlobClient client = createNiceMock(AzureBlobClient.class); PayloadSlicer slicer = createNiceMock(PayloadSlicer.class); MutableBlobMetadata metadata = new MutableBlobMetadataImpl(); MutableContentMetadata contentMetadata = new BaseMutableContentMetadata(); contentMetadata.setContentLength(MultipartUploadStrategy.MAX_BLOCK_SIZE * MultipartUploadStrategy.MAX_NUMBER_OF_BLOCKS + 1); metadata.setName(blobName); metadata.setContentMetadata(contentMetadata); Blob blob = new BlobImpl(metadata); ByteSource bytes = ByteSource.wrap("ABCD".getBytes(Charsets.UTF_8)); Payload payload = Payloads.newByteSourcePayload(bytes); payload.setContentMetadata(contentMetadata); blob.setPayload(payload); AzureBlobBlockUploadStrategy strat = new AzureBlobBlockUploadStrategy(client, slicer); strat.execute(container, blob); }
Source:
<code>public void listRevisionsWithPaginationAndRepeatStream() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); for (int value = 0; value < numberExpected; value++) { settings.add(new ConfigurationSetting().key(keyPrefix).value("myValue" + value).label(labelPrefix)); } List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (ConfigurationSetting setting : settings) { results.add(client.setSettingWithResponse(setting)); <START> } <END> SettingSelector filter = new SettingSelector().keys(keyPrefix).labels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); }</code><technical_language>for loops condensed one</technical_language>

Target:
public void listRevisionsWithPaginationAndRepeatStream() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (int value = 0; value < numberExpected; value++) { ConfigurationSetting setting = new ConfigurationSetting().key(keyPrefix).value("myValue" + value).label(labelPrefix); settings.add(setting); results.add(client.setSettingWithResponse(setting)); } SettingSelector filter = new SettingSelector().keys(keyPrefix).labels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); }
Source:
<code>public void parserShouldReturnGlobPattern() throws Exception { <START> Assert.assertEquals("**/*.csv", locustParser.getDefaultGlobPattern()); <END> }</code><technical_language>import static method for remove Assert</technical_language>

Target:
public void parserShouldReturnGlobPattern() throws Exception { assertEquals("**/*.csv", locustParser.getDefaultGlobPattern()); }
Source:
<code>public static void pauseFlash() { <START> Log.d(TAG, "pauseFlash()"); <END> if (!paused && isAvailable()) { paused = true; if (isOn()) { startAgain = true; flashOff(); } } }</code><technical_language>remove log altogether, this added for debugging purposes. I is bad practice log for debugging instead of Android Studio's debugger. breakpoints ftw! :smile:</technical_language>

Target:
public static void pauseFlash() { if (!paused && isAvailable()) { paused = true; if (isOn()) { startAgain = true; flashOff(); } } }
Source:
<code>private TVAElementType determineType(Content content) { if (content instanceof Brand) { return TVAElementType.BRAND; } if (content instanceof Series) { return TVAElementType.SERIES; } <START> return TVAElementType.ITEM; <END> }</code><technical_language>//TODO? do this if of type Item if throwing? is more complex that</technical_language>

Target:
private TVAElementType determineType(Content content) { if (content instanceof Brand) { return TVAElementType.BRAND; } if (content instanceof Series) { return TVAElementType.SERIES; } if (content instanceof Item) { return TVAElementType.ITEM; } throw new RuntimeException("Content " + content.getCanonicalUri() + " of unexpected type. Expected Brand/Series/Item"); }
Source:
<code>public void execute(Context context) throws SQLException { context.execute(new AddColumnsBuilder(getDialect(), "users") .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_type") .setIsNullable(true) .setLimit(40) .build()) .addColumn(newVarcharColumnDefBuilder() <START> .setColumnName("homepage_value") <END> .setIsNullable(true) .setLimit(40) .build()) .build()); }</code><technical_language>column homepage_parameter</technical_language>

Target:
public void execute(Context context) throws SQLException { context.execute(new AddColumnsBuilder(getDialect(), "users") .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_type") .setIsNullable(true) .setLimit(40) .build()) .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_parameter") .setIsNullable(true) .setLimit(40) .build()) .build()); }
Source:
<code>private MergeOperator createMergeOperator(List<Type> sourceTypes, List<Integer> outputChannels, List<Integer> sortChannels, List<SortOrder> sortOrder) { MergeOperator.MergeOperatorFactory factory = new MergeOperator.MergeOperatorFactory( operatorId.getAndIncrement(), <START> new PlanNodeId("plan_node_id" + operatorId.getAndIncrement()), <END> exchangeClientFactory, serdeFactory, new SimplePageWithPositionComparator.Factory(), sourceTypes, outputChannels, sortChannels, sortOrder); DriverContext driverContext = createTaskContext(executor, executor, TEST_SESSION) .addPipelineContext(0, true, true) .addDriverContext(); return (MergeOperator) factory.createOperator(driverContext); }</code><technical_language>operatorId.getAndIncrement() is called producing values for operatorId sourceId; is this intentional</technical_language>

Target:
private MergeOperator createMergeOperator(List<Type> sourceTypes, List<Integer> outputChannels, List<Integer> sortChannels, List<SortOrder> sortOrder) { int mergeOperatorId = operatorId.getAndIncrement(); MergeOperator.MergeOperatorFactory factory = new MergeOperator.MergeOperatorFactory( mergeOperatorId, new PlanNodeId("plan_node_id" + mergeOperatorId), exchangeClientFactory, serdeFactory, orderingCompiler, sourceTypes, outputChannels, sortChannels, sortOrder); DriverContext driverContext = createTaskContext(executor, executor, TEST_SESSION) .addPipelineContext(0, true, true) .addDriverContext(); return (MergeOperator) factory.createOperator(driverContext); }
Source:
<code>public Query createQuery() { final int size = fieldContexts.size(); final ConversionContext conversionContext = new ContextualExceptionBridgeHelper(); if ( size == 1 ) { return queryCustomizer.setWrappedQuery( createQuery( fieldContexts.get( 0 ), conversionContext ) ).createQuery(); } else { <START> BooleanQuery.Builder builder = new BooleanQuery.Builder(); <END> for ( FieldContext fieldContext : fieldContexts ) { builder.add( createQuery( fieldContext, conversionContext ), BooleanClause.Occur.SHOULD ); } return queryCustomizer.setWrappedQuery( builder.build() ).createQuery(); } }</code><technical_language>mind naming variable aggregatedFieldsQueryBuilder instead of builder</technical_language>

Target:
public Query createQuery() { final int size = fieldContexts.size(); final ConversionContext conversionContext = new ContextualExceptionBridgeHelper(); if ( size == 1 ) { return queryCustomizer.setWrappedQuery( createQuery( fieldContexts.get( 0 ), conversionContext ) ).createQuery(); } else { BooleanQuery.Builder aggregatedFieldsQueryBuilder = new BooleanQuery.Builder(); for ( FieldContext fieldContext : fieldContexts ) { aggregatedFieldsQueryBuilder.add( createQuery( fieldContext, conversionContext ), BooleanClause.Occur.SHOULD ); } return queryCustomizer.setWrappedQuery( aggregatedFieldsQueryBuilder.build() ).createQuery(); } }
Source:
<code>protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { return retryTemplate.execute(context -> { <START> System.out.println("Retring " + context.getRetryCount() + " " + method + " "); <END> try { return super.doExecute(url, method, requestCallback, responseExtractor); } catch (GoodDataRestException e) { if (!failOverStrategy.retryAllowed(method.toString(), e.getStatusCode(), url)) { context.setExhaustedOnly(); } throw e; } }); }</code><technical_language>Typo..</technical_language>

Target:
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { return retryTemplate.execute(context -> { System.out.println("Retrying " + context.getRetryCount() + " " + method + " "); try { return super.doExecute(url, method, requestCallback, responseExtractor); } catch (GoodDataRestException e) { if (!retryStrategy.retryAllowed(method.toString(), e.getStatusCode(), url)) { context.setExhaustedOnly(); } throw e; } }); }
Source:
<code>public static PillPayloadV2 decryptedToPillPayloadVersion3(final byte[] decryptedRawMotion) throws InvalidEncryptedPayloadException { final double maxAccelerationMS2; final long cosTheta; final long motionMask; final long maxAccelerationTransform; try (final LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream(new ByteArrayInputStream(decryptedRawMotion))) { final byte rawMaxByte = littleEndianDataInputStream.readByte(); maxAccelerationMS2 = (UnsignedBytes.toInt(rawMaxByte) << 7) * COUNTS_IN_G; cosTheta = littleEndianDataInputStream.readByte() & 0xFFL; motionMask = littleEndianDataInputStream.readLong(); }catch (IOException ioe){ throw new InvalidEncryptedPayloadException(ioe.getMessage()); } <START> return PillPayloadV2.createWithMotionMask((((long) (1000 * maxAccelerationMS2)) - 383) * 2, motionMask, cosTheta); <END> }</code><technical_language>383 a constant</technical_language>

Target:
public static PillPayloadV2 decryptedToPillPayloadVersion3(final byte[] decryptedRawMotion) throws InvalidEncryptedPayloadException { final double maxAccelerationMS2; final long cosTheta; final long motionMask; final long maxAccelerationTransform; try (final LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream(new ByteArrayInputStream(decryptedRawMotion))) { final byte rawMaxByte = littleEndianDataInputStream.readByte(); maxAccelerationMS2 = (UnsignedBytes.toInt(rawMaxByte) << 7) * COUNTS_IN_G; cosTheta = littleEndianDataInputStream.readByte() & 0xFFL; motionMask = littleEndianDataInputStream.readLong(); }catch (IOException ioe){ throw new InvalidEncryptedPayloadException(ioe.getMessage()); } return PillPayloadV2.createWithMotionMask((((long) (1000 * maxAccelerationMS2)) - PILL_1P5_MOTION_OFFSET) * PILL_1P5_MOTION_MULTIPLIER, motionMask, cosTheta); }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DeleteRequest["); sb.append("BlobID=").append(blobId); <START> sb.append("PartitionId=").append(blobId.getPartition()); <END> sb.append(", ").append("ClientId=").append(clientId); sb.append(", ").append("CorrelationId=").append(correlationId); sb.append(", ").append("AccountId=").append(blobId.getAccountId()); sb.append(", ").append("ContainerId=").append(blobId.getContainerId()); sb.append(", ").append("DeletionTimeInMs=").append(deletionTimeInMs); sb.append("]"); return sb.toString(); }</code><technical_language>need a comma partitionid</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DeleteRequest["); sb.append("BlobID=").append(blobId); sb.append(", ").append("PartitionId=").append(blobId.getPartition()); sb.append(", ").append("ClientId=").append(clientId); sb.append(", ").append("CorrelationId=").append(correlationId); sb.append(", ").append("AccountId=").append(blobId.getAccountId()); sb.append(", ").append("ContainerId=").append(blobId.getContainerId()); sb.append(", ").append("DeletionTimeInMs=").append(deletionTimeInMs); sb.append("]"); return sb.toString(); }
Source:
<code>public void testSubmitOldStyleEvidence() throws StripeException, InterruptedException { int chargeValueCents = 100; Stripe.apiVersion = "2014-11-20"; Charge disputedCharge = createDisputedCharge(chargeValueCents); String myEvidence = "Here's evidence showing this charge is legitimate."; Dispute initialDispute = disputedCharge.getDispute(); assertNull(initialDispute.getEvidence()); assertNull(initialDispute.getEvidenceSubObject()); Map<String, Object> disputeParams = ImmutableMap.<String, Object>of("evidence", myEvidence); Dispute updatedDispute = disputedCharge.updateDispute(disputeParams); assertNotNull(updatedDispute); assertEquals(myEvidence, updatedDispute.getEvidence()); <START> assertNull(initialDispute.getEvidenceSubObject()); <END> }</code><technical_language>is this initialDispute? checking updatedDispute</technical_language>

Target:
public void testSubmitOldStyleEvidence() throws StripeException, InterruptedException { int chargeValueCents = 100; Stripe.apiVersion = "2014-11-20"; Charge disputedCharge = createDisputedCharge(chargeValueCents); String myEvidence = "Here's evidence showing this charge is legitimate."; Dispute initialDispute = disputedCharge.getDispute(); assertNull(initialDispute.getEvidence()); assertNull(initialDispute.getEvidenceSubObject()); Map<String, Object> disputeParams = ImmutableMap.<String, Object>of("evidence", myEvidence); Dispute updatedDispute = disputedCharge.updateDispute(disputeParams); assertNotNull(updatedDispute); assertEquals(myEvidence, updatedDispute.getEvidence()); assertNull(updatedDispute.getEvidenceSubObject()); }
Source:
<code>public TextAnalyticsClientBuilder subscriptionKey(String subscriptionKey) { <START> Objects.requireNonNull(subscriptionKey); <END> this.subscriptionKey = subscriptionKey; this.tokenCredential = null; return this; }</code><technical_language>Add message</technical_language>

Target:
public TextAnalyticsClientBuilder subscriptionKey(String subscriptionKey) { Objects.requireNonNull(subscriptionKey, "'subscriptionKey' cannot be null."); this.subscriptionKey = subscriptionKey; return this; }
Source:
<code>public RetrieveSentences(RetrieveSentences.Args args) throws Exception { Path indexPath = Paths.get(args.index); if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) { throw new IllegalArgumentException(args.index + " does not exist or is not a directory."); } this.reader = DirectoryReader.open(FSDirectory.open(indexPath)); Constructor passageClass = Class.forName("io.anserini.qa.passage." + args.scorer + "PassageScorer") .getConstructor(String.class, Integer.class); if (args.scorer.equals("Idf")) { scorer = (PassageScorer) passageClass.newInstance(args.index, args.k); <START> } else { <END> scorer = (PassageScorer) passageClass.newInstance(args.embeddings, args.k); } }</code><technical_language>add explicit condition, throw exception if matching current options</technical_language>

Target:
public RetrieveSentences(RetrieveSentences.Args args) throws Exception { Path indexPath = Paths.get(args.index); if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) { throw new IllegalArgumentException(args.index + " does not exist or is not a directory."); } this.reader = DirectoryReader.open(FSDirectory.open(indexPath)); Constructor passageClass = Class.forName("io.anserini.qa.passage." + args.scorer + "PassageScorer") .getConstructor(String.class, Integer.class); if (args.scorer.equals("Idf")) { scorer = (PassageScorer) passageClass.newInstance(args.index, args.k); } else if (args.scorer.equals("Wmd")) { scorer = (PassageScorer) passageClass.newInstance(args.embeddings, args.k); } else { throw new IllegalArgumentException("Scorer should either be Idf or Wmd"); } }
Source:
<code>private void disposeLookupSourceIfRequested() { verify(lookupSourceNotNeeded.isPresent()); if (!lookupSourceNotNeeded.get().isDone()) { return; } index.clear(); <START> operatorContext.setRevocableMemoryReservation(0L); <END> operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes()); state = State.DISPOSED; }</code><technical_language>I separate method in PartitionedLookupSourceFactory return future denoting set LookupSource is longer needed. getSuppliedLookupSourceNoLongerNeededFuture</technical_language>

Target:
private void disposeLookupSourceIfRequested() { checkState(state == State.LOOKUP_SOURCE_BUILT); verify(lookupSourceNotNeeded.isPresent()); if (!lookupSourceNotNeeded.get().isDone()) { return; } index.clear(); operatorContext.setRevocableMemoryReservation(0L); operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes()); lookupSourceSupplier = null; state = State.DISPOSED; }
Source:
<code>public void testCheckNoneOnHistoricProcessInstanceAndReadHistoryPermissionOnProcessDefinition() { processEngineConfiguration.setEnableHistoricInstancePermissions(true); String processInstanceId = startProcessAndExecuteJob(ONE_INCIDENT_PROCESS_KEY) .getProcessInstanceId(); createGrantAuthorization(Resources.HISTORIC_PROCESS_INSTANCE, processInstanceId, userId, HistoricProcessInstancePermissions.NONE); <START> createGrantAuthorization(PROCESS_DEFINITION, ONE_INCIDENT_PROCESS_KEY, userId, READ_HISTORY); <END> HistoricIncidentQuery query = historyService.createHistoricIncidentQuery(); assertThat(query.list()) .extracting("processInstanceId") .containsExactly(processInstanceId); }</code><technical_language>suggestion createGrantAuthorization(PROCESS_DEFINITION, ONE_INCIDENT_PROCESS_KEY, userId, ProcessDefinitionPermissions.READ_HISTORY);</technical_language>

Target:
public void testCheckNoneOnHistoricProcessInstanceAndReadHistoryPermissionOnProcessDefinition() { processEngineConfiguration.setEnableHistoricInstancePermissions(true); String processInstanceId = startProcessAndExecuteJob(ONE_INCIDENT_PROCESS_KEY) .getProcessInstanceId(); createGrantAuthorization(Resources.HISTORIC_PROCESS_INSTANCE, processInstanceId, userId, HistoricProcessInstancePermissions.NONE); createGrantAuthorization(PROCESS_DEFINITION, ONE_INCIDENT_PROCESS_KEY, userId, ProcessDefinitionPermissions.READ_HISTORY); HistoricIncidentQuery query = historyService.createHistoricIncidentQuery(); assertThat(query.list()) .extracting("processInstanceId") .containsExactly(processInstanceId); }
Source:
<code>public static @Nullable IViewPart newView(String viewId, boolean generateSuffix) { IViewPart viewPart = null; String primaryId = null; String secondaryId = null; <START> if (viewId.contains(TmfView.PRIMARY_SECONDARY_ID_SEPARATOR)) { <END> int index = viewId.indexOf(TmfView.PRIMARY_SECONDARY_ID_SEPARATOR); primaryId = viewId.substring(0, index); secondaryId = getBaseSecId(viewId.substring(index + 1)); } else { primaryId = viewId; } if (generateSuffix) { if (secondaryId == null) { secondaryId = UUID.randomUUID().toString(); } else { secondaryId += INTERNAL_SECONDARY_ID_SEPARATOR + UUID.randomUUID().toString(); } } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = workbenchWindow.getActivePage(); try { viewPart = page.showView(primaryId, secondaryId, IWorkbenchPage.VIEW_ACTIVATE); page.activate(viewPart); } catch (PartInitException e) { } return viewPart; }</code><technical_language>indexOf() check if returns != -1</technical_language>

Target:
public static @Nullable IViewPart newView(String viewId, boolean generateSuffix) { IViewPart viewPart = null; String primaryId = null; String secondaryId = null; int index = viewId.indexOf(TmfView.PRIMARY_SECONDARY_ID_SEPARATOR); if (index != -1) { primaryId = viewId.substring(0, index); secondaryId = getBaseSecId(viewId.substring(index + 1)); } else { primaryId = viewId; } if (generateSuffix) { if (secondaryId == null) { secondaryId = UUID.randomUUID().toString(); } else { secondaryId += INTERNAL_SECONDARY_ID_SEPARATOR + UUID.randomUUID().toString(); } } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = workbenchWindow.getActivePage(); try { viewPart = page.showView(primaryId, secondaryId, IWorkbenchPage.VIEW_ACTIVATE); page.activate(viewPart); } catch (PartInitException e) { } return viewPart; }
Source:
<code>public void testValidateFieldUnexpectedWidget() { FormField field = mock(FormField.class); IsWidget widget = mock(IsWidget.class); when(field.getWidget()).thenReturn(widget); when(field.isRequired()).thenReturn(true); <START> try { <END> fieldStateValidator.validate(field); fail("IllegalStateException expected"); } catch (IllegalStateException ise) { } }</code><technical_language>Alternatively, AssertJ method right now. JUnit 5 is out yet</technical_language>

Target:
public void testValidateFieldUnexpectedWidget() { FormField field = mock(FormField.class); IsWidget widget = mock(IsWidget.class); when(field.getWidget()).thenReturn(widget); when(field.isRequired()).thenReturn(true); assertThatThrownBy(() -> fieldStateValidator.validate(field)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Unexpected widget type: impossible to read the value"); }
Source:
<code>private void waitForCredentialVisible(final String credUsername) { <START> System.out.println("WaitforCredName: " + credUsername); <END> assertTrue(waitFor().withTimeout(20, TimeUnit.SECONDS).until(() -> credentialsId.resolve().getText().contains(credUsername)) ); credentialsId.select(credUsername); }</code><technical_language>remove sout</technical_language>

Target:
private void waitForCredentialVisible(final String credUsername) { assertTrue(waitFor().withTimeout(5, TimeUnit.SECONDS).until(() -> credentialsId.resolve().getText().contains(credUsername)) ); credentialsId.select(credUsername); }
Source:
<code>private boolean isConnected() { <START> return influxDB != null; <END> }</code><technical_language>influxdb.ping() a connection is established</technical_language>

Target:
private boolean isConnected() { return connected; }
Source:
<code>private void loadCache() { int retryAttempt = 0; while(true) { final GetBucketRequest request = new GetBucketRequest(bucket); request.withMaxKeys(Math.min(maxKeys, DEFAULT_MAX_KEYS)); if (prefix != null) { request.withPrefix(prefix); } if (truncated) { request.withMarker(nextMarker); } final GetBucketResponse response; try { response = this.client.getBucket(request); final ListBucketResult result = response.getListBucketResult(); truncated = result.getTruncated(); nextMarker = result.getNextMarker(); this.cache = result.getObjects(); this.cachePointer = 0; return; } catch (final IOException e) { if (retryAttempt >= retryCount) { <START> throw new RuntimeException("Failed to get the next set of objects from the getBucket request", e); <END> } retryAttempt++; } } }</code><technical_language>need add this message reached max number of retries</technical_language>

Target:
private void loadCache() { int retryAttempt = 0; while(true) { final GetBucketRequest request = new GetBucketRequest(bucket); request.withMaxKeys(Math.min(maxKeys, DEFAULT_MAX_KEYS)); if (prefix != null) { request.withPrefix(prefix); } if (truncated) { request.withMarker(nextMarker); } final GetBucketResponse response; try { response = this.client.getBucket(request); final ListBucketResult result = response.getListBucketResult(); truncated = result.getTruncated(); nextMarker = result.getNextMarker(); this.cache = result.getObjects(); this.cachePointer = 0; return; } catch (final IOException e) { if (retryAttempt >= retryCount) { throw new RuntimeException("Failed to get the next set of objects from the getBucket request after " + retryCount + " retries", e); } retryAttempt++; } } }
Source:
<code>private static Map<String, String> extractChallenge(String authenticateHeader, String authChallengePrefix) { if (!isValidChallenge(authenticateHeader, authChallengePrefix)) { return null; } authenticateHeader = authenticateHeader.toLowerCase().replace(authChallengePrefix.toLowerCase(), ""); String[] challenges = authenticateHeader.split(", "); <START> Map<String, String> challengeMap = new HashMap<String, String>(); <END> for (String pair : challenges) { String[] keyValue = pair.split("="); challengeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return challengeMap; }</code><technical_language>nit: type inference suggestion Map<String, String> challengeMap = new HashMap<>();</technical_language>

Target:
private static Map<String, String> extractChallenge(String authenticateHeader, String authChallengePrefix) { if (!isValidChallenge(authenticateHeader, authChallengePrefix)) { return null; } authenticateHeader = authenticateHeader.toLowerCase(Locale.ROOT).replace(authChallengePrefix.toLowerCase(Locale.ROOT), ""); String[] challenges = authenticateHeader.split(", "); Map<String, String> challengeMap = new HashMap<>(); for (String pair : challenges) { String[] keyValue = pair.split("="); challengeMap.put(keyValue[0].replaceAll("\"", ""), keyValue[1].replaceAll("\"", "")); } return challengeMap; }
Source:
<code>public Glide build(Context context) { if (sourceExecutor == null) { if (uncaughtThrowableStrategy != null) { sourceExecutor = GlideExecutor.newSourceExecutor(uncaughtThrowableStrategy); } sourceExecutor = GlideExecutor.newSourceExecutor(); } if (diskCacheExecutor == null) { if (uncaughtThrowableStrategy != null) { diskCacheExecutor = GlideExecutor.newDiskCacheExecutor(uncaughtThrowableStrategy); <START> } <END> diskCacheExecutor = GlideExecutor.newDiskCacheExecutor(); } if (memorySizeCalculator == null) { memorySizeCalculator = new MemorySizeCalculator.Builder(context).build(); } if (connectivityMonitorFactory == null) { connectivityMonitorFactory = new DefaultConnectivityMonitorFactory(); } if (bitmapPool == null) { int size = memorySizeCalculator.getBitmapPoolSize(); if (size > 0) { bitmapPool = new LruBitmapPool(size); } else { bitmapPool = new BitmapPoolAdapter(); } } if (arrayPool == null) { arrayPool = new LruArrayPool(memorySizeCalculator.getArrayPoolSizeInBytes()); } if (memoryCache == null) { memoryCache = new LruResourceCache(memorySizeCalculator.getMemoryCacheSize()); } if (diskCacheFactory == null) { diskCacheFactory = new InternalCacheDiskCacheFactory(context); } if (engine == null) { engine = new Engine(memoryCache, diskCacheFactory, diskCacheExecutor, sourceExecutor, GlideExecutor.newUnlimitedSourceExecutor()); } RequestManagerRetriever requestManagerRetriever = new RequestManagerRetriever( requestManagerFactory); return new Glide( context, engine, memoryCache, bitmapPool, arrayPool, requestManagerRetriever, connectivityMonitorFactory, logLevel, defaultRequestOptions.lock(), defaultTransitionOptions); }</code><technical_language>overriding this newDIskCacheExecutor() always? for newSourceExecutor above</technical_language>

Target:
public Glide build(Context context) { if (sourceExecutor == null) { sourceExecutor = GlideExecutor.newSourceExecutor(); } if (diskCacheExecutor == null) { diskCacheExecutor = GlideExecutor.newDiskCacheExecutor(); } if (memorySizeCalculator == null) { memorySizeCalculator = new MemorySizeCalculator.Builder(context).build(); } if (connectivityMonitorFactory == null) { connectivityMonitorFactory = new DefaultConnectivityMonitorFactory(); } if (bitmapPool == null) { int size = memorySizeCalculator.getBitmapPoolSize(); if (size > 0) { bitmapPool = new LruBitmapPool(size); } else { bitmapPool = new BitmapPoolAdapter(); } } if (arrayPool == null) { arrayPool = new LruArrayPool(memorySizeCalculator.getArrayPoolSizeInBytes()); } if (memoryCache == null) { memoryCache = new LruResourceCache(memorySizeCalculator.getMemoryCacheSize()); } if (diskCacheFactory == null) { diskCacheFactory = new InternalCacheDiskCacheFactory(context); } if (engine == null) { engine = new Engine(memoryCache, diskCacheFactory, diskCacheExecutor, sourceExecutor, GlideExecutor.newUnlimitedSourceExecutor()); } RequestManagerRetriever requestManagerRetriever = new RequestManagerRetriever( requestManagerFactory); return new Glide( context, engine, memoryCache, bitmapPool, arrayPool, requestManagerRetriever, connectivityMonitorFactory, logLevel, defaultRequestOptions.lock(), defaultTransitionOptions); }
Source:
<code>public void delete(Path path, boolean force) throws IOException { logger.debug("Deleting in (" + path + ")..."); if (!Files.exists(path)) { logger.warn(String.format("Path not found: path-[%s]", path)); return; } RepositoryPath repositoryPath=(RepositoryPath)path; <START> deleteMetadata(repositoryPath); <END> super.delete(path, force); artifactEventListenerRegistry.dispatchArtifactPathDeletedEvent(path); logger.debug(String.format("Removed [%s]", path)); }</code><technical_language>@puneethps try move this if (!Files.exists(path)) check</technical_language>

Target:
public void delete(Path path, boolean force) throws IOException { logger.debug("Deleting in (" + path + ")..."); RepositoryPath repositoryPath=(RepositoryPath)path; deleteMetadata(repositoryPath); if (!Files.exists(path)) { logger.warn(String.format("Path not found: path-[%s]", path)); return; } super.delete(path, force); artifactEventListenerRegistry.dispatchArtifactPathDeletedEvent(path); logger.debug(String.format("Removed [%s]", path)); }
Source:
<code>public void testFilterNicsWithUnmanagedNetworksUmngmtNetRemoved(){ List<VdsNetworkInterface> existingInterfaces = new ArrayList<VdsNetworkInterface>(); for(int i=0; i<10; i++){ Nic nic = new Nic(); nic.setName("eth" + i); NetworkImplementationDetails networkImplementationDetails = new NetworkImplementationDetails(true, i%2==1); nic.setNetworkImplementationDetails(networkImplementationDetails); existingInterfaces.add(nic); } UnmanagedNetworkValidator validator = new UnmanagedNetworkValidator(); Set<String> removedUnmanagedNetworks = new HashSet<String>(); <START> removedUnmanagedNetworks.add("eth4"); <END> removedUnmanagedNetworks.add("eth6"); removedUnmanagedNetworks.add("eth8"); List<VdsNetworkInterface> unmanagedNicsList = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, removedUnmanagedNetworks); assertEquals(2, unmanagedNicsList.size()); for(int i=0; i<2; i++){ assertEquals("eth" + (i*2), unmanagedNicsList.get(i).getName()); } }</code><technical_language>use: new HashSet<String>(Arrays.asList("eth4", ));</technical_language>

Target:
public void testFilterNicsWithUnmanagedNetworksUmngmtNetRemoved(){ VdsNetworkInterface nicWithUnmanagedToBeRemoved = createNicWithNetworkImplementationDetails("eth_unmanaged1_toBeRemoved", false); VdsNetworkInterface nicWithUnmanaged = createNicWithNetworkImplementationDetails("eth_unmanaged", false); VdsNetworkInterface nicWithManagedToBeRemoved = createNicWithNetworkImplementationDetails("eth_managed_toBeRemoved", true); VdsNetworkInterface nicWithManaged = createNicWithNetworkImplementationDetails("eth_managed", true); List<VdsNetworkInterface> existingInterfaces = Arrays.asList(nicWithUnmanagedToBeRemoved, nicWithUnmanaged, nicWithManagedToBeRemoved, nicWithManaged); Set<String> removedUnmanagedNetworks = new HashSet<>(Arrays.asList("eth_unmanaged1_toBeRemoved", "eth_managed_toBeRemoved")); List<VdsNetworkInterface> unmanagedNicsList = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, removedUnmanagedNetworks); assertEquals(1, unmanagedNicsList.size()); assertEquals("eth_unmanaged", unmanagedNicsList.get(0).getName()); }
Source:
<code>public <B> Trampoline<B> bind(final F<A, Trampoline<B>> f) { <START> return codense(sub, o -> suspend(new P1<Trampoline<B>>() { <END> public Trampoline<B> _1() { return cont.f(o).bind(f); } })); }</code><technical_language>P.lazy(F<Unit, A>) construct P1</technical_language>

Target:
public <B> Trampoline<B> bind(final F<A, Trampoline<B>> f) { return codense(sub, o -> suspend(P.lazy(u -> cont.f(o).bind(f)))); }
Source:
<code>private void stopLifeCycle() { final AtomicBoolean isLifeCycleStopped = new AtomicBoolean(false); final AtomicBoolean isTimeout = new AtomicBoolean(false); final Display display = Display.getCurrent(); final Thread shutdownThread = ThreadUtils.runSafeAsync( "dpp-shutdown", log, () -> { try { lifecycle.stop(); } finally { isLifeCycleStopped.set(true); if (display != null) { try { display.wake(); } catch (SWTException ignore) { } } } }); isLifecycleStarted = false; int threadTimeout = 10000; if (display != null && !display.isDisposed()) { display.timerExec( threadTimeout, () -> { isTimeout.set(true); display.wake(); }); <START> while (isLifeCycleStopped.get() == false && isTimeout.get() == false) { <END> if (!display.readAndDispatch()) display.sleep(); } if (isLifeCycleStopped.get()) return; threadTimeout = 1; } try { shutdownThread.join(threadTimeout); } catch (InterruptedException e) { log.warn("interrupted while waiting for the plugin context to shutdown"); Thread.currentThread().interrupt(); } if (shutdownThread.isAlive()) log.error("could not shutdown Saros gracefully"); }</code><technical_language>AtomicBoolean.get() returns a boolean, compare false. this done improve readability? suggestion while (!isLifeCycleStopped.get() && !isTimeout.get()) {</technical_language>

Target:
private void stopLifeCycle() { log.debug("stopping lifecycle..."); if (!isLifecycleStarted) { log.debug("lifecycle is already stopped"); return; } isLifecycleStarted = false; final AtomicBoolean isLifeCycleStopped = new AtomicBoolean(false); final AtomicBoolean isTimeout = new AtomicBoolean(false); final Display display = Display.getCurrent(); final Thread shutdownThread = ThreadUtils.runSafeAsync( "dpp-shutdown", log, () -> { try { lifecycle.stop(); } finally { isLifeCycleStopped.set(true); if (display != null) { try { display.wake(); } catch (SWTException ignore) { } } } }); int threadTimeout = 10000; if (display != null && !display.isDisposed()) { display.timerExec( threadTimeout, () -> { isTimeout.set(true); display.wake(); }); while (!isLifeCycleStopped.get() && !isTimeout.get()) { if (!display.readAndDispatch()) display.sleep(); } if (!isLifeCycleStopped.get()) threadTimeout = 1; } try { shutdownThread.join(threadTimeout); } catch (InterruptedException e) { log.warn("interrupted while waiting for the current lifecycle to stop"); Thread.currentThread().interrupt(); } if (shutdownThread.isAlive()) log.error("timeout while stopping lifecycle"); log.debug("lifecycle stopped"); }
Source:
<code>private GitHubUser(GHUser gitHubUser, GitUser author) throws IOException { <START> if (gitHubUser == null) { <END> this.login = generateLogin(author.getName()); this.name = author.getName(); this.email = author.getEmail(); } else { this.login = gitHubUser.getLogin(); this.name = Objects.firstNonNull(Strings.emptyToNull(gitHubUser.getName()), author.getName()); this.email = Objects.firstNonNull(Strings.emptyToNull(gitHubUser.getEmail()), author.getEmail()); } }</code><technical_language>more common put != null condition first</technical_language>

Target:
private GitHubUser(GHUser gitHubUser, GitUser author) throws IOException { this.login = getLogin(gitHubUser).or(generateLogin(author.getName())); this.name = getFullName(gitHubUser).or(author.getName()); this.email = getEMail(gitHubUser).or(author.getEmail()); }
Source:
<code>public List<User> getCollaborators(IRepositoryIdProvider repository) throws IOException { List<User> collaborators = super.getCollaborators(repository); List<User> collaboratorsWithFullDetails = new ArrayList<>(); <START> collaborators.forEach(user -> { <END> try { collaboratorsWithFullDetails.add(userService.getUser(user.getLogin())); } catch (IOException e) { logger.error("Unable to get full details for user " + user.getLogin()); } }); return collaboratorsWithFullDetails; }</code><technical_language>This is a mapping operation, .stream().map() collaborators get new list</technical_language>

Target:
public List<User> getCollaborators(IRepositoryIdProvider repository) throws IOException { return super.getCollaborators(repository).stream() .map(user -> { try { return userService.getUser(user.getLogin()); } catch (IOException e) { logger.warn("Unable to get full details for user " + user.getLogin()); return user; } }).collect(Collectors.toList()); }
Source:
<code>public ChecksumDTO extract(final Jar jar, final Locale locale) { Objects.requireNonNull(jar, "jar"); Objects.requireNonNull(locale, "locale"); ChecksumDTO checksumDTO = new ChecksumDTO(); checksumDTO.md5 = calcChecksum(jar, "MD5"); <START> checksumDTO.sha1 = calcChecksum(jar, "SHA-1"); <END> checksumDTO.sha256 = calcChecksum(jar, "SHA-256"); if (checksumDTO.md5 == null && checksumDTO.sha1 == null && checksumDTO.sha256 == null) { return null; } return checksumDTO; }</code><technical_language>aQute.libg.cryptography package for classes compute MD5, SHA1, SHA256. provide a nice asHex method return digest a hex string</technical_language>

Target:
public ChecksumDTO extract(final Jar jar, final Locale locale) { Objects.requireNonNull(jar, "jar"); Objects.requireNonNull(locale, "locale"); ChecksumDTO checksumDTO = new ChecksumDTO(); checksumDTO.md5 = calcChecksum(jar, MD5.ALGORITHM); checksumDTO.sha1 = calcChecksum(jar, SHA1.ALGORITHM); checksumDTO.sha256 = calcChecksum(jar, SHA256.ALGORITHM); checksumDTO.sha512 = calcChecksum(jar, SHA512.ALGORITHM); if (checksumDTO.md5 == null && checksumDTO.sha1 == null && checksumDTO.sha256 == null && checksumDTO.sha512 == null) { return null; } return checksumDTO; }