auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private int countEntries(Iterable<Entry<Key,Value>> scanner) { int count = 0; <START> for (Entry<Key,Value> keyValueEntry : scanner) { <END> count++; } return count; }</code><technical_language>I this method replaced Guava Iterables.size()</technical_language>

Target:
private int countEntries(Iterable<Entry<Key,Value>> scanner) { return Iterables.size(scanner); }
Source:
<code>public DeleteQuery build() { <START> Checks.checkNotNull(uri, "Please specify uri"); <END> return new DeleteQuery( uri, where, whereArgs ); }</code><technical_language>Static import</technical_language>

Target:
public DeleteQuery build() { checkNotNull(uri, "Please specify uri"); return new DeleteQuery( uri, where, whereArgs ); }
Source:
<code>public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putSerializable(COMMENTS_KEY, mComments); <START> } <END></code><technical_language>[onCreate](<LINK_0> expects CONTEXT, CONTEXTID, TITLE_KEY set in saved instance state set here. Is this related android:configChanges is set</technical_language>

Target:
public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putSerializable(COMMENTS_KEY, mComments); state.putInt(CONTEXTID, mCommentContextId); state.putString(CONTEXT, mCommentContext); state.putString(TITLE_KEY, mTitle); state.putInt(GUIDEID_KEY, mGuideid); }
Source:
<code>public void onClose(int code, String reason) { if (log.isDebugEnabled()) { <START> log.debug("websocket connection closed - code: " + code + " reason: " + reason); <END> } if (code != 1000) { this.error = new SignalFlowException(code, reason); log.info("Lost WebSocket connection with ({}).", connection, code); SignalFlowExceptionStreamMessage errorMessage = new SignalFlowExceptionStreamMessage( this.error); for (TransportChannel channel : this.channels.values()) { channel.offer(errorMessage); } } this.channels.clear(); this.connection = null; }</code><technical_language>logger formatting: java log.debug("websocket connection closed ({} {})", code, reason);</technical_language>

Target:
public void onClose(int code, String reason) { log.debug("websocket connection closed ({} {})", code, reason); if (code != 1000) { this.error = new SignalFlowException(code, reason); log.info("Lost WebSocket connection with ({}).", connection, code); SignalFlowExceptionStreamMessage errorMessage = new SignalFlowExceptionStreamMessage( this.error); for (TransportChannel channel : this.channels.values()) { channel.offer(errorMessage); } } this.channels.clear(); this.connection = null; }
Source:
<code>public String selectFirstSuggestedCategory() { WebElement suggestion = categorySelectModule.findElement(autoCompleteSuggestion); String categoryName = suggestion.getText().trim(); <START> suggestion.click(); <END> PageObjectLogging.log("selectCategorySuggestions", "category selected from suggestions", true); return categoryName; }</code><technical_language>wait.forElementClickable() called click</technical_language>

Target:
public String selectFirstSuggestedCategory() { WebElement suggestion = categorySelectModule.findElement(autoCompleteSuggestion); String categoryName = suggestion.getText().trim(); webDriverWait.until(ExpectedConditions.elementToBeClickable(suggestion)); suggestion.click(); PageObjectLogging.log("selectCategorySuggestions", "category selected from suggestions", true); return categoryName; }
Source:
<code>private void fetchAndDisplayCaption(Contribution contribution) { if ((contribution.getState() != Contribution.STATE_COMPLETED)) { titleView.setText(contribution.getDisplayTitle()); } else { Timber.d("Fetching caption for %s", contribution.getFilename()); String wikibaseMediaId = "M"+contribution.getPageId(); <START> compositeDisposable.add(mediaClient.getCaptionByWikibaseIdentifier(wikibaseMediaId) <END> .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .subscribe(subscriber -> { if (!subscriber.trim().equals(NO_CAPTION)) { titleView.setText(subscriber); } else titleView.setText(contribution.getDisplayTitle()); })); } }</code><technical_language>saving this db</technical_language>

Target:
private void fetchAndDisplayCaption(Contribution contribution) { if ((contribution.getState() != Contribution.STATE_COMPLETED)) { titleView.setText(contribution.getDisplayTitle()); } else { final String pageId = contribution.getPageId(); if (pageId != null) { Timber.d("Fetching caption for %s", contribution.getFilename()); String wikibaseMediaId = PAGE_ID_PREFIX + pageId; compositeDisposable.add(mediaClient.getCaptionByWikibaseIdentifier(wikibaseMediaId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .subscribe(subscriber -> { if (!subscriber.trim().equals(MediaClient.NO_CAPTION)) { titleView.setText(subscriber); } else { titleView.setText(contribution.getDisplayTitle()); } })); } else { titleView.setText(contribution.getDisplayTitle()); } } }
Source:
<code>public void init(@NonNull Map<UUID, Node> nodes, @NonNull DistanceReporter distanceReporter) { this.distanceReporter = distanceReporter; localDc = newLocalDcHelper().discoverLocalDc().orElse(null); filter = newNodeFilterHelper().createNodeFilter(localDc); for (Node node : nodes.values()) { if (filter.test(node)) { <START> distanceReporter.setDistance(node, NodeDistance.LOCAL); <END> if (node.getState() != NodeState.DOWN) { liveNodes.add(node); } } else { distanceReporter.setDistance(node, NodeDistance.IGNORED); } } }</code><technical_language>Is safe set distance LOCALeven if node filter works for BasicStrategy require dc</technical_language>

Target:
public void init(@NonNull Map<UUID, Node> nodes, @NonNull DistanceReporter distanceReporter) { this.distanceReporter = distanceReporter; localDc = discoverLocalDc(nodes).orElse(null); filter = createNodeFilter(localDc, nodes); for (Node node : nodes.values()) { if (filter.test(node)) { distanceReporter.setDistance(node, NodeDistance.LOCAL); if (node.getState() != NodeState.DOWN) { liveNodes.add(node); } } else { distanceReporter.setDistance(node, NodeDistance.IGNORED); } } }
Source:
<code><START> public IOValue getDIOValue(IOLine ioLine) throws InvalidOperatingModeException, XBeeException { <END> if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); ATCommandResponse response = sendATCommand(new ATCommand("IS")); if (response == null || response.getResponseStatus() != ATCommandStatus.OK) throw new XBeeException(XBeeException.INVALID_OPERATION); IOSample ioSample = new IOSample(response.getResponse()); if (!ioSample.hasDigitalValues() || !ioSample.getDigitalValues().containsKey(ioLine)) throw new XBeeException(XBeeException.INVALID_OPERATION); return ioSample.getDigitalValues().get(ioLine); }</code><technical_language>This need revisited throw proper exceptions</technical_language>

