auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<String> getAccountUris(final ServerContext vsoDeploymentContext) { List<String> accountUris = new ArrayList<String>(); final Client accountClient = vsoDeploymentContext.getClient(); final String accountApiUrlFormat = VsoAuthenticationProvider.VSO_AUTH_URL + ACCOUNT_ENDPOINT; final WebTarget resourceTarget = accountClient.target(String.format(accountApiUrlFormat, vsoDeploymentContext.getUserId())); final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("api-version", "3.0-preview.1"); parameters.put("charset", "UTF-8"); final Invocation invocation = resourceTarget.request( new MediaType("application", "json", parameters)) .buildGet(); final String response = invocation.invoke(String.class); final ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = null; try { rootNode = objectMapper.readTree(response); } catch (IOException e) { <START> logger.error("Could not parse Account response", e); <END> return accountUris; } final List<JsonNode> nodes = rootNode.findValues(TFS_SERVICE_URL_PROPERTY_NAME); for (final JsonNode node : nodes) { accountUris.add(StringUtils.removeEnd(node.path("$value").asText(), "/")); } return accountUris; }</code><technical_language>more throw error user happened. get empty list indication wrong</technical_language>

Target:
private List<String> getAccountUris(final ServerContext vsoDeploymentContext) { List<String> accountUris = new ArrayList<String>(); final Client accountClient = vsoDeploymentContext.getClient(); final String accountApiUrlFormat = VsoAuthenticationProvider.VSO_AUTH_URL + ACCOUNT_ENDPOINT; final WebTarget resourceTarget = accountClient.target(String.format(accountApiUrlFormat, vsoDeploymentContext.getUserId())); final Map<String, String> parameters = new HashMap<String, String>(); parameters.put("api-version", "3.0-preview.1"); parameters.put("charset", "UTF-8"); final Invocation invocation = resourceTarget.request( new MediaType("application", "json", parameters)) .buildGet(); final String response = invocation.invoke(String.class); final ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = null; try { rootNode = objectMapper.readTree(response); } catch (IOException e) { logger.error("Could not parse Account response", e); throw new TeamServicesException(TeamServicesException.KEY_VSO_AUTH_FAILED, e); } final List<JsonNode> nodes = rootNode.findValues(TFS_SERVICE_URL_PROPERTY_NAME); for (final JsonNode node : nodes) { accountUris.add(StringUtils.removeEnd(node.path("$value").asText(), "/")); } return accountUris; }
Source:
<code>public boolean matches(AttributeSet other) { if (other.attributes.size() != attributes.size()) return false; Iterator<Map.Entry<String, Attribute<?>>> i = attributes.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, Attribute<?>> e = i.next(); String key = e.getKey(); Attribute<?> value = e.getValue(); if (value == null) { <START> if (!(other.attributes.get(key)==null && other.attributes.containsKey(key))) <END> return false; } else { if (!value.matches(other.attributes.get(key))) return false; } } return true; }</code><technical_language>I want check containsKey I more entry keys null values</technical_language>

Target:
public boolean matches(AttributeSet other) { if (other.attributes.size() != attributes.size()) return false; Iterator<Map.Entry<String, Attribute<?>>> i = attributes.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, Attribute<?>> e = i.next(); String key = e.getKey(); Attribute<?> value = e.getValue(); if (value == null) { if (!(other.attributes.containsKey(key) && other.attributes.get(key)==null)) return false; } else { if (!value.matches(other.attributes.get(key))) return false; } } return true; }
Source:
<code>public void addExecutorInGUI() { String name = "executor_" + RandomStringUtils.randomAlphanumeric(6); ConfigFragment config = page.getConfigFragment(); WizardWindow wizard = config.getResourceManager().addResource(); Editor editor = wizard.getEditor(); editor.text("name", name); editor.text(JNDI_NAME, JNDI_VALID); wizard.clickSave(); <START> Console.withBrowser(browser).dismissReloadRequiredWindowIfPresent(); <END> assertTrue("Executor should be present in table", config.resourceIsPresent(name)); ResourceAddress address = new ResourceAddress(eeAddress).add(EE_CHILD, name); verifier.verifyResource(address, true, 5000); removeEEChild(EE_CHILD, name); }</code><technical_language>In <LINK_0> merged WizardWindow.finishAndDismissReloadRequiredWindow() instead</technical_language>

Target:
public void addExecutorInGUI() { String name = "executor_" + RandomStringUtils.randomAlphanumeric(6); ConfigFragment config = page.getConfigFragment(); WizardWindow wizard = config.getResourceManager().addResource(); Editor editor = wizard.getEditor(); editor.text("name", name); editor.text(JNDI_NAME, JNDI_VALID); wizard.saveAndDismissReloadRequiredWindow(); assertTrue("Executor should be present in table", config.resourceIsPresent(name)); ResourceAddress address = new ResourceAddress(eeAddress).add(EE_CHILD, name); verifier.verifyResource(address, true, 5000); removeEEChild(EE_CHILD, name); }
Source:
<code>public Client resolveArgument(final MethodParameter parameter, final ModelAndViewContainer mavContainer, final NativeWebRequest request, final WebDataBinderFactory binderFactory) throws Exception { final Optional<String> clientId = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName); if (!featureToggleService.isFeatureEnabled(CHECK_APPLICATION_LEVEL_PERMISSIONS) || clientId.filter(settings.getAdminClientId()::equals).isPresent() <START> || settings.getAuthMode() == OFF) { <END> return Client.PERMIT_ALL; } return clientId.map(client -> new AuthorizedClient(client, getScopes())) .orElseThrow(() -> new UnauthorizedUserException("Client unauthorized")); }</code><technical_language>bracket battle :-D</technical_language>

