auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected boolean waitForWritable(DistributionSchedule.WriteSet writeSet, long key, int allowedNonWritableCount, long durationMs) { if (durationMs < 0) { return true; } final long startTime = MathUtils.nowInNano(); boolean success = true; if (durationMs == 0) { success = isWritesetWritable(writeSet, key, allowedNonWritableCount); } else { int backoff = 1; <START> final Instant deadline = Instant.now().plus(durationMs, ChronoUnit.MILLIS); <END> while (!isWritesetWritable(writeSet, key, allowedNonWritableCount)) { if (Instant.now().isBefore(deadline)) { long maxSleep = Duration.between(Instant.now(), deadline).toMillis(); if (maxSleep < 0) { maxSleep = 1; } long sleepMs = Math.min(backoff, maxSleep); try { Thread.sleep(sleepMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); success = isWritesetWritable(writeSet, key, allowedNonWritableCount); break; } backoff = backoff * 2; } else { success = false; break; } } } if (success) { sendWaitStats.registerSuccessfulEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } else { sendWaitStats.registerFailedEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } return success; }</code><technical_language>move instant allocation isWritesetWritable check, need do object allocation normal case, channels writable time. line 1053 problem traffic is high</technical_language>

Target:
protected boolean waitForWritable(DistributionSchedule.WriteSet writeSet, long key, int allowedNonWritableCount, long durationMs) { if (durationMs < 0) { return true; } final long startTime = MathUtils.nowInNano(); boolean success = isWritesetWritable(writeSet, key, allowedNonWritableCount); if (!success && durationMs > 0) { int backoff = 1; final int maxBackoff = 4; final long deadline = startTime + TimeUnit.MILLISECONDS.toNanos(durationMs); while (!isWritesetWritable(writeSet, key, allowedNonWritableCount)) { if (MathUtils.nowInNano() < deadline) { long maxSleep = MathUtils.elapsedMSec(startTime); if (maxSleep < 0) { maxSleep = 1; } long sleepMs = Math.min(backoff, maxSleep); try { TimeUnit.MILLISECONDS.sleep(sleepMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); success = isWritesetWritable(writeSet, key, allowedNonWritableCount); break; } if (backoff <= maxBackoff) { backoff++; } } else { success = false; break; } } if (backoff > 1) { LOG.info("Spent ms waiting for writable channels", MathUtils.elapsedMSec(startTime), writeSet.size() - allowedNonWritableCount); } } if (success) { clientChannelWriteWaitStats.registerSuccessfulEvent( MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } else { clientChannelWriteWaitStats.registerFailedEvent( MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } return success; }
Source:
<code>public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { <START> nanosecond = 0; <END> } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, offset ); }</code><technical_language>if condition be: if ( !isNanosecondPrecisionSupported() )</technical_language>

Target:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, offset ); }
Source:
<code>public void sendSeatOverrideMail(User user) { String subject = "Your seat was reset"; <START> String message = "Your seat was reset by an admin.\nPlease log in to My Area to select your new seat."; <END> sendMail(user.getUsername(), user.getUsername(), subject, message); }</code><technical_language>I this message is generic blunt. this is exceptional intrusive, this rewritten some apology reasoning</technical_language>

Target:
public void sendSeatOverrideMail(User user) { String subject = "Your seat was reset"; String message = "Unfortunately we had to reallocate your reserved seat.\n" + "Please contact us if you have any questions.\n" + "You can reserve a new seat through <a href=\"<LINK_0>\">My Area</a>."; sendMail(user.getUsername(), user.getUsername(), subject, message); }
Source:
<code>void testUpdateWhenResultDetailIsNotEmpty() { when(mockResultServiceEventData.getResultDetails()).thenReturn("SomeData"); underTest.update(mockAttemptAuditEventResult, mockResultServiceEventData); verify(mockResultServiceEventDataBuilder, times(1)).setResultDetails(any()); <START> } <END></code><technical_language>"SomeData"</technical_language>

Target:
void testUpdateWhenResultDetailIsNotEmpty() { String detailsValue = "SomeData"; when(mockResultServiceEventData.getResultDetails()).thenReturn(detailsValue); underTest.update(mockAttemptAuditEventResult, mockResultServiceEventData); verify(mockResultServiceEventDataBuilder, times(1)).setResultDetails(any()); verify(mockResultServiceEventDataBuilder, times(1)).setResultDetails(detailsValue); }
Source:
<code>public ExtSource createExtSource(PerunSession sess, ExtSource extSource, Map<String, String> attributes) throws InternalErrorException, ExtSourceExistsException { getPerunBl().getAuditer().log(sess, new ExtSourceCreated(extSource)); ExtSource extSource1 = getExtSourcesManagerImpl().createExtSource(sess, extSource, attributes); extSourcesByIdMap.put(extSource1.getId(), extSource); <START> extSourcesByNameMap.put(extSource1.getName(), extSource); <END> return extSource1; }</code><technical_language>Is reason extSource instead of returned one? If yes, change name of variable 'returnedExtSource' 'createdExtSource'</technical_language>

Target:
public ExtSource createExtSource(PerunSession sess, ExtSource extSource, Map<String, String> attributes) throws InternalErrorException, ExtSourceExistsException { getPerunBl().getAuditer().log(sess, new ExtSourceCreated(extSource)); ExtSource extSourceImpl = getExtSourcesManagerImpl().createExtSource(sess, extSource, attributes); extSourcesByIdMap.put(extSourceImpl.getId(), extSource); extSourcesByNameMap.put(extSourceImpl.getName(), extSource); return extSourceImpl; }
Source:
<code>protected void setValue(final int rowIndex, final int columnIndex, final Date value) { DTCellValue52 dtCellValue52 = table52.getData() .get(rowIndex) .get(columnIndex); dtCellValue52 .setDateValue(value); try { updateManager.update(table52, getUpdates(rowIndex, columnIndex)); <START> } catch (UpdateException e) { <END> e.printStackTrace(); } }</code><technical_language>This _smells_ bad.. reasoning catch UpdateException</technical_language>

