auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Long> getAgentProvider(String providedServiceLabel, long accountId) { final Map<Long, Integer> result = new HashMap<>(); create().select(INSTANCE.AGENT_ID, LABEL.VALUE) .from(INSTANCE) .join(INSTANCE_LABEL_MAP) .on(INSTANCE_LABEL_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .join(LABEL) .on(LABEL.ID.eq(INSTANCE_LABEL_MAP.LABEL_ID).and(LABEL.KEY.eq(providedServiceLabel))) .where(INSTANCE.ACCOUNT_ID.eq(accountId) .and(INSTANCE.AGENT_ID.isNotNull()) .and(INSTANCE.STATE.eq(InstanceConstants.STATE_RUNNING)) .and(INSTANCE.HEALTH_STATE.in(HealthcheckConstants.HEALTH_STATE_HEALTHY, HealthcheckConstants.HEALTH_STATE_UPDATING_HEALTHY))) .orderBy(INSTANCE.AGENT_ID.asc()) .fetchInto(new RecordHandler<Record2<Long, String>>() { @Override public void next(Record2<Long, String> record) { Long agentId = record.getValue(INSTANCE.AGENT_ID); String p = record.getValue(LABEL.VALUE); Integer pVal = 1; try { pVal = Integer.valueOf(p); } catch (Exception e) { log.warn("Priority value not found for agent {}. Set it as default", agentId); } result.put(agentId, pVal); } }); List<Long> returnAgentIds = new ArrayList<>(result.keySet()); Collections.sort(returnAgentIds, new Comparator<Long>() { @Override public int compare(Long id1, Long id2) { <START> if (result.get(id1) > result.get(id2)) { <END> return 1; } else if (result.get(id1) < result.get(id2)) { return -1; } return 0; } }); return returnAgentIds; }</code><technical_language>Instead of re-implementing Integer comparison, of this method: <LINK_0></technical_language>

Target:
public List<Long> getAgentProvider(String providedServiceLabel, long accountId) { final Map<Long, Integer> result = new HashMap<>(); create().select(INSTANCE.AGENT_ID, LABEL.VALUE) .from(INSTANCE) .join(INSTANCE_LABEL_MAP) .on(INSTANCE_LABEL_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .join(LABEL) .on(LABEL.ID.eq(INSTANCE_LABEL_MAP.LABEL_ID).and(LABEL.KEY.eq(providedServiceLabel))) .join(INSTANCE_HOST_MAP) .on(INSTANCE.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID)) .join(HOST) .on(INSTANCE_HOST_MAP.HOST_ID.eq(HOST.ID)) .join(AGENT) .on(AGENT.ID.eq(HOST.AGENT_ID)) .where(INSTANCE.ACCOUNT_ID.eq(accountId) .and(INSTANCE.AGENT_ID.isNotNull()) .and(INSTANCE.STATE.eq(InstanceConstants.STATE_RUNNING)) .and(INSTANCE.HEALTH_STATE.in(HealthcheckConstants.HEALTH_STATE_HEALTHY, HealthcheckConstants.HEALTH_STATE_UPDATING_HEALTHY))) .and(AGENT.STATE.eq(CommonStatesConstants.ACTIVE)) .orderBy(INSTANCE.AGENT_ID.asc()) .fetchInto(new RecordHandler<Record2<Long, String>>() { @Override public void next(Record2<Long, String> record) { Long agentId = record.getValue(INSTANCE.AGENT_ID); String p = record.getValue(LABEL.VALUE); Integer pVal = 1; try { pVal = Integer.valueOf(p); } catch (Exception e) { log.warn("Priority value not found for agent {}. Set it as default", agentId); } result.put(agentId, pVal); } }); List<Long> returnAgentIds = new ArrayList<>(result.keySet()); Collections.sort(returnAgentIds, new Comparator<Long>() { @Override public int compare(Long id1, Long id2) { return result.get(id1).compareTo(result.get(id2)); } }); return returnAgentIds; }
Source:
<code>public OAuth2Error checkError() { if (StringUtils.isBlank(responseType) || StringUtils.isBlank(clientId) || StringUtils.isBlank(redirectUri) || !OAuth2Client.isRedirectURIValid(redirectUri) || StringUtils.isBlank(state)) { return OAuth2Error.INVALID_REQUEST; } ClientRegistry registry = Framework.getService(ClientRegistry.class); OAuth2Client client = null; try { client = registry.getClient(clientId); if (client == null || !client.isEnabled()) { return OAuth2Error.UNAUTHORIZED_CLIENT; } } catch (DirectoryException e) { log.warn(e, e); return OAuth2Error.SERVER_ERROR; } String clientName = client.getName(); if (StringUtils.isBlank(clientName)) { log.error(String.format( "No name set for OAuth2 client %s. It is a required field, please make sure you update this OAuth2 client.", client)); } String clientRequestURI = client.getRedirectURI(); if (StringUtils.isBlank(clientRequestURI)) { log.error(String.format( "No redirect URI set for OAuth2 client %s. It is required to validate the %s parameter, please make sure you update this OAuth2 client.", client, OAuth2Request.REDIRECT_URI)); return OAuth2Error.INVALID_REQUEST; } if (!redirectUri.equals(clientRequestURI)) { return OAuth2Error.INVALID_REQUEST; <START> } <END> if (!"code".equals(responseType)) { return OAuth2Error.UNSUPPORTED_RESPONSE_TYPE; } return null; }</code><technical_language>this implemented a TTL of 10 minutes for authorizationRequestStore transient store</technical_language>

Target:
public OAuth2Error checkError() { if (StringUtils.isBlank(responseType) || StringUtils.isBlank(clientId) || StringUtils.isBlank(redirectUri) || !OAuth2Client.isRedirectURIValid(redirectUri) || StringUtils.isBlank(state)) { return OAuth2Error.INVALID_REQUEST; } ClientRegistry registry = Framework.getService(ClientRegistry.class); OAuth2Client client = null; try { client = registry.getClient(clientId); if (client == null || !client.isEnabled()) { return OAuth2Error.UNAUTHORIZED_CLIENT; } } catch (DirectoryException e) { log.warn(e, e); return OAuth2Error.SERVER_ERROR; } String clientName = client.getName(); if (StringUtils.isBlank(clientName)) { log.error(String.format( "No name set for OAuth2 client %s. It is a required field, please make sure you update this OAuth2 client.", client)); } String clientRequestURI = client.getRedirectURI(); if (StringUtils.isBlank(clientRequestURI)) { log.error(String.format( "No redirect URI set for OAuth2 client %s. It is required to validate the %s parameter, please make sure you update this OAuth2 client.", client, REDIRECT_URI_PARAM)); return OAuth2Error.INVALID_REQUEST; } if (!redirectUri.equals(clientRequestURI)) { return OAuth2Error.INVALID_REQUEST; } if (!CODE_RESPONSE_TYPE.equals(responseType)) { return OAuth2Error.UNSUPPORTED_RESPONSE_TYPE; } return null; }
Source:
<code>void serializeRecordedEvents(List<RecordedEvent> events, String filePath) { try { JsonWriter writer = new JsonWriter(new FileWriter(filePath)); writer.beginObject(); writer.name("events"); writer.beginArray(); for (RecordedEvent event : events) { writer.beginObject(); writer.name("entityRef_ID").value(event.getEntityRefId()); writer.name("timestamp").value(event.getTimestamp()); writer.name("position").value(event.getPosition()); writer.name("event_class").value(event.getEvent().getClass().toString()); writer.name("event_data"); writer.beginObject(); writeSpecificEventData(writer, event.getEvent()); writer.endObject(); writer.endObject(); } writer.endArray(); writer.endObject(); writer.close(); } catch (Exception e) { <START> e.printStackTrace(); END> } }</code><technical_language>put this a logger ;)</technical_language>