Target:
public Client resolveArgument(final MethodParameter parameter, final ModelAndViewContainer mavContainer, final NativeWebRequest request, final WebDataBinderFactory binderFactory) throws Exception { final Optional<String> clientId = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName); if (!featureToggleService.isFeatureEnabled(CHECK_APPLICATION_LEVEL_PERMISSIONS) || clientId.filter(settings.getAdminClientId()::equals).isPresent() || settings.getAuthMode() == OFF) { return Client.FULL_ACCESS; } return clientId.map(client -> new NakadiClient(client, getScopes())) .orElseThrow(() -> new UnauthorizedUserException("Client unauthorized")); }
Source:
<code>protected void executeCommand() { Guid storagePoolId = getDiskImage().getStoragePoolId() != null ? getDiskImage().getStoragePoolId() .getValue() : Guid.Empty; Guid storageDomainId = getDiskImage().getStorageIds() != null && getDiskImage().getStorageIds().size() > 0 ? getDiskImage().getStorageIds() .get(0) : Guid.Empty; Guid imageGroupId = getDiskImage().getimage_group_id() != null ? getDiskImage().getimage_group_id().getValue() : Guid.Empty; VDSReturnValue vdsReturnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.MergeSnapshots, new MergeSnapshotsVDSCommandParameters(storagePoolId, storageDomainId, getVmId(), imageGroupId, getDiskImage().getImageId(), getDestinationDiskImage().getImageId(), getDiskImage().isWipeAfterDelete(), getStoragePool().getcompatibility_version() .toString())); if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getReturnValue().getInternalTaskIdList().add( <START> createTaskSuspendTransaction(vdsReturnValue.getCreationInfo(), <END> VdcActionType.RemoveSnapshot, ExecutionMessageDirector.resolveStepMessage(StepEnum.MERGE_SNAPSHOTS, getJobMessageProperties()), VdcObjectType.Storage, storageDomainId)); setSucceeded(vdsReturnValue.getSucceeded()); } else { setSucceeded(false); } }</code><technical_language>createTask? doesnt call createTaskSuspendTransaction</technical_language>

Target:
protected void executeCommand() { Guid storagePoolId = getDiskImage().getStoragePoolId() != null ? getDiskImage().getStoragePoolId() .getValue() : Guid.Empty; Guid storageDomainId = getDiskImage().getStorageIds() != null && getDiskImage().getStorageIds().size() > 0 ? getDiskImage().getStorageIds() .get(0) : Guid.Empty; Guid imageGroupId = getDiskImage().getimage_group_id() != null ? getDiskImage().getimage_group_id().getValue() : Guid.Empty; VDSReturnValue vdsReturnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.MergeSnapshots, new MergeSnapshotsVDSCommandParameters(storagePoolId, storageDomainId, getVmId(), imageGroupId, getDiskImage().getImageId(), getDestinationDiskImage().getImageId(), getDiskImage().isWipeAfterDelete(), getStoragePool().getcompatibility_version() .toString())); if (vdsReturnValue != null && vdsReturnValue.getCreationInfo() != null) { getReturnValue().getInternalTaskIdList().add( createTask(vdsReturnValue.getCreationInfo(), VdcActionType.RemoveSnapshot, ExecutionMessageDirector.resolveStepMessage(StepEnum.MERGE_SNAPSHOTS, getJobMessageProperties()), VdcObjectType.Storage, storageDomainId)); setSucceeded(vdsReturnValue.getSucceeded()); } else { setSucceeded(false); } }
Source:
<code>public String createNonce(String seed, Repository repo, long timestamp) throws IllegalStateException { <START> String path = repo.getDirectory() != null ? repo.getDirectory().getPath() : ""; END> try { byte[] keyBytes = seed.getBytes("ISO-8859-1"); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); String input = path + ":" + String.valueOf(timestamp); byte[] rawHmac = mac.doFinal(input.getBytes("UTF-8")); String sentNonce = String.format( "%d-%20X", new Long(timestamp), rawHmac); return sentNonce; } catch (InvalidKeyException e) { throw new IllegalStateException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } }</code><technical_language>DFS is part of JGit say: String path; if (repo instanceof DfsRepository) path = ((DfsRepository) repo).getRepositoryName(); else if (repo.getDirectory() != null) path = repo.getDirectory().getPath(); else throw new IllegalStateException();</technical_language>

Target:
public String createNonce(String seed, Repository repo, long timestamp) throws IllegalStateException { String path; if (repo instanceof DfsRepository) path = ((DfsRepository) repo).getDescription().getRepositoryName(); else if (repo.getDirectory() != null) path = repo.getDirectory().getPath(); else throw new IllegalStateException(); try { byte[] keyBytes = seed.getBytes("ISO-8859-1"); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); String input = path + ":" + String.valueOf(timestamp); byte[] rawHmac = mac.doFinal(input.getBytes("UTF-8")); String sentNonce = String.format( "%d-%20X", new Long(timestamp), rawHmac); return sentNonce; } catch (InvalidKeyException e) { throw new IllegalStateException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } }
Source:
<code>public GdbConsoleTerminateLaunchAction(ILaunch launch) { fLaunch = launch; setText(ConsoleMessages.ConsoleTerminateLaunchAction_name); setToolTipText(ConsoleMessages.ConsoleTerminateLaunchAction_description); <START> setImageDescriptor(GdbUIPlugin.getImageDescriptor(IConsoleImagesConst.IMG_CONSOLE_TERMINATE_ACTIVE_COLOR)); <END> }</code><technical_language>call setDisabledImageDescriptor() disabled image constant. way, if action disabled, correct image is selected</technical_language>