Target:
protected void setValue(final int rowIndex, final int columnIndex, final Date value) { DTCellValue52 dtCellValue52 = table52.getData() .get(rowIndex) .get(columnIndex); dtCellValue52 .setDateValue(value); updateManager.update(table52, getUpdates(rowIndex, columnIndex)); }
Source:
<code>private void setConverters(Element element, RestHolder holder) { List<DeclaredType> converters = annotationHelper.extractAnnotationClassArrayParameter(element, getTarget(), "converters"); <START> if (converters != null && !converters.isEmpty()) { <END> JFieldVar restTemplateField = holder.getRestTemplateField(); JBlock init = holder.getInit().body(); init.add(invoke(restTemplateField, "getMessageConverters").invoke("clear")); for (DeclaredType converterType : converters) { JInvocation newConverter = codeModelHelper.newBeanOrEBean(holder, converterType, holder.getInitContextParam()); init.add(invoke(restTemplateField, "getMessageConverters").invoke("add").arg(newConverter)); } } }</code><technical_language>Checking for null is unnecessary. do in validateConverters() method, if user passes null, usage of annotation is invalid, do generate code for it</technical_language>

Target:
private void setConverters(Element element, RestHolder holder) { List<DeclaredType> converters = annotationHelper.extractAnnotationClassArrayParameter(element, getTarget(), "converters"); JFieldVar restTemplateField = holder.getRestTemplateField(); JBlock init = holder.getInit().body(); init.add(invoke(restTemplateField, "getMessageConverters").invoke("clear")); for (DeclaredType converterType : converters) { JInvocation newConverter = codeModelHelper.newBeanOrEBean(holder, converterType, holder.getInitContextParam()); init.add(invoke(restTemplateField, "getMessageConverters").invoke("add").arg(newConverter)); } }
Source:
<code>public void waitProposalIntoSignaturesContainer(final String expectedProposal) { <START> webDriverWaitFactory <END> .get(ELEMENT_TIMEOUT_SEC) .until( (ExpectedCondition<Boolean>) webDriver -> getAllVisibleTextFromSignaturesContainer().contains(expectedProposal)); }</code><technical_language>seleniumWebDriverHelper</technical_language>

Target:
public void waitProposalIntoSignaturesContainer(final String expectedProposal) { seleniumWebDriverHelper.waitTextContains(signaturesContainer, expectedProposal); }
Source:
<code><START> @Override public void helpHandleDiscoveryError( <END> String siteAddress, String endpointAddress, String username, String password, String userAvatarUrl, int errorMessage) { }</code><technical_language>I annotations separate lines</technical_language>

Target:
public void helpHandleDiscoveryError( String siteAddress, String endpointAddress, String username, String password, String userAvatarUrl, int errorMessage) { }
Source:
<code>static <T> Iterator<Optional<T>> yieldingIteratorFrom(WorkProcessor<T> processor) { return new AbstractIterator<Optional<T>>() { @Override protected Optional<T> computeNext() { if (processor.process()) { if (processor.isFinished()) { return endOfData(); } return Optional.of(processor.getResult()); } else if (processor.isBlocked()) { throw new IllegalStateException("Work is blocked"); } <START> else { <END> return Optional.empty(); } } }; }</code><technical_language>redundant else</technical_language>

Target:
static <T> Iterator<Optional<T>> yieldingIteratorFrom(WorkProcessor<T> processor) { requireNonNull(processor, "processor is null"); return new AbstractIterator<Optional<T>>() { @Override protected Optional<T> computeNext() { if (processor.process()) { if (processor.isFinished()) { return endOfData(); } return Optional.of(processor.getResult()); } else if (processor.isBlocked()) { throw new IllegalStateException("Cannot iterate over blocking WorkProcessor"); } return Optional.empty(); } }; }
Source:
<code>public static SortedMap<String, String> getAllProviderNames() { SortedMap<String, String> ret = new TreeMap<String, String>(); IConfigurationElement[] configs = getConfigurationElements(); for (IConfigurationElement config : configs) { if (config.getName().equals("provider")) { String currentId = config.getAttribute("id"); String currentName = config.getAttribute("name"); <START> String currentType = config.getAttribute("type"); END> if (currentName != null && currentId != null) { ret.put(currentName, currentId); } } } return ret; }</code><technical_language>currentType used, removed here</technical_language>

Target:
public static SortedMap<String, String> getAllProviderNames() { SortedMap<String, String> ret = new TreeMap<String, String>(); IConfigurationElement[] configs = getConfigurationElements(); for (IConfigurationElement config : configs) { if (config.getName().equals("provider")) { String currentId = config.getAttribute("id"); String currentName = config.getAttribute("name"); if (currentName != null && currentId != null) { ret.put(currentName, currentId); } } } return ret; }
Source:
<code>public String toString() { <START> return "name=" + name + ";javaType=" + javaType + ";uuid=" + uuid.toString(); <END> }</code><technical_language>please org.ovirt.engine.core.common.utils.ToStringBuilder</technical_language>

Target:
public String toString() { ToStringBuilder builder = ToStringBuilder.forInstance(this); builder.append("name", name); builder.append("javaType", javaType); builder.append("uuid", uuid); return builder.toString(); }
Source:
<code>public void onLoadFinished(Loader<Cursor> loader, final Cursor data) { if (data == null) { Toast.makeText(this, getResources().getString(R.string.cloud_error_failed_restart), Toast.LENGTH_LONG).show(); return; } if (mCloudCursorData != null && mCloudCursorData == data) return; <START> mCloudCursorData = data; <END> if (cloudLoaderAsyncTask != null && cloudLoaderAsyncTask.getStatus() == AsyncTask.Status.RUNNING) { return; } cloudLoaderAsyncTask = new CloudLoaderAsyncTask(new WeakReference<>(this), cloudHandler, mCloudCursorData); cloudLoaderAsyncTask.execute(); }</code><technical_language>this is a hack, implemented, other solutions work</technical_language>

