auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void syncAStack(Stack stack) { try { checkedMeasure(() -> { ThreadBasedUserCrnProvider.doAsInternalActor(() -> { Set<InstanceMetaData> notTerminatedForStack = stack.getAllInstanceMetaDataList().stream() .filter(Predicate.not(InstanceMetaData::isTerminated)) .collect(Collectors.toSet()); Set<InstanceMetaData> checkableInstances = notTerminatedForStack.stream() .filter(Predicate.not(InstanceMetaData::isDeletedOnProvider)) .collect(Collectors.toSet()); int alreadyDeletedCount = notTerminatedForStack.size() - checkableInstances.size(); if (alreadyDeletedCount > 0) { LOGGER.info(":::Auto sync::: Count of already in deleted on provider side state: {}", alreadyDeletedCount); } if (!checkableInstances.isEmpty()) { SyncResult syncResult = freeipaChecker.getStatus(stack, checkableInstances); List<ProviderSyncResult> results = providerChecker.updateAndGetStatuses(stack, checkableInstances); <START> if (results.size() > 0) { <END> updateStackStatus(stack, syncResult, results, alreadyDeletedCount); } } }); return null; }, LOGGER, ":::Auto sync::: freeipa stack sync in {}ms"); } catch (Exception e) { LOGGER.info(":::Auto sync::: Error occurred during freeipa sync: {}", e.getMessage(), e); } }</code><technical_language>please isEmpty()</technical_language>

Target:
private void syncAStack(Stack stack) { try { checkedMeasure(() -> { ThreadBasedUserCrnProvider.doAsInternalActor(() -> { Set<InstanceMetaData> notTerminatedForStack = stack.getAllInstanceMetaDataList().stream() .filter(Predicate.not(InstanceMetaData::isTerminated)) .collect(Collectors.toSet()); Set<InstanceMetaData> checkableInstances = notTerminatedForStack.stream() .filter(Predicate.not(InstanceMetaData::isDeletedOnProvider)) .collect(Collectors.toSet()); int alreadyDeletedCount = notTerminatedForStack.size() - checkableInstances.size(); if (alreadyDeletedCount > 0) { LOGGER.info(":::Auto sync::: Count of already in deleted on provider side state: {}", alreadyDeletedCount); } if (!checkableInstances.isEmpty()) { SyncResult syncResult = freeipaChecker.getStatus(stack, checkableInstances); List<ProviderSyncResult> results = providerChecker.updateAndGetStatuses(stack, checkableInstances); if (!results.isEmpty()) { updateStackStatus(stack, syncResult, results, alreadyDeletedCount); } else { LOGGER.debug("results is empty, skip update"); } } }); return null; }, LOGGER, ":::Auto sync::: freeipa stack sync in {}ms"); } catch (Exception e) { LOGGER.info(":::Auto sync::: Error occurred during freeipa sync: {}", e.getMessage(), e); } }
Source:
<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { requestsReceived.incrementAndGet(); if (latch.isPresent()) { try { latch.get().await(); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> } } response.setStatus(SC_OK); if (request.getUserPrincipal() != null) { response.getOutputStream().write(request.getUserPrincipal().getName().getBytes()); } response.setHeader("X-Protocol", request.getProtocol()); try { if (request.getParameter("sleep") != null) { Thread.sleep(Long.parseLong(request.getParameter("sleep"))); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }</code><technical_language>Is this used</technical_language>

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) { try { if (requestLatch != null) { requestLatch.countDown(); } response.setStatus(SC_OK); response.setHeader("X-Protocol", request.getProtocol()); if (request.getUserPrincipal() != null) { response.getOutputStream().write(request.getUserPrincipal().getName().getBytes()); } if (request.getParameter("sleep") != null) { Thread.sleep(Long.parseLong(request.getParameter("sleep"))); } } catch (Exception t) { if (t instanceof InterruptedException) { Thread.currentThread().interrupt(); } exception.set(t); } }
Source:
<code>public RevisionResource parse(ChangeResource change, IdString id) throws ResourceNotFoundException, OrmException { <START> if (id.equals("current")) { <END> PatchSet.Id p = change.getChange().currentPatchSetId(); PatchSet ps = p != null ? dbProvider.get().patchSets().get(p) : null; if (ps == null) { throw new ResourceNotFoundException(id); } return new RevisionResource(change, ps); } List<PatchSet> match = Lists.newArrayListWithExpectedSize(2); for (PatchSet ps : find(change, id.get())) { Change.Id changeId = ps.getId().getParentKey(); if (changeId.equals(change.getChange().getId()) && change.getControl().isPatchVisible(ps, dbProvider.get())) { match.add(ps); } } if (match.size() != 1) { throw new ResourceNotFoundException(id); } return new RevisionResource(change, match.get(0)); }</code><technical_language>please update in rest-api-changes.txt description of revision-id 'current' used</technical_language>

Target:
public RevisionResource parse(ChangeResource change, IdString id) throws ResourceNotFoundException, OrmException { if (id.equals("current")) { PatchSet.Id p = change.getChange().currentPatchSetId(); PatchSet ps = p != null ? dbProvider.get().patchSets().get(p) : null; if (ps != null && visible(change, ps)) { return new RevisionResource(change, ps); } throw new ResourceNotFoundException(id); } List<PatchSet> match = Lists.newArrayListWithExpectedSize(2); for (PatchSet ps : find(change, id.get())) { Change.Id changeId = ps.getId().getParentKey(); if (changeId.equals(change.getChange().getId()) && visible(change, ps)) { match.add(ps); } } if (match.size() != 1) { throw new ResourceNotFoundException(id); } return new RevisionResource(change, match.get(0)); }
Source:
<code>protected void onNewIntent(Intent intent) { super.onNewIntent(intent); <START> assert intent != null; <END> if (intent.getExtras() != null){ if (intent.getExtras().containsKey(RES_ITEM)) bottomNavigation.setSelectedItemId(intent.getIntExtra(RES_ITEM, R.id.dashboard)); else if (intent.getExtras().containsKey(NOTIFICATION_DIALOG)){ new ConfirmDialogFragment.Builder() .withTitle(intent.getExtras().getString("title")) .withMessage(intent.getExtras().getString("message")) .withNegativeButton("") .withPositiveButton(getString(R.string.Modal_OK)) .build().show(getSupportFragmentManager(), null); } } }</code><technical_language>do want assert here</technical_language>

Target:
protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.getExtras() != null){ if (intent.getExtras().containsKey(RES_ITEM)) bottomNavigation.setSelectedItemId(intent.getIntExtra(RES_ITEM, R.id.dashboard)); else if (intent.getExtras().containsKey(NOTIFICATION_DIALOG)){ new ConfirmDialogFragment.Builder() .withTitle(intent.getExtras().getString("title")) .withMessage(intent.getExtras().getString("message")) .withNegativeButton("") .withPositiveButton(getString(R.string.Modal_OK)) .build().show(getSupportFragmentManager(), null); } } }
Source:
<code>public static String revisionHistoryToJson(List<DocumentRevision> history, List<? extends Attachment> attachments) { Preconditions.checkNotNull(history, "History must not be null"); <START> Preconditions.checkArgument(history.size() > 0, "History must not have at least one DocumentRevision."); <END> Preconditions.checkArgument(checkHistoryIsInDescendingOrder(history), "History must be in descending order."); DocumentRevision currentNode = history.get(0); Map<String, Object> m = currentNode.asMap(); if (attachments != null && !attachments.isEmpty()) { addAttachments(attachments, m, CouchUtils.generationFromRevId(currentNode.getRevision())); } m.put(CouchConstants._revisions, createRevisions(history)); return sJsonHelper.toJson(m); }</code><technical_language>correct error message while changing stuff here</technical_language>

