auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String generateDockerCfg(Map<String, AuthConfig> authConfigs) throws InfrastructureException { try (StringWriter strWriter = new StringWriter(); JsonWriter jsonWriter = new Gson().newJsonWriter(strWriter)) { Base64.Encoder encoder = Base64.getEncoder(); jsonWriter.beginObject(); for (Map.Entry<String, AuthConfig> entry : authConfigs.entrySet()) { String name = entry.getKey(); AuthConfig authConfig = entry.getValue(); try { if (!name.startsWith("https://") && !name.startsWith("http://")) { name = "https://" + name; } jsonWriter.name(name); jsonWriter.beginObject(); jsonWriter.name("username"); jsonWriter.value(authConfig.getUsername()); jsonWriter.name("password"); jsonWriter.value(authConfig.getPassword()); jsonWriter.name("email"); jsonWriter.value("email@email"); String auth = new StringBuilder(authConfig.getUsername()) .append(':') .append(authConfig.getPassword()) .toString(); jsonWriter.name("auth"); jsonWriter.value(encoder.encodeToString(auth.getBytes())); jsonWriter.endObject(); } catch (IOException e) { <START> throw new InfrastructureException(e); <END> } } jsonWriter.endObject(); jsonWriter.flush(); return strWriter.toString(); } catch (IOException e) { throw new InfrastructureException(e); } }</code><technical_language>I IOException message user-friendly. wrap introduction for a user</technical_language>

Target:
private String generateDockerCfg(Map<String, AuthConfig> authConfigs) throws InfrastructureException { try (StringWriter strWriter = new StringWriter(); JsonWriter jsonWriter = new Gson().newJsonWriter(strWriter)) { Base64.Encoder encoder = Base64.getEncoder(); jsonWriter.beginObject(); for (Map.Entry<String, AuthConfig> entry : authConfigs.entrySet()) { String name = entry.getKey(); AuthConfig authConfig = entry.getValue(); try { if (!name.startsWith("https://") && !name.startsWith("http://")) { name = "https://" + name; } jsonWriter.name(name); jsonWriter.beginObject(); jsonWriter.name("username"); jsonWriter.value(authConfig.getUsername()); jsonWriter.name("password"); jsonWriter.value(authConfig.getPassword()); jsonWriter.name("email"); jsonWriter.value("email@email"); String auth = new StringBuilder(authConfig.getUsername()) .append(':') .append(authConfig.getPassword()) .toString(); jsonWriter.name("auth"); jsonWriter.value(encoder.encodeToString(auth.getBytes())); jsonWriter.endObject(); } catch (IOException e) { throw new InfrastructureException( "Unexpected exception occured while building the 'ImagePullSecret' from private docker registry user preferences", e); } } jsonWriter.endObject(); jsonWriter.flush(); return strWriter.toString(); } catch (IOException e) { throw new InfrastructureException(e); } }
Source:
<code>public boolean isScanMarkerRow(FlatRow row) { <START> return row.getCells() == null || row.getCells().isEmpty(); <END> }</code><technical_language>getCells() null</technical_language>