Target:
public GdbConsoleTerminateLaunchAction(ILaunch launch) { fLaunch = launch; setText(ConsoleMessages.ConsoleTerminateLaunchAction_name); setToolTipText(ConsoleMessages.ConsoleTerminateLaunchAction_description); setImageDescriptor(GdbUIPlugin.getImageDescriptor(IConsoleImagesConst.IMG_CONSOLE_TERMINATE_ACTIVE_COLOR)); setDisabledImageDescriptor(GdbUIPlugin.getImageDescriptor(IConsoleImagesConst.IMG_CONSOLE_TERMINATE_DISABLED_COLOR)); DebugPlugin.getDefault().getLaunchManager().addLaunchListener(this); }
Source:
<code>public Router getRouter() { try { NonBlockingRouter router = new NonBlockingRouter(routerConfig, routerMetrics, networkClientFactory, notificationSystem, clusterMap, <START> kms, cryptoService, cryptoJobHandler, accountService, time, defaultPartitionClass); <END> router.setRequestHandlerPool(requestHandlerPool); return router; } catch (IOException e) { throw new IllegalStateException("Error instantiating NonBlocking Router ", e); } }</code><technical_language>minor: format this file</technical_language>

Target:
public Router getRouter() throws InstantiationException { try { MetricRegistry registry = clusterMap.getMetricRegistry(); RequestHandlerPool requestHandlerPool = getRequestHandlerPool(verifiableProperties, clusterMap, notificationSystem); NetworkClientFactory networkClientFactory = new LocalNetworkClientFactory((LocalRequestResponseChannel) requestHandlerPool.getChannel(), new NetworkConfig(verifiableProperties), new NetworkMetrics(registry), time); NonBlockingRouter router = new NonBlockingRouter(routerConfig, routerMetrics, networkClientFactory, notificationSystem, clusterMap, kms, cryptoService, cryptoJobHandler, accountService, time, defaultPartitionClass); router.addResourceToClose(requestHandlerPool); logger.info("Instantiated NonBlockingRouter"); return router; } catch (Exception e) { logger.error("Error instantiating NonBlocking Router", e); throw new InstantiationException("Error instantiating NonBlocking Router: " + e.toString()); } }
Source:
<code>public String format(String input) { <START> List<String> sentences = StringUtil.getStringAsSentences(input); <END> StringBuilder result = new StringBuilder(); for (String sentence : sentences) { Title title = new Title(sentence); title.getWords().stream().filter(Word::isSmallerWord).forEach(Word::toLowerCase); title.getWords().stream().filter(Word::isLargerWord).forEach(Word::toUpperFirst); title.getFirstWord().ifPresent(Word::toUpperFirst); title.getLastWord().ifPresent(Word::toUpperFirst); for (int i = 0; i < (title.getWords().size() - 2); i++) { if (title.getWords().get(i).endsWithColon()) { title.getWords().get(i + 1).toUpperFirst(); } } result.append(title.toString() + " "); } result.deleteCharAt(result.length() - 1); return result.toString(); }</code><technical_language>stream magic here: suggestion return StringUtil .getStringAsSentences(input) .stream() .map(sentence -> { Title title = new Title(sentence); title.getWords().stream().filter(Word::isSmallerWord).forEach(Word::toLowerCase); title.getWords().stream().filter(Word::isLargerWord).forEach(Word::toUpperFirst); title.getFirstWord().ifPresent(Word::toUpperFirst); title.getLastWord().ifPresent(Word::toUpperFirst); for (int i = 0; i < (title.getWords().size() - 2); i++) { if (title.getWords().get(i).endsWithColon()) { title.getWords().get(i + 1).toUpperFirst(); } } return title.toString(); }) .collect(Collectors.joining(" "));</technical_language>

Target:
public String format(String input) { return StringUtil.getStringAsSentences(input) .stream() .map(sentence -> { Title title = new Title(sentence); title.getWords().stream().filter(Word::isSmallerWord).forEach(Word::toLowerCase); title.getWords().stream().filter(Word::isLargerWord).forEach(Word::toUpperFirst); title.getFirstWord().ifPresent(Word::toUpperFirst); title.getLastWord().ifPresent(Word::toUpperFirst); for (int i = 0; i < (title.getWords().size() - 2); i++) { if (title.getWords().get(i).endsWithColon()) { title.getWords().get(i + 1).toUpperFirst(); } } return title.toString(); }) .collect(Collectors.joining(" ")); }
Source:
<code>public void suggestions_without_query_should_contain_recently_browsed() throws Exception { ComponentDto project = db.components().insertComponent(newPrivateProjectDto(organization)); componentIndexer.indexOnStartup(null); authorizationIndexerTester.allowOnlyAnyone(project); SuggestionsWsResponse response = actionTester.newRequest() .setMethod("POST") <START> .setParam(PARAM_RECENTLY_BROWSED, Stream.of(project.getKey()).collect(joining(","))) <END> .executeProtobuf(SuggestionsWsResponse.class); assertThat(response.getResultsList()) .filteredOn(q -> q.getItemsCount() > 0) .extracting(Category::getQ) .containsExactly(Qualifiers.PROJECT); assertThat(response.getResultsList()) .flatExtracting(Category::getItemsList) .extracting(Suggestion::getKey, Suggestion::getOrganization) .containsExactly(tuple(project.getKey(), organization.getKey())); }</code><technical_language>stream is useless here, put project key</technical_language>