Target:
void serializeRecordedEvents(List<RecordedEvent> events, String filePath) { try { JsonWriter writer = new JsonWriter(new FileWriter(filePath)); writer.beginObject(); writer.name("events"); writer.beginArray(); for (RecordedEvent event : events) { writer.beginObject(); writer.name("entityRef_ID").value(event.getEntityId()); writer.name("timestamp").value(event.getTimestamp()); writer.name("position").value(event.getPosition()); writer.name("event_class").value(event.getEvent().getClass().toString()); writer.name("event_data"); writer.beginObject(); writeSpecificEventData(writer, event.getEvent()); writer.endObject(); writer.endObject(); } writer.endArray(); writer.endObject(); writer.close(); } catch (Exception e) { logger.error("Error while serializing events:", e); } }
Source:
<code>private static LocalTime changeHours(LocalTime localTime, int hoursDelta) { final Timestamp time = Timestamps.getCurrentTime(); final Calendar calendar = Calendar.getInstance(); <START> calendar.set(Calendar.HOUR, localTime.getHours()); <END> calendar.set(Calendar.MINUTE, localTime.getMinutes()); calendar.set(Calendar.SECOND, localTime.getSeconds()); calendar.set(Calendar.MILLISECOND, localTime.getMillis()); calendar.add(Calendar.HOUR, hoursDelta); final int hours = calendar.get(Calendar.HOUR); final int minutes = calendar.get(Calendar.MINUTE); final int seconds = calendar.get(Calendar.SECOND); final int millis = calendar.get(Calendar.MILLISECOND); final long nanos = time.getNanos(); final LocalTime result = LocalTime.newBuilder() .setHours(hours) .setMinutes(minutes) .setSeconds(seconds) .setMillis(millis) .setNanos(nanos) .build(); return result; }</code><technical_language>Pease add on-demand static import for Calendar</technical_language>

Target:
private static LocalTime changeHours(LocalTime localTime, int hoursDelta) { return add(localTime, HOUR, hoursDelta); }
Source:
<code>private void doCopyRetry(FileSystem sourceFs, List<ReplChangeManager.FileInfo> srcFileList, FileSystem destinationFs, Path destination, boolean useRegularCopy) throws IOException, LoginException, HiveFatalException { int repeat = 0; boolean isCopyError = false; List<Path> pathList = Lists.transform(srcFileList, ReplChangeManager.FileInfo::getEffectivePath); while (!pathList.isEmpty() && (repeat < MAX_COPY_RETRY)) { try { if (repeat > 0) { pathList = getFilesToRetry(sourceFs, srcFileList, destinationFs, destination, isCopyError); if (pathList.isEmpty()) { break; } } LOG.info("Attempt: " + (repeat+1) + ". Copying files: " + pathList); isCopyError = true; doCopyOnce(sourceFs, pathList, destinationFs, destination, useRegularCopy); isCopyError = false; } catch (IOException e) { LOG.info("file operation failed", e); if (repeat >= (MAX_COPY_RETRY - 1)) { break; } if (!(e instanceof FileNotFoundException)) { int sleepTime = FileUtils.getSleepTime(repeat); LOG.info("Sleep for " + sleepTime + " milliseconds before retry " + (repeat+1)); try { Thread.sleep(sleepTime); } catch (InterruptedException timerEx) { LOG.info("sleep interrupted", timerEx.getMessage()); } FileSystem.closeAllForUGI(Utils.getUGI()); sourceFs = pathList.get(0).getFileSystem(hiveConf); destinationFs = destination.getFileSystem(hiveConf); } } repeat++; } if (!pathList.isEmpty()) { LOG.error("File copy failed even after several attempts. Files list: " + pathList); <START> throw new IOException(ErrorMsg.REPL_FILE_SYSTEM_RETRY.getMsg()); <END> } }</code><technical_language>This is File copy error file system retry case</technical_language>