Target:
public boolean isScanMarkerRow(FlatRow row) { return row.getCells().isEmpty(); }
Source:
<code>public E next() { if (Graph.this.modcount != expectedModCount) { throw new ConcurrentModificationException(); } if (iteratorStack.isEmpty()) { throw new NoSuchElementException(); } Node<E> resultNode = iteratorStack.getLast().next(); if (consumedNodes.add(resultNode)) { iteratorStack.add(Iterators.filter(resultNode.getChildren().iterator(), <START> new Predicate<Node<E>>() { <END> public boolean apply(Node<E> input) { return !consumedNodes.contains(input); } })); } ListIterator<Iterator<Node<E>>> reverseStackIterator = iteratorStack.listIterator(iteratorStack .size()); while (reverseStackIterator.hasPrevious() && !reverseStackIterator.previous().hasNext()) { reverseStackIterator.remove(); } return resultNode.getElement(); }</code><technical_language>find more elegant if current instance of ChildrenIterator used, ChildrenIterator implements Predicate<Node<E>>. iteratorStack.add(Iterators.filter(resultNode.getChildren().iterator(), this); /** * Predicate implementation, nodes consumed accepted. * * @param input * node filter * @return true If if node is in comsumedNodes. */ public boolean apply(Node<E> input) { return !consumedNodes.contains(input); }</technical_language>

Target:
public E next() { if (Graph.this.modcount != expectedModCount) { throw new ConcurrentModificationException(); } if (iteratorStack.isEmpty()) { throw new NoSuchElementException(); } Node<E> resultNode = iteratorStack.getLast().next(); if (consumedNodes.add(resultNode)) { iteratorStack.add(Iterators.filter(resultNode.getChildren().iterator(), this)); } ListIterator<Iterator<Node<E>>> reverseStackIterator = iteratorStack.listIterator(iteratorStack .size()); while (reverseStackIterator.hasPrevious() && !reverseStackIterator.previous().hasNext()) { reverseStackIterator.remove(); } return resultNode.getElement(); }
Source:
<code>public String getMessage() { StringBuilder message = new StringBuilder(); message.append("Error ").append(errorCode); message.append(" for user ").append(user); <START> if (!tableInfo.isEmpty()) { <END> message.append(" on table ").append(tableInfo); } message.append(" - ").append(super.getMessage()); return message.toString(); }</code><technical_language>equivalent. StringUtils version checks for null "" in call</technical_language>

Target:
public String getMessage() { StringBuilder message = new StringBuilder(); message.append("Error ").append(errorCode); message.append(" for user ").append(user); if (!StringUtils.isEmpty(tableInfo)) { message.append(" on table ").append(tableInfo); } message.append(" - ").append(super.getMessage()); return message.toString(); }
Source:
<code>public boolean isAllowTagsPropagation() { try { return this.getAnalysisEnvironment().getSkylarkSemantics().experimentalAllowTagsPropagation(); } catch (InterruptedException e) { <START> return false; <END> } }</code><technical_language>InterruptedException fetched (i.e. ctrl+c) told stop fetching. I proper do is add a throws InterruptedException</technical_language>

Target:
public boolean isAllowTagsPropagation() throws InterruptedException { return this.getAnalysisEnvironment().getSkylarkSemantics().experimentalAllowTagsPropagation(); }
Source:
<code>private String response(StatementResult result) { StringBuilder response = new StringBuilder(); response.append("\nSummary:"); ResultSummary summary = result.summary(); response.append("\nConstraints Added: ") .append(summary.counters().constraintsAdded()) .append("\nConstraints Removed: ") .append(summary.counters().constraintsRemoved()) .append("\nContains Updates: ") .append(summary.counters().containsUpdates()) .append("\nIndexes Added: ") .append(summary.counters().indexesAdded()) .append("\nIndexes Removed: ") .append(summary.counters().indexesRemoved()) .append("\nLabels Added: ") .append(summary.counters().labelsAdded()) .append("\nLabels Removed: ") .append(summary.counters().labelsRemoved()) .append("\nNodes Created: ") .append(summary.counters().nodesCreated()) .append("\nNodes Deleted: ") .append(summary.counters().nodesDeleted()) .append("\nRelationships Created: ") .append(summary.counters().relationshipsCreated()) .append("\nRelationships Deleted: ") .append(summary.counters().relationshipsDeleted()); response.append("\n\nRecords: "); if (isRecordQueryResults()) { <START> result.stream().forEach(record -> response.append("\n") <END> .append(record) ); } else { response.append("Skipped"); result.consume(); } return response.toString(); }</code><technical_language>Lambda in critical path a performance impact</technical_language>

Target:
private String response(StatementResult result) { StringBuilder response = new StringBuilder(); response.append("\nSummary:"); ResultSummary summary = result.summary(); response.append("\nConstraints Added: ") .append(summary.counters().constraintsAdded()) .append("\nConstraints Removed: ") .append(summary.counters().constraintsRemoved()) .append("\nContains Updates: ") .append(summary.counters().containsUpdates()) .append("\nIndexes Added: ") .append(summary.counters().indexesAdded()) .append("\nIndexes Removed: ") .append(summary.counters().indexesRemoved()) .append("\nLabels Added: ") .append(summary.counters().labelsAdded()) .append("\nLabels Removed: ") .append(summary.counters().labelsRemoved()) .append("\nNodes Created: ") .append(summary.counters().nodesCreated()) .append("\nNodes Deleted: ") .append(summary.counters().nodesDeleted()) .append("\nRelationships Created: ") .append(summary.counters().relationshipsCreated()) .append("\nRelationships Deleted: ") .append(summary.counters().relationshipsDeleted()); response.append("\n\nRecords: "); if (isRecordQueryResults()) { for (Record record : result.list()) { response.append("\n").append(record); } } else { response.append("Skipped"); result.consume(); } return response.toString(); }
Source:
<code>public Optional<PlanNode> apply(PlanNode node, Captures captures, Context context) { PlanNodeMatcher planNodeMatcher = new PlanNodeMatcher(context.getLookup()); Set<Rule> matching = ruleSet.rules().stream() .filter(rule -> matches(rule.getPattern(), node, planNodeMatcher)) .collect(toSet()); if (matching.size() == 0) { return empty(); } <START> return apply(node, getOnlyElement(matching), context); <END> }</code><technical_language>I get rid of RuleSetAdapter because: * assumes rules in RuleSet semantics (e.g: rule matches) * wraps executes rules in a actual optimization * allow test rules interact (e.g: trait rules other rewrite rules) * allows test rule set grouped in RuleSet, want test grouped rules (e.g: trait rules rewrites). * is a work RuleAssert limitation of testing singular rule. I test multiple rules explicitly in RuleAssert assertions</technical_language>

Target:
public Optional<PlanNode> apply(PlanNode node, Captures captures, Context context) { PlanNodeMatcher planNodeMatcher = new PlanNodeMatcher(context.getLookup()); Set<RuleMatch> matching = ruleSet.rules().stream() .map(rule -> new RuleMatch(rule, planNodeMatcher.match(rule.getPattern(), node))) .filter(ruleMatch -> ruleMatch.match.isPresent()) .collect(toSet()); if (matching.size() == 0) { return empty(); } return getOnlyElement(matching).apply(context); }
Source:
<code>protected List<Member> addIndirectMembers(PerunSession sess, Group group, List<Member> members, int sourceGroupId) throws InternalErrorException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException { List<Member> oldMembers = this.getGroupMembers(sess, group); for(Member member: members) { groupsManagerImpl.addMember(sess, group, member, MembershipType.INDIRECT, sourceGroupId); <START> getPerunBl().getAuditer().log(sess, "{} added to as INDIRECT.", member, group); <END> } List<Member> newMembers = this.getGroupMembers(sess, group); newMembers.removeAll(oldMembers); return newMembers; }</code><technical_language>Task#2630 logging AuditerLog</technical_language>

Target:
protected List<Member> addIndirectMembers(PerunSession sess, Group group, List<Member> members, int sourceGroupId) throws InternalErrorException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException { List<Member> oldMembers = this.getGroupActiveMembers(sess, group); for(Member member: members) { groupsManagerImpl.addMember(sess, group, member, MembershipType.INDIRECT, sourceGroupId); User user = getPerunBl().getUsersManagerBl().getUserByMember(sess, member); List<Resource> resources = getPerunBl().getResourcesManagerBl().getAssignedResources(sess, group); for (Resource resource : resources) { Facility facility = getPerunBl().getResourcesManagerBl().getFacility(sess, resource); try { getPerunBl().getAttributesManagerBl().setRequiredAttributes(sess, facility, resource, user, member); } catch(WrongAttributeAssignmentException ex) { throw new ConsistencyErrorException(ex); } catch(AttributeNotExistsException ex) { throw new ConsistencyErrorException(ex); } } } List<Member> newMembers = this.getGroupActiveMembers(sess, group); newMembers.removeAll(oldMembers); return newMembers; }
Source:
<code>public static void authenticate(HadoopDruidIndexerConfig config) { String principal = config.getSchema().getTuningConfig().getPrincipal(); String keytab = config.getSchema().getTuningConfig().getKeytab(); if (Strings.isNullOrEmpty(principal) || Strings.isNullOrEmpty(keytab)) { return; } Configuration conf = new Configuration(); UserGroupInformation.setConfiguration(conf); if (UserGroupInformation.isSecurityEnabled()) { try { if (UserGroupInformation.getCurrentUser().hasKerberosCredentials() == false <START> || UserGroupInformation.getCurrentUser().getUserName() != principal) { <END> log.info("trying to authenticate user [%s] with keytab [%s]", principal, keytab); UserGroupInformation.loginUserFromKeytab(principal, keytab); } } catch (IOException e) { log.error(e, "Failed to authenticate user principal [%s] with keytab [%s]", principal, keytab); } } }</code><technical_language>this .equals !=</technical_language>

Target:
public static void authenticate(HadoopDruidIndexerConfig config) { String principal = config.HADOOP_KERBEROS_CONFIG.getPrincipal(); String keytab = config.HADOOP_KERBEROS_CONFIG.getKeytab(); if (!Strings.isNullOrEmpty(principal) && !Strings.isNullOrEmpty(keytab)) { Configuration conf = new Configuration(); UserGroupInformation.setConfiguration(conf); if (UserGroupInformation.isSecurityEnabled()) { try { if (UserGroupInformation.getCurrentUser().hasKerberosCredentials() == false || !UserGroupInformation.getCurrentUser().getUserName().equals(principal)) { log.info("trying to authenticate user [%s] with keytab [%s]", principal, keytab); UserGroupInformation.loginUserFromKeytab(principal, keytab); } } catch (IOException e) { throw new ISE(e, "Failed to authenticate user principal [%s] with keytab [%s]", principal, keytab); } } } }
Source:
<code>public boolean visible() { switch (state_) { case HIDE: <START> return false; <END> case MINIMIZE: return false; default: return true; } }</code><technical_language>nit: need this return false; line</technical_language>

Target:
public boolean visible() { switch (state_) { case HIDE: case MINIMIZE: return false; default: return true; } }
Source:
<code><START> public String getValidCidr (ClaudiaData claudiaData, String region,int subNetElement) throws InfrastructureException{ <END> String cidr = String.format(NETWORK_CIDR, NET_ELEMENT, subNetElement); if (checkCidrValid(claudiaData, region, cidr)) { return cidr; } else { return getValidCidr (claudiaData, region,subNetElement+1); } }</code><technical_language>ClaudiaData claudiaData, String region, int subNetElement</technical_language>

Target:
private String getValidCidr (ClaudiaData claudiaData, String region, int subNetElement) throws InfrastructureException { String cidr = String.format(NETWORK_CIDR, NET_ELEMENT, subNetElement); if (checkCidrValid(claudiaData, region, cidr)) { return cidr; } else { return getValidCidr (claudiaData, region,subNetElement+1); } }
Source:
<code>public void onAuthStateChanged(@NonNull FirebaseAuth auth) { mSendButton.setEnabled(isSignedIn()); mMessageEdit.setEnabled(isSignedIn()); if (isSignedIn()) { attachRecyclerViewAdapter(); } else { Toast.makeText(this, R.string.signing_in, Toast.LENGTH_SHORT).show(); auth.signInAnonymously() .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { <START> attachRecyclerViewAdapter(); <END> } }) .addOnCompleteListener(new SignInResultNotifier(this)); } }</code><technical_language>I this success handler is necessary, sign in successfully listener trigger isSignedIn true attach adapter</technical_language>

