auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ImmutableBitmap fromByteBuffer(ByteBuffer buffer, int numBytes) { <START> if (numBytes == 0) { <END> return null; } buffer.limit(buffer.position() + numBytes); return new WrappedImmutableRoaringBitmap(new ImmutableRoaringBitmap(buffer)); }</code><technical_language>Nullable</technical_language>

Target:
public ImmutableBitmap fromByteBuffer(ByteBuffer buffer, int numBytes) { buffer.limit(buffer.position() + numBytes); return new WrappedImmutableRoaringBitmap(new ImmutableRoaringBitmap(buffer)); }
Source:
<code>public Set<User> getMembers(DateTime when) { <START> if (registered == null) { <END> return Bennu.getInstance().getStudentsSet().stream() .filter(student -> student.getAlumni() != null || student.hasAnyRegistrationInState(RegistrationStateType.CONCLUDED) || student.hasAnyRegistrationInState(RegistrationStateType.STUDYPLANCONCLUDED) || isAlumni(student)) .map(student -> student.getPerson().getUser()) .collect(Collectors.toSet()); } else { return Bennu.getInstance().getAlumnisSet().stream() .filter(alumni -> alumni.getStudent().getPerson().getUser() != null) .map(alumni -> alumni.getStudent().getPerson().getUser()) .filter(user -> isMember(user, when)) .collect(Collectors.toSet()); } }</code><technical_language>false</technical_language>

Target:
public Set<User> getMembers(DateTime when) { Set<Student> students = Bennu.getInstance().getStudentsSet(); if (registered == null) { students = students.stream() .filter(student -> student.getAlumni() != null || hasConcludedRegistration(student) || isAlumni(student)) .collect(Collectors.toSet()); } else if (registered) { students = students.stream().filter(student -> student.getAlumni() != null && isAlumni(student)) .collect(Collectors.toSet()); } else if (!registered) { students = students.stream() .filter(student -> student.getAlumni() == null && hasConcludedRegistration(student) && !isAlumni(student)) .collect(Collectors.toSet()); } if (degree != null) { students = students.stream().filter(student -> isDegreeConcluded(student)).collect(Collectors.toSet()); } return students.stream().map(student -> student.getPerson().getUser()).collect(Collectors.toSet()); }
Source:
<code>public void acronym(String text, String definition) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>pattern is for builder emit content possible, failing. Consider like: characters(format("{0}({1})",text,definition));</technical_language>

Target:
public void acronym(String text, String definition) { assertOpenBlock(); try { currentBlock.write(text); currentBlock.write('('); currentBlock.write(definition); currentBlock.write(')'); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>private void writeTestReportDocuments(Set<String> combinedTests, Map<String, List<Report.Test>> testsByName) { for (Map.Entry<String, List<Report.Test>> entry : testsByName.entrySet()) { if (combinedTests.contains(entry.getKey())) { continue; } TestAggregations ta = new TestAggregations(entry.getKey(), entry.getValue()); TestReportDocument testReport = new TestReportDocument(ta, targetDir, testReportConfig); freemarker.template.Configuration cfg = initConfig(); try { testReport.createReportDirectory(); testReport.createTestCharts(); Template reportTemplate = cfg.getTemplate("testReport.ftl"); PrintWriter printWriter = new PrintWriter(targetDir + File.separator + "test_" + testReport.testName + ".html"); Map root = new HashMap(); root.put("testReport", testReport); root.put("enums", DefaultObjectWrapper.getDefaultInstance().getEnumModels()); reportTemplate.process(root, printWriter); <START> printWriter.close(); <END> } catch (Exception e) { log.error("Templating exception", e); } } }</code><technical_language>piece of code is multiple times, refactor a common method</technical_language>

Target:
private void writeTestReportDocuments(Set<String> combinedTests, Map<String, List<Report.Test>> testsByName) { for (Map.Entry<String, List<Report.Test>> entry : testsByName.entrySet()) { if (combinedTests.contains(entry.getKey())) { continue; } TestAggregations ta = new TestAggregations(entry.getKey(), entry.getValue()); TestReportDocument testReport = new TestReportDocument(ta, targetDir, testReportConfig); testReport.createReportDirectory(); testReport.createTestCharts(); Map root = new HashMap(); root.put("testReport", testReport); root.put("enums", DefaultObjectWrapper.getDefaultInstance().getEnumModels()); processTemplate(root, targetDir, "test_" + testReport.testName + ".html", "testReport.ftl"); } }
Source:
<code>public void preQuery(final UpToken token, final QueryHandler completeHandler) { final ZonesInfo zonesInfo = getZonesInfo(token); if (zonesInfo != null) { completeHandler.complete(0, null, null); return; } <START> final RequestTranscation transcation = createUploadRequestTranscation(token); <END> transcation.quertUploadHosts(true, new RequestTranscation.RequestCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response) { if (responseInfo != null && responseInfo.isOK() && response != null){ ZonesInfo zonesInfoP = ZonesInfo.createZonesInfo(response); ZonesInfoMap.put(token.index(), zonesInfoP); completeHandler.complete(0, responseInfo, requestMetrics); } else { if (responseInfo.isNetworkBroken()){ completeHandler.complete(ResponseInfo.NetworkError, responseInfo, requestMetrics); } else { ZonesInfo zonesInfoP = FixedZone.localsZoneInfo().getZonesInfo(token); ZonesInfoMap.put(token.index(), zonesInfoP); completeHandler.complete(0, responseInfo, requestMetrics); } } destoryUploadRequestTranscation(transcation); } }); }</code><technical_language>RequestTranscation => RequestTransaction transcation => transaction</technical_language>