Target:
private void doCopyRetry(FileSystem sourceFs, List<ReplChangeManager.FileInfo> srcFileList, FileSystem destinationFs, Path destination, boolean useRegularCopy) throws IOException, LoginException, HiveFatalException { int repeat = 0; boolean isCopyError = false; List<Path> pathList = Lists.transform(srcFileList, ReplChangeManager.FileInfo::getEffectivePath); while (!pathList.isEmpty() && (repeat < MAX_COPY_RETRY)) { try { if (repeat > 0) { pathList = getFilesToRetry(sourceFs, srcFileList, destinationFs, destination, isCopyError); if (pathList.isEmpty()) { break; } } LOG.info("Attempt: " + (repeat+1) + ". Copying files: " + pathList); isCopyError = true; doCopyOnce(sourceFs, pathList, destinationFs, destination, useRegularCopy); isCopyError = false; } catch (IOException e) { LOG.info("file operation failed", e); if (repeat >= (MAX_COPY_RETRY - 1)) { break; } if (!(e instanceof FileNotFoundException)) { int sleepTime = FileUtils.getSleepTime(repeat); LOG.info("Sleep for " + sleepTime + " milliseconds before retry " + (repeat+1)); try { Thread.sleep(sleepTime); } catch (InterruptedException timerEx) { LOG.info("sleep interrupted", timerEx.getMessage()); } FileSystem.closeAllForUGI(Utils.getUGI()); sourceFs = pathList.get(0).getFileSystem(hiveConf); destinationFs = destination.getFileSystem(hiveConf); } } repeat++; } if (!pathList.isEmpty()) { LOG.error("File copy failed even after several attempts. Files list: " + pathList); throw new IOException(ErrorMsg.REPL_FILE_SYSTEM_OPERATION_RETRY.getMsg()); } }
Source:
<code>private static void fillRwadefGeneralInformation(Swagger swagger, Definition definition, List<String> produces, List<String> consumes) { Info info = swagger.getInfo(); if (info.getContact() != null) { org.restlet.ext.apispark.internal.model.Contact contact = new org.restlet.ext.apispark.internal.model.Contact(); contact.setEmail(info.getContact().getEmail()); contact.setName(info.getContact().getName()); contact.setUrl(info.getContact().getUrl()); definition.setContact(contact); } if (info.getLicense() != null) { org.restlet.ext.apispark.internal.model.License license = new org.restlet.ext.apispark.internal.model.License(); license.setName(info.getLicense().getName()); license.setUrl(info.getLicense().getUrl()); definition.setLicense(license); } Contract contract = new Contract(); contract.setDescription(info.getDescription()); contract.setName(info.getTitle()); definition.setContract(contract); if (swagger.getProduces() != null) { produces.addAll(swagger.getProduces()); } if (swagger.getConsumes() != null) { consumes.addAll(swagger.getConsumes()); } definition.setVersion(info.getVersion()); definition.setTermsOfService(info.getTermsOfService()); definition.setAttribution(null); <START> definition.setKeywords(new ArrayList<String>()); <END> }</code><technical_language>empty list instead of null</technical_language>

Target:
private static void fillRwadefGeneralInformation(Swagger swagger, Definition definition, List<String> produces, List<String> consumes) { Info info = swagger.getInfo(); if (info.getContact() != null) { org.restlet.ext.apispark.internal.model.Contact contact = new org.restlet.ext.apispark.internal.model.Contact(); contact.setEmail(info.getContact().getEmail()); contact.setName(info.getContact().getName()); contact.setUrl(info.getContact().getUrl()); definition.setContact(contact); } if (info.getLicense() != null) { org.restlet.ext.apispark.internal.model.License license = new org.restlet.ext.apispark.internal.model.License(); license.setName(info.getLicense().getName()); license.setUrl(info.getLicense().getUrl()); definition.setLicense(license); } Contract contract = new Contract(); contract.setDescription(info.getDescription()); contract.setName(info.getTitle()); definition.setContract(contract); if (swagger.getProduces() != null) { produces.addAll(swagger.getProduces()); } if (swagger.getConsumes() != null) { consumes.addAll(swagger.getConsumes()); } definition.setVersion(info.getVersion()); definition.setTermsOfService(info.getTermsOfService()); definition.setAttribution(null); }
Source:
<code>protected boolean shouldProcessLine(String itemKey, ConcurStandardAccountingExtractDetailLine saeLine) { switch (saeLine.getPaymentCode()) { case ConcurConstants.PAYMENT_CODE_CASH : return true; case ConcurConstants.PAYMENT_CODE_UNIVERSITY_BILLED_OR_PAID : reportCorporateCardPayment(saeLine); return true; case ConcurConstants.PAYMENT_CODE_PRE_PAID_OR_OTHER : LOG.warn("Found a transaction with a Pre-Paid/Other payment code; it will not be processed. Item key: " + itemKey); reportUnprocessedLine(saeLine, "The line has the Pre-Paid/Other (COPD) payment code"); return false; case ConcurConstants.PAYMENT_CODE_PSEUDO : LOG.warn("Found a transaction with a Pseudo payment code; it will not be processed. Item key: " + itemKey); reportBypassOfLineWithPseudoPaymentCode(saeLine); reportUnprocessedLine(saeLine, "The line has the Pseudo (XXXX) payment code"); return false; default : LOG.warn("Found a transaction with an unknown payment code; it will not be processed. Item key: " + itemKey); <START> reportUnprocessedLine(saeLine, "The line has an unrecognized payment code"); <END> return false; } }</code><technical_language>I warning messages server log give enough information track problem actual detail line issue. want consider adding Concur ReportId message server log noise</technical_language>

Target:
protected boolean shouldProcessLine(String itemKey, ConcurStandardAccountingExtractDetailLine saeLine) { switch (saeLine.getPaymentCode()) { case ConcurConstants.PAYMENT_CODE_CASH : return true; case ConcurConstants.PAYMENT_CODE_UNIVERSITY_BILLED_OR_PAID : reportCorporateCardPayment(saeLine); return true; case ConcurConstants.PAYMENT_CODE_PRE_PAID_OR_OTHER : reportUnprocessedLine(saeLine, "The line has the Pre-Paid/Other (COPD) payment code"); return false; case ConcurConstants.PAYMENT_CODE_PSEUDO : reportBypassOfLineWithPseudoPaymentCode(saeLine); reportUnprocessedLine(saeLine, "The line has the Pseudo (XXXX) payment code"); return false; default : reportUnprocessedLine(saeLine, "The line has an unrecognized payment code"); return false; } }
Source:
<code>private AtomicOperation doJsonify(List<Long> records, boolean includePrimaryKey, Compoundable store, StringBuilder jsonStr) { AtomicOperation operation = store.startAtomicOperation(); try { Map<Long, Map<String, Set<Object>>> result = Maps.newHashMap(); Map<String, Set<Object>> resultNoKey = Maps.newHashMap(); for (Long record: records) { Map<String, Set<Object>> rec = Maps.newHashMap(); Map<String, Set<TObject>> r = operation.browse(record); for (Map.Entry<String, Set<TObject>> entry: r.entrySet()) { Set<Object> values = Transformers.transformSet(entry.getValue(), <START> new Function<TObject, Object>() { <END> @Override public Object apply(TObject input) { return Convert .thriftToJava(input); } }); rec.put(entry.getKey(), values); if (!includePrimaryKey) { resultNoKey.put(entry.getKey(), values); } } if (includePrimaryKey) { result.put(record, rec); } } if (includePrimaryKey){ jsonStr.append(Convert.javaToJson(result)); } else { jsonStr.append(Convert.javaToJson(resultNoKey)); } return operation; } catch (AtomicStateException e) { return null; } }</code><technical_language>define a new static instance of this function in org.cinchapi.concourse.server.storage.Functions class. TOBJECT_TO_JAVA want reuse again. necessary, a nice code refactoring if get a chance do</technical_language>