Target:
public IOValue getDIOValue(IOLine ioLine) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); ATCommandResponse response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); if (response == null || response.getResponseStatus() != ATCommandStatus.OK || response == null || response.getResponse().length == 0) throw new XBeeException(XBeeException.INVALID_OPERATION); IOSample ioSample = new IOSample(response.getResponse()); if (!ioSample.hasDigitalValues() || !ioSample.getDigitalValues().containsKey(ioLine)) throw new XBeeException(XBeeException.INVALID_OPERATION); return ioSample.getDigitalValues().get(ioLine); }
Source:
<code>public void run() { try { digest = MD5FileUtils.computeMd5ForFile(file); } catch (Throwable t) { if (t instanceof IOException) { ioe = (IOException) t; } else { <START> ioe = new IOException(t); <END> } } }</code><technical_language>Do unit tests throwing exceptions</technical_language>

Target:
public void run() { try { digest = MD5FileUtils.computeMd5ForFile(file); } catch (IOException e) { ioe = e; } catch (Throwable t) { ioe = new IOException(t); } }
Source:
<code>private JPanel getScrollPanel() { if (scrollPanel == null) { scrollPanel = new JPanel(); <START> scrollPanel.setLayout(new VerticalLayout()); <END> scrollPanel.add(getMainProxyPanel()); scrollPanel.add(getSecurityProtocolsPanel()); scrollPanel.add(getProxiesOptionsPanel()); } return scrollPanel; }</code><technical_language>layout passed in constructor</technical_language>

Target:
private JPanel getScrollPanel() { if (scrollPanel == null) { scrollPanel = new JPanel(new VerticalLayout()); scrollPanel.add(getMainProxyPanel()); scrollPanel.add(getSecurityProtocolsPanel()); scrollPanel.add(getProxiesOptionsPanel()); } return scrollPanel; }
Source:
<code>private static String getUrl(IRepositoryElement element) { if (element instanceof ITask) { ITask task = (ITask) element; AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(task.getConnectorKind()); TaskRepository repository = TasksUiInternal.getRepository(task); if (connector.getBrowseableUrl(repository, element) != null) { <START> return connector.getBrowseableUrl(repository, element).toString(); <END> } else { return TasksUi.getRepositoryConnector(task.getConnectorKind()).getTaskUrl(task.getRepositoryUrl(), task.getTaskId()); } } else if (element.getUrl() != null) { return element.getUrl(); } return null; }</code><technical_language>In case URL is expensive construct, call getBrowseableUrl once</technical_language>

Target:
private static String getUrl(IRepositoryElement element) { if (element instanceof ITask) { ITask task = (ITask) element; AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(task.getConnectorKind()); TaskRepository repository = TasksUiInternal.getRepository(task); URL location = connector.getBrowseableUrl(repository, element); if (location != null) { return location.toString(); } else if (task.getUrl() != null) { return task.getUrl(); } else { return TasksUi.getRepositoryConnector(task.getConnectorKind()).getTaskUrl(task.getRepositoryUrl(), task.getTaskId()); } } else if (element.getUrl() != null) { return element.getUrl(); } return null; }
Source:
<code>public String toString() { return String <START> .format("DlmsDeviceMessageMetadata[correlationUid=%s, domain=%s, domainVersion=%s, messageType=%s, organisation=%s, device=%s, ipAddress=%s, retryCount=%d, messagePriority=%d, scheduleTimes=%s]", <END> this.correlationUid, this.domain, this.domainVersion, this.messageType, this.organisationIdentification, this.deviceIdentification, this.ipAddress, this.retryCount, this.messagePriority, this.scheduleTime); }</code><technical_language>scheduleTimes --> scheduleTime</technical_language>

Target:
public String toString() { return String .format("DlmsDeviceMessageMetadata[correlationUid=%s, domain=%s, domainVersion=%s, messageType=%s, organisation=%s, device=%s, ipAddress=%s, retryCount=%d, messagePriority=%d]", this.correlationUid, this.domain, this.domainVersion, this.messageType, this.organisationIdentification, this.deviceIdentification, this.ipAddress, this.retryCount, this.messagePriority); }
Source:
<code>protected void createMockedRepositoriesFolder() { String repositoriesPath = repositoriesFolder.toPath().toString() + "/"; when(configuration.getGitoliteBaseUrl()).thenReturn(repositoriesPath); <START> log.info("Initialized bare repository folder in {}", repositoriesPath); <END> }</code><technical_language>I remember, this stubbing is required for testing repository removal. unused now, this stubbing is required for mocked git server module work expected I remember. I remember in version for git-server tests (of this is a fork)</technical_language>