Target:
public void onAuthStateChanged(@NonNull FirebaseAuth auth) { mSendButton.setEnabled(isSignedIn()); mMessageEdit.setEnabled(isSignedIn()); if (isSignedIn()) { attachRecyclerViewAdapter(); } else { Toast.makeText(this, R.string.signing_in, Toast.LENGTH_SHORT).show(); auth.signInAnonymously().addOnCompleteListener(new SignInResultNotifier(this)); } }
Source:
<code>private void initFirewallType() { <START> ListModel<FirewallType> firewallType = getFirewallType(); <END> firewallType.setItems(Arrays.asList(FirewallType.values())); firewallType.setIsChangeable(false); firewallType.setSelectedItem(FirewallType.FIREWALLD); }</code><technical_language>need in case of edit select firewall type configured cluster select default</technical_language>

Target:
private void initFirewallType() { ListModel<FirewallType> firewallType = getFirewallType(); firewallType.setItems(Arrays.asList(FirewallType.values())); firewallType.setIsChangeable(true); firewallType.setSelectedItem(FirewallType.FIREWALLD); }
Source:
<code>protected AuroraController getController() { String klass = config.getStringValue(Key.AURORA_CONTROLLER_CLASS); Config localConfig = Config.toLocalMode(this.config); <START> switch (klass) { <END> case "com.twitter.heron.scheduler.aurora.AuroraCLIController": return new AuroraCLIController( Runtime.topologyName(runtime), Context.cluster(localConfig), Context.role(localConfig), Context.environ(localConfig), AuroraContext.getHeronAuroraPath(localConfig), Context.verbose(localConfig)); case "com.twitter.heron.scheduler.aurora.AuroraHeronShellController": return new AuroraHeronShellController( Runtime.topologyName(runtime), Context.cluster(localConfig), Context.role(localConfig), Context.environ(localConfig), AuroraContext.getHeronAuroraPath(localConfig), Context.verbose(localConfig)); default: throw new RuntimeException("aurora controller class not found " + klass); } }</code><technical_language>This implementation is ugly bad. alternative is constant enum; another alternative is a boolean decide cases fail otherwise. Polymorphism another one</technical_language>