Target:
public static String revisionHistoryToJson(List<DocumentRevision> history, List<? extends Attachment> attachments) { Preconditions.checkNotNull(history, "History must not be null"); Preconditions.checkArgument(history.size() > 0, "History must have at least one DocumentRevision."); Preconditions.checkArgument(checkHistoryIsInDescendingOrder(history), "History must be in descending order."); DocumentRevision currentNode = history.get(0); Map<String, Object> m = currentNode.asMap(); if (attachments != null && !attachments.isEmpty()) { addAttachments(attachments, m, CouchUtils.generationFromRevId(currentNode.getRevision())); } m.put(CouchConstants._revisions, createRevisions(history)); return sJsonHelper.toJson(m); }
Source:
<code><START> protected static void assignSSLContextProvider(BrokerHandlerConfig config, MqttBrokerConnection connection, <END> PinnedCallback callback) throws IllegalArgumentException { final PinTrustManager trustManager = new PinTrustManager(); connection.setSSLContextProvider(new PinningSSLContextProvider(trustManager)); trustManager.setCallback(callback); if (config.certificatepin) { try { Pin pin; if (StringUtils.isBlank(config.certificate)) { pin = Pin.LearningPin(PinType.CERTIFICATE_TYPE); } else { String[] split = config.certificate.split(":"); if (split.length != 2) { throw new NoSuchAlgorithmException("Algorithm is missing"); } pin = Pin.CheckingPin(PinType.CERTIFICATE_TYPE, new PinMessageDigest(split[0]), HexUtils.hexToBytes(split[1])); } trustManager.addPinning(pin); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } } if (config.publickeypin) { try { Pin pin; if (StringUtils.isBlank(config.publickey)) { pin = Pin.LearningPin(PinType.PUBLIC_KEY_TYPE); } else { String[] split = config.publickey.split(":"); if (split.length != 2) { throw new NoSuchAlgorithmException("Algorithm is missing"); } pin = Pin.CheckingPin(PinType.PUBLIC_KEY_TYPE, new PinMessageDigest(split[0]), HexUtils.hexToBytes(split[1])); } trustManager.addPinning(pin); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } } }</code><technical_language>guess this static is fact instance variables involved. this moved a util class static again. wdyt</technical_language>

Target:
protected void assignSSLContextProvider(BrokerHandlerConfig config, MqttBrokerConnection connection, PinnedCallback callback) throws IllegalArgumentException { final PinTrustManager trustManager = new PinTrustManager(); connection.setSSLContextProvider(new PinningSSLContextProvider(trustManager)); trustManager.setCallback(callback); if (config.certificatepin) { try { Pin pin; if (StringUtils.isBlank(config.certificate)) { pin = Pin.LearningPin(PinType.CERTIFICATE_TYPE); } else { String[] split = config.certificate.split(":"); if (split.length != 2) { throw new NoSuchAlgorithmException("Algorithm is missing"); } pin = Pin.CheckingPin(PinType.CERTIFICATE_TYPE, new PinMessageDigest(split[0]), HexUtils.hexToBytes(split[1])); } trustManager.addPinning(pin); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } } if (config.publickeypin) { try { Pin pin; if (StringUtils.isBlank(config.publickey)) { pin = Pin.LearningPin(PinType.PUBLIC_KEY_TYPE); } else { String[] split = config.publickey.split(":"); if (split.length != 2) { throw new NoSuchAlgorithmException("Algorithm is missing"); } pin = Pin.CheckingPin(PinType.PUBLIC_KEY_TYPE, new PinMessageDigest(split[0]), HexUtils.hexToBytes(split[1])); } trustManager.addPinning(pin); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } } }
Source:
<code>public Dac findById(Integer dacId) { Dac dac = dacDAO.findById(dacId); List<User> chairs = dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.CHAIRPERSON.getRoleId()); List<User> members = dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.MEMBER.getRoleId()); if (dac != null) { dac.setChairpersons(chairs); dac.setMembers(members); } <START> return dac; <END> }</code><technical_language>I return dac if null (and I Objects.nonNull for this). like: suggestion if (Objects.nonNull(dac)) { dac.setChairpersons(chairs); dac.setMembers(members); return dac; } throw new NotFoundException("Could find DAC provided id: " + dacId);</technical_language>

Target:
public Dac findById(Integer dacId) { Dac dac = dacDAO.findById(dacId); List<User> chairs = dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.CHAIRPERSON.getRoleId()); List<User> members = dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.MEMBER.getRoleId()); if (Objects.nonNull(dac)) { dac.setChairpersons(chairs); dac.setMembers(members); return dac; } throw new NotFoundException("Could not find DAC with the provided id: " + dacId); }
Source:
<code>public long getSerial() { <START> return getAttribute(SERIAL).incrementAndGet(); <END> }</code><technical_language>prefer setAttribute(getAttribute(SERIAL) + 1), type Long AtomicLong. some point hook in setAttribute for more efficient persistence a datagrid..</technical_language>