Target:
public void suggestions_without_query_should_contain_recently_browsed() throws Exception { ComponentDto project = db.components().insertComponent(newPrivateProjectDto(organization)); componentIndexer.indexOnStartup(null); userSessionRule.addProjectPermission(USER, project); SuggestionsWsResponse response = ws.newRequest() .setMethod("POST") .setParam(PARAM_RECENTLY_BROWSED, project.getKey()) .executeProtobuf(SuggestionsWsResponse.class); assertThat(response.getResultsList()) .filteredOn(q -> q.getItemsCount() > 0) .extracting(Category::getQ) .containsExactly(Qualifiers.PROJECT); assertThat(response.getResultsList()) .flatExtracting(Category::getItemsList) .extracting(Suggestion::getKey, Suggestion::getIsRecentlyBrowsed) .containsExactly(tuple(project.getKey(), true)); }
Source:
<code>public void handleActualMeterReadsResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final MeterReadsGasResponseDto actualMeterReadsGas) { LOGGER.info("handleActualMeterReadsResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send( <END> ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception) .withDataObject(this.monitoringMapper.map(actualMeterReadsGas, MeterReadsGas.class)) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleActualMeterReadsResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final MeterReadsGasResponseDto actualMeterReadsGas) { LOGGER.info("handleActualMeterReadsResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } final ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception) .withDataObject(this.monitoringMapper.map(actualMeterReadsGas, MeterReadsGas.class)) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public static void browsePostOrPage(Context context, SiteModel site, PostModel post) { if (site == null || post == null || TextUtils.isEmpty(post.getLink())) return; String url = UrlUtils.appendUrlParameter(post.getLink(), "preview", "true"); <START> url = url.replace(site.getUrl(), site.getUnmappedUrl()); <END> String shareableUrl = post.getLink(); String shareSubject = post.getTitle(); if (site.isWPCom()) { WPWebViewActivity.openPostUrlByUsingGlobalWPCOMCredentials(context, url, shareableUrl, shareSubject); } else if (site.isJetpackConnected()) { WPWebViewActivity.openJetpackBlogPostPreview(context, url, shareableUrl, shareSubject, site.getFrameNonce()); } else { WPWebViewActivity.openUrlByUsingBlogCredentials(context, site, post, url, new String[]{post.getLink()}); } }</code><technical_language>unmapped URL null (for example, for hosted sites), a crash. skip this if getUnmappedUrl() returns empty string</technical_language>

Target:
public static void browsePostOrPage(Context context, SiteModel site, PostModel post) { if (site == null || post == null || TextUtils.isEmpty(post.getLink())) return; String url = UrlUtils.appendUrlParameter(post.getLink(), "preview", "true"); String shareableUrl = post.getLink(); String shareSubject = post.getTitle(); if (site.isWPCom()) { if (!TextUtils.isEmpty(site.getUnmappedUrl())) { url = url.replace(site.getUrl(), site.getUnmappedUrl()); } WPWebViewActivity.openPostUrlByUsingGlobalWPCOMCredentials(context, url, shareableUrl, shareSubject); } else if (site.isJetpackConnected()) { WPWebViewActivity.openJetpackBlogPostPreview(context, url, shareableUrl, shareSubject, site.getFrameNonce()); } else { WPWebViewActivity.openUrlByUsingBlogCredentials(context, site, post, url, new String[]{post.getLink()}); } }
Source:
<code>private void updateDestination() { destinationSpinner.removeActionListener(destinationListener); destinationSpinner.removeAllItems(); <START> for (Destination format : Destination.destinationValues()) { <END> destinationSpinner.addItem(format); } destinationSpinner.setSelectedItem(controller.getDestination()); destinationSpinner.addActionListener(destinationListener); }</code><technical_language>values</technical_language>

Target:
private void updateDestination() { destinationSpinner.removeActionListener(destinationListener); destinationSpinner.removeAllItems(); for (Destination format : Destination.values()) { destinationSpinner.addItem(format); } destinationSpinner.setSelectedItem(controller.getDestination()); destinationSpinner.addActionListener(destinationListener); }
Source:
<code>public void testRefreshView() { final String typeName = "typeName"; final DataType parent = mock(DataType.class); <START> final List<DataType> expectedDataTypes = new ArrayList<DataType>() {{ <END> add(mock(DataType.class)); }}; when(dataTypeUtils.externalDataTypes(parent, typeName)).thenReturn(expectedDataTypes); dataTypeSelect.init(listItem, parent); dataTypeSelect.refreshView(typeName); assertEquals(expectedDataTypes, dataTypeSelect.getSubDataTypes()); verify(listItem).refreshSubItems(expectedDataTypes); }</code><technical_language>shorter: Collections.singletonList(mock(DataType.class));</technical_language>

Target:
public void testRefreshView() { final String typeName = "typeName"; final DataType parent = mock(DataType.class); final List<DataType> expectedDataTypes = Collections.singletonList(mock(DataType.class)); when(dataTypeUtils.externalDataTypes(parent, typeName)).thenReturn(expectedDataTypes); dataTypeSelect.init(listItem, parent); dataTypeSelect.refreshView(typeName); assertEquals(expectedDataTypes, dataTypeSelect.getSubDataTypes()); verify(listItem).refreshSubItems(expectedDataTypes); }
Source:
<code>public static String prettyHexString(String hexString) { <START> String prettyHexString = ""; <END> if (hexString.length() % 2 != 0) hexString = "0" + hexString; int iterations = hexString.length() / 2; for (int i = 0; i < iterations; i++) prettyHexString += hexString.substring(2 * i, 2 * i + 2) + " "; return prettyHexString.trim(); }</code><technical_language>Check if hexString is null</technical_language>