Target:
private AtomicOperation doJsonify(List<Long> records, boolean includePrimaryKey, Compoundable store, StringBuilder jsonStr) { AtomicOperation operation = store.startAtomicOperation(); try { List<Map<String, Set<Object>>> result = Lists.newLinkedList(); Set<Map<String, Set<Object>>> resultNoKey = Sets.newHashSet(); for (Long record: records) { Map<String, Set<Object>> rec = Maps.newHashMap(); Map<String, Set<TObject>> r = operation.browse(record); for (Map.Entry<String, Set<TObject>> entry: r.entrySet()) { Set<Object> values = Transformers.transformSet(entry.getValue(), Functions.TOBJECT_TO_JAVA); rec.put(entry.getKey(), values); } if (includePrimaryKey) { Set<Object> recordSet = Sets.newHashSet(); recordSet.add(record); rec.put("$primaryKey$", recordSet); result.add(rec); } else { resultNoKey.add(rec); } } if (includePrimaryKey) { jsonStr.append(Convert.javaToJson(result)); } else { jsonStr.append(Convert.javaToJson(resultNoKey)); } return operation; } catch (AtomicStateException e) { return null; } }
Source:
<code>public boolean equals(final Object o) { if (o instanceof IntraLineDiffKey) { final IntraLineDiffKey k = (IntraLineDiffKey) o; return aId.equals(k.aId) && bId.equals(k.bId) <START> && ignoreWhitespace.equals(k.ignoreWhitespace); <END> } return false; }</code><technical_language>&& ignoreWhitespace == k.ignoreWhitespace</technical_language>

Target:
public boolean equals(final Object o) { if (o instanceof IntraLineDiffKey) { final IntraLineDiffKey k = (IntraLineDiffKey) o; return aId.equals(k.aId) && bId.equals(k.bId) && ignoreWhitespace == k.ignoreWhitespace; } return false; }
Source:
<code>private Mono<ServicePrincipal> submitRolesAsync(final ServicePrincipal servicePrincipal) { Mono<ServicePrincipal> create; if (rolesToCreate.isEmpty()) { create = Mono.just(servicePrincipal); } else { create = Flux .fromIterable(rolesToCreate.entrySet()) .flatMap( roleEntry -> manager() .roleAssignments() .define(this.manager().sdkContext().randomUuid()) .forServicePrincipal(servicePrincipal) .withBuiltInRole(roleEntry.getValue()) .withScope(roleEntry.getKey()) .createAsync()) .doOnNext( indexable -> <START> cachedRoleAssignments.put((indexable).id(), indexable)) <END> .last() .map( indexable -> { rolesToCreate.clear(); return servicePrincipal; }); } Mono<ServicePrincipal> delete; if (rolesToDelete.isEmpty()) { delete = Mono.just(servicePrincipal); } else { delete = Flux .fromIterable(rolesToDelete) .flatMap( role -> manager() .roleAssignments() .deleteByIdAsync(cachedRoleAssignments.get(role).id()) .thenReturn(role)) .doOnNext(s -> cachedRoleAssignments.remove(s)) .last() .map( s -> { rolesToDelete.clear(); return servicePrincipal; }); } return create.mergeWith(delete).last(); }</code><technical_language>indexable.id()</technical_language>

Target:
private Mono<ServicePrincipal> submitRolesAsync(final ServicePrincipal servicePrincipal) { Mono<ServicePrincipal> create; if (rolesToCreate.isEmpty()) { create = Mono.just(servicePrincipal); } else { create = Flux .fromIterable(rolesToCreate.entrySet()) .flatMap( roleEntry -> manager() .roleAssignments() .define(this.manager().sdkContext().randomUuid()) .forServicePrincipal(servicePrincipal) .withBuiltInRole(roleEntry.getValue()) .withScope(roleEntry.getKey()) .createAsync()) .doOnNext( indexable -> cachedRoleAssignments.put(indexable.id(), indexable)) .last() .map( indexable -> { rolesToCreate.clear(); return servicePrincipal; }); } Mono<ServicePrincipal> delete; if (rolesToDelete.isEmpty()) { delete = Mono.just(servicePrincipal); } else { delete = Flux .fromIterable(rolesToDelete) .flatMap( role -> manager() .roleAssignments() .deleteByIdAsync(cachedRoleAssignments.get(role).id()) .thenReturn(role)) .doOnNext(s -> cachedRoleAssignments.remove(s)) .last() .map( s -> { rolesToDelete.clear(); return servicePrincipal; }); } return create.mergeWith(delete).last(); }
Source:
<code>protected void handleSuccess(boolean isUseEmulator, @NonNull String providerId, @NonNull FirebaseUser user, @NonNull OAuthCredential credential, boolean isNewUser, boolean setPendingCredential) { String accessToken = isUseEmulator <START> ? "fake_access_token" <END> : credential.getAccessToken(); String secret = isUseEmulator ? "fake_secret" : credential.getAccessToken(); IdpResponse.Builder response = new IdpResponse.Builder( new User.Builder( providerId, user.getEmail()) .setName(user.getDisplayName()) .setPhotoUri(user.getPhotoUrl()) .build()) .setToken(accessToken) .setSecret(secret); if (setPendingCredential) { response.setPendingCredential(credential); } response.setNewUser(isNewUser); setResult(Resource.<IdpResponse>forSuccess(response.build())); }</code><technical_language>I assume this is account for emulator returning credentials? imagine</technical_language>

Target:
protected void handleSuccess(boolean isUseEmulator, @NonNull String providerId, @NonNull FirebaseUser user, @NonNull OAuthCredential credential, boolean isNewUser, boolean setPendingCredential) { String accessToken = credential.getAccessToken(); if (accessToken == null && isUseEmulator) { accessToken = "fake_access_token"; } String secret = credential.getSecret(); if (secret == null && isUseEmulator) { secret = "fake_secret"; } IdpResponse.Builder response = new IdpResponse.Builder( new User.Builder( providerId, user.getEmail()) .setName(user.getDisplayName()) .setPhotoUri(user.getPhotoUrl()) .build()) .setToken(accessToken) .setSecret(secret); if (setPendingCredential) { response.setPendingCredential(credential); } response.setNewUser(isNewUser); setResult(Resource.<IdpResponse>forSuccess(response.build())); }
Source:
<code><START> private ActionModeWrapper() { } <END></code><technical_language>actionBarWrapper</technical_language>