Target:
public long getSerial() { long next = getAttribute(SERIAL) + 1; setAttribute(SERIAL, next); return next; }
Source:
<code>protected <T> Optional<T> resolveDefaultProperty(IClientConfigKey<T> key) { return Optional.ofNullable(defaultProperties.get(key.key())) .map(value -> { final Class type = key.type(); if (!value.getClass().equals(type)) { if (value.getClass().equals(String.class)) { final String strValue = (String) value; if (Integer.class.equals(type)) { return (T)Integer.valueOf(strValue); } else if (Boolean.class.equals(type)) { return (T)Boolean.valueOf(strValue); } else if (Float.class.equals(type)) { return(T) Float.valueOf(strValue); } else if (Long.class.equals(type)) { return (T)Long.valueOf(strValue); } else if (Double.class.equals(type)) { return (T)Double.valueOf(strValue); } else if (TimeUnit.class.equals(type)) { return (T)TimeUnit.valueOf(strValue); } else { <START> LOG.warn("Unsupported value type `{}` for key `{}` with value `{}`", <END> type, key.key(), value); return null; } } else { LOG.warn("Invalid value type for key `{}`. Expecting `{}`. Got `{}` for value `{}`", key.key(), type, value.getClass(), value); return null; } } else { return (T)value; } }); }</code><technical_language>do similar in a catch Exception block in case of parse methods fails</technical_language>

Target:
protected <T> Optional<T> resolveDefaultProperty(IClientConfigKey<T> key) { return Optional.ofNullable(defaultProperties.get(key.key())) .map(value -> { final Class type = key.type(); if (!value.getClass().equals(type)) { try { if (value.getClass().equals(String.class)) { final String strValue = (String) value; if (Integer.class.equals(type)) { return (T) Integer.valueOf(strValue); } else if (Boolean.class.equals(type)) { return (T) Boolean.valueOf(strValue); } else if (Float.class.equals(type)) { return (T) Float.valueOf(strValue); } else if (Long.class.equals(type)) { return (T) Long.valueOf(strValue); } else if (Double.class.equals(type)) { return (T) Double.valueOf(strValue); } else if (TimeUnit.class.equals(type)) { return (T) TimeUnit.valueOf(strValue); } else { throw new IllegalArgumentException("Unsupported value type `" + type + "'"); } } else { throw new IllegalArgumentException("Incompatible value type `" + value.getClass() + "` while expecting '" + type + "`"); } } catch (Exception e) { throw new IllegalArgumentException("Error parsing value '" + value + "' for '" + key.key() + "'", e); } } else { return (T)value; } }); }
Source:
<code>public void setup() throws InvalidKeyException, NoSuchAlgorithmException { if (interceptorManager.isPlaybackMode()) { connectionString = "Endpoint=http://localhost:8080;Id=0000000000000;Secret=MDAwMDAw"; <START> tokenCredential = null; <END> String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(tokenCredential) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(tokenCredential) .endpoint(endpoint) .addPolicy(interceptorManager.getRecordPolicy()) .buildClient(); } }</code><technical_language>do set this null pass builder</technical_language>

Target:
public void setup() throws InvalidKeyException, NoSuchAlgorithmException { if (interceptorManager.isPlaybackMode()) { connectionString = "Endpoint=http://localhost:8080;Id=0000000000000;Secret=MDAwMDAw"; String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .connectionString(connectionString) .endpoint(endpoint) .httpClient(interceptorManager.getPlaybackClient()) .buildClient(); } else { connectionString = Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); tokenCredential = new DefaultAzureCredentialBuilder().build(); String endpoint = new ConfigurationClientCredentials(connectionString).getBaseUri(); client = new ConfigurationClientBuilder() .credential(tokenCredential) .endpoint(endpoint) .addPolicy(interceptorManager.getRecordPolicy()) .buildClient(); } }
Source:
<code>public void createFromSelectableStringAttributeAndSelectableNumberAttribute() { mockProductAttributeSettings(STRING_ATTRIBUTE_NAME, NUMBER_ATTRIBUTE_NAME); final List<ProductVariant> variants = Arrays.asList(mockProductVariant(stringAttribute1, numberAttribute1), mockProductVariant(stringAttribute2, numberAttribute2)); final AttributeWithProductType attributeWithProductType = AttributeWithProductType.of(stringAttribute1, productTypeRef); <START> <END> final SelectableProductAttributeViewModel attributeViewModel = viewModelFactory.create(variants, attributeWithProductType); final Map<String, Map<String, List<String>>> selectData = attributeViewModel.getSelectData(); assertThat(selectData).isNotEmpty(); final Map<String, List<String>> attribute1Data = selectData.get(stringAttribute1.getValueAsString()); assertThat(attribute1Data).containsKey(NUMBER_ATTRIBUTE_NAME); assertThat(attribute1Data.get(NUMBER_ATTRIBUTE_NAME)).containsExactly("120"); final Map<String, List<String>> attribute2Data = selectData.get(stringAttribute2.getValueAsString()); assertThat(attribute2Data).containsKey(NUMBER_ATTRIBUTE_NAME); assertThat(attribute2Data.get(NUMBER_ATTRIBUTE_NAME)).containsExactly("130"); }</code><technical_language>I type Map<String, Map<String, List<String>> is easy test nicely reduced. For example, instead of 5 assertions (11 lines) below, have: assertThat(attributeViewModel.getSelectData()) .hasSize(2) .containsEntry(stringAttribute1.getValueAsString(), singletonMap(NUMBER_ATTRIBUTE_NAME, singletonList("120"))) .containsEntry(stringAttribute2.getValueAsString(), singletonMap(NUMBER_ATTRIBUTE_NAME, singletonList("130"))); extracting entry a method simplifies "singleton" structures. ways, a suggestion</technical_language>