Target:
public static String prettyHexString(String hexString) { if (hexString == null) throw new NullPointerException("Hexadecimal string cannot be null."); String prettyHexString = ""; if (hexString.length() % 2 != 0) hexString = "0" + hexString; int iterations = hexString.length() / 2; for (int i = 0; i < iterations; i++) prettyHexString += hexString.substring(2 * i, 2 * i + 2) + " "; return prettyHexString.trim(); }
Source:
<code>public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { boolean result = false; if (SEMANTIC_DELETION_PROPERTY.equals(property)) { result = expectedValue.equals(DeleteActionUtil.isSemanticDeletion((IGraphicalEditPart) receiver)); } else if (READ_ONLY_PROPERTY.equals(property)) { final Object model = ((IGraphicalEditPart) receiver).getModel(); if (model instanceof View && !(((View) model).getElement() instanceof <START> PrimitiveType)) <END> { result = true; } else { result = expectedValue.equals(DeleteActionUtil.isReadOnly((IGraphicalEditPart) receiver)); } } return result; }</code><technical_language>PrimitivesTypes ? a problem Metaclass, : if(((View)model).getElement() instance of Class){ Class clazz = model.getElement; if(clazz.isMetaclass()[ }</technical_language>

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { boolean result = false; if (SEMANTIC_DELETION_PROPERTY.equals(property)) { result = expectedValue.equals(DeleteActionUtil.isSemanticDeletion((IGraphicalEditPart) receiver)); } else if (READ_ONLY_PROPERTY.equals(property)) { final Object model = ((IGraphicalEditPart) receiver).getModel(); if (model instanceof View && ((View)model).getElement() instanceof org.eclipse.uml2.uml.Class){ org.eclipse.uml2.uml.Class clazz = (org.eclipse.uml2.uml.Class) ((View)model).getElement(); if(clazz.isMetaclass()){ result = true; } } else { result = expectedValue.equals(DeleteActionUtil.isReadOnly((IGraphicalEditPart) receiver)); } } return result; }
Source:
<code>protected void accumulateConsecutiveDnsTimeoutCount(int code) { final DnsResult result = new DnsResult(code); final int index = mResultIndices.add(); <START> if (index >= 0 && index < mSize) { <END> mDnsEvents[index] = result; } if (result.isTimeout()) { mConsecutiveTimeoutCount++; } else { mConsecutiveTimeoutCount = 0; } }</code><technical_language>I suggest simply mDnsEvents[mResultIndices.add()];, RingBufferIndices class is defined return out of bounds. contractual</technical_language>

Target:
protected void accumulateConsecutiveDnsTimeoutCount(int code) { final DnsResult result = new DnsResult(code); mDnsEvents[mResultIndices.add()] = result; if (result.isTimeout()) { mConsecutiveTimeoutCount++; } else { mConsecutiveTimeoutCount = 0; } }
Source:
<code>public Point getDPI () { checkDevice (); long hDC = internal_new_GC (null); int dpiX = OS.GetDeviceCaps (hDC, OS.LOGPIXELSX); int dpiY = OS.GetDeviceCaps (hDC, OS.LOGPIXELSY); internal_dispose_GC (hDC, null); return <START> DPIUtil.autoScaleDown(new <END> Point (dpiX, dpiY)); }</code><technical_language>I settled for this solution well, I tested Win7 125% {120, 120}. GTK 125%, I get {96, 96}. this implementation effectively 100% 200% is return DPIUtil#DPI_ZOOM_100 (which is 96) x coordinate. 125%, DPIUtil effectively a deviceZoom of 100%, explains results. undecided this point change Win32 GTK, need return 125%</technical_language>

Target:
public Point getDPI () { checkDevice (); long hDC = internal_new_GC (null); int widthMM = OS.GetDeviceCaps(hDC, OS.HORZSIZE); int width = OS.GetDeviceCaps(hDC, OS.HORZRES); int dpi = Compatibility.round (254 * width, widthMM * 10); return new Point (dpi, dpi); }
Source:
<code>public void testGeneIdorGeneNameNonExisting() { List<FeatureCoordinates> featureCoordinates = findByIdOrNameHelper(GENE_ID_NON_EXISTING, GENE_NAME_NON_EXISITNG); <START> assertTrue(featureCoordinates.size() == 0); <END> featureCoordinates = findByIdOrNameHelper(GENE_ID_NON_EXISTING, null); assertTrue(featureCoordinates.size() == 0); featureCoordinates = findByIdOrNameHelper(null, GENE_NAME_NON_EXISITNG); assertTrue(featureCoordinates.size() == 0); }</code><technical_language>if this test fails, test logs show size of list, making harder understand problem suggestion assertEquals(0, featureCoordinates.size());</technical_language>

Target:
public void testGeneIdorGeneNameNonExisting() { List<FeatureCoordinates> featureCoordinates = findByIdOrNameHelper(GENE_ID_NON_EXISTING, GENE_NAME_NON_EXISITNG); assertEquals(0, featureCoordinates.size()); featureCoordinates = findByIdOrNameHelper(GENE_ID_NON_EXISTING, null); assertEquals(0, featureCoordinates.size()); featureCoordinates = findByIdOrNameHelper(null, GENE_NAME_NON_EXISITNG); assertEquals(0, featureCoordinates.size()); }
Source:
<code>public static InputStream getResource(String resource) throws IOException { File resourceFile = new File(resource); if (resourceFile.exists() && !resourceFile.isFile()) { throw new IOException(String.format("%s is not a file. ", resourceFile.getAbsolutePath())); } InputStream is = resourceFile.exists() ? new FileInputStream(resourceFile) : Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); if (is == null) { <START> throw new IOException(String.format("Resource: %s is not found", resource)); <END> } return is; }</code><technical_language>Nitpick: : strange updated wording</technical_language>

Target:
public static InputStream getResource(String resource) throws IOException { File resourceFile = new File(resource); if (resourceFile.exists() && !resourceFile.isFile()) { throw new IOException(String.format("%s is not a file. ", resourceFile.getAbsolutePath())); } InputStream is = resourceFile.exists() ? new FileInputStream(resourceFile) : Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); if (is == null) { throw new IOException(String.format("Resource %s is not found", resource)); } return is; }
Source:
<code>public CurrentTemperatureCharacteristic( Supplier<CompletableFuture<Double>> getter, Consumer<HomekitCharacteristicChangeCallback> subscriber, Runnable unsubscriber) { <START> this(0, 100, 0.1, getter, subscriber, unsubscriber); <END> }</code><technical_language>public static final double MIN_TEMPERATURE_VALUE = 0; (and similar)?You re-use in Accessory</technical_language>