Target:
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) { if (data == null) { Toast.makeText(this, getResources().getString(R.string.cloud_error_failed_restart), Toast.LENGTH_LONG).show(); return; } if (cloudCursorData != null && cloudCursorData == data) return; cloudCursorData = data; if (cloudLoaderAsyncTask != null && cloudLoaderAsyncTask.getStatus() == AsyncTask.Status.RUNNING) { return; } cloudLoaderAsyncTask = new CloudLoaderAsyncTask(this, cloudHandler, cloudCursorData); cloudLoaderAsyncTask.execute(); }
Source:
<code>public void suggestions_without_query_should_order_results() throws Exception { ComponentDto project1 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Alpha")); ComponentDto project2 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Bravo")); ComponentDto project3 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Charlie")); ComponentDto project4 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Delta")); doReturn(asList(project4, project2)).when(favoriteFinder).list(); componentIndexer.indexOnStartup(null); authorizationIndexerTester.allowOnlyAnyone(project1); authorizationIndexerTester.allowOnlyAnyone(project2); authorizationIndexerTester.allowOnlyAnyone(project3); authorizationIndexerTester.allowOnlyAnyone(project4); <START> SuggestionsWsResponse response = actionTester.newRequest() <END> .setMethod("POST") .setParam(PARAM_RECENTLY_BROWSED, Stream.of(project3, project1).map(ComponentDto::getKey).collect(joining(","))) .executeProtobuf(SuggestionsWsResponse.class); assertThat(response.getResultsList()) .flatExtracting(Category::getItemsList) .extracting(Suggestion::getKey) .containsExactly( project2.getKey(), project4.getKey(), project1.getKey(), project3.getKey() ); }</code><technical_language>remark: in places, WsActionTester is named ws in test. For consistency, I suggest name</technical_language>

Target:
public void suggestions_without_query_should_order_results() throws Exception { ComponentDto project1 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Alpha")); ComponentDto project2 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Bravo")); ComponentDto project3 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Charlie")); ComponentDto project4 = db.components().insertComponent(newPrivateProjectDto(organization).setName("Delta")); doReturn(asList(project4, project2)).when(favoriteFinder).list(); componentIndexer.indexOnStartup(null); userSessionRule.addProjectPermission(USER, project1); userSessionRule.addProjectPermission(USER, project2); userSessionRule.addProjectPermission(USER, project3); userSessionRule.addProjectPermission(USER, project4); SuggestionsWsResponse response = ws.newRequest() .setMethod("POST") .setParam(PARAM_RECENTLY_BROWSED, Stream.of(project3, project1).map(ComponentDto::getKey).collect(joining(","))) .executeProtobuf(SuggestionsWsResponse.class); assertThat(response.getResultsList()) .flatExtracting(Category::getItemsList) .extracting(Suggestion::getName, Suggestion::getIsFavorite, Suggestion::getIsRecentlyBrowsed) .containsExactly( tuple("Bravo", true, false), tuple("Delta", true, false), tuple("Alpha", false, true), tuple("Charlie", false, true)); }
Source:
<code>public void operationComplete(int rc, Set<LedgerFragment> fragments) { if (rc == BKException.Code.OK) { Set<BookieSocketAddress> bookies = Sets.newHashSet(); for (LedgerFragment f : fragments) { bookies.addAll(f.getAddresses()); } publishSuspectedLedgersAsync( bookies.stream().map(BookieSocketAddress::toString).collect(Collectors.toList()), Sets.newHashSet(lh.getId()) ).whenComplete((result, cause) -> { if (null != cause) { <START> callback.processResult(Code.ReplicationException, null, null); <END> } else { callback.processResult(Code.OK, null, null); } }); } else { callback.processResult(rc, null, null); } lh.closeAsync().whenComplete((result, cause) -> { if (null != cause) { LOG.warn("Error closing ledger : {}", lh.getId(), cause.getMessage()); } }); }</code><technical_language>want this 'cause' is lost in log errors. hide completely here</technical_language>

Target:
public void operationComplete(int rc, Set<LedgerFragment> fragments) { if (rc == BKException.Code.OK) { Set<BookieSocketAddress> bookies = Sets.newHashSet(); for (LedgerFragment f : fragments) { bookies.addAll(f.getAddresses()); } publishSuspectedLedgersAsync( bookies.stream().map(BookieSocketAddress::toString).collect(Collectors.toList()), Sets.newHashSet(lh.getId()) ).whenComplete((result, cause) -> { if (null != cause) { LOG.error("Auditor exception publishing suspected ledger with lost bookies {}", lh.getId(), bookies, cause); callback.processResult(Code.ReplicationException, null, null); } else { callback.processResult(Code.OK, null, null); } }); } else { callback.processResult(rc, null, null); } lh.closeAsync().whenComplete((result, cause) -> { if (null != cause) { LOG.warn("Error closing ledger : {}", lh.getId(), cause.getMessage()); } }); }
Source:
<code>public String getRestURI(String baseServiceURI) { StringBuilder b = new StringBuilder(128); b.append(baseServiceURI); if (!baseServiceURI.endsWith("/")) { b.append('/'); } <START> b.append("lock/"); <END> return b.toString(); }</code><technical_language>trailing /</technical_language>