Target:
public void preQuery(final UpToken token, final QueryHandler completeHandler) { final ZonesInfo zonesInfo = getZonesInfo(token); if (zonesInfo != null) { completeHandler.complete(0, null, null); return; } final RequestTransaction transaction = createUploadRequestTransaction(token); transaction.queryUploadHosts(true, new RequestTransaction.RequestCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response) { if (responseInfo != null && responseInfo.isOK() && response != null){ ZonesInfo zonesInfoP = ZonesInfo.createZonesInfo(response); ZonesInfoMap.put(token.index(), zonesInfoP); completeHandler.complete(0, responseInfo, requestMetrics); } else { if (responseInfo.isNetworkBroken()){ completeHandler.complete(ResponseInfo.NetworkError, responseInfo, requestMetrics); } else { ZonesInfo zonesInfoP = FixedZone.localsZoneInfo().getZonesInfo(token); ZonesInfoMap.put(token.index(), zonesInfoP); completeHandler.complete(0, responseInfo, requestMetrics); } } destroyUploadRequestTransaction(transaction); } }); }
Source:
<code><START> private boolean isSwrveRemoteNotification(final Bundle msg) { <END> Object rawId = msg.get(SwrveGcmConstants.SWRVE_TRACKING_KEY); String msgId = (rawId != null) ? rawId.toString() : null; return !SwrveHelper.isNullOrEmpty(msgId); }</code><technical_language>is this longer static</technical_language>

Target:
protected boolean isSwrveRemoteNotification(final Bundle msg) { Object rawId = msg.get(SwrveGcmConstants.SWRVE_TRACKING_KEY); String msgId = (rawId != null) ? rawId.toString() : null; return !SwrveHelper.isNullOrEmpty(msgId); }
Source:
<code>public final boolean matchesSafely(final T item) { try { final Iterator<String> headers = headers(item).iterator(); if (headers.hasNext()) { headers.next(); } <START> final List<String> values = new ArrayList<String>(0); <END> while (headers.hasNext()) { final String[] parts = AbstractHmHeader.split(headers.next()); if (this.header.matches(parts[0].trim())) { values.add(parts[1].trim()); } } final boolean result = this.value.matches(values); if (!result) { this.failed = values; } return result; } catch (final IOException ex) { throw new IllegalStateException(ex); } }</code><technical_language>@Happy-Neko Variable type relaxed Collection</technical_language>

Target:
public final boolean matchesSafely(final T item) { try { final Iterator<String> headers = headers(item).iterator(); if (headers.hasNext()) { headers.next(); } final Collection<String> values = new ArrayList<String>(0); while (headers.hasNext()) { final String[] parts = AbstractHmHeader.split(headers.next()); if (this.header.matches(parts[0].trim())) { values.add(parts[1].trim()); } } final boolean result = this.value.matches(values); if (!result) { this.failed = values; } return result; } catch (final IOException ex) { throw new IllegalStateException(ex); } }
Source:
<code>public void testDelete() throws Exception { URI uri = api().delete(resourcegroup); <START> assertNotNull(uri); <END> assertTrue(uri.toString().contains("api-version")); assertTrue(uri.toString().contains("operationresults")); String[] params = uri.getQuery().split("&"); String apiversion = ""; for (String param : params) { String name = param.split("=")[0]; if (name.equals("api-version")){ apiversion = param.split("=")[1]; break; } } JobStatus status = api.getJobApi().jobDone(uri, apiversion); assertEquals(status, JobStatus.DONE); uri = api().delete("jcloudstest"); assertNotNull(uri); uri = api().delete("blahblah"); assertNull(uri); }</code><technical_language>This is sensible... If resource deleted generating a task (200 response) this null delete operation succeeded. do polling if URI is null</technical_language>

Target:
public void testDelete() throws Exception { URI uri = api().delete(resourcegroup); if (uri != null){ assertTrue(uri.toString().contains("api-version")); assertTrue(uri.toString().contains("operationresults")); boolean jobDone = Predicates2.retry(new Predicate<URI>() { @Override public boolean apply(URI uri) { return JobStatus.DONE == api.getJobApi().jobStatus(uri); } }, 60 * 1 * 1000 ).apply(uri); assertTrue(jobDone, "delete operation did not complete in the configured timeout"); } uri = api().delete("jcloudstest"); if (uri != null){ assertTrue(uri.toString().contains("api-version")); assertTrue(uri.toString().contains("operationresults")); boolean jobDone = Predicates2.retry(new Predicate<URI>() { @Override public boolean apply(URI uri) { return JobStatus.DONE == api.getJobApi().jobStatus(uri); } }, 60 * 1 * 1000 ).apply(uri); assertTrue(jobDone, "delete operation did not complete in the configured timeout"); } }
Source:
<code>public void testRemoveValueUnequalStoreEntryCacheAccessExceptionEqualCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(realStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "value")); this.cacheWriter = spy(realCache); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); <START> assertFalse(ehcache.remove("key", "value")); <END> verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); assertThat(realCache.getEntries().containsKey("key"), is(true)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }</code><technical_language>drop assertion operation results expecting resilience strategy called</technical_language>