Target:
protected AuroraController getController() throws ClassNotFoundException, InstantiationException, IllegalAccessException { Boolean cliController = config.getBooleanValue(Key.AURORA_CONTROLLER_CLASS); Config localConfig = Config.toLocalMode(this.config); if (cliController) { return new AuroraCLIController( Runtime.topologyName(runtime), Context.cluster(localConfig), Context.role(localConfig), Context.environ(localConfig), AuroraContext.getHeronAuroraPath(localConfig), Context.verbose(localConfig)); } else { return new AuroraHeronShellController( Runtime.topologyName(runtime), Context.cluster(localConfig), Context.role(localConfig), Context.environ(localConfig), AuroraContext.getHeronAuroraPath(localConfig), Context.verbose(localConfig)); } }
Source:
<code>public String toHtml(Map<String, String> dynamicUpdateModes) { boolean hasUpdateModes = !dynamicUpdateModes.isEmpty(); List<ConfigKey> configs = sortedConfigs(); StringBuilder b = new StringBuilder(); b.append("<ul class=\"config-list\">\n"); for (ConfigKey key : configs) { if (key.internalConfig) { continue; } b.append("<li>\n"); b.append(String.format("<h4>" + "<a id=\"%1$s\" href=\"#%1$s\">%1$s</a>" + <START> "</h4>\n", key.name)); <END> b.append("<p>"); b.append(key.documentation.replaceAll("\n", "<br>")); b.append("</p>\n"); b.append("<table>" + "<tbody>\n"); for (String detail : headers()) { if (detail.equals("Name") || detail.equals("Description")) continue; addConfigDetail(b, detail, getConfigValue(key, detail)); } if (hasUpdateModes) { String updateMode = dynamicUpdateModes.get(key.name); if (updateMode == null) updateMode = "read-only"; addConfigDetail(b, "Update Mode:", updateMode); } b.append("</tbody></table>\n"); b.append("</li>\n"); } b.append("</ul>\n"); return b.toString(); }</code><technical_language>This stopbugs complain ... %n in format string instead of \n</technical_language>

Target:
public String toHtml(Map<String, String> dynamicUpdateModes) { boolean hasUpdateModes = !dynamicUpdateModes.isEmpty(); List<ConfigKey> configs = sortedConfigs(); StringBuilder b = new StringBuilder(); b.append("<ul class=\"config-list\">\n"); for (ConfigKey key : configs) { if (key.internalConfig) { continue; } b.append("<li>\n"); b.append(String.format("<h4>" + "<a id=\"%1$s\" href=\"#%1$s\">%1$s</a>" + "</h4>%n", key.name)); b.append("<p>"); b.append(key.documentation.replaceAll("\n", "<br>")); b.append("</p>\n"); b.append("<table>" + "<tbody>\n"); for (String detail : headers()) { if (detail.equals("Name") || detail.equals("Description")) continue; addConfigDetail(b, detail, getConfigValue(key, detail)); } if (hasUpdateModes) { String updateMode = dynamicUpdateModes.get(key.name); if (updateMode == null) updateMode = "read-only"; addConfigDetail(b, "Update Mode", updateMode); } b.append("</tbody></table>\n"); b.append("</li>\n"); } b.append("</ul>\n"); return b.toString(); }
Source:
<code>public MBeanServer getMBeanServer() { <START> return MBeanServerFactory.createMBeanServer(); <END> }</code><technical_language>I want change this of tests. platform MBeanServer exists default registrations end in a MBeanServer JVM's registrations (like heap thread mbeans)</technical_language>

Target:
public MBeanServer getMBeanServer() { return ManagementFactory.getPlatformMBeanServer(); }
Source:
<code>public void rollback() { <START> if (!sortedWriteToTmpPathEnabled) { <END> for (TempFile file : tempFiles) { cleanupFile(file.getPath()); } } outputWriter.rollback(); }</code><technical_language>note: This confusing. forget clean feature is rolled out</technical_language>

Target:
public void rollback() { if (!sortedWriteToTempPathEnabled) { for (TempFile file : tempFiles) { cleanupFile(file.getPath()); } } outputWriter.rollback(); }
Source:
<code>public void testMinimalWidthOneCellInEachRowWithPadding() throws Exception { gridData.appendColumn(column); gridData.appendRow(new DMNGridRow()); gridData.appendRow(new DMNGridRow()); gridData.appendRow(new DMNGridRow()); <START> mockCellsWithPadding(0, 0, PADDING, 100d); <END> mockCellsWithPadding(1, 0, PADDING, 150); mockCellsWithPadding(2, 0, PADDING, 125); Assertions.assertThat(column.getMinimumWidth()).isEqualTo(170); }</code><technical_language>I d is necessary here, simplified to: mockCellsWithPadding(0, 0, PADDING, 100);</technical_language>

Target:
public void testMinimalWidthOneCellInEachRowWithPadding() throws Exception { gridData.appendColumn(column); gridData.appendRow(new DMNGridRow()); gridData.appendRow(new DMNGridRow()); gridData.appendRow(new DMNGridRow()); mockCellsWithPadding(0, 0, PADDING, 100); mockCellsWithPadding(1, 0, PADDING, 150); mockCellsWithPadding(2, 0, PADDING, 125); Assertions.assertThat(column.getMinimumWidth()).isEqualTo(170); }
Source:
<code>private void fillDriverSpecificChannelConfiguration(final Tocd mainOcd, final List<Tad> driverSpecificChannelConfiguration) { if (mainOcd == null || driverSpecificChannelConfiguration == null) { return; } final ChannelDescriptor basicChanneldescriptor = new BaseChannelDescriptor(); final Object baseChannelDescriptor = basicChanneldescriptor.getDescriptor(); if (nonNull(baseChannelDescriptor) && baseChannelDescriptor instanceof List<?>) { List<Tad> channelConfiguration = (List<Tad>) baseChannelDescriptor; channelConfiguration.addAll(driverSpecificChannelConfiguration); for (final Tad attribute : channelConfiguration) { <START> for (final String channelName : this.assetConfiguration.getAssetChannels().keySet()) { <END> final Tad newAttribute = cloneAd(attribute, channelName); mainOcd.addAD(newAttribute); } } } }</code><technical_language>iteration entrySet is faster</technical_language>