Target:
public String getRestURI(String baseServiceURI) { StringBuilder b = new StringBuilder(128); b.append(baseServiceURI); if (!baseServiceURI.endsWith("/")) { b.append('/'); } b.append("lock"); return b.toString(); }
Source:
<code><START> private EventHubClientManager createOrGetEventHubClientManagerForSSP(String streamId, SystemStreamPartition ssp) { <END> EventHubClientManager eventHubClientManager; if (config.getPerPartitionConnection(systemName)) { if (perPartitionEventHubManagers.containsKey(ssp)) { LOG.warn(String.format("Trying to create new EventHubClientManager for ssp=%s. But one already exists", ssp)); eventHubClientManager = perPartitionEventHubManagers.get(ssp); } else { LOG.info("Creating EventHub client manager for SSP: " + ssp); eventHubClientManager = eventHubClientManagerFactory.getEventHubClientManager(systemName, streamId, config); eventHubClientManager.init(); perPartitionEventHubManagers.put(ssp, eventHubClientManager); } } else { if (!perStreamEventHubManagers.containsKey(streamId)) { LOG.info("Creating EventHub client manager for stream: " + streamId); EventHubClientManager perStreamEventHubClientManager = eventHubClientManagerFactory.getEventHubClientManager(systemName, streamId, config); perStreamEventHubClientManager.init(); perStreamEventHubManagers.put(streamId, perStreamEventHubClientManager); } eventHubClientManager = perStreamEventHubManagers.get(streamId); perPartitionEventHubManagers.put(ssp, eventHubClientManager); } Validate.notNull(eventHubClientManager, String.format("Fail to create or get EventHubClientManager for ssp=%s", ssp)); return eventHubClientManager; }</code><technical_language>Do data is overhead in terms memory? add this description if do</technical_language>

Target:
private EventHubClientManager createOrGetEventHubClientManagerForSSP(String streamId, SystemStreamPartition ssp) { EventHubClientManager eventHubClientManager; if (config.getPerPartitionConnection(systemName)) { if (perPartitionEventHubManagers.containsKey(ssp)) { LOG.warn(String.format("Trying to create new EventHubClientManager for ssp=%s. But one already exists", ssp)); eventHubClientManager = perPartitionEventHubManagers.get(ssp); } else { LOG.info("Creating EventHub client manager for SSP: " + ssp); eventHubClientManager = eventHubClientManagerFactory.getEventHubClientManager(systemName, streamId, config); eventHubClientManager.init(); perPartitionEventHubManagers.put(ssp, eventHubClientManager); } } else { if (!perStreamEventHubManagers.containsKey(streamId)) { LOG.info("Creating EventHub client manager for stream: " + streamId); EventHubClientManager perStreamEventHubClientManager = eventHubClientManagerFactory.getEventHubClientManager(systemName, streamId, config); perStreamEventHubClientManager.init(); perStreamEventHubManagers.put(streamId, perStreamEventHubClientManager); } eventHubClientManager = perStreamEventHubManagers.get(streamId); perPartitionEventHubManagers.put(ssp, eventHubClientManager); } LOG.info("EventHub client created for ssp: " + ssp); Validate.notNull(eventHubClientManager, String.format("Fail to create or get EventHubClientManager for ssp=%s", ssp)); return eventHubClientManager; }
Source:
<code>public void testGetScalerUnit() throws Exception { DlmsDeviceMessageMetadata dlmsDeviceMessageMetadata = new DlmsDeviceMessageMetadata(); dlmsDeviceMessageMetadata.setDeviceIdentification("E0004001515495114"); dlmsDeviceMessageMetadata.setIpAddress("89.200.96.223"); LnClientConnection connection = dlmsConnectionFactory .getConnection(domainHelperService.findDlmsDevice(dlmsDeviceMessageMetadata)); ScalerUnitTestResponse execute = commandExecutor.execute(connection, new TestChannelQuery()); <START> Assert.assertEquals(execute.getScalerUnit().getDlmsUnit(), DlmsUnit.wh); <END> }</code><technical_language>expected actual other</technical_language>

Target:
public void testGetScalerUnit() throws Exception { final DlmsDeviceMessageMetadata dlmsDeviceMessageMetadata = new DlmsDeviceMessageMetadata(); dlmsDeviceMessageMetadata.setDeviceIdentification("E0004001515495114"); dlmsDeviceMessageMetadata.setIpAddress("89.200.96.223"); final LnClientConnection connection = this.dlmsConnectionFactory.getConnection(this.domainHelperService .findDlmsDevice(dlmsDeviceMessageMetadata)); final ScalerUnitTestResponse execute = this.commandExecutor.execute(connection, new TestChannelQuery()); Assert.assertEquals(DlmsUnit.WH, execute.getScalerUnit().getDlmsUnit()); }
Source:
<code><START> public void close() throws IOException { <END> if (this.sysOutStream != null) { try { this.sysOutStream.close(); } catch (Exception e) { } } if (this.sysErrStream != null) { try { this.sysErrStream.close(); } catch (Exception e) { } } }</code><technical_language>I this is work reliably. read split a multi-byte sequence end of content creating a string is break. Is reason want a stream reading temporary file a reader</technical_language>

Target:
public void close() throws IOException { FileUtils.close(this.sysOutStore); FileUtils.close(this.sysErrStore); }
Source:
<code>public Map<String,Serializable> getProcessedInput(ContractDefinition processContract, Map<String, Serializable> inputs, long maxSizeForTenant, long tenantId, boolean deleteFile) throws FileNotFoundException { this.deleteFile = deleteFile; <START> return this.getProcessedInput(processContract, inputs, maxSizeForTenant, tenantId); <END> }</code><technical_language>I done opposite: method call new avoid a new object attribute manage..</technical_language>

Target:
public Map<String,Serializable> getProcessedInput(ContractDefinition processContract, Map<String, Serializable> inputs, long maxSizeForTenant, long tenantId, boolean deleteFile) throws FileNotFoundException { this.maxSizeForTenant = maxSizeForTenant; this.tenantId = tenantId; final Map<String, Serializable> processedInputs = new HashMap<String, Serializable>(); final Map<String, Serializable> contractDefinitionMap = processContract == null? Collections.<String, Serializable>emptyMap() : createContractInputMap(processContract.getInputs()); for (final Entry<String, Serializable> inputEntry : inputs.entrySet()) { processedInputs.put(inputEntry.getKey(), convertInputToExpectedType(inputEntry.getValue(), contractDefinitionMap.get(inputEntry.getKey()), deleteFile)); } return processedInputs; }
Source:
<code>public AirGoogleMapOptions zOrderOnTop(boolean zOrderOnTop) { <START> return this; <END> }</code><technical_language>need set options</technical_language>