Target:
protected void createMockedRepositoriesFolder() { String repositoriesPath = repositoriesFolder.toPath().toString() + "/"; when(configuration.getGitoliteBaseUrl()).thenReturn(repositoriesPath); when(configuration.getRepositoriesDirectory()).thenReturn(repositoriesFolder); log.info("Initialized bare repository folder in {}", repositoriesPath); }
Source:
<code>public KijiRowData next(int pageSize) { KijiDataRequestBuilder builder = KijiDataRequest.builder(); builder.withTimeRange(mColumnDataRequest.getMinTimestamp(), mColumnDataRequest.getMaxTimestamp()).addColumns() .withFilter(new KijiPaginationFilter(pageSize, mOffset, mColumnDataRequest.getColumn(mColumnName.getFamily(), mColumnName.getQualifier()).getFilter())) .withMaxVersions(mMaxVersions).add(mColumnName); KijiDataRequest nextPageDataRequest = builder.build(); LOG.debug("DataRequest in pager is: [{}]", nextPageDataRequest.toString()); HBaseDataRequestAdapter adapter = new HBaseDataRequestAdapter(nextPageDataRequest); try { Get hbaseGet = adapter.toGet(mEntityId, mLayout); incrementOffset(pageSize); Result nextResultPage = mTable.getHTable().get(hbaseGet); if (nextResultPage.size() < pageSize) { mHasNext = false; } return new HBaseKijiRowData(mEntityId, nextPageDataRequest, mTable, nextResultPage); <START> } catch (IOException ioe) { <END> LOG.error("Unable to get next page of results: {}", ioe); return null; } }</code><technical_language>a nervous this eating exception returning null. Java Iterators throw a NoSuchElement exception run end: <LINK_0></technical_language>

Target:
public KijiRowData next(int pageSize) { KijiDataRequestBuilder builder = KijiDataRequest.builder(); builder.withTimeRange(mColumnDataRequest.getMinTimestamp(), mColumnDataRequest.getMaxTimestamp()).addColumns() .withFilter(new KijiPaginationFilter(pageSize, mOffset, mColumnDataRequest.getColumn(mColumnName.getFamily(), mColumnName.getQualifier()).getFilter())) .withMaxVersions(mMaxVersions).add(mColumnName); KijiDataRequest nextPageDataRequest = builder.build(); LOG.debug("DataRequest in pager is: [{}]", nextPageDataRequest.toString()); HBaseDataRequestAdapter adapter = new HBaseDataRequestAdapter(nextPageDataRequest); try { Get hbaseGet = adapter.toGet(mEntityId, mLayout); incrementOffset(pageSize); Result nextResultPage = mTable.getHTable().get(hbaseGet); if (nextResultPage.size() < pageSize) { mHasNext = false; } return new HBaseKijiRowData(mEntityId, nextPageDataRequest, mTable, nextResultPage); } catch (IOException ioe) { LOG.error("Unable to get next page of results: {}", ioe); return new HBaseKijiRowData(mEntityId, nextPageDataRequest, mTable, new Result()); } }
Source:
<code>private void doRemoveRepository(final OrganizationalUnit orgUnit, final String alias, final Optional<org.guvnor.structure.organizationalunit.config.RepositoryInfo> thisRepositoryConfig, final Consumer<Repository> notification, final boolean lock) { SpaceConfigStorage configStorage = this.spaceConfigStorage.get(orgUnit.getName()); try { if (lock) { configStorage.startBatch(); } Repository repo = this.configuredRepositories.getRepositoryByRepositoryAlias(orgUnit.getSpace(), alias); if (repo != null) { notification.accept(repo); } for (Repository repository : orgUnit.getRepositories()) { if (repository.getAlias().equals(alias)) { organizationalUnitService.removeRepository(orgUnit, repository); metadataStore.delete(alias); } } <START> } finally { <END> if (lock) { configStorage.endBatch(); } } }</code><technical_language>@adrielparedes call for metadatastore ^</technical_language>

Target:
private void doRemoveRepository(final OrganizationalUnit orgUnit, final String alias, final Optional<org.guvnor.structure.organizationalunit.config.RepositoryInfo> thisRepositoryConfig, final Consumer<Repository> notification, final boolean lock) { SpaceConfigStorage configStorage = this.spaceConfigStorage.get(orgUnit.getName()); try { if (lock) { configStorage.startBatch(); } Repository repo = this.configuredRepositories.getRepositoryByRepositoryAlias(orgUnit.getSpace(), alias); if (repo != null) { this.close(repo.getDefaultBranch()); notification.accept(repo); } for (Repository repository : orgUnit.getRepositories()) { if (repository.getAlias().equals(alias)) { organizationalUnitService.removeRepository(orgUnit, repository); metadataStore.delete(alias); } } } finally { if (lock) { configStorage.endBatch(); } } }
Source:
<code>protected void executeQueryCommand() { VDS vds = vdsDao.get(lldpVDSCommandParameters.getVdsId()); if <START> (vds != null <END> && FeatureSupported.isLlldpInformationSupported(vds.getClusterCompatibilityVersion())) { VDSReturnValue command = runVdsCommand(VDSCommandType.GetLldp, lldpVDSCommandParameters); getQueryReturnValue().setReturnValue(command.getReturnValue()); } else { getQueryReturnValue().setReturnValue(null); } }</code><technical_language>query fail validation if vdsId is invalid</technical_language>

Target:
protected void executeQueryCommand() { VDS vds = getVds(lldpVDSCommandParameters.getVdsId()); if (FeatureSupported.isLlldpInformationSupported(vds.getClusterCompatibilityVersion())) { VDSReturnValue command = runVdsCommand(VDSCommandType.GetLldp, lldpVDSCommandParameters); getQueryReturnValue().setReturnValue(command.getReturnValue()); } else { getQueryReturnValue().setReturnValue(null); } }
Source:
<code>private boolean isActionInsertFactFragment(final List<? extends MetaData> metaData) { if (!metaData.stream().allMatch((c) -> (c instanceof MoveColumnToMetaData))) { return false; } if (!metaData.stream().map(c -> (MoveColumnToMetaData) c).allMatch(c -> c.getColumn() instanceof ActionInsertFactCol52)) { return false; } final BaseColumn firstColumnInFragment = ((MoveColumnToMetaData) metaData.get(0)).getColumn(); <START> final BaseColumn lastColumnInFragment = ((MoveColumnToMetaData) metaData.get(metaData.size() - 1)).getColumn(); <END> final int firstColumnIndex = model.getExpandedColumns().indexOf(firstColumnInFragment); final int lastColumnIndex = model.getExpandedColumns().indexOf(lastColumnInFragment); return lastColumnIndex - firstColumnIndex == metaData.size() - 1; }</code><technical_language>metaData.size() - 1 turned local var reused line 196</technical_language>