Target:
private void fillDriverSpecificChannelConfiguration(final Tocd mainOcd, final List<Tad> driverSpecificChannelConfiguration) { if (mainOcd == null || driverSpecificChannelConfiguration == null) { return; } final ChannelDescriptor basicChanneldescriptor = new BaseChannelDescriptor(); final Object baseChannelDescriptor = basicChanneldescriptor.getDescriptor(); if (nonNull(baseChannelDescriptor) && baseChannelDescriptor instanceof List<?>) { List<Tad> channelConfiguration = (List<Tad>) baseChannelDescriptor; channelConfiguration.addAll(driverSpecificChannelConfiguration); for (final Tad attribute : channelConfiguration) { for (final Entry<String, Channel> entry : this.assetConfiguration.getAssetChannels().entrySet()) { final String channelName = entry.getKey(); final Tad newAttribute = cloneAd(attribute, channelName); mainOcd.addAD(newAttribute); } } } }
Source:
<code>private void appendParameters(StringBuilder builder, String... paramPairs) { <START> Arrays.stream(paramPairs).forEach(paramPair -> builder.append(paramPair).append("&")); <END> builder.deleteCharAt(builder.lastIndexOf("&")); }</code><technical_language>I prefer try change mutable object while traversing stream. i make: builder.append(Arrays.stream(paramPairs).collect(Collectors.joining("&")));</technical_language>

Target:
private void appendParameters(StringBuilder builder, String... paramPairs) { builder.append(Arrays.stream(paramPairs).collect(Collectors.joining("&"))); }
Source:
<code>private void visitUnaryExpression(UnaryExpressionTree tree) { visitReadVariable(tree.expression()); <START> visitAssignedVariable(tree.expression()); <END> }</code><technical_language>unary operators write? e.g. -</technical_language>

Target:
private void visitUnaryExpression(UnaryExpressionTree tree) { tree.expression().accept(this); visitAssignedVariable(tree.expression()); }
Source:
<code>private static FairyModule getFairyModuleForLocale(DataMaster dataMaster, Locale locale, Random random) { LanguageCode code = LanguageCode.valueOf(locale.getLanguage().toUpperCase()); switch (code) { case PL: return new PlFairyModule(dataMaster, random); case EN: return new EnFairyModule(dataMaster, random); case ES: return new EsFairyModule(dataMaster, random); default: <START> return new EnFairyModule(dataMaster, random); <END> } }</code><technical_language>I log "No data for language - EN"</technical_language>

Target:
private static FairyModule getFairyModuleForLocale(DataMaster dataMaster, Locale locale, Random random) { LanguageCode code = LanguageCode.valueOf(locale.getLanguage().toUpperCase()); switch (code) { case PL: return new PlFairyModule(dataMaster, random); case EN: return new EnFairyModule(dataMaster, random); case ES: return new EsFairyModule(dataMaster, random); default: LOG.info("No data for your language - using EN"); return new EnFairyModule(dataMaster, random); } }
Source:
<code>private UserModel createUser(RealmModel realm, String username) { return new AbstractUserAdapterFederatedStorage(session, realm, model) { @Override <START> public String doGetUsername() { <END> return username; } @Override public void doSetUsername(String username1) { if (!username1.equals(username)) { throw new RuntimeException("Unsupported to change username"); } } }; }</code><technical_language>UserStorage SPI needs compatible. means UserStorage providers developed in previous Keycloak versions work newest version changes needed in sources. BackwardsCompatibilityUserStorage provider work this change needed... similar good for other user storage providers - nice if changes required in</technical_language>

Target:
private UserModel createUser(RealmModel realm, String username) { return new AbstractUserAdapterFederatedStorage(session, realm, model) { @Override public String getUsername() { return username; } @Override public void setUsername(String username1) { if (!username1.equals(username)) { throw new RuntimeException("Unsupported to change username"); } } }; }
Source:
<code>public void tearDown(ManagementClient managementClient, String containerId) throws Exception { <START> this.module.remove(); <END> }</code><technical_language>This reverse minimum permissions changes</technical_language>

Target:
public void tearDown(ManagementClient managementClient, String containerId) throws Exception { this.module.remove(); if (writeMinimumPermissions()) { final ModelNode address = new ModelNode(); address.add("subsystem", "security-manager"); address.add("deployment-permissions", "default"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION); operation.get(ModelDescriptionConstants.OP_ADDR).set(address); operation.get("name").set("minimum-permissions"); operation.get("value").set(backupList); ManagementOperations.executeOperation(managementClient.getControllerClient(), operation); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); } }
Source:
<code><START> public void init(){ END> intervalTree.clear(); intervalTree.put(1, 10, "foo1"); intervalTree.put(2, 9, "foo2"); intervalTree.put(3, 8, "foo3"); intervalTree.put(4, 7, "foo4"); intervalTree.put(5, 6, "foo5"); intervalTree.put(1, 9, "foo6"); }</code><technical_language>In general I safer replace sorts of @BeforeMethod calls direct calls a function returns a new interval tree call explicitly in test</technical_language>

Target:
public void init(){ intervalTree.clear(); intervalTree.put(1, 10, "foo1:10"); intervalTree.put(2, 9, "foo2:8"); intervalTree.put(3, 8, "foo3:6"); intervalTree.put(4, 7, "foo4:4"); intervalTree.put(5, 6, "foo5:2"); intervalTree.put(1, 9, "foo6:9"); }
Source:
<code>private long findCollisionIndex( long value ) { <START> long low = 0 + 0; <END> long high = numberOfCollisions - 1; while ( low <= high ) { long mid = (low + high) / 2; long midValue = collisionNodeIdCache.get( mid ); switch ( unsignedDifference( midValue, value ) ) { case EQ: return mid; case LT: low = mid + 1; break; default: high = mid - 1; break; } } return ID_NOT_FOUND; }</code><technical_language>0 do</technical_language>