Target:
public void createFromSelectableStringAttributeAndSelectableNumberAttribute() { final String stringValue = "v1"; final AttributeWithProductType stringAttributeWithProductType = attributeWithProductType(STRING_ATTRIBUTE_NAME, AttributeAccess.ofString(), stringValue); when(fakeAttributeFormatter.encodedValue(eq(stringAttributeWithProductType))).thenReturn(stringValue); final AttributeWithProductType numberAttributeWithProductType = attributeWithProductType(NUMBER_ATTRIBUTE_NAME, AttributeAccess.ofDouble(), 12.0); when(fakeAttributeFormatter.encodedValue(eq(numberAttributeWithProductType))).thenReturn("120"); mockProductAttributeSettings(STRING_ATTRIBUTE_NAME, NUMBER_ATTRIBUTE_NAME); final ProductVariant productVariant = mockProductVariant(stringAttributeWithProductType, numberAttributeWithProductType); final List<ProductVariant> variants = Collections.singletonList(productVariant); final SelectableProductAttributeViewModel attributeViewModel = viewModelFactory.create(variants, stringAttributeWithProductType); assertThat(attributeViewModel.getSelectData()) .hasSize(1) .containsEntry(stringValue, singletonMap(NUMBER_ATTRIBUTE_NAME, singletonList("120"))); }
Source:
<code>public void perform(final IServer server) { IWorkbenchPart part = null; try { part = bringViewToFront(viewId); } catch(PartInitException pie) { <START> WTPOveridePlugin.getInstance().getLog().log(new Status(IStatus.ERROR, WTPOveridePlugin.PLUGIN_ID, "Error loading MBean Explorer", pie)); <END> } if( part != null ) { final CommonNavigator view = (CommonNavigator) part.getAdapter(CommonNavigator.class); if (view != null) { Display.getDefault().asyncExec(new Runnable() { public void run() { Object connection = adaptToViewItem(server); if( connection != null ) { view.getCommonViewer().collapseAll(); view.getCommonViewer().expandToLevel(2); ISelection sel = new StructuredSelection(new Object[] { connection }); view.getCommonViewer().setSelection(sel, true); } } }); } } }</code><technical_language>wrong logger</technical_language>

Target:
public void perform(final IServer server) { IWorkbenchPart part = null; try { part = bringViewToFront(viewId); } catch(PartInitException pie) { CDKCoreActivator.pluginLog().logError("Error opening view " + viewId, pie); } if( part != null ) { final CommonNavigator view = (CommonNavigator) part.getAdapter(CommonNavigator.class); if (view != null && view.getCommonViewer() != null && view.getCommonViewer().getTree() != null && !view.getCommonViewer().getTree().isDisposed()){ Object connection = adaptToViewItem(server); if( connection != null ) { view.getCommonViewer().collapseAll(); view.getCommonViewer().expandToLevel(2); ISelection sel = new StructuredSelection(new Object[] { connection }); view.getCommonViewer().setSelection(sel, true); } } } }
Source:
<code>private void openSubscriptionFilter() { SubscriptionFilterDialog filterDialog = new SubscriptionFilterDialog(getContext(), autoDownload,keepUpdated,autoDelete) { @Override protected void updateFilter(ArrayList<SubscriptionFilter> filterValues) { currentFeeds = new ArrayList<>(); <START> for(SubscriptionFilter filter: filterValues){ <END> switch (filter.getOption()) { case STRING_AUTO_DOWNLOAD: autoDownload = filter.getValue(); break; case STRING_KEEP_UPDATED: keepUpdated = filter.getValue(); break; case STRING_AUTO_DELETE: autoDelete = filter.getValue(); break; } } prefs.edit().putString(PREF_AUTO_DOWNLOAD,autoDownload).apply(); prefs.edit().putString(PREF_KEEP_UPDATED,keepUpdated).apply(); prefs.edit().putString(PREF_AUTO_DELETE,autoDelete).apply(); loadFilter(); } }; filterDialog.openDialog(); }</code><technical_language>Please add spaces: for (SubscriptionFilter filter : filterValues) { ^ ^ ^ Also, please add similar spaces if statements. I AntennaPod is consistent (around 30% of code spaces) in order unify style, I want new code style</technical_language>

Target:
private void openSubscriptionFilter() { SubscriptionFilter.AutoDownload autoDownload= SubscriptionFilter.AutoDownload.valueOf(prefs.getString(PREF_AUTO_DOWNLOAD, SubscriptionFilter.STRING_NO_FILTER)); SubscriptionFilter.KeepUpdated keepUpdated = SubscriptionFilter.KeepUpdated.valueOf(prefs.getString(PREF_KEEP_UPDATED, SubscriptionFilter.STRING_NO_FILTER)); SubscriptionFilter.AutoDelete autoDelete = SubscriptionFilter.AutoDelete.valueOf(prefs.getString(PREF_AUTO_DELETE, SubscriptionFilter.STRING_NO_FILTER)); SubscriptionFilterDialog filterDialog = new SubscriptionFilterDialog(getContext(), autoDownload, keepUpdated, autoDelete) { @Override protected void updateFilter(SubscriptionFilter.AutoDownload autoDownload, SubscriptionFilter.KeepUpdated keepUpdated, SubscriptionFilter.AutoDelete autoDelete) { currentFeeds = new ArrayList<>(); prefs.edit().putString(PREF_AUTO_DOWNLOAD,autoDownload.name()).apply(); prefs.edit().putString(PREF_KEEP_UPDATED,keepUpdated.name()).apply(); prefs.edit().putString(PREF_AUTO_DELETE,autoDelete.name()).apply(); loadFilter(autoDownload, keepUpdated, autoDelete); } }; filterDialog.openDialog().show(); }
Source:
<code>public void testBackgroundAppFunctionality() throws Exception { openStartActivity(); driver().backgroundApp(); <START> String currentActivity = execCmd(System.getenv("ANDROID_HOME")+"/platform-tools/"+"adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"); <END> Assert.assertTrue(currentActivity.contains("com.android.launcher2.Launcher")); driver().resumeApp(); currentActivity = execCmd(System.getenv("ANDROID_HOME")+"/platform-tools/"+"adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"); Assert.assertTrue(currentActivity.contains("io.selendroid.testapp.HomeScreenActivity")); }</code><technical_language>want move this line a private method, code duplication of this line</technical_language>

Target:
public void testBackgroundAppFunctionality() throws Exception { openStartActivity(); driver().backgroundApp(); String currentActivity = adbCurrentActivity(); Assert.assertTrue(currentActivity.contains("com.android.launcher2.Launcher")); driver().resumeApp(); currentActivity = adbCurrentActivity(); Assert.assertTrue(currentActivity.contains("io.selendroid.testapp.HomeScreenActivity")); }
Source:
<code>private static Map<String, VisorBaselineNode> toMapWithResolvedAddresses(Collection<? extends BaselineNode> nodes) { if (F.isEmpty(nodes)) return null; Map<String, VisorBaselineNode> map = new TreeMap<>(); for (BaselineNode node : nodes) { Collection<IgniteBiTuple<String, String>> addrs = Collections.emptyList(); if (node instanceof IgniteClusterNode) { try { addrs = IgniteUtils.toInetAddresses((ClusterNode)node).stream() .map(addr -> new IgniteBiTuple<>(addr.getHostAddress(), addr.getHostName())) .collect(Collectors.toList()); <START> } catch (IgniteCheckedException ex) { <END> throw IgniteUtils.convertException(ex); } } VisorBaselineNode dto = new VisorBaselineNode(node, addrs); map.put(dto.getConsistentId(), dto); } return map; }</code><technical_language>} catch (IgniteCheckedException ex) { throw IgniteUtils.convertException(ex); }</technical_language>