Target:
private boolean isActionInsertFactFragment(final List<? extends MetaData> metaData) { if (!metaData.stream().allMatch((c) -> (c instanceof MoveColumnToMetaData))) { return false; } if (!metaData.stream().map(c -> (MoveColumnToMetaData) c).allMatch(c -> c.getColumn() instanceof ActionInsertFactCol52)) { return false; } final int lastMetaDataIndex = metaData.size() - 1; final BaseColumn firstColumnInFragment = ((MoveColumnToMetaData) metaData.get(0)).getColumn(); final BaseColumn lastColumnInFragment = ((MoveColumnToMetaData) metaData.get(lastMetaDataIndex)).getColumn(); final int firstColumnIndex = model.getExpandedColumns().indexOf(firstColumnInFragment); final int lastColumnIndex = model.getExpandedColumns().indexOf(lastColumnInFragment); return lastColumnIndex - firstColumnIndex == lastMetaDataIndex; }
Source:
<code>protected void applyValidatorResult(Validator validator) { IStatus status = validator.getStatus(); String message = status.getMessage(); if (message == null || message.length() == 0) { message = null; } switch (status.getSeverity()) { case IStatus.OK: if (status == Status.OK_STATUS) { if (getUserName().length() > 0) { message = Messages.AbstractRepositorySettingsPage_Authentication_credentials_are_valid; } else { message = Messages.AbstractRepositorySettingsPage_Repository_is_valid; } } setMessage(message, IMessageProvider.INFORMATION); <START> saveToValidatedProperties(); <END> break; case IStatus.INFO: setMessage(message, IMessageProvider.INFORMATION); break; case IStatus.WARNING: setMessage(message, IMessageProvider.WARNING); break; default: setMessage(message, IMessageProvider.ERROR); break; } setErrorMessage(null); isValid = status.getSeverity() == IStatus.OK || status.getSeverity() == IStatus.INFO; }</code><technical_language>invoked validateSettings()</technical_language>

Target:
protected void applyValidatorResult(Validator validator) { IStatus status = validator.getStatus(); String message = status.getMessage(); if (message == null || message.length() == 0) { message = null; } switch (status.getSeverity()) { case IStatus.OK: if (status == Status.OK_STATUS) { if (getUserName().length() > 0) { message = Messages.AbstractRepositorySettingsPage_Authentication_credentials_are_valid; } else { message = Messages.AbstractRepositorySettingsPage_Repository_is_valid; } } setMessage(message, IMessageProvider.INFORMATION); break; case IStatus.INFO: setMessage(message, IMessageProvider.INFORMATION); break; case IStatus.WARNING: setMessage(message, IMessageProvider.WARNING); break; default: setMessage(message, IMessageProvider.ERROR); break; } setErrorMessage(null); isValid = status.getSeverity() == IStatus.OK || status.getSeverity() == IStatus.INFO; }
Source:
<code>private boolean addMacToMap(Map<String, Integer> macMap, String mac) { <START> boolean returnValue = false; <END> if (!macMap.containsKey(mac)) { macMap.put(mac, 1); returnValue = true; } else if (allowDuplicate()) { incrementMacInMap(macMap, mac); returnValue = true; } return returnValue; }</code><technical_language>I a variable for this return spot, this method is complicated need a variable track return value</technical_language>

Target:
private boolean addMacToMap(Map<String, Integer> macMap, String mac) { if (!macMap.containsKey(mac)) { macMap.put(mac, 1); return true; } else if (allowDuplicate()) { incrementMacInMap(macMap, mac); return true; } return false; }
Source:
<code>private boolean flush(ByteBuffer buf) throws IOException { int remaining = buf.remaining(); if (remaining > 0) { <START> long start = SystemTime.getInstance().nanoseconds(); <END> int written = socketChannel.write(buf); logger.trace("Flushed bytes in ns", written, SystemTime.getInstance().nanoseconds() - start); return written >= remaining; } return true; }</code><technical_language>minor: consider startTimeNs in another method</technical_language>

Target:
private boolean flush(ByteBuffer buf) throws IOException { int remaining = buf.remaining(); if (remaining > 0) { long startNs = SystemTime.getInstance().nanoseconds(); int written = socketChannel.write(buf); logger.trace("Flushed bytes in ns", written, SystemTime.getInstance().nanoseconds() - startNs); return written >= remaining; } return true; }
Source:
<code>public RGBValues createRGBValuesFromString(EDataType eDataType, String <START> initialValue) { <END> Iterator<String> it = Splitter.on(',').split(initialValue).iterator(); RGBValues result = new RGBValues(); if (it.hasNext()) { result.setRed(toInt(it.next())); } if (it.hasNext()) { result.setGreen(toInt(it.next())); } if (it.hasNext()) { result.setBlue(toInt(it.next())); } return result; }</code><technical_language>potentiel NPE corrected in next commit added this review in next patch set</technical_language>