Target:
public CurrentTemperatureCharacteristic( Supplier<CompletableFuture<Double>> getter, Consumer<HomekitCharacteristicChangeCallback> subscriber, Runnable unsubscriber) { this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, DEFAULT_STEP, getter, subscriber, unsubscriber); }
Source:
<code>public int compareTo(@Nonnull OutputDataStream otherStream) { if (getSizeInBytes() == otherStream.getSizeInBytes()) { return 0; } <START> return getSizeInBytes() < otherStream.getSizeInBytes() ? -1 : 1; <END> }</code><technical_language>return Long.compare(sizeInButes, other.sizeInBytes);</technical_language>

Target:
public int compareTo(@Nonnull OutputDataStream otherStream) { return Long.compare(sizeInBytes, otherStream.sizeInBytes); }
Source:
<code>public void createFolder(String path) { if (exists(ensureTrailingSlashPresent(path))) { return; } List<String> parts = Splitter.on('/').splitToList(path); StringBuilder sb = new StringBuilder(); for (String objectName : parts) { <START> sb.append(ensureTrailingSlashPresent(objectName)); <END> if (!exists(sb.toString())) { createEmptyObject(sb.toString()); } } }</code><technical_language>sb.append(objectName); sb.append('/'); more readable objectName end path separator</technical_language>

Target:
public void createFolder(String path) { if (exists(ensureTrailingSlashPresent(path))) { return; } List<String> parts = PATH_SPLITTER.splitToList(path); StringBuilder sb = new StringBuilder(); for (String objectName : parts) { sb.append(objectName); sb.append(PATH_SEPARATOR); if (!exists(sb.toString())) { createEmptyObject(sb.toString()); } } }
Source:
<code>public MediaType getContentType() { if (this.readOnly && this.cachedContentType != null) { return this.cachedContentType; } else { String value = getFirst(CONTENT_TYPE); MediaType contentType = (StringUtils.hasLength(value) ? MediaType.parseMediaType(value) : null); if (this.readOnly) { this.cachedContentType = contentType; } return contentType; <START> } <END> }</code><technical_language>This improved. this.readOnly check shows this method is mixing concerns: map lookup caching. I prefer if caching done in a separate wrapper class(ReadOnlyHttpHeaders), is returned HttpHeaders.readOnlyHttpHeaders is called (instead of backing map unmodifiable MultiValueMap)</technical_language>

Target:
public MediaType getContentType() { String value = getFirst(CONTENT_TYPE); return (StringUtils.hasLength(value) ? MediaType.parseMediaType(value) : null); }
Source:
<code>public static void init() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ITEMS.register(modEventBus); for (SlimeBlock.SlimeType type : SlimeBlock.SlimeType.values()) { System.out.println(type); <START> System.out.println(type.toString()); <END> } }</code><technical_language>Leftover debug</technical_language>

Target:
public static void init() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ITEMS.register(modEventBus); }
Source:
<code>public CharSequence getStr(int col) { <START> return columnNumber == 0 ? "table" : "column"; <END> }</code><technical_language>sparse array</technical_language>

Target:
public CharSequence getStr(int col) { return description; }
Source:
<code>public void coverage() { <START> coverPrivateConstructor(FraTradeCsvLoader.class); <END> }</code><technical_language>is FraTradeCsvLoader class tested here</technical_language>

Target:
public void coverage() { coverPrivateConstructor(FraTradeCsvLoader.class); coverPrivateConstructor(SwapTradeCsvLoader.class); coverPrivateConstructor(TermDepositTradeCsvLoader.class); coverPrivateConstructor(FullSwapTradeCsvLoader.class); }
Source:
<code><START> public List<CtfTmfEventField> getValue() { <END> return new ArrayList<CtfTmfEventField>(Arrays.asList((CtfTmfEventField[])super.getValue())); }</code><technical_language>return type Object, toString() function is called converted a List else string good Hmm, good point. getValue() return type is passed constructor. pass a field[] reuse sub-fields attribute in super class... I easiest/cleanest override .toString() in here, Arrays.toString() correctly print array</technical_language>

Target:
public CtfTmfEventField[] getValue() { return (CtfTmfEventField[])super.getValue(); }
Source:
<code>private void writeAndFlush(final Channel channel, final CompletionKey key, final Object request, final boolean allowFastFail) { if (channel == null) { errorOut(key); return; } if (isWritable != channel.isWritable()) { isWritable = !isWritable; } if (allowFastFail && !isWritable) { <START> errorOut(key); <END> return; } try { final long startTime = MathUtils.nowInNano(); ChannelFuture future = channel.writeAndFlush(request); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { nettyOpLogger.registerSuccessfulEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); completionObjects.get(key).setOutstanding(); } else { nettyOpLogger.registerFailedEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } } }); } catch (Throwable e) { LOG.warn("Operation failed", requestToString(request), e); errorOut(key); } }</code><technical_language>This returns BookieHandleNotAvailableException. is interpreted able connect bookie basically cannelPool returning NULL. I return a error (busy??). if handle differently bubble application application reason</technical_language>