Target:
public AirGoogleMapOptions zOrderOnTop(boolean zOrderOnTop) { options.zOrderOnTop(zOrderOnTop); return this; }
Source:
<code>public synchronized boolean append(@NonNull ICTFPacketDescriptor entry) { ICTFPacketDescriptor entryToAdd = entry; if (entryToAdd.getTimestampBegin() > entryToAdd.getTimestampEnd()) { Activator.log(IStatus.WARNING, "Packet at offset " + entryToAdd.getOffsetBytes() + " begin timestamp is after end timestamp"); entryToAdd = new StreamInputPacketIndexEntry(entryToAdd, Long.MAX_VALUE); } if (!contains(entryToAdd)) { fEntries.add(entryToAdd); <START> fEntries.sort(OFFSET_COMPARE); <END> return true; } return false; }</code><technical_language>binary search, returned insertion point avoid sorting</technical_language>

Target:
public synchronized boolean append(@NonNull ICTFPacketDescriptor entry) { ICTFPacketDescriptor entryToAdd = entry; if (entryToAdd.getTimestampBegin() > entryToAdd.getTimestampEnd()) { Activator.log(IStatus.WARNING, "Packet at offset " + entryToAdd.getOffsetBytes() + " begin timestamp is after end timestamp"); entryToAdd = new StreamInputPacketIndexEntry(entryToAdd, Long.MAX_VALUE); } if (canAdd(entryToAdd)) { fEntries.add(entryToAdd); return true; } return false; }
Source:
<code><START> public Response exportInventory() { <END> try { return ResponseUtil.ok(inventoryService.buildExport()); } catch (Exception e) { return ResponseUtil.internalError(e); } }</code><technical_language>here, pagination needed. If want pagination treated multipart streaming, pagination is in InventoryService. I know, this hit a OOME in preliminar tests of QE</technical_language>

Target:
public Response exportInventory() { try { StreamingOutput streamingOutput = inventoryService::buildExport; return ResponseUtil.ok(streamingOutput); } catch (Exception e) { return ResponseUtil.internalError(e); } }
Source:
<code>void onJobProcessingStart() { <START> cryptoJobMetrics.operationRate.mark(); <END> jobProcessingStartTimeMs = System.currentTimeMillis(); cryptoJobMetrics.jobQueuingTimeInMs.update(jobProcessingStartTimeMs - jobSubmissionTimeMs); }</code><technical_language>this fired job submission</technical_language>

Target:
void onJobProcessingStart() { jobProcessingStartTimeMs = System.currentTimeMillis(); cryptoJobMetrics.jobQueuingTimeInMs.update(jobProcessingStartTimeMs - jobSubmissionTimeMs); }
Source:
<code>public void testAlterTableAddPartition1() throws IOException { <START> String sql = FileUtil.readTextFile(new File("src/test/resources/queries/default/alter_table_add_partition_1.sql")); <END> Expr expr = parseQuery(sql); assertEquals(OpType.AlterTable, expr.getType()); AlterTable alterTable = (AlterTable)expr; assertEquals(alterTable.getAlterTableOpType(), AlterTableOpType.ADD_PARTITION); assertEquals(2, alterTable.getColumns().length); assertEquals(2, alterTable.getValues().length); assertEquals("col1", alterTable.getColumns()[0].getName()); assertEquals("col2", alterTable.getColumns()[1].getName()); LiteralValue value1 = (LiteralValue)alterTable.getValues()[0]; assertEquals("1", value1.getValue()); LiteralValue value2 = (LiteralValue)alterTable.getValues()[1]; assertEquals("2", value2.getValue()); }</code><technical_language>FileUtil.readTextFileFromResource instead of direct paths? Direct path errors setting a base directory</technical_language>

Target:
public void testAlterTableAddPartition1() throws IOException { String sql = FileUtil.readTextFileFromResource("queries/default/alter_table_add_partition_1.sql"); Expr expr = parseQuery(sql); assertEquals(OpType.AlterTable, expr.getType()); AlterTable alterTable = (AlterTable)expr; assertEquals(alterTable.getAlterTableOpType(), AlterTableOpType.ADD_PARTITION); assertEquals(2, alterTable.getColumns().length); assertEquals(2, alterTable.getValues().length); assertEquals("col1", alterTable.getColumns()[0].getName()); assertEquals("col2", alterTable.getColumns()[1].getName()); LiteralValue value1 = (LiteralValue)alterTable.getValues()[0]; assertEquals("1", value1.getValue()); LiteralValue value2 = (LiteralValue)alterTable.getValues()[1]; assertEquals("2", value2.getValue()); }
Source:
<code>private ConnectionStateListener getConnectionStateListener(){ return new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (!newState.isConnected()) { <START> LOG.error(" connection to zookeeper broken "); <END> } } }; }</code><technical_language>Please include connection state. ZK a complicated graph of connectivity states (many of recoverable). debug this, want state moved into</technical_language>