Target:
private static Map<String, VisorBaselineNode> toMapWithResolvedAddresses(Collection<? extends BaselineNode> nodes) { if (F.isEmpty(nodes)) return null; Map<String, VisorBaselineNode> map = new TreeMap<>(); for (BaselineNode node : nodes) { Collection<VisorBaselineNode.ResolvedAddresses> addrs = new ArrayList<>(); if (node instanceof IgniteClusterNode) { for (InetAddress inetAddress: resolveInetAddresses((ClusterNode)node)) addrs.add(new VisorBaselineNode.ResolvedAddresses(inetAddress)); } VisorBaselineNode dto = new VisorBaselineNode(node, addrs); map.put(dto.getConsistentId(), dto); } return map; }
Source:
<code>protected Event doExecute(final RequestContext requestContext) { val authentication = WebUtils.getAuthentication(requestContext); val principal = authentication.getPrincipal(); val flowId = requestContext.getActiveFlow().getId(); val applicationContext = ApplicationContextProvider.getApplicationContext(); <START> val provider = (DuoMultifactorAuthenticationProvider) <END> MultifactorAuthenticationUtils.getMultifactorAuthenticationProviderById(flowId, applicationContext).orElseThrow(AuthenticationException::new); val enrollEvent = new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_ENROLL); val denyEvent = new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_DENY); val unavailableEvent = new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_UNAVAILABLE); val errorEvent = new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_ERROR); val duoAuthenticationService = provider.getDuoAuthenticationService(); val account = duoAuthenticationService.getDuoUserAccount(principal.getId()); switch (account.getStatus()) { case ENROLL: if (!StringUtils.isEmpty(provider.getRegistrationUrl())) { LOGGER.error("Duo webflow resolved to event ENROLL, but no registration url was provided."); return errorEvent; } requestContext.getFlowScope().put("duoRegistrationUrl", provider.getRegistrationUrl()); return enrollEvent; case ALLOW: return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_BYPASS); case DENY: return denyEvent; case UNAVAILABLE: return unavailableEvent; default: } return success(); }</code><technical_language>nitpick: fix wrapping</technical_language>