Target:
private ActionModeWrapper() { onView(TITLE_MATCHER) .check(matches(isDisplayed())); onView(NAVIGATE_UP_MATCHER) .check(matches(isDisplayed())); onView(CONFIRM_MATCHER) .check(matches(isDisplayed())); }
Source:
<code>private void rewireGeneric(GenericConstraint constraint, List<ResolverBundle> visited) { if (constraint.getSelectedSupplier() != null) return; GenericDescription[] suppliers = ((GenericSpecification) constraint.getVersionConstraint()).getSuppliers(); if (suppliers == null) return; VersionHashMap<GenericCapability> namespace = resolverGenerics.get(constraint.getNameSpace()); if (namespace == null) { System.err.println("Could not find matching capability for " + constraint.getVersionConstraint()); return; } String constraintName = constraint.getName(); List<GenericCapability> matches = constraintName == null ? namespace.get(constraintName) : namespace.getAllValues(); for (GenericCapability match : matches) { for (GenericDescription supplier : suppliers) if (match.getBaseDescription() == supplier) constraint.addPossibleSupplier(match); } VersionSupplier[] matchingCapabilities = constraint.getPossibleSuppliers(); if (matchingCapabilities != null) for (VersionSupplier <START> matchingCapabilitie : <END> matchingCapabilities) { rewireBundle(matchingCapabilitie.getResolverBundle(), visited); } }</code><technical_language>rename matchingCapability</technical_language>

Target:
private void rewireGeneric(GenericConstraint constraint, List<ResolverBundle> visited) { if (constraint.getSelectedSupplier() != null) return; GenericDescription[] suppliers = ((GenericSpecification) constraint.getVersionConstraint()).getSuppliers(); if (suppliers == null) return; VersionHashMap<GenericCapability> namespace = resolverGenerics.get(constraint.getNameSpace()); if (namespace == null) { System.err.println("Could not find matching capability for " + constraint.getVersionConstraint()); return; } String constraintName = constraint.getName(); List<GenericCapability> matches = constraintName == null ? namespace.get(constraintName) : namespace.getAllValues(); for (GenericCapability match : matches) { for (GenericDescription supplier : suppliers) if (match.getBaseDescription() == supplier) constraint.addPossibleSupplier(match); } VersionSupplier[] matchingCapabilities = constraint.getPossibleSuppliers(); if (matchingCapabilities != null) for (VersionSupplier matchingCapability : matchingCapabilities) { rewireBundle(matchingCapability.getResolverBundle(), visited); } }
Source:
<code>public RepoObjectMetadata getManuscript(ArticleIdentity article) { RepoCollectionMetadata articleCollection = findCollectionFor(article); Map<String, ?> manuscript = (Map<String, ?>) ((Map<String, ?>) articleCollection.getJsonUserMetadata().get()).get("manuscript"); RepoVersion manuscriptVersion = parseRepoVersion(manuscript); <START> RepoObjectMetadata repoObjectMetadata; <END> try { repoObjectMetadata = contentRepoService.getRepoObjectMetadata(manuscriptVersion); } catch (NotFoundException nfe){ throw entityNotFound(nfe.getMessage() + ": " + manuscriptVersion); } return repoObjectMetadata; }</code><technical_language>This variable needed. do return contentRepoService.getRepoObjectMetadata(manuscriptVersion); try-block</technical_language>

Target:
public RepoObjectMetadata getManuscript(ArticleIdentity article) { RepoCollectionMetadata articleCollection = findCollectionFor(article); Map<String, ?> manuscript = (Map<String, ?>) ((Map<String, ?>) articleCollection.getJsonUserMetadata().get()).get("manuscript"); RepoVersion manuscriptVersion = parseRepoVersion(manuscript); try { return contentRepoService.getRepoObjectMetadata(manuscriptVersion); } catch (NotFoundException nfe){ throw reportNotFound(article, "object metadata", nfe); } }
Source:
<code>protected Collection<GrantedAuthority> extractAuthorities(Jwt jwt) { <START> return JwtAuthorityConverter.getInstance().convert(jwt); <END> }</code><technical_language>Allow injecting Converter<Jwt, Collection<GrantedAuthority>></technical_language>

Target:
protected Collection<GrantedAuthority> extractAuthorities(Jwt jwt) { return this.jwtGrantedAuthoritiesConverter.convert(jwt); }
Source:
<code>public void syncOrTimeout(String path) throws KeeperException { final CountDownLatch latch = new CountDownLatch(1); long startTime = EnvironmentEdgeManager.currentTime(); this.recoverableZooKeeper.sync(path, (i, s, o) -> latch.countDown(), null); try { if (!latch.await(zkSyncTimeout, TimeUnit.MILLISECONDS)) { <START> LOG.error("sync() operation to ZK timed out. Configured timeout: {}ms. This usually points " <END> + "to a ZK side issue. Check ZK server logs and metrics.", zkSyncTimeout); throw new KeeperException.RequestTimeoutException(); } } catch (InterruptedException e) { LOG.warn("Interrupted waiting for ZK sync() to finish.", e); Thread.currentThread().interrupt(); return; } if (LOG.isDebugEnabled()) { LOG.debug("ZK sync() operation took {}ms", EnvironmentEdgeManager.currentTime() - startTime); } }</code><technical_language>IMHO error is fine warn. warn for InterruptedException also</technical_language>

Target:
public void syncOrTimeout(String path) throws KeeperException { final CountDownLatch latch = new CountDownLatch(1); long startTime = EnvironmentEdgeManager.currentTime(); this.recoverableZooKeeper.sync(path, (i, s, o) -> latch.countDown(), null); try { if (!latch.await(zkSyncTimeout, TimeUnit.MILLISECONDS)) { LOG.warn("sync() operation to ZK timed out. Configured timeout: {}ms. This usually points " + "to a ZK side issue. Check ZK server logs and metrics.", zkSyncTimeout); throw new KeeperException.RequestTimeoutException(); } } catch (InterruptedException e) { LOG.warn("Interrupted waiting for ZK sync() to finish.", e); Thread.currentThread().interrupt(); return; } if (LOG.isDebugEnabled()) { LOG.debug("ZK sync() operation took {}ms", EnvironmentEdgeManager.currentTime() - startTime); } }
Source:
<code>public void testPreconfiguredIteratorWithDefaultIterator3() throws AccumuloException, TableNotFoundException, AccumuloSecurityException, TableExistsException { Connector conn = getConnector(); String tableName = getUniqueNames(2)[0]; NewTableConfiguration ntc = new NewTableConfiguration(); IteratorSetting setting = new IteratorSetting(10, "someName", "foo.bar"); ntc.attachIterator(setting, EnumSet.of(IteratorScope.scan)); conn.tableOperations().create(tableName, ntc); check(conn, tableName, new String[] {"table.iterator.scan.someName=10,foo.bar"}, true); Map<String,EnumSet<IteratorScope>> iteratorList = conn.tableOperations().listIterators(tableName); <START> assertEquals(2, iteratorList.size()); <END> conn.tableOperations().removeIterator(tableName, "someName", EnumSet.of(IteratorScope.scan)); check(conn, tableName, new String[] {}, true); iteratorList = conn.tableOperations().listIterators(tableName); assertEquals(1, iteratorList.size()); }</code><technical_language>check EnumSet inthe ensure scan scope is set</technical_language>