Target:
private long findCollisionIndex( long value ) { long low = 0; long high = numberOfCollisions - 1; while ( low <= high ) { long mid = (low + high) / 2; long midValue = collisionNodeIdCache.get( mid ); switch ( unsignedDifference( midValue, value ) ) { case EQ: return mid; case LT: low = mid + 1; break; default: high = mid - 1; break; } } return ID_NOT_FOUND; }
Source:
<code><START> private boolean connectedToNetworkTypeForMarshmallow(int networkType) { <END> Network[] networks = connectivityManager.getAllNetworks(); for (Network network : networks) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (networkInfo.getType() == networkType) { return networkInfo.getState() == NetworkInfo.State.CONNECTED; } } return false; }</code><technical_language>this isConnectedToMobileNetwork()</technical_language>

Target:
private boolean connectedToNetworkTypeForMarshmallow(int networkType) { Network[] networks = connectivityManager.getAllNetworks(); for (Network network : networks) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); if (networkInfo.getType() == networkType) { return networkInfo.isConnected(); } } return false; }
Source:
<code>public int read() throws IOException { <START> return 0; <END> }</code><technical_language>this return 0 -1</technical_language>

Target:
public int read() throws IOException { return -1; }
Source:
<code>protected ITranslationUnit getTranslationUnitViaEditorOrWorkspace(IMarker marker) { IResource resource = marker.getResource(); if (resource instanceof IFile) { <START> IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); <END> IEditorPart editor = ResourceUtil.findEditor(page, (IFile) resource); if (editor != null) { return (ITranslationUnit) CDTUITools.getEditorInputCElement(editor.getEditorInput()); } } return getTranslationUnitViaWorkspace(marker); }</code><technical_language>This check find editor if is open in another window, meaning get TU for file disk instead of file in editor. windows need searched (note is page window)</technical_language>

Target:
protected Optional<ITranslationUnit> getTranslationUnitViaEditorOrWorkspace(IMarker marker) { return Optional.ofNullable(getTranslationUnitViaWorkspace(marker)).map(toWorkingCopy); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, <START> ServletException <END> { if (request instanceof HttpServletRequest && !Boolean.parseBoolean((String) request.getAttribute(ATTRIBUTE_ACTION_DISPATCHED))) { String[] xactions = request.getParameterValues("xaction"); HttpServletRequest hrequest = (HttpServletRequest) request; Enumeration<String> parameterNames = hrequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String parameter = parameterNames.nextElement(); if (parameter.startsWith(ACTION_PREFIX) && (xactions == null || Stream.of(xactions) .anyMatch(it -> Objects.equals(parameter, String.format("action_%s", it))))) { String targetURL = getTargetURL(hrequest, parameter); RequestDispatcher dispatcher = hrequest.getRequestDispatcher(targetURL); if (dispatcher != null) { LOGGER.debug("Forwarding request to " + targetURL); request.setAttribute(ATTRIBUTE_ACTION_DISPATCHED, "true"); dispatcher.forward(hrequest, response); request.removeAttribute(ATTRIBUTE_ACTION_DISPATCHED); return; } } } } chain.doFilter(request, response); }</code><technical_language>this change done automatic formatting? right. configure IDE [XWiki code style](<LINK_0></technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && !Boolean.parseBoolean((String) request.getAttribute(ATTRIBUTE_ACTION_DISPATCHED))) { HttpServletRequest hrequest = (HttpServletRequest) request; Enumeration<String> parameterNames = hrequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String parameter = parameterNames.nextElement(); String[] xactions = request.getParameterValues("xaction"); if (parameter.startsWith(ACTION_PREFIX) && (xactions == null || Stream.of(xactions) .anyMatch(it -> Objects.equals(parameter, String.format("action_%s", it))))) { String targetURL = getTargetURL(hrequest, parameter); RequestDispatcher dispatcher = hrequest.getRequestDispatcher(targetURL); if (dispatcher != null) { LOGGER.debug("Forwarding request to " + targetURL); request.setAttribute(ATTRIBUTE_ACTION_DISPATCHED, "true"); dispatcher.forward(hrequest, response); request.removeAttribute(ATTRIBUTE_ACTION_DISPATCHED); return; } } } } chain.doFilter(request, response); }
Source:
<code>public static void waitForStreamedTargetDeallocated(Client client) throws Exception { boolean passed = false; System.out.println("Quiesce client...."); quiesce(client); System.out.println("Quiesce done...."); VoltTable stats = null; long ftime = 0; long st = System.currentTimeMillis(); long end = System.currentTimeMillis() + (10 * 60 * 1000); while (true) { <START> stats = client.callProcedure("@Statistics", "export", 0).getResults()[0]; <END> boolean passedThisTime = true; long ctime = System.currentTimeMillis(); if (ctime > end) { System.out.println("Waited too long..."); System.out.println(stats); break; } if (ctime - st > (3 * 60 * 1000)) { System.out.println(stats); st = System.currentTimeMillis(); } while (stats.advanceRow()) { passedThisTime = false; String target = stats.getString("TARGET"); String ttable = stats.getString("SOURCE"); Long host = stats.getLong("HOST_ID"); Long pid = stats.getLong("PARTITION_ID"); if (target.isEmpty()) { System.out.println("Stream Not Dropped but target is disabled: " + ttable + " host:" + host + " partid:" + pid); } else { System.out.println("Stream Not Dropped: " + ttable + " to " + target + " host:" + host + " partid:" + pid); } } if (passedThisTime) { passed = true; break; } Thread.sleep(5000); } System.out.println("Passed is: " + passed); assertTrue(passed); }</code><technical_language>move stats pulling timeout check</technical_language>