Target:
private ConnectionStateListener getConnectionStateListener(){ return new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (!newState.isConnected()) { LOG.error( " connection to zookeeper broken. It is in "+ newState.name()+" state."); } } }; }
Source:
<code>public Response getRunningTasks(@Context final HttpServletRequest req) { return workItemsResponse( new Function<TaskRunner, Collection<? extends TaskRunnerWorkItem>>() { @Override public Collection<? extends TaskRunnerWorkItem> apply(TaskRunner taskRunner) { <START> if (authConfig.isEnabled()) { <END> final AuthorizationInfo authorizationInfo = (AuthorizationInfo) req.getAttribute(AuthConfig.DRUID_AUTH_TOKEN); return Collections2.filter( taskRunner.getRunningTasks(), new Predicate<TaskRunnerWorkItem>() { @Override public boolean apply(TaskRunnerWorkItem input) { final String taskId = input.getTaskId(); final Optional<Task> optionalTask = taskStorageQueryAdapter.getTask(taskId); if (!optionalTask.isPresent()) { throw new WebApplicationException( Response.serverError().entity( String.format("No task information found for task with id: [%s]", taskId) ).build() ); } return authorizationInfo.isAuthorized( new Resource(optionalTask.get().getDataSource(), ResourceType.DATASOURCE), Action.READ ).isAllowed(); } } ); } else { return taskRunner.getRunningTasks(); } } } ); }</code><technical_language>this change in getPendingTasks() same, refactor a private helper method</technical_language>

Target:
public Response getRunningTasks(@Context final HttpServletRequest req) { return workItemsResponse( new Function<TaskRunner, Collection<? extends TaskRunnerWorkItem>>() { @Override public Collection<? extends TaskRunnerWorkItem> apply(TaskRunner taskRunner) { if (authConfig.isEnabled()) { return securedTaskRunnerWorkItem(taskRunner.getRunningTasks(), req); } else { return taskRunner.getRunningTasks(); } } } ); }
Source:
<code>private boolean isVirtual(ContextInfo info) { <START> if (info.isVirtual != null) <END> return info.isVirtual; info.isVirtual = ClassTypeHelper.isVirtual(info.method); return info.isVirtual; }</code><technical_language>Slightly shorter: if (info.isVirtual == null) { info.isVirtual = ClassTypeHelper.isVirtual(info.method); } return info.isVirtual;</technical_language>

Target:
private boolean isVirtual(ContextInfo info) { if (info.isVirtual == null) { info.isVirtual = ClassTypeHelper.isVirtual(info.method); } return info.isVirtual; }
Source:
<code>protected void contentChanged(ITmfTreeViewerEntry rootEntry) { String selectedThread = fSelectedThread; if (selectedThread != null) { for (ITmfTreeViewerEntry entry : rootEntry.getChildren()) { if (entry instanceof CpuUsageEntry) { if (selectedThread.equals(((CpuUsageEntry) entry).getTid())) { List<ITmfTreeViewerEntry> list = Collections.singletonList(entry); <START> if (list != null) { <END> super.setSelection(list); } return; } } } } }</code><technical_language>null check here? ... oh, super.setSelection() takes a @NonNull. declare list @NonNull instead. suppress warning, Collections.singletonList() returns a nonnull, compiler doesn't. (This uglier, long-term solution.)</technical_language>

Target:
protected void contentChanged(ITmfTreeViewerEntry rootEntry) { String selectedThread = fSelectedThread; if (selectedThread != null) { for (ITmfTreeViewerEntry entry : rootEntry.getChildren()) { if (entry instanceof CpuUsageEntry) { if (selectedThread.equals(((CpuUsageEntry) entry).getTid())) { @SuppressWarnings("null") @NonNull List<ITmfTreeViewerEntry> list = Collections.singletonList(entry); super.setSelection(list); return; } } } } }
Source:
<code>protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String repository = request.getParameter("repository"); String workspace = request.getParameter("workspace"); String path = request.getParameter("path"); String property = request.getParameter("property"); Connector connector = (Connector) request.getSession().getAttribute("connector"); try { Session session = connector.find(repository).session(workspace); Node node = session.getNode(path); Property p; try { p = node.getProperty(property); } catch (PathNotFoundException e) { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.write("<html>"); <START> writer.write("Empty"); <END> writer.write("</html>"); return; } Binary binary = p.getBinary(); InputStream in = binary.getStream(); String contentType = node.getProperty("jcr:mimeType").getString(); response.setContentType(contentType); int b; while ((b = in.read()) != -1) { response.getOutputStream().write(b); } binary.dispose(); } catch (Exception e) { throw new ServletException(e); } }</code><technical_language>a message Empty</technical_language>

Target:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String repository = request.getParameter("repository"); String workspace = request.getParameter("workspace"); String path = request.getParameter("path"); String property = request.getParameter("property"); Connector connector = (Connector) request.getSession().getAttribute("connector"); try { Session session = connector.find(repository).session(workspace); Node node = session.getNode(path); Property p; try { p = node.getProperty(property); } catch (PathNotFoundException e) { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.write("<html>"); writer.write("<p>Content not found or recently removed</p>"); writer.write("</html>"); return; } Binary binary = p.getBinary(); InputStream in = binary.getStream(); String contentType = node.getProperty("jcr:mimeType").getString(); response.setContentType(contentType); int b; while ((b = in.read()) != -1) { response.getOutputStream().write(b); } binary.dispose(); } catch (Exception e) { throw new ServletException(e); } }
Source:
<code>private static Connection makeConnection(String url, Properties props) throws SQLException { <START> return new ${JDBCCONNECTCLASS}(hostSpecs(props), <END> user(props), database(props), props, url); }</code><technical_language>Yes, easier understad a piece of code lookt at. :-) I separate discussions here: - do preprocessing in Maven? - Is preprocessing a good all? target of current PR is Mavenization. Hence, question is "How do preprocessing in Maven?". pretty simple: Maven filter source code automatically compilation, solution as-is work Maven is correctly configured. need is called "Templating Maven Plugin", is alpha currently web site is moving Codehaus Mojohaus moment (bad, do NOW). A approach is apply a workaround a combination of "Maven Resources Plugin" (which filter pretty long is text) setting source path output of plugin. a lot patch version numbers build dates source code works pretty well. drawback is IDEs of solutions able support it. conclusion is do preprocessing complex. question is is a good idea patch sources all. I do this part of PR, open issue for discuss in a larger audience. personal opinion is I single source code for single platform. development pretty easy new people jump right in easily. call "one code for platform". If multiple platforms a matrix supported (and project leads want that), git branches. A solution Strategy pattern, solving complexity runtime simply loading implementations. In fact, problem is JDBC levels. simply support latest level, JVM complain unkown classes instantiate them, is case if code is JDK 6 compliant (you offer interface JDK 8 need load JDK 8 classes class is used). this is go</technical_language>