Target:
public void testRemoveValueUnequalStoreEntryCacheAccessExceptionEqualCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(fakeStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "value")); this.cacheWriter = spy(fakeWriter); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); ehcache.remove("key", "value"); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
<code>public void getJoinCond(ASTNode node) { if (node == null) { return; } int rootType = node.getToken().getType(); if (rootType == TOK_JOIN || rootType == TOK_LEFTOUTERJOIN || rootType == TOK_RIGHTOUTERJOIN || rootType == TOK_FULLOUTERJOIN || rootType == TOK_LEFTSEMIJOIN || rootType == TOK_UNIQUEJOIN) { ASTNode left = (ASTNode) node.getChild(0); ASTNode right = (ASTNode) node.getChild(1); String joinType = ""; String JoinToken = node.getToken().getText(); if (JoinToken.equals("TOK_JOIN")) { joinType = "inner join"; } else if (JoinToken.equals("TOK_LEFTOUTERJOIN")) { joinType = "left outer join"; } else if (JoinToken.equals("TOK_RIGHTOUTERJOIN")) { joinType = "right outer join"; } else if (JoinToken.equals("TOK_FULLOUTERJOIN")) { joinType = "full outer join"; } else if (JoinToken.equals("TOK_LEFTSEMIJOIN")) { joinType = "left semi join"; } else if (JoinToken.equals("TOK_UNIQUEJOIN")) { joinType = "unique join"; } else { <START> LOG.info("Non supported join type : " + JoinToken); <END> } String joinCond = ""; if (node.getChildCount() > 2) { joinCond = HQLParser.getString((ASTNode) node.getChild(2)); } String joinClause = joinType.concat(HQLParser.getString(right)) .concat(" on ").concat(joinCond); joinCondition.append(" ").append(joinClause); } for (int i = 0; i < node.getChildCount(); i++) { ASTNode child = (ASTNode) node.getChild(i); getJoinCond(child); } }</code><technical_language>throw exception instead</technical_language>

Target:
public void getJoinCond(ASTNode node) { if (node == null) { return; } try { int rootType = node.getToken().getType(); if (rootType == TOK_JOIN || rootType == TOK_LEFTOUTERJOIN || rootType == TOK_RIGHTOUTERJOIN || rootType == TOK_FULLOUTERJOIN || rootType == TOK_LEFTSEMIJOIN || rootType == TOK_UNIQUEJOIN) { ASTNode left = (ASTNode) node.getChild(0); ASTNode right = (ASTNode) node.getChild(1); String joinType = ""; String JoinToken = node.getToken().getText(); if (JoinToken.equals("TOK_JOIN")) { joinType = "inner join"; } else if (JoinToken.equals("TOK_LEFTOUTERJOIN")) { joinType = "left outer join"; } else if (JoinToken.equals("TOK_RIGHTOUTERJOIN")) { joinType = "right outer join"; } else if (JoinToken.equals("TOK_FULLOUTERJOIN")) { joinType = "full outer join"; } else if (JoinToken.equals("TOK_LEFTSEMIJOIN")) { joinType = "left semi join"; } else if (JoinToken.equals("TOK_UNIQUEJOIN")) { joinType = "unique join"; } else { LOG.info("Non supported join type : " + JoinToken); } String joinCond = ""; if (node.getChildCount() > 2) { joinCond = HQLParser.getString((ASTNode) node.getChild(2)); } String joinClause = joinType.concat(HQLParser.getString(right)) .concat(" on ").concat(joinCond); joinCondition.append(" ").append(joinClause); } } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < node.getChildCount(); i++) { ASTNode child = (ASTNode) node.getChild(i); getJoinCond(child); } }
Source:
<code><START> public void testIgnoreDefault() <END> { Map<String, String> result = sessionProperties.createHeaderFromSession( createTestSession( ImmutableMap.of( "int_session_prop", 0, "double_session_prop", 0.0, "bool_session_prop", false))); assertTrue(result.isEmpty()); }</code><technical_language>default values equal Java defaults (e.g., -1)</technical_language>

Target:
public void testIgnoreDefault() { Map<String, Object> sessionValues = ImmutableMap.<String, Object>builder() .put("int_session_prop", -1) .put("long_session_prop", 1) .put("double_session_prop", 0.01) .put("bool_session_prop", false) .put("another_string_session_prop", "123") .build(); Map<String, String> result = sessionProperties.toHeader(createTestSession(sessionValues)); assertTrue(result.isEmpty()); }
Source:
<code>public void loadProductiveCollectionSheet(int centerId, CollectionSheetRequestPayload payload) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(collectionDataManager.fetchProductiveCollectionSheet(centerId, payload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<CollectionSheetResponse>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); try { if (e instanceof HttpException) { <START> String errorMessage = ((HttpException) e).response().errorBody() <END> .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(CollectionSheetResponse sheet) { getMvpView().showProgressbar(false); getMvpView().showProductive(sheet); } })); }</code><technical_language>this utils method show error <LINK_0></technical_language>

Target:
public void loadProductiveCollectionSheet(int centerId, CollectionSheetRequestPayload payload) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(collectionDataManager.fetchProductiveCollectionSheet(centerId, payload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<CollectionSheetResponse>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(CollectionSheetResponse collectionSheetResponse) { getMvpView().showProgressbar(false); getMvpView().showProductive(collectionSheetResponse); } })); }
Source:
<code>private Object handleMessage(String message) { Map parsed; try { parsed = GSON.fromJson(message, Map.class); Map<String, Object> numberTypeFix = (Map<String, Object>) parsed; if (numberTypeFix.containsKey("id")) { if (numberTypeFix.get("id") instanceof Number) { numberTypeFix.put("id", ((Number) numberTypeFix.get("id")).intValue()); <START> } <END> } } catch (RuntimeException ex) { return response(null, error(PARSE_ERROR, "Parse error", message)); } return exec(parsed); }</code><technical_language>avoid searching map 3 times for "id" entry</technical_language>