Target:
public static void waitForStreamedTargetDeallocated(Client client) throws Exception { boolean passed = false; System.out.println("Quiesce client...."); quiesce(client); System.out.println("Quiesce done...."); VoltTable stats = null; long st = System.currentTimeMillis(); long end = System.currentTimeMillis() + (10 * 60 * 1000); while (true) { boolean passedThisTime = true; long ctime = System.currentTimeMillis(); if (ctime > end) { System.out.println("Waited too long..."); System.out.println(stats); break; } if (ctime - st > (3 * 60 * 1000)) { System.out.println(stats); st = System.currentTimeMillis(); } stats = client.callProcedure("@Statistics", "export", 0).getResults()[0]; while (stats.advanceRow()) { passedThisTime = false; String target = stats.getString("TARGET"); String ttable = stats.getString("SOURCE"); Long host = stats.getLong("HOST_ID"); Long pid = stats.getLong("PARTITION_ID"); if (target.isEmpty()) { System.out.println("Stream Not Dropped but target is disabled: " + ttable + " host:" + host + " partid:" + pid); } else { System.out.println("Stream Not Dropped: " + ttable + " to " + target + " host:" + host + " partid:" + pid); } } if (passedThisTime) { passed = true; break; } Thread.sleep(5000); } System.out.println("Passed is: " + passed); assertTrue(passed); }
Source:
<code>public void setup() throws Exception { super.setup(); S3AFileSystem fs = getFileSystem(); <START> assertTrue("FS needs to have a metadatastore.", <END> fs.hasMetadataStore()); assertTrue("Metadatastore should persist authoritative bit", metadataStorePersistsAuthoritativeBit(fs.getMetadataStore())); guardedFs = fs; metadataStore = fs.getMetadataStore(); rawFS = createUnguardedFS(); assertFalse("Raw FS still has S3Guard " + rawFS, rawFS.hasMetadataStore()); }</code><technical_language>this assume</technical_language>

Target:
public void setup() throws Exception { super.setup(); S3AFileSystem fs = getFileSystem(); assumeTrue("FS needs to have a metadatastore.", fs.hasMetadataStore()); assumeTrue("Metadatastore should persist authoritative bit", metadataStorePersistsAuthoritativeBit(fs.getMetadataStore())); guardedFs = fs; metadataStore = fs.getMetadataStore(); rawFs = createUnguardedFS(); assertFalse("Raw FS still has S3Guard " + rawFs, rawFs.hasMetadataStore()); }
Source:
<code>public TextsSizeMismatch(WebElementsCollection collection, List<String> actualTexts, List<String> expectedTexts, String explanation, long timeoutMs) { super(collection.driver(), <START> "\nActual: " + actualTexts + ", List size: " + actualTexts.size() + <END> "\nExpected: " + expectedTexts + ", List size: " + expectedTexts.size() + (explanation == null ? "" : "\nBecause: " + explanation) + "\nCollection: " + collection.description()); super.timeoutMs = timeoutMs; }</code><technical_language>please platform specific [System.lineSeparator()](<LINK_0> insead of \n in exception class</technical_language>

Target:
public TextsSizeMismatch(WebElementsCollection collection, List<String> actualTexts, List<String> expectedTexts, String explanation, long timeoutMs) { super(collection.driver(), lineSeparator() + "Actual: " + actualTexts + ", List size: " + actualTexts.size() + lineSeparator() + "Expected: " + expectedTexts + ", List size: " + expectedTexts.size() + (explanation == null ? "" : lineSeparator() + "Because: " + explanation) + lineSeparator() + "Collection: " + collection.description()); super.timeoutMs = timeoutMs; }
Source:
<code>public String evaluateNamespaceName(NamespaceResolutionContext resolutionCtx) throws InfrastructureException { String namespace = evalPlaceholders(defaultNamespaceName, resolutionCtx); if (!NamespaceNameValidator.isValid(namespace)) { Optional<KubernetesNamespaceMeta> namespaceMetaOptional; String normalizedNamespace = NamespaceNameValidator.normalize(namespace); if (normalizedNamespace.isEmpty()) { throw new InfrastructureException( format( "Evaluated empty namespace name for workspace %s", resolutionCtx.getWorkspaceId())); } do { normalizedNamespace = normalizedNamespace .substring(0, Math.min(55, normalizedNamespace.length())) .concat(NameGenerator.generate("-", 6)); namespaceMetaOptional = fetchNamespace(normalizedNamespace); <START> } while (namespaceMetaOptional.isPresent()); <END> namespace = normalizedNamespace; } LOG.debug( "Evaluated the namespace for workspace using the namespace default to {}", resolutionCtx.getWorkspaceId(), namespace); return namespace; }</code><technical_language>please limit this loop some finite number of fail in case runs out? a bit scary this</technical_language>

Target:
public String evaluateNamespaceName(NamespaceResolutionContext resolutionCtx) throws InfrastructureException { String namespace; Optional<Pair<String, String>> storedNamespace = getPreferencesNamespaceName(resolutionCtx); if (storedNamespace.isEmpty() || !isStoredTemplateValid(storedNamespace.get().second)) { namespace = evalPlaceholders(defaultNamespaceName, resolutionCtx); } else { namespace = storedNamespace.get().first; } if (!NamespaceNameValidator.isValid(namespace)) { Optional<KubernetesNamespaceMeta> namespaceMetaOptional; String normalizedNamespace = normalizeNamespaceName(namespace); if (normalizedNamespace.isEmpty()) { throw new InfrastructureException( format( "Evaluated empty namespace name for workspace %s", resolutionCtx.getWorkspaceId())); } do { normalizedNamespace = normalizedNamespace .substring(0, Math.min(55, normalizedNamespace.length())) .concat(NameGenerator.generate("-", 6)); namespaceMetaOptional = fetchNamespace(normalizedNamespace); } while (namespaceMetaOptional.isPresent()); namespace = normalizedNamespace; } LOG.debug( "Evaluated the namespace for workspace using the namespace default to {}", resolutionCtx.getWorkspaceId(), namespace); if (resolutionCtx.isPersistAfterCreate() && !defaultNamespaceName.contains(WORKSPACEID_PLACEHOLDER)) { recordEvaluatedNamespaceName(namespace, resolutionCtx); } return namespace; }
Source:
<code>public void invoke(Request request, Response response) throws IOException, ServletException { Tracer tracer = traceService.getTracer(); Optional.ofNullable(request.getHeader(X_CLOUD_TRACE_HEADER)).ifPresent(traceHeader -> { SpanContext spanContext = traceService .getSpanContextFactory() .fromHeader(traceHeader); traceService.getSpanContextHandler().attach(spanContext); <START> log.trace("Tracing request with header: " + request.getHeader(X_CLOUD_TRACE_HEADER)); <END> }); TraceContext context = tracer.startSpan(request.getRequestURI()); getNext().invoke(request, response); tracer.endSpan(context); }</code><technical_language>debug level I</technical_language>

Target:
public void invoke(Request request, Response response) throws IOException, ServletException { Tracer tracer = traceService.getTracer(); String traceHeader = request.getHeader(X_CLOUD_TRACE_HEADER); if (traceHeader != null) { SpanContext spanContext = traceService .getSpanContextFactory() .fromHeader(traceHeader); traceService.getSpanContextHandler().attach(spanContext); log.debug("Tracing request with header: " + request.getHeader(X_CLOUD_TRACE_HEADER)); } TraceContext context = tracer.startSpan(request.getRequestURI()); getNext().invoke(request, response); tracer.endSpan(context); }
Source:
<code>private boolean checkForMenuHintUpdates() { if (menuHint.hasHint()) { try { <START> int propRV = sendSetProperty("MENU_HINT", menuHint.format()); <END> if (propRV != 0) { if (Sage.DBG) System.out.println("MiniClient did not succeed with menu hint change to:" + menuHint.menuName + ", errcode=" + propRV); } menuHint.clear(); } catch (java.io.IOException e) { if (Sage.DBG) System.out.println("Error w/ MiniClient UI:" + e); connectionError(); return false; } } return true; }</code><technical_language>suggest format() first, storing in a local var clearing hint in a block synchronized menuHint object. in setMenuHint, synchronize code in menuHint object well. I realize other code done this way...but been. :)</technical_language>