Target:
public RGBValues createRGBValuesFromString(EDataType eDataType, String initialValue) { RGBValues result = new RGBValues(); if (!StringUtil.isEmpty(initialValue)) { Iterator<String> it = Splitter.on(',').split(initialValue).iterator(); if (it.hasNext()) { result.setRed(toInt(it.next())); } if (it.hasNext()) { result.setGreen(toInt(it.next())); } if (it.hasNext()) { result.setBlue(toInt(it.next())); } } return result; }
Source:
<code><START> public Long sumMetric(final Task task, final DimFilter filter, final String metric) <END> { TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("test_ds") .filters(filter) .aggregators( ImmutableList.<AggregatorFactory>of( new LongSumAggregatorFactory(metric, metric) ) ).granularity(Granularities.ALL) .intervals("2000/3000") .build(); List<Result<TimeseriesResultValue>> results = task.getQueryRunner(query).run(QueryPlus.wrap(query), ImmutableMap.of()).toList(); if (results.isEmpty()) { return 0L; } else { return results.get(0).getValue().getLongMetric(metric); } }</code><technical_language>Please annotate @Nullable</technical_language>

Target:
public Long sumMetric(final Task task, final DimFilter filter, final String metric) { TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("test_ds") .filters(filter) .aggregators( ImmutableList.of( new LongSumAggregatorFactory(metric, metric) ) ).granularity(Granularities.ALL) .intervals("2000/3000") .build(); List<Result<TimeseriesResultValue>> results = task.getQueryRunner(query).run(QueryPlus.wrap(query), ImmutableMap.of()).toList(); if (results.isEmpty()) { return 0L; } else { return results.get(0).getValue().getLongMetric(metric); } }
Source:
<code>public void openContextMenuByPathSelectedItem(String path) { final String itemXpath = getItemXpathByPath(path); for (int i = 1; ; i++) { waitAndSelectItem(path); waitItemIsSelected(path); seleniumWebDriverHelper.waitAndContextClick(By.xpath(itemXpath)); waitContextMenu(); try { waitItemIsSelected(path, REDRAW_UI_ELEMENTS_TIMEOUT_SEC); return; } catch (TimeoutException e) { seleniumWebDriverHelper.hideContextMenu(); waitContextMenuPopUpClosed(); <START> if (i >= 2) { <END> final String errorMessage = format( "Selection of the project tree item which located by \"%s\" has been lost, context menu event can't be performed for this element", getItemXpathByPath(path)); throw new RuntimeException(errorMessage); } } } }</code><technical_language>i > 1 simpler</technical_language>

Target:
public void openContextMenuByPathSelectedItem(String path) { final String itemXpath = getItemXpathByPath(path); for (int i = 1; ; i++) { waitAndSelectItem(path); waitItemIsSelected(path); seleniumWebDriverHelper.waitAndContextClick(By.xpath(itemXpath)); waitContextMenu(); try { waitItemIsSelected(path, REDRAW_UI_ELEMENTS_TIMEOUT_SEC); return; } catch (TimeoutException e) { seleniumWebDriverHelper.hideContextMenu(); waitContextMenuPopUpClosed(); if (i > 1) { final String errorMessage = format( "Selection of the project tree item which located by \"%s\" has been lost, context menu event can't be performed for this element", getItemXpathByPath(path)); throw new RuntimeException(errorMessage); } } } }
Source:
<code>public static PersistentVolumeClaim newPVC( String name, String accessMode, String quantity, String storageClassName) { SpecNested<PersistentVolumeClaimBuilder> specs = new PersistentVolumeClaimBuilder() .withNewMetadata() .withName(name) .endMetadata() .withNewSpec() .withAccessModes(accessMode); <START> if (storageClassName != null && !storageClassName.equals("")) { <END> specs.withStorageClassName(storageClassName); } return specs .withNewResources() .withRequests(ImmutableMap.of(STORAGE_PARAM, new Quantity(quantity))) .endResources() .endSpec() .build(); }</code><technical_language>!Strings.isNullOrEmpty(storageClassName)</technical_language>

Target:
public static PersistentVolumeClaim newPVC( String name, String accessMode, String quantity, String storageClassName) { SpecNested<PersistentVolumeClaimBuilder> specs = new PersistentVolumeClaimBuilder() .withNewMetadata() .withName(name) .endMetadata() .withNewSpec() .withAccessModes(accessMode); if (!isNullOrEmpty(storageClassName)) { specs.withStorageClassName(storageClassName); } return specs .withNewResources() .withRequests(ImmutableMap.of(STORAGE_PARAM, new Quantity(quantity))) .endResources() .endSpec() .build(); }
Source:
<code>private void showResetPasswordDialog() { ResetPasswordAlertDialogFragment.newInstance(this, <START> getEmail()).show(getSupportFragmentManager(), null); <END> }</code><technical_language>start new line .show() instead of breaking in middle of arguments. note breaking lines in other places</technical_language>

Target:
private void showResetPasswordDialog() { ResetPasswordDialogFragment.newInstance(getEmail()).show(getSupportFragmentManager(), null); }
Source:
<code>private SimplePrincipal(String name) { <START> this.name = name; <END> }</code><technical_language>name null? If possible, add assertion</technical_language>

Target:
private SimplePrincipal(String name) { assert(name != null); this.name = name; }
Source:
<code>void expandSubDataTypes(final DataType dataType) { dataType.getSubDataTypes().forEach(subType -> { <START> final Element subDataTypeRow = getRowElement(subType); <END> final Element arrow = getArrowElement(subDataTypeRow); show(subDataTypeRow); if (!isCollapsed(arrow)) { expandSubDataTypes(subType); } }); }</code><technical_language>more of this type of code move View in Presenter.. if simple moving of this View do view.expandSubType(subType) Element manipulation in View. agree.. Happy consider a new JIRA/work for incremental/agile development</technical_language>