Target:
private Object handleMessage(String message) { Map parsed; try { parsed = GSON.fromJson(message, Map.class); Map<String, Object> numberTypeFix = (Map<String, Object>) parsed; if (numberTypeFix.containsKey("id")) { Object id = numberTypeFix.get("id"); if (id instanceof Number) { numberTypeFix.put("id", ((Number) id).intValue()); } } } catch (RuntimeException ex) { return response(null, error(PARSE_ERROR, "Parse error", message)); } return exec(parsed); }
Source:
<code>public List<String> getColumnNames() { if ( count ) { return new ArrayList<String>( ) { { add( "n" ); } <START> }; <END> } return projection != null ? new ArrayList<>( projection.keySet() ) : Collections.<String>emptyList(); }</code><technical_language>Simply Arrays.asList(). list immutable I add element column names afterwards</technical_language>

Target:
public List<String> getColumnNames() { if ( operation.isAggregation ) { return Collections.singletonList( "n" ); } return projection != null ? new ArrayList<>( projection.keySet() ) : Collections.<String>emptyList(); }
Source:
<code>public CompletableFuture<Void> visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable { Object key = command.getKey(); TypeConverter<Object, Object, Object, Object> converter = determineTypeConverter(command.getFlags()); if (ctx.isOriginLocal()) { command.setKey(converter.boxKey(key)); } ctx.onReturn((ctx1, command1, rv, throwable) -> { if (throwable != null) throw throwable; if (rv == null) { return null; } CacheEntry entry = (CacheEntry) rv; Object returnValue = entry.getValue(); <START> if (needsUnboxing(ctx)) { <END> returnValue = converter.unboxValue(entry.getValue()); } return CompletableFuture.completedFuture(entryFactory .create(entry.getKey(), returnValue, entry.getMetadata(), entry.getLifespan(), entry.getMaxIdle())); }); return ctx.continueInvocation(); }</code><technical_language>ctx1</technical_language>

Target:
public CompletableFuture<Void> visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable { Object key = command.getKey(); TypeConverter<Object, Object, Object, Object> converter = determineTypeConverter(command.getFlags()); if (ctx.isOriginLocal()) { command.setKey(converter.boxKey(key)); } return ctx.onReturn((rCtx, rCommand, rv, throwable) -> { if (throwable != null) throw throwable; if (rv == null || !needsUnboxing(rCtx)) { return null; } CacheEntry entry = (CacheEntry) rv; Object returnValue = converter.unboxValue(entry.getValue()); return CompletableFuture.completedFuture(entryFactory .create(entry.getKey(), returnValue, entry.getMetadata(), entry.getLifespan(), entry.getMaxIdle())); }); }
Source:
<code>public InternalTypeResolver(Function<ColumnHandle, String> nameResolver, Function<String, Class<? extends ColumnHandle>> classResolver, <START> Map<String,Class<? extends TupleExpression>> expressionResolver) <END> { this.nameResolver = requireNonNull(nameResolver, "nameResolver is null"); this.classResolver = requireNonNull(classResolver, "classResolver is null"); this.expressionResolver = expressionResolver; }</code><technical_language>requireNonNull</technical_language>

Target:
public InternalTypeResolver(Function<ColumnHandle, String> nameResolver, Function<String, Class<? extends ColumnHandle>> classResolver, Map<String, Class<? extends TupleExpression>> expressionResolver) { this.nameResolver = requireNonNull(nameResolver, "nameResolver is null"); this.classResolver = requireNonNull(classResolver, "classResolver is null"); this.expressionResolver = requireNonNull(expressionResolver, "expression resolver is null"); }
Source:
<code>private static void updateScenarioStatus(@Nullable ITmfEvent event, IXmlStateSystemContainer container, final TmfXmlScenarioInfo info) { ITmfStateSystemBuilder ss = (ITmfStateSystemBuilder) container.getStateSystem(); long ts = getTimestamp(event, ss); ITmfStateValue value; try { switch (info.getStatus()) { case IN_PROGRESS: value = STATUS_MAP.get(ScenarioStatusType.IN_PROGRESS); break; case ABANDONED: value = STATUS_MAP.get(ScenarioStatusType.ABANDONED); break; case MATCHED: value = STATUS_MAP.get(ScenarioStatusType.MATCHED); break; case PENDING: value = STATUS_MAP.get(ScenarioStatusType.PENDING); break; default: value = TmfStateValue.nullValue(); break; } <START> if (value != null) { <END> ss.modifyAttribute(ts, value, info.getStatusQuark()); } } catch (StateValueTypeException | AttributeNotFoundException e) { Activator.logError("failed to update scenario status"); } }</code><technical_language>In this case, keys in STATUS_MAP, more a checkNotNull()</technical_language>

Target:
private static void updateScenarioStatus(@Nullable ITmfEvent event, IXmlStateSystemContainer container, final TmfXmlScenarioInfo info) { ITmfStateSystemBuilder ss = (ITmfStateSystemBuilder) container.getStateSystem(); long ts = getTimestamp(event, ss); ITmfStateValue value; try { switch (info.getStatus()) { case IN_PROGRESS: value = STATUS_MAP.get(ScenarioStatusType.IN_PROGRESS); break; case ABANDONED: value = STATUS_MAP.get(ScenarioStatusType.ABANDONED); break; case MATCHED: value = STATUS_MAP.get(ScenarioStatusType.MATCHED); break; case PENDING: value = STATUS_MAP.get(ScenarioStatusType.PENDING); break; default: value = TmfStateValue.nullValue(); break; } ss.modifyAttribute(ts, NonNullUtils.checkNotNull(value), info.getStatusQuark()); } catch (StateValueTypeException | AttributeNotFoundException e) { Activator.logError("failed to update scenario status"); } }
Source:
<code>public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { Args.notNull(cookie, "Cookie"); if (value == null) { return; } final int age; try { age = Integer.parseInt(value); } catch (final NumberFormatException e) { <START> return; <END> } if (age < 0) { return; } cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L)); }</code><technical_language>@heejeongkim do want quietly ignore malformed max-age expires attributes strict RFC 6265 policy? right me</technical_language>