Target:
private boolean checkForMenuHintUpdates() { String hintText; synchronized (menuHint) { hintText=menuHint.format(); menuHint.clear(); } if (hintText!=null) { try { int propRV = sendSetProperty("MENU_HINT", hintText); if (propRV != 0) { if (Sage.DBG) System.out.println("MiniClient did not succeed with menu hint change to:" + hintText + ", errcode=" + propRV); } } catch (java.io.IOException e) { if (Sage.DBG) System.out.println("Error w/ MiniClient UI:" + e); connectionError(); return false; } } return true; }
Source:
<code>static void waitForReconnectDelay() { <START> Observer.waitForReconnectDelayHelper(reconnectDelayMs); <END> }</code><technical_language>Nit: need call Observer explicitly</technical_language>

Target:
static void waitForReconnectDelay() { waitForReconnectDelayHelper(reconnectDelayMs); }
Source:
<code>protected void setUp() throws Exception { super.setUp(); enableNormalize(); if (this.collapseModuleExportProperties) { this.setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015); this.setLanguageOut(LanguageMode.ECMASCRIPT5); <START> } <END> }</code><technical_language>I this part is redundant settings in setupModuleExportsOnly below, it</technical_language>

Target:
protected void setUp() throws Exception { super.setUp(); enableNormalize(); }
Source:
<code>public void onSocialChanged(AccountStore.OnSocialChanged event) { if (event.isError()) { AppLog.e(T.API, "SignupGoogleFragment.onSocialChanged: " + event.error.type + " - " + event.error.message); switch (event.error.type) { case TWO_STEP_ENABLED: AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_SOCIAL_2FA_NEEDED); <START> ToastUtils.showToast(getContext(), getString(R.string.signup_user_exists, mGoogleEmail), <END> ToastUtils.Duration.LONG); PushSocialPayload payload = new PushSocialPayload(mIdToken, SERVICE_TYPE_GOOGLE); mDispatcher.dispatch(AccountActionBuilder.newPushSocialLoginAction(payload)); break; case USER_EXISTS: AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_SOCIAL_ACCOUNTS_NEED_CONNECTING); ToastUtils.showToast(getContext(), getString(R.string.signup_user_exists, mGoogleEmail), ToastUtils.Duration.LONG); mLoginListener.loginViaSocialAccount(mGoogleEmail, mIdToken, SERVICE_TYPE_GOOGLE, true); mDispatcher.unregister(this); getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); break; default: showErrorDialog(getString(R.string.login_error_generic)); break; } } else if (event.requiresTwoStepAuth) { mLoginListener.needs2faSocial(mGoogleEmail, event.userId, event.nonceAuthenticator, event.nonceBackup, event.nonceSms); mDispatcher.unregister(this); getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); } }</code><technical_language>shorten length of signup_user_exists? a long toast, easy read disappears, especially expecting it. Also, phrase "continue login" is a bit cryptic and/or unfriendly. want ask Editorial for copy</technical_language>

Target:
public void onSocialChanged(AccountStore.OnSocialChanged event) { if (event.isError()) { AppLog.e(T.API, "SignupGoogleFragment.onSocialChanged: " + event.error.type + " - " + event.error.message); switch (event.error.type) { case TWO_STEP_ENABLED: AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_SOCIAL_2FA_NEEDED); mLoginListener.showSignupToLoginMessage(); PushSocialPayload payload = new PushSocialPayload(mIdToken, SERVICE_TYPE_GOOGLE); mDispatcher.dispatch(AccountActionBuilder.newPushSocialLoginAction(payload)); break; case USER_EXISTS: AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_SOCIAL_ACCOUNTS_NEED_CONNECTING); mLoginListener.showSignupToLoginMessage(); mLoginListener.loginViaSocialAccount(mGoogleEmail, mIdToken, SERVICE_TYPE_GOOGLE, true); mDispatcher.unregister(this); getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); break; default: showErrorDialog(getString(R.string.login_error_generic)); break; } } else if (event.requiresTwoStepAuth) { mLoginListener.needs2faSocial(mGoogleEmail, event.userId, event.nonceAuthenticator, event.nonceBackup, event.nonceSms); mDispatcher.unregister(this); getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); } }