Target:
void expandSubDataTypes(final DataType dataType) { dataType.getSubDataTypes().forEach(view::expandSubType); }
Source:
<code>public void testMultiTenantBatching() throws Exception{ long start = System.currentTimeMillis() - TIME_DIFF; long end = System.currentTimeMillis() + TIME_DIFF; <START> HttpResponse response = httpPost( TID, postMultiPath, JSONMetricsContainerTest.generateMultitenantJSONMetricsData() ); <END> try { assertEquals( 200, response.getStatusLine().getStatusCode() ); verify( context, atLeastOnce() ).update( anyLong(), anyInt() ); final Locator locator = Locator.createLocatorFromPathComponents( "tenantOne", "mzord.duration" ); Points<SimpleNumber> points = AstyanaxReader.getInstance().getDataToRoll( SimpleNumber.class, locator, new Range( start, end ), CassandraModel.getColumnFamily( BasicRollup.class, Granularity.FULL ) ); assertEquals( 1, points.getPoints().size() ); final Locator locatorTwo = Locator.createLocatorFromPathComponents( "tenantTwo", "mzord.duration" ); Points<SimpleNumber> pointsTwo = AstyanaxReader.getInstance().getDataToRoll( SimpleNumber.class, locator, new Range( start, end ), CassandraModel.getColumnFamily( BasicRollup.class, Granularity.FULL ) ); assertEquals( 1, pointsTwo.getPoints().size() ); } finally { EntityUtils.consume( response.getEntity() ); } }</code><technical_language>post multiple metrics ingest/multi, some valid timestamp some delayed/future timestamp supposed fail, request</technical_language>

Target:
public void testMultiTenantBatching() throws Exception{ long start = System.currentTimeMillis() - TIME_DIFF_MS; long end = System.currentTimeMillis() + TIME_DIFF_MS; HttpResponse response = httpPost( TID, postMultiPath, generateMultitenantJSONMetricsData() ); try { assertEquals( 200, response.getStatusLine().getStatusCode() ); verify( context, atLeastOnce() ).update( anyLong(), anyInt() ); final Locator locator = Locator.createLocatorFromPathComponents( "tenantOne", "mzord.duration" ); Points<SimpleNumber> points = AstyanaxReader.getInstance().getDataToRoll( SimpleNumber.class, locator, new Range( start, end ), CassandraModel.getColumnFamily( BasicRollup.class, Granularity.FULL ) ); assertEquals( 1, points.getPoints().size() ); final Locator locatorTwo = Locator.createLocatorFromPathComponents( "tenantTwo", "mzord.duration" ); Points<SimpleNumber> pointsTwo = AstyanaxReader.getInstance().getDataToRoll( SimpleNumber.class, locator, new Range( start, end ), CassandraModel.getColumnFamily( BasicRollup.class, Granularity.FULL ) ); assertEquals( 1, pointsTwo.getPoints().size() ); } finally { EntityUtils.consume( response.getEntity() ); } }
Source:
<code>public void testOnSchedule() throws Exception { Mockito.doNothing(). when(scheduler).startExecutorMonitor(Mockito.anyInt(), Mockito.any(Process.class)); Process[] mockProcesses = new Process[3]; for (int i = 0; i < 3; i++) { mockProcesses[i] = Mockito.mock(Process.class); Mockito.doReturn(mockProcesses[i]).when(scheduler).startExecutorProcess(i); } PackingPlan packingPlan = Mockito.mock(PackingPlan.class); Set<PackingPlan.ContainerPlan> containers = new HashSet<>(); containers.add(PackingTestUtils.testContainerPlan(1)); <START> containers.add(PackingTestUtils.testContainerPlan(2)); <END> Mockito.when(packingPlan.getContainers()).thenReturn(containers); Assert.assertTrue(scheduler.onSchedule(packingPlan)); Assert.assertEquals(3, scheduler.getProcessToContainer().size()); for (int i = 0; i < 3; i++) { Mockito.verify(scheduler).startExecutor(i); Mockito.verify(scheduler).startExecutorProcess(i); Mockito.verify(scheduler).startExecutorMonitor(i, mockProcesses[i]); } }</code><technical_language>container id 3 instead of 2 assert ok consecutive</technical_language>

Target:
public void testOnSchedule() throws Exception { Mockito.doNothing(). when(scheduler).startExecutorMonitor(Mockito.anyInt(), Mockito.any(Process.class)); Process[] mockProcesses = new Process[4]; for (int i = 0; i < 4; i++) { mockProcesses[i] = Mockito.mock(Process.class); Mockito.doReturn(mockProcesses[i]).when(scheduler).startExecutorProcess(i); } PackingPlan packingPlan = Mockito.mock(PackingPlan.class); Set<PackingPlan.ContainerPlan> containers = new HashSet<>(); containers.add(PackingTestUtils.testContainerPlan(1)); containers.add(PackingTestUtils.testContainerPlan(3)); Mockito.when(packingPlan.getContainers()).thenReturn(containers); Assert.assertTrue(scheduler.onSchedule(packingPlan)); verifyIdsOfLaunchedContainers(0, 1, 3); for (int i = 0; i < 4; i++) { if (i == 2) { continue; } Mockito.verify(scheduler).startExecutor(i); Mockito.verify(scheduler).startExecutorProcess(i); Mockito.verify(scheduler).startExecutorMonitor(i, mockProcesses[i]); } }
Source:
<code><START> private static Bitmap getBitmapScaledToContainer(String imageFilepath, int containerHeight, <END> int containerWidth) { BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageFilepath, o); int imageHeight = o.outHeight; int imageWidth = o.outWidth; int heightScale = Math.round((float) imageHeight / containerHeight); int widthScale = Math.round((float) imageWidth / containerWidth); int scale = Math.max(widthScale, heightScale); if (scale == 0) { scale = 1; } return performSafeScaleDown(imageFilepath, scale, 0); }</code><technical_language>This scales in BitmapFactory scale proportions, right? a bit problematic. Feels do of: 1) Scale _last_ scale factor is larger container (IE: bounding box is 100x100, image is 480x480, scale x 4 120x120, in imageview is displayed 100x100. If scaled x5 (the current behavior, round(4.8) -> 5) get 60x60, fit in container 2) Do #1, resize exact boundaries</technical_language>