Target:
public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { Args.notNull(cookie, "Cookie"); if (value == null) { throw new MalformedCookieException("Missing value for 'max-age' attribute"); } final int age; try { age = Integer.parseInt(value); } catch (final NumberFormatException e) { throw new MalformedCookieException ("Invalid 'max-age' attribute: " + value); } if (age < 0) { throw new MalformedCookieException ("Negative 'max-age' attribute: " + value); } cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L)); }
Source:
<code>private String transformToPluralForm(String singular) { StringBuilder plural = new StringBuilder(); plural.append(singular); if (singular.endsWith(LAST_CHAR_Y)) { int length = plural.length(); plural.replace(length - 1, length, PLURAL_SUFFIX_IES); } else if (singular.endsWith(LAST_CHAR_S) || singular.endsWith(LAST_CHAR_X) || singular.endsWith(LAST_CHAR_Z) || singular.endsWith(LAST_CHARS_CH) || singular.endsWith(LAST_CHARS_SH)) { <START> <END> plural.append(PLURAL_SUFFIX_ES); } else { plural.append(PLURAL_SUFFIX_S); } return plural.toString(); }</code><technical_language>This benefit inilne examples (takle values tests)</technical_language>

Target:
private String transformToPluralForm(String singular) { StringBuilder plural = new StringBuilder(); plural.append(singular); if (singular.endsWith(String.valueOf(LAST_CHAR_Y))) { int length = plural.length(); plural.replace(length - 1, length, PLURAL_SUFFIX_IES); } else if (singular.endsWith(String.valueOf(LAST_CHAR_S)) || singular.endsWith(String.valueOf(LAST_CHAR_X)) || singular.endsWith(String.valueOf(LAST_CHAR_Z)) || singular.endsWith(LAST_CHARS_CH) || singular.endsWith(LAST_CHARS_SH)) { plural.append(PLURAL_SUFFIX_ES); } else { plural.append(PLURAL_SUFFIX_S); } return plural.toString(); }
Source:
<code>private List<Pair<Throwable, ErrorType>> collectUnsuppressedErrors(Component obj, MessagingException me, ErrorTypeLocator locator) { List<Pair<Throwable, ErrorType>> errors = new ArrayList<>(4); final List<Throwable> exceptionsAsList = getExceptionsAsList(me); for (Throwable e : exceptionsAsList) { <START> if (e instanceof SuppressedMuleException) { <END> break; } else { ErrorType type = errorTypeFromException(obj, locator, e); if (!isUnknownMuleError(type) && !isCriticalMuleError(type)) { errors.add(new Pair<>(e, type)); } } } return errors; }</code><technical_language>handle this getExceptionsAsList(me), adding unwanted elements list is avoided start</technical_language>

Target:
private List<Pair<Throwable, ErrorType>> collectUnsuppressedErrors(Component obj, MessagingException me, ErrorTypeLocator locator) { List<Pair<Throwable, ErrorType>> errors = new ArrayList<>(4); final List<Throwable> exceptionsAsList = getExceptionsAsList(me); for (Throwable e : exceptionsAsList) { ErrorType type = errorTypeFromException(obj, locator, e); if (!isUnknownMuleError(type) && !isCriticalMuleError(type)) { errors.add(new Pair<>(e, type)); } } return errors; }
Source:
<code>public void addTimer(final TimerImpl timerEntity) { String timedObjectId = timerEntity.getTimedObjectId(); synchronized (this) { if(!knownTimerIds.containsKey(timedObjectId)) { <START> EjbLogger.EJB3_TIMER_LOGGER.timerCannotBeAdded(timerEntity); <END> } } String createTimer = sql(CREATE_TIMER); Connection connection = null; PreparedStatement statement = null; try { synchronized (this) { knownTimerIds.get(timerEntity.getTimedObjectId()).add(timerEntity.getId()); } connection = dataSource.getConnection(); statement = connection.prepareStatement(createTimer); statementParameters(timerEntity, statement); statement.execute(); } catch (SQLException e) { throw new RuntimeException(e); } finally { safeClose(statement); safeClose(connection); } }</code><technical_language>need add 'throw' keyword</technical_language>

Target:
public void addTimer(final TimerImpl timerEntity) { String timedObjectId = timerEntity.getTimedObjectId(); synchronized (this) { if(!knownTimerIds.containsKey(timedObjectId)) { throw EjbLogger.EJB3_TIMER_LOGGER.timerCannotBeAdded(timerEntity); } } String createTimer = sql(CREATE_TIMER); Connection connection = null; PreparedStatement statement = null; try { synchronized (this) { knownTimerIds.get(timerEntity.getTimedObjectId()).add(timerEntity.getId()); } connection = dataSource.getConnection(); statement = connection.prepareStatement(createTimer); statementParameters(timerEntity, statement); statement.execute(); } catch (SQLException e) { throw new RuntimeException(e); } finally { safeClose(statement); safeClose(connection); } }
Source:
<code>public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException { ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) { <START> String respBody = null; <END> respBody = response.getEntity(String.class); throw new ApiException( response.getStatusInfo().getStatusCode(), "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'", response.getHeaders(), respBody); } statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if (returnType == null) return null; else return response.getEntity(returnType); } else { String message = "error"; String respBody = null; if (response.hasEntity()) { try { respBody = response.getEntity(String.class); message = respBody; } catch (RuntimeException e) { } } throw new ApiException( response.getStatusInfo().getStatusCode(), message, response.getHeaders(), respBody); } }</code><technical_language>@psytester change to: String respBody = response.getEntity(String.class);</technical_language>