Target:
private static Connection makeConnection(String url, Properties props) throws SQLException { return new ${template.jdbc.connect.class}(hostSpecs(props), user(props), database(props), props, url); }
Source:
<code><START> public String asString() throws Exception { <END> return this.print(); }</code><technical_language>@victornoel IOException</technical_language>

Target:
public String asString() throws IOException { return this.print(); }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) { <END> return true; } if (o == null || getClass() != o.getClass()) { return false; } Select select = (Select) o; return Objects.equals(element, select.element); }</code><technical_language>Nowadays, tend follow a pattern of: if (!(o instanceof Select)) { return false; } Select = (Select) o; return Objects.equals(this.element, that.element);</technical_language>

Target:
public boolean equals(Object o) { if (!(o instanceof Select)) { return false; } Select select = (Select) o; return Objects.equals(element, select.element); }
Source:
<code>protected void handleEvent(Event event) { EventContext ctx = event.getContext(); if (ctx instanceof DocumentEventContext) { String name = event.getName(); DocumentEventContext docCtx = (DocumentEventContext) ctx; CoreSession session = docCtx.getCoreSession(); DocumentModel doc = docCtx.getSourceDocument(); if (doc == null) { return; } String docId = doc.getId(); TagService tagService = Framework.getLocalService(TagService.class); boolean nxtagsEnabled = Framework.getService(ConfigurationService.class) <START> .isBooleanPropertyTrue(TagServiceImpl.FACETED_TAG_SERVICE_ENABLED); <END> if (doc instanceof DeletedDocumentModel && !nxtagsEnabled) { tagService.removeTags(session, docId); return; } switch (name) { case DOCUMENT_PROXY_PUBLISHED: if (doc.isProxy()) { DocumentModel version = session.getSourceDocument(doc.getRef()); tagService.copyTags(session, version.getId(), docId); } break; case DOCUMENT_RESTORED: String versionUUID = (String) ctx.getProperty(VersioningDocument.RESTORED_VERSION_UUID_KEY); tagService.replaceTags(session, versionUUID, docId); break; case DOCUMENT_REMOVED: if (!nxtagsEnabled) { tagService.removeTags(session, docId); } break; case TRANSITION_EVENT: tagService.removeTags(session, docId); break; default: break; } } }</code><technical_language>facetedTags</technical_language>

Target:
protected void handleEvent(Event event) { EventContext ctx = event.getContext(); if (ctx instanceof DocumentEventContext) { String name = event.getName(); DocumentEventContext docCtx = (DocumentEventContext) ctx; CoreSession session = docCtx.getCoreSession(); DocumentModel doc = docCtx.getSourceDocument(); if (doc == null) { return; } String docId = doc.getId(); TagService tagService = Framework.getLocalService(TagService.class); boolean facetedTags = Framework.getService(ConfigurationService.class) .isBooleanPropertyTrue(TagServiceImpl.FACETED_TAG_SERVICE_ENABLED); if (doc instanceof DeletedDocumentModel && !facetedTags) { tagService.removeTags(session, docId); return; } switch (name) { case DOCUMENT_PROXY_PUBLISHED: if (doc.isProxy()) { DocumentModel version = session.getSourceDocument(doc.getRef()); tagService.copyTags(session, version.getId(), docId); } break; case DOCUMENT_RESTORED: String versionUUID = (String) ctx.getProperty(VersioningDocument.RESTORED_VERSION_UUID_KEY); tagService.replaceTags(session, versionUUID, docId); break; case DOCUMENT_REMOVED: if (!facetedTags) { tagService.removeTags(session, docId); } break; case TRANSITION_EVENT: tagService.removeTags(session, docId); break; default: break; } } }
Source:
<code>private ApplicationReportModel createAppDependencyGraphReport(GraphContext context) { <START> ApplicationReportService applicationReportService = new ApplicationReportService(context); <END> ApplicationReportModel report = applicationReportService.create(); report.setReportPriority(104); report.setReportIconClass("glyphicon glyphicon-tree-deciduous"); report.setTemplatePath(TEMPLATE); report.setTemplateType(TemplateType.FREEMARKER); report.setDisplayInApplicationReportIndex(Boolean.TRUE); report.setDescription(REPORT_DESCRIPTION); return report; }</code><technical_language>'104' a constant</technical_language>

Target:
private ApplicationReportModel createAppDependencyGraphReport(GraphContext context) { ApplicationReportService applicationReportService = new ApplicationReportService(context); ApplicationReportModel report = applicationReportService.create(); report.setReportPriority(104); report.setReportIconClass("glyphicon glyphicon-tree-deciduous"); report.setTemplatePath(TEMPLATE); report.setTemplateType(TemplateType.FREEMARKER); report.setDisplayInApplicationReportIndex(Boolean.TRUE); return report; }
Source:
<code>public void requestBannerAd(Context context, MediationBannerListener mediationBannerListener, Bundle serverParameters, AdSize adSize, MediationAdRequest mediationAdRequest, Bundle mediationExtras) { vungleBannerAdapter = new VungleBannerAdapter(context, VungleInterstitialAdapter.this, mediationBannerListener); bannerAdContainer = new RelativeLayout(context) { @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); vungleBannerAdapter.attach(this); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); vungleBannerAdapter.detach(); } }; int adLayoutHeight = adSize.getHeightInPixels(context); if (adLayoutHeight <= 0) { float density = context.getResources().getDisplayMetrics().density; <START> adLayoutHeight = Math.round(mAdConfig.getAdSize().getHeight() * density); <END> } RelativeLayout.LayoutParams adViewLayoutParams = new RelativeLayout.LayoutParams(adSize.getWidthInPixels(context), adLayoutHeight); bannerAdContainer.setLayoutParams(adViewLayoutParams); vungleBannerAdapter .requestBannerAd(adSize, mediationAdRequest, serverParameters, mediationExtras); }</code><technical_language>Is mAdConfig sense? banner size returned in VungleBannerAdapter#getSupportedAdSize()</technical_language>