Target:
private static Bitmap getBitmapScaledToContainer(String imageFilepath, int containerHeight, int containerWidth) { BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageFilepath, o); int imageHeight = o.outHeight; int imageWidth = o.outWidth; return getBitmapScaledByTargetOrContainer(imageFilepath, imageHeight, imageWidth, -1, -1, containerHeight, containerWidth, true); }
Source:
<code>public void handleGetFirmwareVersionResponse(DeviceMessageMetadata deviceMessageMetadata, ResponseMessageResultType deviceResult, OsgpException exception, List<FirmwareVersionDto> firmwareVersionList) { LOGGER.info("handleGetFirmwareVersionResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { <START> LOGGER.error("Replace Keys Response not ok. Unexpected Exception", exception); <END> result = ResponseMessageResultType.NOT_OK; } final List<FirmwareVersion> firmwareVersions = this.configurationMapper.mapAsList(firmwareVersionList, FirmwareVersion.class); final FirmwareVersionResponse firmwareVersionResponse = new FirmwareVersionResponse(firmwareVersions); this.webServiceResponseMessageSender.send(new ResponseMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), result, exception, firmwareVersionResponse, deviceMessageMetadata.getMessagePriority()), deviceMessageMetadata.getMessageType()); }</code><technical_language>Copied log message</technical_language>

Target:
public void handleGetFirmwareVersionResponse(DeviceMessageMetadata deviceMessageMetadata, ResponseMessageResultType deviceResult, OsgpException exception, List<FirmwareVersionDto> firmwareVersionList) { LOGGER.info("handleGetFirmwareVersionResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Get firmware version response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } final List<FirmwareVersion> firmwareVersions = this.configurationMapper.mapAsList(firmwareVersionList, FirmwareVersion.class); final FirmwareVersionResponse firmwareVersionResponse = new FirmwareVersionResponse(firmwareVersions); this.webServiceResponseMessageSender.send(new ResponseMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), result, exception, firmwareVersionResponse, deviceMessageMetadata.getMessagePriority()), deviceMessageMetadata.getMessageType()); }
Source:
<code>public String reduce(String query, Map<String, String> responses) { LOG.info("Reducing query with responses from {}.", query, responses.keySet()); try { String path = getPath(query, LOG); if (path != null && path.equalsIgnoreCase(DiagnosticsRequestType.POSITION.toString())) { return JsonUtils.toJson(responses); } } catch (Exception e) { <START> LOG.warn("Failed to reduce responses {}", responses, e); <END> return null; } return null; }</code><technical_language>want propagate exception here</technical_language>

Target:
public String reduce(String query, Map<String, String> responses) { LOG.info("Reducing query with responses from {}.", query, responses.keySet()); try { String path = getPath(query, LOG); if (path != null && path.equalsIgnoreCase(DiagnosticsRequestType.POSITION.toString())) { return JsonUtils.toJson(responses); } } catch (Exception e) { LOG.warn("Failed to reduce responses {}", responses, e); throw new DatastreamRuntimeException(e); } return null; }
Source:
<code>public void shouldConcatenateSeveralLists() { final List<Integer> list1 = Collections.unmodifiableList( IntStream.range(0, 4).boxed().collect(Collectors.toList()) ); final List<Integer> list2 = Collections.unmodifiableList( IntStream.range(4, 8).boxed().collect(Collectors.toList()) ); final List<Integer> list3 = Collections.unmodifiableList( IntStream.range(8, 12).boxed().collect(Collectors.toList()) ); final List<Integer> list4 = Collections.unmodifiableList( IntStream.range(12, 16).boxed().collect(Collectors.toList()) ); final List<Integer> sortedCancatenatedList = new ArrayList<>(list1); sortedCancatenatedList.addAll(list2); sortedCancatenatedList.addAll(list3); sortedCancatenatedList.addAll(list4); <START> Collections.sort(sortedCancatenatedList); <END> final List<Integer> expected = sortedCancatenatedList; final List<Integer> actual = ListOps.concat(list1, list2, EMPTY_LIST, list3, list4); Collections.sort(actual); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }</code><technical_language>confused motivating sort. I expecting a chunks are, in series, appended. In fact, expecting order is preserved. feel missing a subtle point</technical_language>

Target:
public void shouldConcatenateSeveralLists() { final List<Integer> list1 = Collections.unmodifiableList( Arrays.asList(0, 1, 2, 3) ); final List<Integer> list2 = Collections.unmodifiableList( Arrays.asList(4, 5, 6, 7) ); final List<Integer> list3 = Collections.unmodifiableList( Arrays.asList(8, 9, 10, 11) ); final List<Integer> list4 = Collections.unmodifiableList( Arrays.asList(12, 13, 14, 15) ); final List<Integer> expected = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); final List<Integer> actual = ListOps.concat(list1, list2, EMPTY_LIST, list3, list4); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }
Source:
<code>public void play() { driver.switchTo().frame(iframe); try { <START> Thread.sleep(2000); END> } catch (InterruptedException e) { e.printStackTrace(); } playTriggerButton.click(); driver.switchTo().defaultContent(); }</code><technical_language>fixed in a way? 2s is enough local machine sufficient in case of Jenkins machines</technical_language>

Target:
public void play() { waitForVideoReadyToPlay(); runInAdFrame(() -> playTriggerButton.click()); }
Source:
<code>public void setReadingTimeNow() { <START> Date formatted = Calendar.getInstance().getTime(); <END> updateReadingSplitDateTime(formatted); }</code><technical_language>new Date() is enough</technical_language>

Target:
public void setReadingTimeNow() { Date formatted = new Date(); updateReadingSplitDateTime(formatted); }
Source:
<code>private void unmarshal(final InputStream inputStream) throws JAXBException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document document = null; try { dbf.setFeature("<LINK_0>", false); dbf.setFeature("<LINK_2>", false); dbf.setFeature("<LINK_1>", false); dbf.setExpandEntityReferences(false); DocumentBuilder db = dbf.newDocumentBuilder(); document = db.parse(inputStream); } catch (ParserConfigurationException e) { <START> LOG.debug("Could not set features on {}", dbf); <END> } catch (SAXException | IOException e) { LOG.warn("Error parsing input. Set log to DEBUG for more information."); LOG.debug("Error parsing input. {}", e); throw new JAXBException(e); } JAXBContext jc = JAXBContext.newInstance(Rpfs.class); Unmarshaller u = jc.createUnmarshaller(); rpfs = (Rpfs) u.unmarshal(document); }</code><technical_language>Is worth log exception also</technical_language>

Target:
private void unmarshal(final InputStream inputStream) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(Rpfs.class); Unmarshaller u = jc.createUnmarshaller(); rpfs = (Rpfs) u.unmarshal(inputStream); }
Source:
<code>public void tearDown() throws Exception { <START> fixture = null; <END> builder = null; }</code><technical_language>is this tear necessary? next setup overwrites anyway, it</technical_language>

Target:
public void tearDown() throws Exception { }
Source:
<code>public synchronized void addNodeToDetect(DFSInputStream dfsInputStream, DatanodeInfo datanodeInfo) { HashSet<DatanodeInfo> datanodeInfos = suspectAndDeadNodes.get(dfsInputStream); if (datanodeInfos == null) { datanodeInfos = new HashSet<DatanodeInfo>(); datanodeInfos.add(datanodeInfo); suspectAndDeadNodes.putIfAbsent(dfsInputStream, datanodeInfos); } else { datanodeInfos.add(datanodeInfo); } <START> LOG.warn("Add datanode to suspectAndDeadNodes", datanodeInfo); <END> addSuspectNodeToDetect(datanodeInfo); }</code><technical_language>case: a lot of stale relicas, log flood</technical_language>

Target:
public synchronized void addNodeToDetect(DFSInputStream dfsInputStream, DatanodeInfo datanodeInfo) { HashSet<DatanodeInfo> datanodeInfos = suspectAndDeadNodes.get(dfsInputStream); if (datanodeInfos == null) { datanodeInfos = new HashSet<DatanodeInfo>(); datanodeInfos.add(datanodeInfo); suspectAndDeadNodes.putIfAbsent(dfsInputStream, datanodeInfos); } else { datanodeInfos.add(datanodeInfo); } LOG.debug("Add datanode to suspectAndDeadNodes.", datanodeInfo); addSuspectNodeToDetect(datanodeInfo); }
Source:
<code>public FormulaConstraints generateConstraint(MolecularFormulaRange range) { logger.debug("io.github.msdk.id.sirius.ConstraintsGenerator started processing"); int size = range.getIsotopeCount(); Element elements[] = Arrays.copyOf(defaultElements, defaultElements.length + size); int k = 0; for (IIsotope isotope: range.isotopes()) { int atomicNumber = isotope.getAtomicNumber(); final Element element = periodicTable.get(atomicNumber); elements[defaultElements.length + k++] = element; } FormulaConstraints constraints = new FormulaConstraints(new ChemicalAlphabet(elements)); for (IIsotope isotope: range.isotopes()) { int atomicNumber = isotope.getAtomicNumber(); final Element element = periodicTable.get(atomicNumber); int min = range.getIsotopeCountMin(isotope); int max = range.getIsotopeCountMax(isotope); constraints.setLowerbound(element, min); if (max!= maxNumberOfOneElements) constraints.setUpperbound(element, max); } <START> logger.debug("io.github.msdk.id.sirius.ConstraintsGenerator finished"); <END> return constraints; }</code><technical_language>package name added more places intended</technical_language>

Target:
public FormulaConstraints generateConstraint(MolecularFormulaRange range) { logger.debug("ConstraintsGenerator started processing"); int size = range.getIsotopeCount(); Element elements[] = Arrays.copyOf(defaultElements, defaultElements.length + size); int k = 0; for (IIsotope isotope: range.isotopes()) { int atomicNumber = isotope.getAtomicNumber(); final Element element = periodicTable.get(atomicNumber); elements[defaultElements.length + k++] = element; } FormulaConstraints constraints = new FormulaConstraints(new ChemicalAlphabet(elements)); for (IIsotope isotope: range.isotopes()) { int atomicNumber = isotope.getAtomicNumber(); final Element element = periodicTable.get(atomicNumber); int min = range.getIsotopeCountMin(isotope); int max = range.getIsotopeCountMax(isotope); constraints.setLowerbound(element, min); if (max!= maxNumberOfOneElements) constraints.setUpperbound(element, max); } logger.debug("ConstraintsGenerator finished"); return constraints; }
Source:
<code>public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupUnAuthorized() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); getClient().perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnauthorized()); <START> <END> }</code><technical_language>double check group created default anonymous permission</technical_language>

Target:
public void postCollectionDefaultBitstreamReadGroupCreateDefaultBitstreamReadGroupUnAuthorized() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); getClient().perform(post("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); Group anon = groupService.findByName(context, Group.ANONYMOUS); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/bitstreamReadGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(anon.getID(), anon.getName()))); }
Source:
<code>public int hashCode() { int hash = 7; <START> hash = 31 * hash + (this.uuid != null ? this.uuid.hashCode() : 0); <END> return hash; }</code><technical_language>please Objects.hash() simplifies code</technical_language>

Target:
public int hashCode() { return Objects.hash(uuid); }