Target:
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException { ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) { String respBody = response.getEntity(String.class); throw new ApiException( response.getStatusInfo().getStatusCode(), "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'", response.getHeaders(), respBody); } statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if (returnType == null) return null; else return response.getEntity(returnType); } else { String message = "error"; String respBody = null; if (response.hasEntity()) { try { respBody = response.getEntity(String.class); message = respBody; } catch (RuntimeException e) { } } throw new ApiException( response.getStatusInfo().getStatusCode(), message, response.getHeaders(), respBody); } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadData(); if (getPackageName().startsWith("com.example")) { throw new RuntimeException("Please change the sample's package name! See README."); } Log.d(TAG, "Creating IAB helper."); <START> OpenIabHelper.Options.Builder builder = new OpenIabHelper.Options.Builder() <END> .addStoreKeys(Config.STORE_KEYS_MAP); mHelper = new OpenIabHelper(this, builder.build()); Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { setupDone = false; complain("Problem setting up in-app billing: " + result); return; } Log.d(TAG, "Setup successful. Querying inventory."); setupDone = true; mHelper.queryInventoryAsync(mGotInventoryListener); } }); }</code><technical_language>Please add .setVerifyMode(OpenIabHelper.Options.VERIFY_EVERYTHING)</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadData(); if (getPackageName().startsWith("com.example")) { throw new RuntimeException("Please change the sample's package name! See README."); } Log.d(TAG, "Creating IAB helper."); OpenIabHelper.Options.Builder builder = new OpenIabHelper.Options.Builder() .setVerifyMode(OpenIabHelper.Options.VERIFY_EVERYTHING) .addStoreKeys(Config.STORE_KEYS_MAP); mHelper = new OpenIabHelper(this, builder.build()); Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { setupDone = false; complain("Problem setting up in-app billing: " + result); return; } Log.d(TAG, "Setup successful. Querying inventory."); setupDone = true; mHelper.queryInventoryAsync(mGotInventoryListener); } }); }
Source:
<code>public Object[][] getData() { return new Object[][]{ <START> {TestClassWithConfigFailureSample.class, 6}, <END> {TestClassWithConfigSkipSample.class, 4}, {TestClassWithConfigSkipAndFailureSample.class, 6} }; }</code><technical_language>do need change values? TestClassWithConfigSkipAndFailureSample 3 => HAS_SKIPPED + HAS_FAILURE is 6 => HAS_SKIPPED + HAS_FSP. Is expected</technical_language>

Target:
public Object[][] getData() { return new Object[][]{ {TestClassWithConfigFailureSample.class, 3}, {TestClassWithConfigSkipSample.class, 2}, {TestClassWithConfigSkipAndFailureSample.class, 3} }; }
Source:
<code>public static boolean tryWriteLock( long address ) { <START> long s, n; <END> for (; ; ) { s = getState( address ); boolean unwritablyLocked = (s & EXL_MASK) != 0; boolean writeCountOverflow = (s & CNT_MASK) == CNT_MASK; if ( unwritablyLocked | writeCountOverflow ) { return failWriteLock( s, writeCountOverflow ); } n = s + CNT_UNIT | MOD_MASK; if ( compareAndSetState( address, s, n ) ) { UnsafeUtil.storeFence(); return true; } } }</code><technical_language>code resembles C adopt horrendous naming standards ;)</technical_language>

Target:
public static boolean tryWriteLock( long address ) { long s; long n; for ( ; ; ) { s = getState( address ); boolean unwritablyLocked = (s & EXL_MASK) != 0; boolean writeCountOverflow = (s & CNT_MASK) == CNT_MASK; if ( unwritablyLocked | writeCountOverflow ) { return failWriteLock( s, writeCountOverflow ); } n = s + CNT_UNIT | MOD_MASK; if ( compareAndSetState( address, s, n ) ) { UnsafeUtil.storeFence(); return true; } } }
Source:
<code><START> public void choosePicture() <END> { Intent getIntent = new Intent(); getIntent.setType("image/*"); getIntent.setAction(Intent.ACTION_GET_CONTENT); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setType("image/*"); Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File externalFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "userPic" + System.currentTimeMillis() + ".jpg"); imageUri = Uri.fromFile(externalFile); if(BuildConfig.DEBUG) { Log.d("photo location", imageUri.toString()); } takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); String pickTitle = getString(R.string.select_picture); Intent chooserIntent = Intent.createChooser(getIntent, pickTitle); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent, takePhotoIntent}); startActivityForResult(chooserIntent, SELECT_PICTURE); }</code><technical_language>FIXME: I get "Android System" option choose photos. I happen (?)</technical_language>

Target:
public void choosePicture() { Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setType("image/*"); Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File externalFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "userPic" + System.currentTimeMillis() + ".jpg"); imageUri = Uri.fromFile(externalFile); if(BuildConfig.DEBUG) { Log.d("photo location", imageUri.toString()); } takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); String pickTitle = getString(R.string.select_picture); Intent chooserIntent = Intent.createChooser(takePhotoIntent, pickTitle); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); startActivityForResult(chooserIntent, SELECT_PICTURE); }
Source:
<code>private void cleanup(ConsumerProcess consumerProcess) { kill(consumerProcess); <START> runningProcesses.remove(consumerProcess); <END> }</code><technical_language>I remove process if kill succeeded. is branch leaves stale consumer supervised anymore removed it</technical_language>