Target:
public void testPreconfiguredIteratorWithDefaultIterator3() throws AccumuloException, TableNotFoundException, AccumuloSecurityException, TableExistsException { Connector conn = getConnector(); String tableName = getUniqueNames(2)[0]; NewTableConfiguration ntc = new NewTableConfiguration(); IteratorSetting setting = new IteratorSetting(10, "someName", "foo.bar"); ntc.attachIterator(setting, EnumSet.of(IteratorScope.scan)); conn.tableOperations().create(tableName, ntc); verifyIterators(conn, tableName, new String[] {"table.iterator.scan.someName=10,foo.bar"}, true); Map<String,EnumSet<IteratorScope>> iteratorList = conn.tableOperations().listIterators(tableName); assertEquals(2, iteratorList.size()); assertEquals(iteratorList.get("someName"), EnumSet.of(IteratorScope.scan)); conn.tableOperations().removeIterator(tableName, "someName", EnumSet.of(IteratorScope.scan)); verifyIterators(conn, tableName, new String[] {}, true); iteratorList = conn.tableOperations().listIterators(tableName); assertEquals(1, iteratorList.size()); }
Source:
<code>public void testStartAndCompleteTaskUseOfAsyncResponseHandler() { <START> ResponseCallback callback = new BlockingResponseCallback(null); <END> testStartAndCompleteTask(new AsyncResponseHandler(callback)); }</code><technical_language>check responses callback</technical_language>

Target:
public void testStartAndCompleteTaskUseOfAsyncResponseHandler() throws Exception { ResponseCallback callback = new BlockingResponseCallback(null); testStartAndCompleteTask(new AsyncResponseHandler(callback)); }
Source:
<code>public void shouldBeAbleToRequestARefund_fullAmount() { Long refundAmount = defaultTestCharge.getAmount(); ValidatableResponse validatableResponse = postRefundFor(defaultTestCharge.getExternalChargeId(), refundAmount, defaultTestCharge.getAmount()); String refundId = assertRefundResponseWith(refundAmount, validatableResponse, ACCEPTED.getStatusCode()); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); assertThat(refundsFoundByChargeId, hasItems(aRefundMatching(refundId, is(notNullValue()), defaultTestCharge.getChargeId(), refundAmount, "REFUNDED"))); <START> assertRefundsHistoryInDBForSuccessfulOrPartialRefund(defaultTestCharge); <END> }</code><technical_language>this deleted is asserted in shouldBeAbleToRequestARefund_partialAmount test is sufficient. need overboard here</technical_language>

Target:
public void shouldBeAbleToRequestARefund_fullAmount() { Long refundAmount = defaultTestCharge.getAmount(); ValidatableResponse validatableResponse = postRefundFor(defaultTestCharge.getExternalChargeId(), refundAmount, defaultTestCharge.getAmount()); String refundId = assertRefundResponseWith(refundAmount, validatableResponse, ACCEPTED.getStatusCode()); List<Map<String, Object>> refundsFoundByChargeId = databaseTestHelper.getRefundsByChargeId(defaultTestCharge.getChargeId()); assertThat(refundsFoundByChargeId.size(), is(1)); assertThat(refundsFoundByChargeId, hasItems(aRefundMatching(refundId, is(notNullValue()), defaultTestCharge.getChargeId(), refundAmount, "REFUNDED"))); assertRefundsHistoryInOrderInDBForSuccessfulOrPartialRefund(defaultTestCharge); }
Source:
<code>private boolean hasFallback(){ <START> return properties.get("fallback") != null; <END> }</code><technical_language>Reminds of containsKey() :smile:</technical_language>

Target:
private boolean hasFallback(){ return properties.containsKey("fallback"); }
Source:
<code>private EncryptionData getAndValidateEncryptionData(String encryptedDataString) { if (encryptedDataString == null) { throw logger.logExceptionAsError(new IllegalStateException(CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB)); } <START> ObjectMapper objectMapper = new ObjectMapper(); <END> try { EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class); if (encryptionData == null) { throw logger.logExceptionAsError(new IllegalStateException( CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB)); } Objects.requireNonNull(encryptionData.contentEncryptionIV()); Objects.requireNonNull(encryptionData.wrappedContentKey().getEncryptedKey()); if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1.equals(encryptionData.encryptionAgent().getProtocol())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT, "Invalid Encryption Agent. This version of the client library does not understand the " + "Encryption Agent set on the blob message: %s", encryptionData.encryptionAgent()))); } return encryptionData; } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } }</code><technical_language>create a static instance of this ObjectMapper avoid creating lots of objects for decryptBlob call</technical_language>

Target:
private EncryptionData getAndValidateEncryptionData(String encryptedDataString) { if (encryptedDataString == null) { return null; } ObjectMapper objectMapper = new ObjectMapper(); try { EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class); if (encryptionData == null) { return encryptionData; } Objects.requireNonNull(encryptionData.getContentEncryptionIV(), "contentEncryptionIV in encryptionData " + "cannot be null"); Objects.requireNonNull(encryptionData.getWrappedContentKey().getEncryptedKey(), "encryptedKey in " + "encryptionData.wrappedContentKey cannot be null"); if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1 .equals(encryptionData.getEncryptionAgent().getProtocol())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT, "Invalid Encryption Agent. This version of the client library does not understand the " + "Encryption Agent set on the blob message: %s", encryptionData.getEncryptionAgent()))); } return encryptionData; } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } }
Source:
<code>NativeVideoAdLoader( NendNativeAdForwarder forwarder, AdUnitMapper mapper, NativeMediationAdRequest nativeMediationAdRequest, Bundle mediationExtras) { Context context = forwarder.contextWeakReference.get(); if (context == null) { Log.e(TAG, "Your context may be released..."); forwarder.failedToLoad(AdRequest.ERROR_CODE_INVALID_REQUEST); return; } this.forwarder = forwarder; VideoOptions nativeVideoOptions = nativeMediationAdRequest.getNativeAdOptions().getVideoOptions(); if (nativeVideoOptions == null) { videoAdLoader = new NendAdNativeVideoLoader(context, mapper.spotId, mapper.apiKey, NendAdNativeVideo.VideoClickOption.LP); } else { videoAdLoader = new NendAdNativeVideoLoader(context, mapper.spotId, mapper.apiKey, (nativeVideoOptions.getClickToExpandRequested() ? NendAdNativeVideo.VideoClickOption.FullScreen : NendAdNativeVideo.VideoClickOption.LP) ); } videoAdLoader.setMediationName(MEDIATION_NAME_ADMOB); <START> videoAdLoader.setUserId(mediationExtras.getString(NendMediationAdapter.KEY_USER_ID, "")); <END> }</code><technical_language>Please null-check mediationExtras here. This NPE if extras null</technical_language>