Target:
public void requestBannerAd(Context context, MediationBannerListener mediationBannerListener, Bundle serverParameters, AdSize adSize, MediationAdRequest mediationAdRequest, Bundle mediationExtras) { vungleBannerAdapter = new VungleBannerAdapter(context, VungleInterstitialAdapter.this, mediationBannerListener); AdConfig.AdSize vungleAdSize = VungleBannerAdapter.getSupportedAdSize(context, adSize); if (vungleAdSize == null) { String message = "Failed to load ad from Vungle: Invalid banner size."; Log.w(TAG, message); mediationBannerListener .onAdFailedToLoad(VungleInterstitialAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } bannerAdContainer = new RelativeLayout(context) { @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (vungleBannerAdapter != null) { vungleBannerAdapter.attach(this); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (vungleBannerAdapter != null) { vungleBannerAdapter.detach(); } } }; int adLayoutHeight = adSize.getHeightInPixels(context); if (adLayoutHeight <= 0) { float density = context.getResources().getDisplayMetrics().density; adLayoutHeight = Math.round(vungleAdSize.getHeight() * density); } RelativeLayout.LayoutParams adViewLayoutParams = new RelativeLayout.LayoutParams(adSize.getWidthInPixels(context), adLayoutHeight); bannerAdContainer.setLayoutParams(adViewLayoutParams); vungleBannerAdapter .requestBannerAd(vungleAdSize, mediationAdRequest, serverParameters, mediationExtras); }
Source:
<code>public void deleteAttribute(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException { <START> getPerunBl().getAuditer().log(sess,new AttributeDeleted(attribute)); <END> this.deleteAllAttributeAuthz(sess, attribute); getAttributesManagerImpl().deleteAttribute(sess, attribute); AttributeDefinition attributeDef = new AttributeDefinition(attribute); synchronized (dependenciesMonitor) { removeOppositeDependenciesForAttribute(attributeDef); if (dependencies.containsKey(attributeDef)) { dependencies.remove(attributeDef); } else { log.warn("Dependencies inconsistency. Dependencies should contain information about {}. ", attributeDef); } if (strongDependencies.containsKey(attributeDef)) { strongDependencies.remove(attributeDef); } else { log.warn("Strong dependencies inconsistency. Strong dependencies should contain information about {}. ", attributeDef); } if (inverseDependencies.containsKey(attributeDef)) { inverseDependencies.remove(attributeDef); } else { log.warn("Inverse dependencies inconsistency. Inverse dependencies should contain information about {}. ", attributeDef); } if (inverseStrongDependencies.containsKey(attributeDef)) { inverseStrongDependencies.remove(attributeDef); } else { log.warn("Inverse strong dependencies inconsistency. Inverse strong dependencies should contain information about {}. ", attributeDef); } } }</code><technical_language>generally log auditer message call impl layer, please move getAttributesManagerImpl().deleteAttribute(sess, attribute);</technical_language>

Target:
public void deleteAttribute(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException { this.deleteAllAttributeAuthz(sess, attribute); getAttributesManagerImpl().deleteAttribute(sess, attribute); getPerunBl().getAuditer().log(sess, new AttributeDeleted(attribute)); AttributeDefinition attributeDef = new AttributeDefinition(attribute); synchronized (dependenciesMonitor) { removeOppositeDependenciesForAttribute(attributeDef); if (dependencies.containsKey(attributeDef)) { dependencies.remove(attributeDef); } else { log.warn("Dependencies inconsistency. Dependencies should contain information about {}. ", attributeDef); } if (strongDependencies.containsKey(attributeDef)) { strongDependencies.remove(attributeDef); } else { log.warn("Strong dependencies inconsistency. Strong dependencies should contain information about {}. ", attributeDef); } if (inverseDependencies.containsKey(attributeDef)) { inverseDependencies.remove(attributeDef); } else { log.warn("Inverse dependencies inconsistency. Inverse dependencies should contain information about {}. ", attributeDef); } if (inverseStrongDependencies.containsKey(attributeDef)) { inverseStrongDependencies.remove(attributeDef); } else { log.warn("Inverse strong dependencies inconsistency. Inverse strong dependencies should contain information about {}. ", attributeDef); } } }
Source:
<code>private boolean shouldCheck(final DetailAST ast) { final Scope customScope; if (ScopeUtil.isInInterfaceOrAnnotationBlock(ast)) { customScope = Scope.PUBLIC; } else { final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS); customScope = ScopeUtil.getScopeFromMods(mods); } final Scope surroundingScope = ScopeUtil.getSurroundingScope(ast); return customScope.isIn(scope) && (surroundingScope == null || surroundingScope.isIn(scope)) && (excludeScope == null || !customScope.isIn(excludeScope) || surroundingScope != null && !surroundingScope.isIn(excludeScope)) && !AnnotationUtil.containsAnnotation(ast, allowedAnnotations); <START> } <END></code><technical_language>doc is requierd</technical_language>

Target:
private boolean shouldCheck(final DetailAST ast) { final Scope customScope; if (ScopeUtil.isInInterfaceOrAnnotationBlock(ast)) { customScope = Scope.PUBLIC; } else { final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS); customScope = ScopeUtil.getScopeFromMods(mods); } final Scope surroundingScope = ScopeUtil.getSurroundingScope(ast); return customScope.isIn(scope) && (surroundingScope == null || surroundingScope.isIn(scope)) && (excludeScope == null || !customScope.isIn(excludeScope) || surroundingScope != null && !surroundingScope.isIn(excludeScope)) && !AnnotationUtil.containsAnnotation(ast, skipAnnotations); }