Target:
private void writeAndFlush(final Channel channel, final CompletionKey key, final Object request, final boolean allowFastFail) { if (channel == null) { LOG.warn("Operation failed: channel == null", requestToString(request)); errorOut(key); return; } final boolean isChannelWritable = channel.isWritable(); if (isWritable != isChannelWritable) { isWritable = isChannelWritable; } if (allowFastFail && !isWritable) { LOG.warn("Operation failed: TooManyRequestsException", requestToString(request)); errorOut(key, BKException.Code.TooManyRequestsException); return; } try { final long startTime = MathUtils.nowInNano(); ChannelPromise promise = channel.newPromise().addListener(future -> { if (future.isSuccess()) { nettyOpLogger.registerSuccessfulEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); CompletionValue completion = completionObjects.get(key); if (completion != null) { completion.setOutstanding(); } } else { nettyOpLogger.registerFailedEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } }); channel.writeAndFlush(request, promise); } catch (Throwable e) { LOG.warn("Operation failed", requestToString(request), e); errorOut(key); } }
Source:
<code>public void init() throws DeviceException { AndroidDebugBridge.initIfNeeded(false ); AndroidDebugBridge bridge = AndroidDebugBridge.createBridge( adbLocation.getAbsolutePath(), false ); long timeOut = 30000; int sleepTime = 1000; while (!bridge.hasInitialDeviceList() && timeOut > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { throw new DeviceException(e); } timeOut -= sleepTime; } if (timeOut <= 0 && !bridge.hasInitialDeviceList()) { throw new DeviceException("Timeout getting device list."); } IDevice[] devices = bridge.getDevices(); if (devices.length == 0) { throw new DeviceException("No connected devices!"); } final String androidSerial = System.getenv("ANDROID_SERIAL"); final Boolean isValidSerial = androidSerial != null && !androidSerial.isEmpty(); for (IDevice iDevice : devices) { <START> if (!isValidSerial || iDevice.getSerialNumber().equals(androidSerial)) { localDevices.add(new ConnectedDevice(iDevice)); <END> } } if (localDevices.isEmpty()) { throw new DeviceException( String.format("Connected device with serial %s not found!", androidSerial)); } }</code><technical_language>this check device is 'online', fix this</technical_language>

Target:
public void init() throws DeviceException { AndroidDebugBridge.initIfNeeded(false ); AndroidDebugBridge bridge = AndroidDebugBridge.createBridge( adbLocation.getAbsolutePath(), false ); long timeOut = 30000; int sleepTime = 1000; while (!bridge.hasInitialDeviceList() && timeOut > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { throw new DeviceException(e); } timeOut -= sleepTime; } if (timeOut <= 0 && !bridge.hasInitialDeviceList()) { throw new DeviceException("Timeout getting device list."); } IDevice[] devices = bridge.getDevices(); if (devices.length == 0) { throw new DeviceException("No connected devices!"); } final String androidSerial = System.getenv("ANDROID_SERIAL"); final Boolean isValidSerial = androidSerial != null && !androidSerial.isEmpty(); final List<IDevice> filteredDevices = Lists.newArrayListWithCapacity(devices.length); for (IDevice iDevice : devices) { if (!isValidSerial || iDevice.getSerialNumber().equals(androidSerial)) { filteredDevices.add(iDevice); } } if (filteredDevices.isEmpty()) { throw new DeviceException("Connected device with serial %s not found!", androidSerial); } for (IDevice device : filteredDevices) { if (device.getState() == IDevice.DeviceState.ONLINE) { localDevices.add(new ConnectedDevice(device)); } else { iLogger.info( "Skipping device '%s' (%s): Device is %s%s.", device.getName(), device.getSerialNumber(), device.getState(), device.getState() == IDevice.DeviceState.UNAUTHORIZED ? ",\n" + " see <LINK_0>" : ""); } } if (localDevices.isEmpty()) { if (isValidSerial) { throw new DeviceException("Connected device with serial $1%s is not online.", androidSerial); } else { throw new DeviceException("No online devices found."); } } }
Source:
<code>public TaggedBlobItem(String containerName, String name) { <START> this(containerName, name, new HashMap<>()); <END> }</code><technical_language>Collections.emptyMap() a singleton instead of creating a new instance</technical_language>

Target:
public TaggedBlobItem(String containerName, String name) { this(containerName, name, Collections.emptyMap()); }
Source:
<code>public void parseNetworkListWithOneNetworkIllegalArgException() throws Exception { WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); String xmlString = new String(getTestNetworksXmlBytes(openNetwork, eapNetwork)); xmlString = xmlString.replaceAll( String.format(XmlUtilTest.XML_STRING_EAP_METHOD_REPLACE_FORMAT, eapNetwork.enterpriseConfig.getEapMethod()), String.format(XmlUtilTest.XML_STRING_EAP_METHOD_REPLACE_FORMAT, WifiEnterpriseConfig.Eap.NONE)); List<WifiConfiguration> retrievedNetworkList = <START> deserializeData(xmlString.getBytes(), true ); <END> assertEquals(1, retrievedNetworkList.size()); for (WifiConfiguration network : retrievedNetworkList) { assertNotEquals(eapNetwork.SSID, network.SSID); } }</code><technical_language>internally String#getBytes() UTF-8 default charset, explicitly more clear</technical_language>

Target:
public void parseNetworkListWithOneNetworkIllegalArgException() throws Exception { WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); String xmlString = new String(getTestNetworksXmlBytes(openNetwork, eapNetwork)); xmlString = xmlString.replaceAll( String.format(XmlUtilTest.XML_STRING_EAP_METHOD_REPLACE_FORMAT, eapNetwork.enterpriseConfig.getEapMethod()), String.format(XmlUtilTest.XML_STRING_EAP_METHOD_REPLACE_FORMAT, WifiEnterpriseConfig.Eap.NONE)); List<WifiConfiguration> retrievedNetworkList = deserializeData(xmlString.getBytes(StandardCharsets.UTF_8), true ); assertEquals(1, retrievedNetworkList.size()); for (WifiConfiguration network : retrievedNetworkList) { assertNotEquals(eapNetwork.SSID, network.SSID); } }
Source:
<code>public String getState(String key) { <START> return _zkAdapter.getDatastreamTaskStateForKey(this.getInternalDatastreamTask(), key); <END> }</code><technical_language>nit: _internalDatastreamTask instead of calling getter right (and other places)? I getter adds additional logic</technical_language>