Target:
private void cleanup(ConsumerProcess consumerProcess) { kill(consumerProcess); }
Source:
<code>public ServiceName getServiceName() { <START> return getServiceName(name); <END> }</code><technical_language>return super.getServiceName().append("config");</technical_language>

Target:
public ServiceName getServiceName() { return super.getServiceName().append("configuration"); }
Source:
<code>public void invalidProviderType() { <START> provider.setType(NON_NETWORK_PROVIDER_TYPE); <END> assertThat(validator.providerTypeValid(), failsWith(VdcBllMessages.ACTION_TYPE_FAILED_PROVIDER_TYPE_MISMATCH)); }</code><technical_language>do this mocking api, this call is mock doesnt do it.</technical_language>

Target:
public void invalidProviderType() { when(provider.getType()).thenReturn(NON_NETWORK_PROVIDER_TYPE); assertThat(validator.providerTypeValid(), failsWith(VdcBllMessages.ACTION_TYPE_FAILED_PROVIDER_TYPE_MISMATCH)); }
Source:
<code>public void visitNode(Tree tree) { AnnotationTree annotation = (AnnotationTree) tree; Set<String> scanPackageAttributeNames = SCAN_PACKAGE_ATTRIBUTES.get(annotation.symbolType().fullyQualifiedName()); if (scanPackageAttributeNames != null) { List<ExpressionTree> scanPackageAttributes = annotation.arguments().stream() .filter(argument -> scanPackageAttributeNames.contains(attributeName(argument))) .collect(Collectors.toList()); if (scanPackageAttributes.isEmpty()) { checkIfAnnotationIsInDefaultPackage(annotation); } else { <START> checkAnnotationPackageAttributes(annotation, scanPackageAttributes); <END> } } }</code><technical_language>IMO pass scanPackageValues method if is empty check default package</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } AnnotationTree annotation = (AnnotationTree) tree; Set<String> scanPackageAttributeNames = SCAN_PACKAGE_ATTRIBUTES.get(annotation.symbolType().fullyQualifiedName()); if (scanPackageAttributeNames != null) { List<ExpressionTree> scanPackageAttributeValues = annotation.arguments().stream() .filter(argument -> scanPackageAttributeNames.contains(attributeName(argument))) .flatMap(SpringScanDefaultPackageCheck::extractValues) .collect(Collectors.toList()); checkAnnotationPackageAttributes(annotation, scanPackageAttributeValues); } }
Source:
<code>public void runToolToMissingS3() { File cwlFile = new File(ResourceHelpers.resourceFilePath("file_provision/split.cwl")); File cwlJSON = new File(ResourceHelpers.resourceFilePath("file_provision/split_to_s3_failed.json")); <START> final ByteArrayOutputStream launcherOutput = new ByteArrayOutputStream(); <END> System.setOut(new PrintStream(launcherOutput)); thrown.expect(AssertionError.class); runTool(cwlFile, cwlJSON); final String standardOutput = launcherOutput.toString(); assertTrue("Error should occur, caused by Amazon S3 Exception", standardOutput.contains("Caused by: com.amazonaws.services.s3.model.AmazonS3Exception")); }</code><technical_language>matter in tests, this closed</technical_language>

Target:
public void runToolToMissingS3() { File cwlFile = new File(ResourceHelpers.resourceFilePath("file_provision/split.cwl")); File cwlJSON = new File(ResourceHelpers.resourceFilePath("file_provision/split_to_s3_failed.json")); ByteArrayOutputStream launcherOutput = null; try { launcherOutput = new ByteArrayOutputStream(); System.setOut(new PrintStream(launcherOutput)); thrown.expect(AssertionError.class); runTool(cwlFile, cwlJSON); final String standardOutput = launcherOutput.toString(); assertTrue("Error should occur, caused by Amazon S3 Exception", standardOutput.contains("Caused by: com.amazonaws.services.s3.model.AmazonS3Exception")); } finally { try { if (launcherOutput != null) { launcherOutput.close(); } } catch (IOException ex) { assertTrue("Error closing output stream.", true); } } }
Source:
<code>public boolean isVideoPlaying() { <START> wait.forElementVisible(videoFeedback); <END> return videoFeedback.isDisplayed(); }</code><technical_language>if want check if video is playing I rely video feedback element. is special css class added of divs related player appears video is playing</technical_language>

Target:
public boolean isVideoPlaying() { wait.forElementVisible(playerStatePlaying); return playerStatePlaying.isDisplayed(); }
Source:
<code>public Iterator<InodeView> iterator() { return RocksUtils.createIterator(db().newIterator(mInodesColumn.get()), <START> (iter) -> getMutable(Longs.fromByteArray(iter.key()), ReadOption.defaults()).get()); <END> }</code><technical_language>this read option other iterator</technical_language>

Target:
public Iterator<InodeView> iterator() { return RocksUtils.createIterator(db().newIterator(mInodesColumn.get(), mIteratorOption), (iter) -> getMutable(Longs.fromByteArray(iter.key()), ReadOption.defaults()).get()); }
Source:
<code>public IBinder getLegacyBrowserServiceBinder() { <START> if (mBrowserServiceLegacyStub != null) { <END> Intent intent = new Intent(MediaBrowserServiceCompat.SERVICE_INTERFACE); return mBrowserServiceLegacyStub.onBind(intent); } return null; }</code><technical_language>nan</technical_language>