Target:
NativeVideoAdLoader( NendNativeAdForwarder forwarder, AdUnitMapper mapper, NativeMediationAdRequest nativeMediationAdRequest, Bundle mediationExtras) { Context context = forwarder.getContextFromWeakReference(); if (context == null) { Log.e(TAG, "Your context may be released..."); forwarder.failedToLoad(AdRequest.ERROR_CODE_INVALID_REQUEST); return; } this.forwarder = forwarder; NendAdNativeVideo.VideoClickOption clickOption = NendAdNativeVideo.VideoClickOption.LP; VideoOptions nativeVideoOptions = nativeMediationAdRequest.getNativeAdOptions().getVideoOptions(); if (nativeVideoOptions != null && nativeVideoOptions.getClickToExpandRequested()) { clickOption = NendAdNativeVideo.VideoClickOption.FullScreen; } videoAdLoader = new NendAdNativeVideoLoader(context, mapper.spotId, mapper.apiKey, clickOption); videoAdLoader.setMediationName(MEDIATION_NAME_ADMOB); if (mediationExtras != null) { videoAdLoader.setUserId(mediationExtras.getString(NendMediationAdapter.KEY_USER_ID, "")); } }
Source:
<code>static Map<String, Map<String, Integer>> getConstraintMap(TopologyDetails topo, Set<String> comps) { Map<String, Map<String, Integer>> matrix = new HashMap<>(); for (String comp : comps) { matrix.put(comp, new HashMap<>()); for (String comp2 : comps) { matrix.get(comp).put(comp2, 0); } <START> } <END> List<List<String>> constraints = (List<List<String>>) topo.getConf().get(Config.TOPOLOGY_CONSTRAINTS); if (constraints != null) { for (List<String> constraintPair : constraints) { String comp1 = constraintPair.get(0); String comp2 = constraintPair.get(1); if (!matrix.containsKey(comp1)) { LOG.warn("Comp: declared in constraints is not valid!", comp1); continue; } if (!matrix.containsKey(comp2)) { LOG.warn("Comp: declared in constraints is not valid!", comp2); continue; } matrix.get(comp1).put(comp2, 1); matrix.get(comp2).put(comp1, 1); } } return matrix; }</code><technical_language>This pretty means user (probably unintentionally) a component exist. In experience, users check logs if is wrong topology miss this error. display some kind of warning for this topology status if client side checking validate components in Config.TOPOLOGY_RAS_CONSTRAINTS valid components of topology</technical_language>

Target:
static Map<String, Map<String, Integer>> getConstraintMap(TopologyDetails topo, Set<String> comps) { Map<String, Map<String, Integer>> matrix = new HashMap<>(); for (String comp : comps) { matrix.put(comp, new HashMap<>()); for (String comp2 : comps) { matrix.get(comp).put(comp2, 0); } } List<List<String>> constraints = (List<List<String>>) topo.getConf().get(Config.TOPOLOGY_RAS_CONSTRAINTS); if (constraints != null) { for (List<String> constraintPair : constraints) { String comp1 = constraintPair.get(0); String comp2 = constraintPair.get(1); if (!matrix.containsKey(comp1)) { LOG.warn("Comp: declared in constraints is not valid!", comp1); continue; } if (!matrix.containsKey(comp2)) { LOG.warn("Comp: declared in constraints is not valid!", comp2); continue; } matrix.get(comp1).put(comp2, 1); matrix.get(comp2).put(comp1, 1); } } return matrix; }
Source:
<code>public boolean checkForUpdate(String currentVersion) { if (currentVersion == null || currentVersion.equals("UNOFFICIAL")) return false; int latest = getLatestVersion(); <START> if (latest > Integer.parseInt(currentVersion)) { <END> return download(latest); } return false; }</code><technical_language>a numeric pattern in PatternUtils, avoid formatting issues</technical_language>

Target:
public boolean checkForUpdate(String currentVersion) { if (currentVersion == null || !PatternUtils.NUMERIC.matcher(currentVersion).matches()) { return false; } int latest = getLatestVersion(); if (latest > Integer.parseInt(currentVersion)) { return download(latest); } return false; }
Source:
<code>private static List<LogEntry> readLog(String logPath) throws FileNotFoundException, IOException { if (logPath == null) { return Collections.emptyList(); } List<LogEntry> log = new ArrayList<>(); try (BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(logPath), UTF_8))) { @SuppressWarnings("nls") Pattern pattern = Pattern.compile("([^,]+)" + ",([0-9]+(?:[.][0-9]+)?)" + ",([^,]+)" + ",([^,]+)" + ",([^,]+)" + ",(.*)"); String line; while ((line = br.readLine()) != null) { Matcher m = pattern.matcher(line); <START> if (m.matches()) { <END> String ref = m.group(1); double t = Double.parseDouble(m.group(2)); long time = ((long) t) * 1000L; long index = (long) (t * 1e6); String user = m.group(3); ObjectId oldId = parseId(m.group(4)); ObjectId newId = parseId(m.group(5)); String msg = m.group(6); String email = user + "@gerrit"; PersonIdent who = new PersonIdent(user, email, time, -480); log.add(new LogEntry(ref, index, who, oldId, newId, msg)); } } } Collections.sort(log, LogEntry::compare); return log; }</code><technical_language>Asserting if match silently ignore errors save some time someday</technical_language>