Target:
public String getState(String key) { return _zkAdapter.getDatastreamTaskStateForKey(_internalDatastreamTask, key); }
Source:
<code>public static void toLowerCase(@Nullable final CharSequence str, final CharSink sink) { <START> if (str == null || str.length() == 0) { <END> return; } for (int i = 0; i < str.length(); i++) { sink.put(toLowerCase(str.charAt(i))); } }</code><technical_language>this implementation improved in terms of hot path isolation: - string is null longer zero (hot) - string is null empty (less frequent - cold) hot path like: java if (str != null) { for (int i = 0, n=str.length(); i < n; i++) { sink.put(toLowerCase(str.charAt(i))); } } note is str.length() is cached local variable, java calling length() method for iteration</technical_language>

Target:
public static void toLowerCase(@Nullable final CharSequence str, final CharSink sink) { if(str != null) { final int len = str.length(); for (int i = 0; i < len; i++) { sink.put(Character.toLowerCase(str.charAt(i))); } } }
Source:
<code>protected void configFacets(IDataModel dataModel, String projectLocation) { super.configFacets(dataModel, projectLocation); FacetDataModelMap map = (FacetDataModelMap) dataModel.getProperty(IFacetProjectCreationDataModelProperties.FACET_DM_MAP); IDataModel configJSF = (IDataModel) map.get("jst.jsf"); if(configJSF == null) { configJSF = DataModelFactory.createDataModel(new JSFFacetInstallDataModelProvider()); map.add(configJSF); } configJSF = (IDataModel) map.get("jst.jsf"); if(configJSF != null) { String template = getProperty(TEMPLATE_VERSION_ID); String version = template.indexOf("1.1") >= 0 ? "1.1" : template.indexOf("1.2") >= 0 ? "1.2" : template.indexOf("2.0") >= 0 ? "2.0" : template.indexOf("2.1") >= 0 ? "2.1" : template.indexOf("2.2") >= 0 ? "2.2" <START> : template.indexOf("2.2") >= 0 ? "2.3" <END> : null; if(version != null) { configJSF.setProperty(IFacetDataModelProperties.FACET_VERSION_STR, version); } IProjectFacet facet = ProjectFacetsManager.getProjectFacet("jst.jsf"); try { IFacetedProject fproj = ProjectFacetsManager.create(getProject(), true, new NullProgressMonitor()); LibraryInstallDelegate libraryDelegate = new LibraryInstallDelegate(fproj, facet.getDefaultVersion()); ILibraryProvider provider = LibraryProviderFramework.getProvider("jsf-no-op-library-provider"); libraryDelegate.setLibraryProvider(provider); configJSF.setProperty(IJSFFacetInstallDataModelProperties.LIBRARY_PROVIDER_DELEGATE, libraryDelegate); } catch (CoreException e) { JsfUiPlugin.getDefault().logError(e); } } }</code><technical_language>template.indexOf("2.3")</technical_language>

Target:
protected void configFacets(IDataModel dataModel, String projectLocation) { super.configFacets(dataModel, projectLocation); FacetDataModelMap map = (FacetDataModelMap) dataModel.getProperty(IFacetProjectCreationDataModelProperties.FACET_DM_MAP); IDataModel configJSF = (IDataModel) map.get("jst.jsf"); if(configJSF == null) { configJSF = DataModelFactory.createDataModel(new JSFFacetInstallDataModelProvider()); map.add(configJSF); } configJSF = (IDataModel) map.get("jst.jsf"); if(configJSF != null) { String template = getProperty(TEMPLATE_VERSION_ID); String version = template.indexOf("1.1") >= 0 ? "1.1" : template.indexOf("1.2") >= 0 ? "1.2" : template.indexOf("2.0") >= 0 ? "2.0" : template.indexOf("2.1") >= 0 ? "2.1" : template.indexOf("2.2") >= 0 ? "2.2" : template.indexOf("2.3") >= 0 ? "2.3" : null; if(version != null) { configJSF.setProperty(IFacetDataModelProperties.FACET_VERSION_STR, version); } IProjectFacet facet = ProjectFacetsManager.getProjectFacet("jst.jsf"); try { IFacetedProject fproj = ProjectFacetsManager.create(getProject(), true, new NullProgressMonitor()); LibraryInstallDelegate libraryDelegate = new LibraryInstallDelegate(fproj, facet.getDefaultVersion()); ILibraryProvider provider = LibraryProviderFramework.getProvider("jsf-no-op-library-provider"); libraryDelegate.setLibraryProvider(provider); configJSF.setProperty(IJSFFacetInstallDataModelProperties.LIBRARY_PROVIDER_DELEGATE, libraryDelegate); } catch (CoreException e) { JsfUiPlugin.getDefault().logError(e); } } }
Source:
<code>public List<String> getMatchingStackFrames(@NonNull String filter, boolean fullTrace, @NonNull Locale locale) { filter = filter.toLowerCase(locale); List<String> matchingFrames = Lists.newArrayList(); if <START> (mStackTrace.length > <END> 0) { final int length = fullTrace ? mStackTrace.length : 1; for (int i = 0; i < length; ++i) { String frameString = mStackTrace[i].toString(); if (frameString.toLowerCase(locale).contains(filter)) { matchingFrames.add(frameString); } } } return matchingFrames; }</code><technical_language>do: if (length > 0) { matchingFrames = Lists.newArrayListWithExpectedSize(length) ... } else { return Collections.emptyList() }</technical_language>

Target:
public List<String> getMatchingStackFrames(@NonNull String filter, boolean fullTrace, @NonNull Locale locale) { filter = filter.toLowerCase(locale); if (mStackTrace.length > 0) { final int length = fullTrace ? mStackTrace.length : 1; List<String> matchingFrames = Lists.newArrayListWithExpectedSize(length); for (int i = 0; i < length; ++i) { String frameString = mStackTrace[i].toString(); if (frameString.toLowerCase(locale).contains(filter)) { matchingFrames.add(frameString); } } return matchingFrames; } else { return Collections.emptyList(); } }