Target:
public IBinder getLegacyBrowserServiceBinder() { Intent intent = new Intent(MediaBrowserServiceCompat.SERVICE_INTERFACE); return mBrowserServiceLegacyStub.onBind(intent); }
Source:
<code>public RecordWriter getRecordWriter(TaskAttemptContext context) <START> throws IOException { <END> Configuration conf = context.getConfiguration(); Connection conn = null; PreparedStatement ps = null; String dbProductName = conf.get(JdbcStorageConfig.DATABASE_TYPE.getPropertyName()).toUpperCase(); String tableName = conf.get(JdbcStorageConfig.TABLE.getPropertyName()); if (tableName == null || tableName.isEmpty()) { throw new IllegalArgumentException("Table name should be defined"); } String[] columnNames = conf.get(serdeConstants.LIST_COLUMNS).split(","); try { initializeDatabaseConnection(conf); conn = dbcpDataSource.getConnection(); ps = conn.prepareStatement( constructQuery(tableName, columnNames, dbProductName)); return new org.apache.hadoop.mapreduce.lib.db.DBOutputFormat() .new DBRecordWriter(conn, ps); } catch (Exception e) { cleanupResources(conn, ps, null); throw new IOException(e.getMessage()); } }</code><technical_language>L182-185 moved if condition</technical_language>

Target:
public RecordWriter getRecordWriter(TaskAttemptContext context) throws IOException { Configuration conf = context.getConfiguration(); String tableName = conf.get(JdbcStorageConfig.TABLE.getPropertyName()); if (tableName == null || tableName.isEmpty()) { throw new IllegalArgumentException("Table name should be defined"); } Connection conn = null; PreparedStatement ps = null; String[] columnNames = conf.get(serdeConstants.LIST_COLUMNS).split(","); try { initializeDatabaseConnection(conf); conn = dbcpDataSource.getConnection(); ps = conn.prepareStatement(constructQuery(tableName, columnNames)); return new org.apache.hadoop.mapreduce.lib.db.DBOutputFormat() .new DBRecordWriter(conn, ps); } catch (Exception e) { cleanupResources(conn, ps, null); throw new IOException(e.getMessage()); } }
Source:
<code>@Test void testProject() { CalciteAssert.that() .with(TWISSANDRA) .query("select \"tweet_id\" from \"userline\" where \"username\" = '!PUBLIC!' limit 2") .returns("tweet_id=f3c329de-d05b-11e5-b58b-90e2ba530b12\n" + "tweet_id=f3dbb03a-d05b-11e5-b58b-90e2ba530b12\n") .explainContains("PLAN=CassandraToEnumerableConverter\n" + " CassandraProject(tweet_id=[$2])\n" + " CassandraLimit(fetch=[2])\n" + " CassandraFilter(condition=[=($0, '!PUBLIC!')])\n"); <START> } <END></code><technical_language>cost lead change</technical_language>

Target:
@Test void testProject() { CalciteAssert.that() .with(TWISSANDRA) .query("select \"tweet_id\" from \"userline\" where \"username\" = '!PUBLIC!' limit 2") .returns("tweet_id=f3c329de-d05b-11e5-b58b-90e2ba530b12\n" + "tweet_id=f3dbb03a-d05b-11e5-b58b-90e2ba530b12\n") .explainContains("PLAN=CassandraToEnumerableConverter\n" + " CassandraLimit(fetch=[2])\n" + " CassandraProject(tweet_id=[$2])\n" + " CassandraFilter(condition=[=($0, '!PUBLIC!')])\n"); }
Source:
<code>public List<PreConfiguredTokenFilter> getPreConfiguredTokenFilters() { return <START> Collections.singletonList(PreConfiguredTokenFilter.singleton("homoglyph_norm", <END> true, HomoglyphTokenFilter::new)); }</code><technical_language>this is syntactic sugar, this line a bit shorter. return Collections.singletonList(PreConfiguredTokenFilter.singleton("homoglyph_norm", return singletonList(singleton("homoglyph_norm", helps readability is accessible easily in intelliJ simply pressing alt-enter while cursor method</technical_language>

Target:
public List<PreConfiguredTokenFilter> getPreConfiguredTokenFilters() { return singletonList(PreConfiguredTokenFilter.singleton("homoglyph_norm", true, in -> new HomoglyphTokenFilter(in, new TranslationTable(TranslationTableDictionaries.latinToCyrillic)))); }
Source:
<code>public Optional<Response> handle(HandlerInput input) { String speechText; String favoriteColor = (String) input.getAttributesManager().getSessionAttributes().get(COLOR_KEY); <START> boolean isAskResponse = false; <END> if (favoriteColor != null && !favoriteColor.isEmpty()) { speechText = String.format("Your favorite color is %s. Goodbye.", favoriteColor); isAskResponse = true; } else { speechText = "I'm not sure what your favorite color is. You can say, my favorite color is " + "red."; } ResponseBuilder responseBuilder = input.getResponseBuilder(); responseBuilder.withSimpleCard("ColorSession", speechText) .withSpeech(speechText); if(!isAskResponse) { responseBuilder.withShouldEndSession(false); } return responseBuilder.build(); }</code><technical_language>this boolean flag is of variable name means. If response is a "Ask" response, want session open (set shouldEndSession false). L55 is opposite. Also, reason for moving this logic MyColorIsIntentHandler here</technical_language>

Target:
public Optional<Response> handle(HandlerInput input) { String speechText; String favoriteColor = (String) input.getAttributesManager().getSessionAttributes().get(COLOR_KEY); boolean noAnswerProvided = false; if (favoriteColor != null && !favoriteColor.isEmpty()) { speechText = String.format("Your favorite color is %s. Goodbye.", favoriteColor); } else { speechText = "I'm not sure what your favorite color is. You can say, my favorite color is " + "red."; noAnswerProvided = true; } return input.getResponseBuilder() .withSimpleCard("ColorSession", speechText) .withSpeech(speechText) .withShouldEndSession(!noAnswerProvided) .build(); }