Target:
private static List<LogEntry> readLog(String logPath) throws FileNotFoundException, IOException { if (logPath == null) { return Collections.emptyList(); } List<LogEntry> log = new ArrayList<>(); try (BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(logPath), UTF_8))) { @SuppressWarnings("nls") Pattern pattern = Pattern.compile("([^,]+)" + ",([0-9]+(?:[.][0-9]+)?)" + ",([^,]+)" + ",([^,]+)" + ",([^,]+)" + ",(.*)"); String line; while ((line = br.readLine()) != null) { Matcher m = pattern.matcher(line); if (!m.matches()) { throw new IOException("unparsed line: " + line); } String ref = m.group(1); double t = Double.parseDouble(m.group(2)); long time = ((long) t) * 1000L; long index = (long) (t * 1e6); String user = m.group(3); ObjectId oldId = parseId(m.group(4)); ObjectId newId = parseId(m.group(5)); String msg = m.group(6); String email = user + "@gerrit"; PersonIdent who = new PersonIdent(user, email, time, -480); log.add(new LogEntry(ref, index, who, oldId, newId, msg)); } } Collections.sort(log, LogEntry::compare); return log; }
Source:
<code>public boolean isTimeDetectionEnabled() { try { return Settings.Global.getInt(mContentResolver, <START> Settings.Global.AUTO_TIME) > 0; <END> } catch (Settings.SettingNotFoundException snfe) { return true; } }</code><technical_language>Technically booleans defined != 0</technical_language>

Target:
public boolean isTimeDetectionEnabled() { try { return Settings.Global.getInt(mContentResolver, Settings.Global.AUTO_TIME) != 0; } catch (Settings.SettingNotFoundException snfe) { return true; } }
Source:
<code>private boolean addToThreadList(ContextManager associateCM) { ContextManagerLink link = threadContextList.get(); if (link == null){ link = new ContextManagerLink(associateCM, null); threadContextList.set(link); return true; } if (associateCM == link.cm) { return true; } if (link.next == null) { ContextManager threadsCM = link.cm; if (threadsCM.activeThread != Thread.currentThread()) { link.cm = associateCM; return true; } link = null; for (int i = 0; i < threadsCM.activeCount; i++) { link = new ContextManagerLink(threadsCM, link); } threadsCM.activeCount = -1; } link = new ContextManagerLink(associateCM, link); threadContextList.set(link); associateCM.activeCount=-1; if(SanityManager.DEBUG){ if(SanityManager.DEBUG_ON("memoryLeakTrace")) { int size = 0; for (; link != null; link = link.next) ++size; if (size > 10) <START> System.out.println("memoryLeakTrace:ContextService:threadLocal " + size); <END> } } return false; }</code><technical_language>Log vs. System.out</technical_language>

Target:
private boolean addToThreadList(ContextManager associateCM) { ContextManagerLink link = threadContextList.get(); if (link == null){ link = new ContextManagerLink(associateCM, null); threadContextList.set(link); return true; } if (associateCM == link.cm) { return true; } if (link.next == null) { ContextManager threadsCM = link.cm; if (threadsCM.activeThread != Thread.currentThread()) { link.cm = associateCM; return true; } link = null; for (int i = 0; i < threadsCM.activeCount; i++) { link = new ContextManagerLink(threadsCM, link); } threadsCM.activeCount = -1; } link = new ContextManagerLink(associateCM, link); threadContextList.set(link); associateCM.activeCount=-1; if (LOG.isTraceEnabled()) { int size = 0; for (; link != null; link = link.next) ++size; if (size > 10) { LOG.trace("memoryLeakTrace:threadLocal " + size); } } return false; }
Source:
<code>public void init() { jobNameLabel.addRequiredIndicator(); jobTypeLabel.addRequiredIndicator(); jobRetriesLabel.addRequiredIndicator(); jobRetriesInput.setType("number"); jobRetriesInput.setAttribute("min", "0"); jobRetriesInput.setDefaultValue("0"); jobRetriesInput.addEventListener("keypress", getNumericInputListener(), false); myParametersGrid.setHeight("200px"); myParametersGrid.setEmptyTableWidget(new Label(constants.No_Parameters_added_yet())); initGridColumns(); initDateTimePicker(); Button button = new Button(Constants.INSTANCE.Add_Parameter(), new ClickHandler() { @Override public void onClick(ClickEvent event) { addNewParameter(); } }); <START> button.addStyleName("btn btn-default"); <END> advancedContent.add(myParametersGrid); advancedContent.add(button); inlineNotification.setType(InlineNotification.InlineNotificationType.DANGER); }</code><technical_language>Setting style needed for this component this is default already</technical_language>

Target:
public void init() { jobNameLabel.addRequiredIndicator(); jobTypeLabel.addRequiredIndicator(); jobRetriesLabel.addRequiredIndicator(); jobRetriesInput.setType("number"); jobRetriesInput.setAttribute("min", "0"); jobRetriesInput.setDefaultValue("0"); jobRetriesInput.addEventListener("keypress", getNumericInputListener(), false); myParametersGrid.setHeight("200px"); myParametersGrid.setEmptyTableWidget(new Label(constants.No_Parameters_added_yet())); initGridColumns(); initDateTimePicker(); Button button = GWT.create(Button.class); button.setText(Constants.INSTANCE.Add_Parameter()); button.addClickHandler(e -> addNewParameter()); advancedContent.add(myParametersGrid); advancedContent.add(button); inlineNotification.setType(InlineNotification.InlineNotificationType.DANGER); }
Source:
<code><START> public List<ConstrainedValue> getValuesWithConstraints(final Object state) { <END> final List<ConstrainedValue> result = new ArrayList<>(); constraints.forEach(new PMap.Consumer<SymbolicValue, Object>() { @Override public void accept(SymbolicValue value, Object valueConstraint) { if (valueConstraint instanceof ObjectConstraint) { ObjectConstraint constraint = (ObjectConstraint) valueConstraint; if (constraint.hasStatus(state)) { result.add(new ConstrainedValue(value, constraint)); } } } }); return result; }</code><technical_language>simply returning a map ? value->constraint ? this avoid create a new object (thus a new concept)</technical_language>

Target:
public Map<SymbolicValue, ObjectConstraint> getValuesWithConstraints(final Object state) { final Map<SymbolicValue, ObjectConstraint> result = new HashMap<>(); constraints.forEach(new PMap.Consumer<SymbolicValue, Object>() { @Override public void accept(SymbolicValue value, Object valueConstraint) { if (valueConstraint instanceof ObjectConstraint) { ObjectConstraint constraint = (ObjectConstraint) valueConstraint; if (constraint.hasStatus(state)) { result.put(value, constraint); } } } }); return result; }