Target:
protected Event doExecute(final RequestContext requestContext) throws Exception { val authentication = WebUtils.getAuthentication(requestContext); val principal = authentication.getPrincipal(); val duoAuthenticationService = provider.getDuoAuthenticationService(); val account = duoAuthenticationService.getDuoUserAccount(principal.getId()); if (account.getStatus() == DuoUserAccountAuthStatus.ENROLL) { if (StringUtils.isBlank(provider.getRegistrationUrl())) { LOGGER.error("Duo webflow resolved to event ENROLL, but no registration url was provided."); return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_ERROR); } requestContext.getFlowScope().put("duoRegistrationUrl", provider.getRegistrationUrl()); return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_ENROLL); } if (account.getStatus() == DuoUserAccountAuthStatus.ALLOW) { return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_BYPASS); } if (account.getStatus() == DuoUserAccountAuthStatus.DENY) { return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_DENY); } if (account.getStatus() == DuoUserAccountAuthStatus.UNAVAILABLE) { return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_UNAVAILABLE); } return success(); }
Source:
<code>public O evaluate(IotasEvent iotasEvent) throws ScriptException { log.debug("Evaluating {}" + iotasEvent); if (iotasEvent != null) { <START> for (Map.Entry<String, Object> fieldAndValue : iotasEvent.getFieldsAndValues().entrySet()) { <END> log.debug("{Putting into engine key = {}, val = {}", fieldAndValue.getKey(), fieldAndValue.getValue()); scriptEngine.put(fieldAndValue.getKey(), fieldAndValue.getValue()); } } final O result = (O) scriptEngine.eval(scriptText); log.debug("Expression evaluated to [{}]", scriptText, result); return result; }</code><technical_language>![image](<LINK_0></technical_language>

Target:
public O evaluate(IotasEvent iotasEvent) throws ScriptException { log.debug("Evaluating with [{}]", expression, iotasEvent); O evaluatedResult = null; if (iotasEvent != null) { final Map<String, Object> fieldsToValues = iotasEvent.getFieldsAndValues(); if (fieldsToValues != null) { getEngineScopeBindings().putAll(fieldsToValues); log.debug("Set script binding to [{}]", fieldsToValues); evaluatedResult = (O) scriptEngine.eval(expression); log.debug("Expression evaluated to [{}]", expression, evaluatedResult); } } return evaluatedResult; }
Source:
<code>public void testDeleteCommentAsAdmin() { assertTrue(this.commentsTab.isCommentFormShown()); this.commentsTab.postComment(COMMENT_CONTENT, true); this.commentsTab.deleteCommentByID(this.commentsTab.getCommentID(COMMENT_CONTENT)); <START> assertEquals(this.commentsTab.getCommentID(COMMENT_CONTENT), -1); <END> }</code><technical_language>sounds expected obtained values swapped</technical_language>

Target:
public void testDeleteCommentAsAdmin() { assertTrue(this.commentsTab.isCommentFormShown()); this.commentsTab.postComment(COMMENT_CONTENT, true); this.commentsTab.deleteCommentByID(this.commentsTab.getCommentID(COMMENT_CONTENT)); assertEquals(-1, this.commentsTab.getCommentID(COMMENT_CONTENT)); }
Source:
<code>public void resetAuthenticator() { if (useProxyAuth && useHttpsServer && !okUsable) { Authenticator.setDefault(null); } <START> System.setProperty("jdk.http.auth.tunneling.disabledSchemes", defaultDisabledList); <END> }</code><technical_language>I understand purpose of this - set jdk.http.auth.tunneling.disabledSchemes in this test, is reset needed</technical_language>

Target:
public void resetAuthenticator() { if (useProxyAuth && useHttpsServer && !okUsable) { Authenticator.setDefault(null); System.setProperty("jdk.http.auth.tunneling.disabledSchemes", defaultDisabledList); } }
Source:
<code>public static boolean execute(WebhookResponse webhook) throws IOException { return execute(webhook.getAnonymousExecutionURI()); <START> } <END></code><technical_language>perfect sense. Thanks for explaining</technical_language>

Target:
public static boolean execute(WebhookResponse webhook) throws IOException { return execute(webhook.getAnonymousExecutionURI().get()); }
Source:
<code>synchronized void deleteOldRedisplayedInAppMessages() { long sixMonthsAgo = System.currentTimeMillis() / 1000 - SIX_MONTHS_TIME_SECONDS; SQLiteDatabase writableDb = dbHelper.getWritableDbWithRetries(); writableDb.delete(OneSignalDbContract.InAppMessageTable.TABLE_NAME, <START> OneSignalDbContract.InAppMessageTable.COLUMN_NAME_LAST_DISPLAY + "<?", <END> new String[]{String.valueOf(sixMonthsAgo)}); writableDb.close(); }</code><technical_language>Space <? -> <</technical_language>

Target:
synchronized void deleteOldRedisplayedInAppMessages() { long sixMonthsAgo = System.currentTimeMillis() / 1000 - OS_IAM_MAX_CACHE_TIME; SQLiteDatabase writableDb = dbHelper.getWritableDbWithRetries(); writableDb.delete(OneSignalDbContract.InAppMessageTable.TABLE_NAME, OneSignalDbContract.InAppMessageTable.COLUMN_NAME_LAST_DISPLAY + "< ?", new String[]{String.valueOf(sixMonthsAgo)}); writableDb.close(); }
Source:
<code>public boolean listPartitionsSpecByExpr(String catName, String dbName, String tblName, byte[] expr, String defaultPartitionName, short maxParts, List<PartitionSpec> result) throws TException { assert result != null; PartitionsByExprRequest req = new PartitionsByExprRequest( dbName, tblName, ByteBuffer.wrap(expr)); if (defaultPartitionName != null) { req.setDefaultPartitionName(defaultPartitionName); } if (maxParts >= 0) { req.setMaxParts(maxParts); } PartitionsSpecByExprResult r; try { r = client.get_partitions_spec_by_expr(req); } catch (TApplicationException te) { if (te.getType() != TApplicationException.UNKNOWN_METHOD && te.getType() != TApplicationException.WRONG_METHOD_NAME) { throw te; } throw new IncompatibleMetastoreException( "Metastore doesn't support listPartitionsByExpr: " + te.getMessage()); } <START> r.setPartitionsSpec(r.getPartitionsSpec()); <END> result.addAll(r.getPartitionsSpec()); return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions(); }</code><technical_language>Is this a noop (getting setting object)</technical_language>

Target:
public boolean listPartitionsSpecByExpr(String catName, String dbName, String tblName, byte[] expr, String defaultPartitionName, short maxParts, List<PartitionSpec> result) throws TException { assert result != null; PartitionsByExprRequest req = new PartitionsByExprRequest( dbName, tblName, ByteBuffer.wrap(expr)); if (defaultPartitionName != null) { req.setDefaultPartitionName(defaultPartitionName); } if (maxParts >= 0) { req.setMaxParts(maxParts); } PartitionsSpecByExprResult r; try { r = client.get_partitions_spec_by_expr(req); } catch (TApplicationException te) { if (te.getType() != TApplicationException.UNKNOWN_METHOD && te.getType() != TApplicationException.WRONG_METHOD_NAME) { throw te; } throw new IncompatibleMetastoreException( "Metastore doesn't support listPartitionsByExpr: " + te.getMessage()); } r.setPartitionsSpec(FilterUtils.filterPartitionSpecsIfEnabled( isClientFilterEnabled, filterHook, r.getPartitionsSpec())); result.addAll(r.getPartitionsSpec()); return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions(); }
Source:
<code>private GlusterVolumeEntity getReplicateVolume(Guid clusterId) { List<GlusterVolumeEntity> replicateVolumes = getReplicateVolumes(clusterId, getReplicateVolumeTypes()); if (replicateVolumes.size() > 0) { <START> return replicateVolumes.get(0); <END> } return null; }</code><technical_language>Empty line removed here</technical_language>

Target:
private GlusterVolumeEntity getReplicateVolume(Guid clusterId) { List<GlusterVolumeEntity> replicateVolumes = getReplicateVolumes(clusterId, volumeTypes); if (replicateVolumes.size() > 0) { return replicateVolumes.get(0); } return null; }
Source:
<code>public void trackEvent(HttpServletRequest request, String action, PID pid, AccessGroupSet principals) { try { AnalyticsUserData userData = new AnalyticsUserData(request); BriefObjectMetadata briefObject = solrSearchService.getObjectById(new SimpleIdRequest(pid, principals)); <START> trackEvent(userData, briefObject.getParentCollection() == null ? "(no collection)" <END> : briefObject.getParentCollectionName(), "download", briefObject.getTitle() + "|" + pid, null); } catch (Exception e) { log.warn("An exception occurred while recording event on {}", action, pid, e); } }</code><technical_language>i find method call in lines 106-108 a compressed for easy readability. willing break this a simpler steps</technical_language>

Target:
public void trackEvent(HttpServletRequest request, String action, PID pid, AccessGroupSet principals) { try { AnalyticsUserData userData = new AnalyticsUserData(request); BriefObjectMetadata briefObject = solrSearchService.getObjectById(new SimpleIdRequest(pid, principals)); String parentCollection = briefObject.getParentCollection() == null ? "(no collection)" : briefObject.getParentCollectionName(); String viewedObjectLabel = briefObject.getTitle() + "|" + pid; trackEvent(userData, parentCollection, "download", viewedObjectLabel, null); } catch (Exception e) { log.warn("An exception occurred while recording event on {}", action, pid, e); } }
Source:
<code>private static double findUpgradeUnitEfficiency( final ProPurchaseOption ppo, final double strategicValue) { return strategicValue >= 1 <START> ? ppo.getAttackEfficiency() * ppo.getDefenseEfficiency() * ppo.getCost() / ppo.getQuantity() <END> : ppo.getAttackEfficiency() * ppo.getMovement() * ppo.getCost() / ppo.getQuantity(); }</code><technical_language>nit, is some redundancy in conditional branches. consolidated like: double multiplier = (strategicValue >= 1) ? ppo.getDefenseEfficiency() : ppo.getMovement(); return ppo.getAttackEfficiency() * multiplier * ppo.getCost() / ppo.getQuantity(); do think</technical_language>

Target:
private static double findUpgradeUnitEfficiency( final ProPurchaseOption ppo, final double strategicValue) { final double multiplier = (strategicValue >= 1) ? ppo.getDefenseEfficiency() : ppo.getMovement(); return ppo.getAttackEfficiency() * multiplier * ppo.getCost() / ppo.getQuantity(); }
Source:
<code>boolean isCheckInSafe(final ContentletRelationships relationships, final ESIndexAPI esIndexAPI) { if (relationships != null && relationships.getRelationshipsRecords().size() > 0) { boolean isClusterReadOnly = esIndexAPI.isClusterInReadOnlyMode(); if (isClusterReadOnly) { <START> for (ContentletRelationships.ContentletRelationshipRecords records : relationships <END> .getRelationshipsRecords()) { if (!records.getRelationship().isRelationshipField()){ return false; } } } } return true; }</code><technical_language>this code a new method suggestion boolean hasLegacyRelationships(...) { for (ContentletRelationships.ContentletRelationshipRecords records : relationships .getRelationshipsRecords()) { if (!records.getRelationship().isRelationshipField()){ return true; } } return false; }</technical_language>

Target:
boolean isCheckInSafe(final ContentletRelationships relationships, final ESIndexAPI esIndexAPI) { if (relationships != null && relationships.getRelationshipsRecords().size() > 0) { boolean isClusterReadOnly = esIndexAPI.isClusterInReadOnlyMode(); if (isClusterReadOnly && hasLegacyRelationships(relationships)) { return false; } } return true; }
Source:
<code>public void dbIndexShouldBePropagatedCorrectly() { LettuceConnectionFactory factory = new LettuceConnectionFactory(); factory.setDatabase(2); <START> factory.afterPropertiesSet(); <END> StringRedisConnection connectionToDbIndex2 = new DefaultStringRedisConnection(factory.getConnection()); try { String key = "key-in-db-2"; connectionToDbIndex2.set(key, "the wheel of time"); assertThat(connection.get(key), nullValue()); assertThat(connectionToDbIndex2.get(key), notNullValue()); } finally { connectionToDbIndex2.close(); } }</code><technical_language>LettuceConnectionFactory stays open shutdown() RedisClient -> Threads stay alive eat resources. lettuce 3.4 introduce reusable thread pools, hand for tests connection factory</technical_language>

Target:
public void dbIndexShouldBePropagatedCorrectly() { LettuceConnectionFactory factory = new LettuceConnectionFactory(); factory.setDatabase(2); factory.afterPropertiesSet(); ConnectionFactoryTracker.add(factory); StringRedisConnection connectionToDbIndex2 = new DefaultStringRedisConnection(factory.getConnection()); try { String key = "key-in-db-2"; connectionToDbIndex2.set(key, "the wheel of time"); assertThat(connection.get(key), nullValue()); assertThat(connectionToDbIndex2.get(key), notNullValue()); } finally { connectionToDbIndex2.close(); } }
Source:
<code>private static void setRGBLayout( ImageLayout result, RenderedImage reference, boolean hasAlpha) { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm; if (hasAlpha) { int[] nBits = new int[] {8, 8, 8, 8}; cm = new ComponentColorModel( cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); } else { int[] nBits = new int[] {8, 8, 8}; cm = new ComponentColorModel( cs, nBits, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); } SampleModel sm = cm.createCompatibleSampleModel( reference.getSampleModel().getWidth(), <START> reference.getSampleModel().getWidth()); <END> result.setColorModel(cm); result.setSampleModel(sm); }</code><technical_language>code patch this beginning, param reference.getSampleModel().getHeight()</technical_language>

Target:
private static void setRGBLayout( ImageLayout result, RenderedImage reference, boolean hasAlpha) { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm; if (hasAlpha) { int[] nBits = new int[] {8, 8, 8, 8}; cm = new ComponentColorModel( cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); } else { int[] nBits = new int[] {8, 8, 8}; cm = new ComponentColorModel( cs, nBits, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); } SampleModel sampleModel = reference.getSampleModel(); SampleModel sm = cm.createCompatibleSampleModel(sampleModel.getWidth(), sampleModel.getHeight()); result.setColorModel(cm); result.setSampleModel(sm); }
Source:
<code>public void encrypt() { CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil(); try { String encryptedString = Base64.encode(cryptoUtil.encrypt(Base64.decode(passwordString)); String encryptedStringTest = Base64.encode(encryptWithSymmetricKey(Base64.decode(passwordString))); <START> if(!encryptedString.equals(encryptedStringTest)){ <END> Assert.hasText(encryptedString, "Error in encrypting with symmetric key"); } } catch (CryptoException e) { e.printStackTrace(); } }</code><technical_language>check formatting</technical_language>

Target:
public void encrypt() throws CryptoException { try { uploadApp(); String serviceEndpoint = "http://" + context.getInstance().getHosts().get("default") + ":" + (Integer.parseInt(FrameworkConstants.SERVER_DEFAULT_HTTP_PORT) + portOffset) + "/services/DssVerifierService/"; String endpoint = "encrypt"; String contentType = "application/json"; String jsonRequest = "{\"" + endpoint + "\":{\"plainText\":\"" + passwordString + "\"}}"; HttpResponse response = this.getHttpResponse(serviceEndpoint + endpoint, contentType, jsonRequest); String encryptedString = response.getData(); int statusCode = response.getResponseCode(); if (statusCode != 500) { String encryptedStringTest = Base64.encode(encryptWithSymmetricKey(Base64.decode(passwordString))); if (!encryptedString.equals(encryptedStringTest)) { Assert.hasText(encryptedString, "Error in encrypting with symmetric key"); } } } catch (CryptoException e) { throw new CryptoException("Error in encrypting with symmetric key"); } catch (Exception e) { throw new CryptoException("Error in encrypting with symmetric key"); } }
Source:
<code><START> public static Set getBloomFilterColumns(Configuration conf) { <END> String columnNames = conf.get(BLOOM_FILTER_COLUMN_NAMES); if (columnNames != null) { return new HashSet<>(Arrays.asList(columnNames.split(","))); } else { return new HashSet(); } }</code><technical_language>Set<String>? generates compile time warnings generics is introduced</technical_language>

Target:
public static Set<String> getBloomFilterColumns(Configuration conf) { String columnNames = conf.get(BLOOM_FILTER_COLUMN_NAMES); if (columnNames != null) { return new HashSet<>(Arrays.asList(columnNames.split(","))); } else { return new HashSet<>(); } }
Source:
<code>private boolean issueSync(ZooKeeper zk) { String sessionId = Long.toHexString(zk.getSessionId()); ZkAsyncCallbacks.SyncCallbackHandler callbackHandler = new ZkAsyncCallbacks.SyncCallbackHandler(sessionId); final long startT = System.currentTimeMillis(); doAsyncSync(zk, SYNC_PATH, startT, callbackHandler); callbackHandler.waitForSuccess(); KeeperException.Code code = KeeperException.Code.get(callbackHandler.getRc()); if (code == KeeperException.Code.OK) { LOG.info("sycnOnNewSession with sessionID async return code: and proceeds", sessionId, code); return true; } LOG.warn( <START> "sycnOnNewSession with sessionID async return code: and not retryable, stop calling handleNewSession", <END> sessionId, code); return false; }</code><technical_language>I this log of issueSync "stop calling handleNewSession" is logic. This issueSync jus tells sync succeeds not. determine handleNewSession not, right</technical_language>

Target:
private boolean issueSync(ZooKeeper zk) { String sessionId = Long.toHexString(zk.getSessionId()); ZkAsyncCallbacks.SyncCallbackHandler callbackHandler = new ZkAsyncCallbacks.SyncCallbackHandler(sessionId); final long startT = System.currentTimeMillis(); doAsyncSync(zk, SYNC_PATH, startT, callbackHandler); callbackHandler.waitForSuccess(); KeeperException.Code code = KeeperException.Code.get(callbackHandler.getRc()); if (code == KeeperException.Code.OK) { LOG.info("sycnOnNewSession with sessionID async return code: and proceeds", sessionId, code); return true; } return false; }
Source:
<code>public void testHasDefaultAnnotationWithImport() { String name = IsAnnotated.class.getCanonicalName(); TypeElement element = compilation.getElements().getTypeElement(name); AnnotationSpec annotation = AnnotationSpec.get(element.getAnnotationMirrors().get(0)); TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(IsAnnotated.class.getSimpleName()); typeBuilder.addAnnotation(annotation); JavaFile file = JavaFile.builder("com.squareup.javapoet", typeBuilder.build()).build(); assertThat(file.toString()).isEqualTo( "package com.squareup.javapoet;\n" + "\n" + "import java.lang.Double;\n" + "import java.lang.Float;\n" + "import java.lang.Override;\n" + "\n" + "@AnnotationSpecTest.HasDefaultsAnnotation(\n" + " o = AnnotationSpecTest.Breakfast.PANCAKES,\n" + " p = 1701,\n" + " f = 11.1,\n" <START> + " m = {\n 9,\n 8,\n 1\n },\n" <END> + " l = Override.class,\n" + " j = @AnnotationSpecTest.AnnotationA,\n" + " q = @AnnotationSpecTest.AnnotationC(\"bar\"),\n" + " r = {\n Float.class,\n Double.class\n }\n" + ")\n" + "class IsAnnotated {\n" + "}\n" ); }</code><technical_language>more readable logical line physical line (and \n end of lines)</technical_language>

Target:
public void testHasDefaultAnnotationWithImport() { String name = IsAnnotated.class.getCanonicalName(); TypeElement element = compilation.getElements().getTypeElement(name); AnnotationSpec annotation = AnnotationSpec.get(element.getAnnotationMirrors().get(0)); TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(IsAnnotated.class.getSimpleName()); typeBuilder.addAnnotation(annotation); JavaFile file = JavaFile.builder("com.squareup.javapoet", typeBuilder.build()).build(); assertThat(file.toString()).isEqualTo( "package com.squareup.javapoet;\n" + "\n" + "import java.lang.Double;\n" + "import java.lang.Float;\n" + "import java.lang.Override;\n" + "\n" + "@AnnotationSpecTest.HasDefaultsAnnotation(\n" + " o = AnnotationSpecTest.Breakfast.PANCAKES,\n" + " p = 1701,\n" + " f = 11.1,\n" + " m = {\n" + " 9,\n" + " 8,\n" + " 1\n" + " },\n" + " l = Override.class,\n" + " j = @AnnotationSpecTest.AnnotationA,\n" + " q = @AnnotationSpecTest.AnnotationC(\"bar\"),\n" + " r = {\n" + " Float.class,\n" + " Double.class\n" + " }\n" + ")\n" + "class IsAnnotated {\n" + "}\n" ); }