auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static SimpleResourceDefinition forDomain(final DelegatingConfigurableAuthorizer authorizer) { <END> return forDomain(authorizer, null); }</code><technical_language>This public API need deprecate, modify method</technical_language>

Target:
public static SimpleResourceDefinition forDomain(final DelegatingConfigurableAuthorizer authorizer) { List<ResourceDefinition> interfaces = Collections.emptyList(); return new CoreManagementResourceDefinition(Environment.DOMAIN, authorizer, null, null, null, interfaces, null); }
Source:
<code>for (int codePoint = 0; codePoint < MAX_CODE_POINT; codePoint++) { int type = Character.getType(codePoint); <START> if (type != Character.UNASSIGNED && type != Character.SURROGATE) { <END> LOWER_CODE_POINTS[codePoint] = Character.toLowerCase(codePoint); UPPER_CODE_POINTS[codePoint] = Character.toUpperCase(codePoint); WHITESPACE_CODE_POINTS[codePoint] = Character.isWhitespace(codePoint); } else { LOWER_CODE_POINTS[codePoint] = 0xFFFD; UPPER_CODE_POINTS[codePoint] = 0xFFFD; WHITESPACE_CODE_POINTS[codePoint] = false; } }</code><technical_language>UNASSIGNED valid UTF8 byte sequences. run UTF_8.encode(UTF_8.decode( in Java get replaced U+FFFD</technical_language>

Target:
for (int codePoint = 0; codePoint < MAX_CODE_POINT; codePoint++) { int type = Character.getType(codePoint); if (type != Character.SURROGATE) { LOWER_CODE_POINTS[codePoint] = Character.toLowerCase(codePoint); UPPER_CODE_POINTS[codePoint] = Character.toUpperCase(codePoint); WHITESPACE_CODE_POINTS[codePoint] = Character.isWhitespace(codePoint); } else { LOWER_CODE_POINTS[codePoint] = REPLACEMENT_CODE_POINT; UPPER_CODE_POINTS[codePoint] = REPLACEMENT_CODE_POINT; WHITESPACE_CODE_POINTS[codePoint] = false; } }
Source:
<code>private ConfigPersistenceService retrieveAndConfigureRuleCorePersistenceService() throws IOException { <START> return getOsgiService(ConfigPersistenceService.class, "(configuration.id=RULE)", 30000L); <END> }</code><technical_language>in this case schould work constants</technical_language>

Target:
private ConfigPersistenceService retrieveAndConfigureRuleCorePersistenceService() throws IOException { return getOsgiService(ConfigPersistenceService.class, String.format("(%s=%s)", Constants.CONFIGURATION_ID, RuleConfiguration.TYPE_ID), 30000L); }
Source:
<code>public Object mapFromContext(Object ctx) { if (ctx == null) { return null; } DirContextAdapter searchResult = (DirContextAdapter) ctx; Attributes attributes = searchResult.getAttributes(); if (attributes == null) { return null; } try { return attributes.get("uid").get(0); } catch (NamingException e) { <START> System.err.println(ERROR_PREFIX + "Failed getting user GUID"); <END> return null; } }</code><technical_language>Please replace this ^ "log.error(...)"</technical_language>

Target:
public Object mapFromContext(Object ctx) { if (ctx == null) { return null; } DirContextAdapter searchResult = (DirContextAdapter) ctx; Attributes attributes = searchResult.getAttributes(); if (attributes == null) { return null; } try { return attributes.get("uid").get(0); } catch (NamingException e) { log.error(ERROR_PREFIX + "Failed getting user GUID"); return null; } }
Source:
<code><START> public Map<String, Map<Partition, Map<String, Long>>> getStartTimeMap(String stateType) { <END> return Collections .unmodifiableMap(_startTimeMap.getOrDefault(stateType, Collections.emptyMap())); }</code><technical_language>other callers, private? In case, need unmodifiableMap</technical_language>

Target:
private Map<String, Map<Partition, Map<String, Long>>> getStartTimeMap(String stateType) { return _startTimeMap.getOrDefault(stateType, Collections.emptyMap()); }
Source:
<code>public List<Conflict> call() { final URL repoUrl = getCommandLocator().command(ResolveGeogitDir.class).call(); <START> if (repoUrl == null) { <END> return Collections.emptyList(); } else { getIndex().getDatabase().open(); return getIndex().getDatabase().getConflicts(null, null); } }</code><technical_language>sense me. InitOp work of conflicts</technical_language>

Target:
public List<Conflict> call() { final URL repoUrl = getCommandLocator().command(ResolveGeogitDir.class).call(); if (repoUrl == null) { return ImmutableList.of(); } else { return getIndex().getDatabase().getConflicts(null, null); } }
Source:
<code>private static boolean typeIsByte(ExpressionTree expression) { if (expression.symbolType().isSubtypeOf("byte")) { return true; } if (expression.is(Tree.Kind.AND)) { <START> BinaryExpressionTree and = (BinaryExpressionTree) expression; <END> return isFFLiteral(and.rightOperand()) || isFFLiteral(and.leftOperand()); } return false; }</code><technical_language>This appears in RawByteBitwiseOperationsCheck.isSecuringByte method, move a common method in LiteralUtils</technical_language>

Target:
private static boolean typeIsByte(ExpressionTree expression) { return expression.symbolType().isSubtypeOf("byte") || ExpressionUtils.isSecuringByte(expression); }
Source:
<code>public String persistenceId() { return "com.arpnetworking.metrics.portal.scheduling.JobCoordinator:" <START> + "repositoryType=" + _repositoryType + "; " <END> + "organizationId=" + _organization.getId(); }</code><technical_language>class name here? If so, please call getter for string want</technical_language>

Target:
public String persistenceId() { return String.format( "job-coordinator-%s", _repositoryType.getCanonicalName()); }
Source:
<code>private void configureLoadListener() { JavaFxUtil.addListener(engine.getLoadWorker().stateProperty(), (observable, oldValue, newValue) -> { <START> if (Worker.State.SUCCEEDED == newValue) { <END> synchronized (waitingMessages) { waitingMessages.forEach(AbstractChatTabController.this::addMessage); waitingMessages.clear(); isChatReady = true; onWebViewLoaded(); } } }); }</code><technical_language>switching this if statement more intuitive (newValue == SUCCEEDED)</technical_language>

Target:
private void configureLoadListener() { JavaFxUtil.addListener(engine.getLoadWorker().stateProperty(), (observable, oldValue, newValue) -> { if (newValue != Worker.State.SUCCEEDED) { return; } synchronized (waitingMessages) { waitingMessages.forEach(AbstractChatTabController.this::addMessage); waitingMessages.clear(); isChatReady = true; onWebViewLoaded(); } }); }
Source:
<code>public ImmutableStaticScriptResourcesBuilder add(Collection<StaticScriptResource> toAdd) throws DuplicateResourceKeyException { <START> for (Iterator<StaticScriptResource> it = toAdd.iterator(); it.hasNext();) { <END> StaticScriptResource staticScriptResource = it.next(); String resourcePath = staticScriptResource.getResourcePath(); StaticScriptResource availableValue = staticScriptResources.get(resourcePath); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring " + StaticScriptResource.class.getSimpleName() + " " + staticScriptResource + " because the given resource path was already provided by " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding " + staticScriptResource); } staticScriptResources.put(resourcePath, staticScriptResource); } } return this; }</code><technical_language>here: for (StaticScriptResource staticScriptResource : toAdd) {</technical_language>

Target:
public ImmutableStaticScriptResourcesBuilder add(Collection<StaticScriptResource> toAdd) throws DuplicateResourceKeyException { for (StaticScriptResource staticScriptResource : toAdd) { String resourcePath = staticScriptResource.getResourcePath(); StaticScriptResource availableValue = staticScriptResources.get(resourcePath); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring " + StaticScriptResource.class.getSimpleName() + " " + staticScriptResource + " because the given resource path was already provided by " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding " + staticScriptResource); } staticScriptResources.put(resourcePath, staticScriptResource); } } return this; }
Source:
<code>public static String validateTopic(String topic) { if (VALID_TOPIC_REGEXP.matcher(topic).matches()) { return topic; } String err = "Topic validation error: \"" + topic + "\" must be an alpha-numeric, colon-delimited string"; <START> LOG.error(err); <END> throw new IllegalArgumentException(err); }</code><technical_language>Log throw is considered anti-pattern: <LINK_0></technical_language>

Target:
public static String validateTopic(String topic) { if (VALID_TOPIC_REGEXP.matcher(topic).matches()) { return topic; } RuntimeException e = new IllegalArgumentException("\"" + topic + "\" must be an alpha-numeric, colon-delimited string"); LOG.error("Topic validation error:", e); throw e; }
Source:
<code>public void testHostSwiftcopt() throws Exception { scratch.file("examples/rule/BUILD"); scratch.file( "examples/rule/apple_rules.bzl", "def swift_binary_impl(ctx):", " copts = ctx.fragments.swift.copts()", " return struct(", " copts=copts,", " )", "swift_binary = rule(", " implementation = swift_binary_impl,", " fragments = ['swift']", ")"); <START> scratch.file("examples/swift_skylark/a.m"); <END> scratch.file( "examples/swift_skylark/BUILD", "package(default_visibility = [' "load(' "swift_binary(", " name='my_target',", ")"); useConfiguration("--swiftcopt=foo", "--host_swiftcopt=bar", "--host_swiftcopt=baz"); ConfiguredTarget target = getConfiguredTarget(" @SuppressWarnings("unchecked") List<String> copts = (List<String>) target.get("copts"); assertThat(copts).doesNotContain("foo"); assertThat(copts).containsAllOf("bar", "baz"); }</code><technical_language>I other test this, try without? If needed curious why</technical_language>

Target:
public void testHostSwiftcopt() throws Exception { scratch.file("examples/rule/BUILD"); scratch.file( "examples/rule/apple_rules.bzl", "def swift_binary_impl(ctx):", " copts = ctx.fragments.swift.copts()", " return struct(", " copts=copts,", " )", "swift_binary = rule(", " implementation = swift_binary_impl,", " fragments = ['swift']", ")"); scratch.file( "examples/swift_skylark/BUILD", "load(' "swift_binary(", " name='my_target',", ")"); useConfiguration("--swiftcopt=foo", "--host_swiftcopt=bar", "--host_swiftcopt=baz"); ConfiguredTarget target = getConfiguredTarget(" @SuppressWarnings("unchecked") List<String> copts = (List<String>) target.get("copts"); assertThat(copts).doesNotContain("foo"); assertThat(copts).containsAllOf("bar", "baz"); }
Source:
<code>@Override public void viewCreated(final boolean isTablet) { List<UiShowDetailItem> items = new ArrayList<>(); if (isTablet) { view.displayAboutData(show); } else { items.add(new UiShowDetailAbout()); } <START> ArrayList<Integer> availableSeasons = getAvailableSeasons(); <END> for (int season : availableSeasons) { items.add(new UiShowDetailSeason(season)); } view.displayData(show, items); }</code><technical_language>Change List<Integer></technical_language>

Target:
@Override public void viewCreated(final boolean isTablet) { List<UiShowDetailItem> items = new ArrayList<>(); if (isTablet) { view.displayAboutData(show); } else { items.add(new UiShowDetailAbout()); } List<Integer> availableSeasons = getAvailableSeasons(); for (int season : availableSeasons) { items.add(new UiShowDetailSeason(season)); } view.displayData(show, items); }
Source:
<code>private URI getFinalURI(final URI uri, final URI initialURI) { URI result = initialURI; if (null != uri && null != uri.fileExtension() && <START> uri.fileExtension().equals("properties")) <END> { final String lastSegment = initialURI.lastSegment(); final String withoutLocalization = LocaleUtil.trimLocalization(lastSegment); if (!lastSegment.equals(withoutLocalization)) { result = initialURI.trimSegments(1); result = result.appendSegment(withoutLocalization); } } return result; }</code><technical_language>is a constant</technical_language>

Target:
private URI getFinalURI(final URI uri, final URI initialURI) { URI result = initialURI; if (null != uri && null != uri.fileExtension() && uri.fileExtension().equals(PropertiesFilesUtils.PROPERTIES_FILE_EXTENSION)) { final String lastSegment = initialURI.lastSegment(); final String withoutLocalization = LocaleUtil.trimLocalization(lastSegment); if (!lastSegment.equals(withoutLocalization)) { result = initialURI.trimSegments(1); result = result.appendSegment(withoutLocalization); } } return result; }
Source:
<code>public void delete(Collection<RepositoryGroup> groupsToDelete) { for (RepositoryGroup <START> groupUUID : <END> groupsToDelete) { preferences.remove( PREFS_GROUP_PREFIX + groupUUID.getUuid().toString()); groupMap.remove(groupUUID.getUuid()); } savePreferences(); }</code><technical_language>"group"</technical_language>

Target:
public void delete(Collection<RepositoryGroup> groupsToDelete) { for (RepositoryGroup group : groupsToDelete) { preferences .remove(PREFS_GROUP_PREFIX + group.getGroupId().toString()); groupMap.remove(group.getGroupId()); } savePreferences(); }
Source:
<code>public ZooKeeper connect(String host, int timeoutMillis) throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Watcher w = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { connected = true; latch.countDown(); } } }; try { zoo = new ZooKeeper(host, timeoutMillis, w, new HashSet<Long>()); latch.await(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } <START> if (connected) { <END> return zoo; } else { throw new RuntimeException("Could not connect to Zookeeper at host:" + host); } }</code><technical_language>if !connected throw skip else return zk</technical_language>

Target:
public ZooKeeper connect(String host, int timeoutMillis) throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Watcher w = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { connected = true; latch.countDown(); } } }; try { zk = new ZooKeeper(host, timeoutMillis, w, new HashSet<Long>()); latch.await(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } if (!connected) { throw new RuntimeException("Could not connect to Zookeeper at host:" + host); } return zk; }
Source:
<code>public static Builder classBuilder(String name) { <START> return new Builder(Kind.CLASS, Objects.requireNonNull(name, "name == null"), null); <END> }</code><technical_language>Static import</technical_language>

Target:
public static Builder classBuilder(String name) { return new Builder(Kind.CLASS, requireNonNull(name, "name == null"), null); }
Source:
<code>private ModelNode parse(final AttributeDefinition attribute, final String value) throws OperationFailedException { final String trimmed = value == null ? null : value.trim(); ModelNode node; if (trimmed != null) { if (attribute.isAllowExpression() && ParseUtils.isExpression(trimmed)) { <START> node = ParseUtils.parsePossibleExpression(trimmed); <END> } else { if(attribute.getType() == STRING || attribute.getType() == PROPERTY) { node = new ModelNode().set(value); } else { node = new ModelNode().set(trimmed); } } if (node.getType() != ModelType.EXPRESSION) { switch (attribute.getType()) { case BIG_DECIMAL: node.set(node.asBigDecimal()); break; case BIG_INTEGER: node.set(node.asBigInteger()); break; case BOOLEAN: node.set(node.asBoolean()); break; case BYTES: node.set(node.asBytes()); break; case DOUBLE: node.set(node.asDouble()); break; case INT: node.set(node.asInt()); break; case LONG: node.set(node.asLong()); break; } } } else { node = new ModelNode(); } final ParameterValidator validator; if (attribute instanceof ListAttributeDefinition) { validator = ((ListAttributeDefinition) attribute).getElementValidator(); } else if (attribute instanceof MapAttributeDefinition) { validator = ((MapAttributeDefinition) attribute).getElementValidator(); } else { validator = attribute.getValidator(); } validator.validateParameter(attribute.getXmlName(), node); return node; }</code><technical_language>This (and others) node = new ModelNode(new ValueExpression(value)); parsePossibleExpression does, for isExpression() call redundant</technical_language>

Target:
private ModelNode parse(final AttributeDefinition attribute, final String value) throws OperationFailedException { ModelNode node = ParseUtils.parseAttributeValue(value, attribute.isAllowExpression(), attribute.getType()); final ParameterValidator validator; if (attribute instanceof ListAttributeDefinition) { validator = ((ListAttributeDefinition) attribute).getElementValidator(); } else if (attribute instanceof MapAttributeDefinition) { validator = ((MapAttributeDefinition) attribute).getElementValidator(); } else { validator = attribute.getValidator(); } validator.validateParameter(attribute.getXmlName(), node); return node; }
Source:
<code>private void reportMissingRegionServers(final ClusterMetrics clusterMetrics) { final Set<Address> regionServers = collectKnownRegionServers(clusterMetrics); final Set<Address> missingRegionServers = new HashSet<>(initialRegionServers); missingRegionServers.removeAll(regionServers); if (!missingRegionServers.isEmpty()) { final StringBuilder stringBuilder = new StringBuilder() .append("region server(s) are missing from this cluster report"); <START> missingRegionServers.forEach(address -> { stringBuilder.append("\n ").append(address); }); <END> getLogger().warn(stringBuilder.toString()); } }</code><technical_language>nit: lambda expression address -> stringBuilder.append("\n ").append(address)</technical_language>

Target:
private void reportMissingRegionServers(final ClusterMetrics clusterMetrics) { final Set<Address> regionServers = collectKnownRegionServers(clusterMetrics); final Set<Address> missingRegionServers = new HashSet<>(initialRegionServers); missingRegionServers.removeAll(regionServers); if (!missingRegionServers.isEmpty()) { final StringBuilder stringBuilder = new StringBuilder() .append("region server(s) are missing from this cluster report"); missingRegionServers.stream() .sorted() .forEach(address -> stringBuilder.append("\n ").append(address)); getLogger().warn(stringBuilder.toString()); } }
Source:
<code>private String getStoriesId() { Stories stories = getAnnotation(Stories.class); <START> if (stories != null){ <END> return ("").equals(stories.id()) ? null : stories.id(); } else { return null; } }</code><technical_language>if(stories == null || stories.isEmpty()) { return null; } else { return stories.id(); }</technical_language>

Target:
private String getStoriesId() { Stories stories = getAnnotation(Stories.class); if(stories == null || stories.id() == null || stories.id().isEmpty()) { return null; } else { return stories.id(); } }
Source:
<code>public static StringNormalizer.Result simplifyPhoneNumber(String phoneNumber) { int numCodePoints = Character.codePointCount(phoneNumber, 0, phoneNumber.length()); IntSequenceBuilder codePoints = new IntSequenceBuilder(numCodePoints); IntSequenceBuilder resultMap = new IntSequenceBuilder(numCodePoints); int i = 0; for (int iterCodePoint = 0; iterCodePoint < numCodePoints; iterCodePoint += 1) { int c = Character.codePointAt(phoneNumber, i); <START> if (!(c == ' ' || c == '-' || c == '.' || c == '(' || c == ')' || c == ':' || c == '/')) { <END> codePoints.add(c); resultMap.add(i); } i += Character.charCount(c); } return new StringNormalizer.Result(phoneNumber.length(), codePoints.toArray(), resultMap.toArray()); }</code><technical_language>distribute ! parenthesis</technical_language>

Target:
public static StringNormalizer.Result simplifyPhoneNumber(String phoneNumber) { int numCodePoints = Character.codePointCount(phoneNumber, 0, phoneNumber.length()); IntSequenceBuilder codePoints = new IntSequenceBuilder(numCodePoints); IntSequenceBuilder resultMap = new IntSequenceBuilder(numCodePoints); int i = 0; for (int iterCodePoint = 0; iterCodePoint < numCodePoints; iterCodePoint += 1) { int c = Character.codePointAt(phoneNumber, i); if (c != ' ' && c != '-' && c != '.' && c != '(' && c != ')' && c != ':' && c != '/') { codePoints.add(c); resultMap.add(i); } i += Character.charCount(c); } return new StringNormalizer.Result(phoneNumber.length(), codePoints.toArray(), resultMap.toArray()); }
Source:
<code>public CompletableFuture<Pair<Set<String>, Set<String>>> sharedWith(FileWrapper file) { return file.getPath(network).thenCompose(path -> { <START> AbsoluteCapability cap = file.getPointer().capability; <END> Set<String> sharedReadAccessWith = network.sharedWithCache.getSharedWith(SharedWithCache.Access.READ, cap); Set<String> sharedWriteAccessWith = network.sharedWithCache.getSharedWith(SharedWithCache.Access.WRITE, cap); return CompletableFuture.completedFuture(new Pair<>(sharedReadAccessWith, sharedWriteAccessWith)); }); }</code><technical_language>need path</technical_language>

Target:
public CompletableFuture<Pair<Set<String>, Set<String>>> sharedWith(FileWrapper file) { AbsoluteCapability cap = file.getPointer().capability; Set<String> sharedReadAccessWith = sharedWithCache.getSharedWith(SharedWithCache.Access.READ, cap); Set<String> sharedWriteAccessWith = sharedWithCache.getSharedWith(SharedWithCache.Access.WRITE, cap); return CompletableFuture.completedFuture(new Pair<>(sharedReadAccessWith, sharedWriteAccessWith)); }
Source:
<code>public OutputStream decorateLogger(AbstractBuild abstractBuild, OutputStream outputStream) throws IOException, InterruptedException { <START> return null; <END> }</code><technical_language>Is this expected null</technical_language>

Target:
public OutputStream decorateLogger(AbstractBuild abstractBuild, OutputStream outputStream) { return null; }
Source:
<code><START> private static FairyModule getFairyModuleForLocale(Locale locale, Random random) { <END> Reflections reflections = new Reflections(FAIRY_PACKAGE); FairyModule fairyModule = null; for (Class<? extends FairyModule> module : reflections.getSubTypesOf(FairyModule.class)) { if (module.getSimpleName().startsWith(capitalize(locale.getLanguage()))) { try { fairyModule = module.getConstructor(Random.class).newInstance(random); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } } checkNotNull(fairyModule, FAIRY_MODULE_NOT_FOUND); return fairyModule; }</code><technical_language>IMHO assume JFairy pass desired module a parameters. should't reflection for that</technical_language>

Target:
private static FairyModule getFairyModuleForLocale(Locale locale, Random random) { LanguageCode code = LanguageCode.valueOf(locale.getLanguage().toUpperCase()); switch (code) { case PL: return new PlFairyModule(random); case EN: return new EnFairyModule(random); default: return new EnFairyModule(random); } }
Source:
<code>private void writeConfigToFile(File configFile) throws IOException { if (!SystemUtil.isWindows()) { update(configFile); return; } int retries = 1; while (retries <= 5) { try { update(configFile); return; <START> } catch (Exception e) { <END> try { System.out.println(String.format("Retry attempt - %s. Error: %s", retries, e.getMessage())); e.printStackTrace(); Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } retries = retries + 1; } } throw new RuntimeException(String.format("Could not write to config file after %s attempts", retries)); }</code><technical_language>catch a specific exception here</technical_language>

Target:
private void writeConfigToFile(File configFile) throws IOException { if (!SystemUtil.isWindows()) { update(configFile); return; } int retries = 1; while (retries <= 5) { try { update(configFile); return; } catch (IOException e) { try { System.out.println(String.format("Retry attempt - %s. Error: %s", retries, e.getMessage())); e.printStackTrace(); Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } retries = retries + 1; } } throw new RuntimeException(String.format("Could not write to config file after %s attempts", retries)); }
Source:
<code>private void enrich(final List<BatchItem> batch, final EventType eventType) throws EnrichmentException { for (BatchItem item : batch) { try { item.setStep(EventPublishingStep.ENRICHING); <START> enrichment.enrich(item.getEvent(), eventType); <END> } catch (EnrichmentException e) { item.setPublishingStatus(EventPublishingStatus.FAILED); item.setDetail(e.getMessage()); throw e; } } }</code><technical_language>result of enrichment is (the return value)</technical_language>

Target:
private void enrich(final List<BatchItem> batch, final EventType eventType) throws EnrichmentException { for (BatchItem item : batch) { try { item.setStep(EventPublishingStep.ENRICHING); enrichment.enrich(item.getEvent(), eventType); } catch (EnrichmentException e) { item.updateStatusAndDetail(EventPublishingStatus.FAILED, e.getMessage()); throw e; } } }
Source:
<code>private Stream<Feature> featuresFromNames(String feature, String... additionalFeatures) { <START> Stream.Builder<Feature> transformedFeatures = Stream.builder(); <END> toStream(feature, additionalFeatures) .forEach( f -> { try { transformedFeatures.add(featuresService.getFeature(f)); } catch (Exception e) { throw new SynchronizedInstallerException( "Failed to retrieve feature [" + f + "]", e); } }); return transformedFeatures.build(); }</code><technical_language>simpler: java private Stream<Feature> featuresFromNames(String feature, String... additionalFeatures) { return toStream(feature, additionalFeatures) .map(this::foobar); } private Feature foobar(String f) { try { return featuresService.getFeature(f); } catch (Exception e) { throw new SynchronizedInstallerException( "Failed retrieve feature [" + f + "]", e); } }</technical_language>

Target:
private Stream<Feature> featuresFromNames(String feature, String... additionalFeatures) { return toStream(feature, additionalFeatures).map(this::getFeature); }
Source:
<code><START> public RebaseOperation createRebaseOperation(ExecutionEvent event) <END> throws ExecutionException { Ref ref; ISelection currentSelection = getCurrentSelectionChecked(event); if (currentSelection instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) currentSelection; Object selected = selection.getFirstElement(); ref = getRef(selected); } else ref = null; final Repository repository = getRepository(event); if (repository == null) return null; BasicConfigurationDialog.show(repository); String currentFullBranch = getFullBranch(repository); if (ref != null && ref.getName().equals(currentFullBranch)) ref = null; if (ref == null) { RebaseTargetSelectionDialog rebaseTargetSelectionDialog = new RebaseTargetSelectionDialog( getShell(event), repository); if (rebaseTargetSelectionDialog.open() == IDialogConstants.OK_ID) { String refName = rebaseTargetSelectionDialog.getRefName(); try { ref = repository.getRef(refName); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } } else return null; } jobname = NLS.bind( UIText.RebaseCurrentRefCommand_RebasingCurrentJobName, Repository.shortenRefName(currentFullBranch), ref); return new RebaseOperation(repository, ref); }</code><technical_language>if move this method setEnabled() diff is a lot easier read</technical_language>

Target:
public RebaseOperation createRebaseOperation(ExecutionEvent event) throws ExecutionException { Ref ref; ISelection currentSelection = getCurrentSelectionChecked(event); if (currentSelection instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) currentSelection; Object selected = selection.getFirstElement(); ref = getRef(selected); } else ref = null; final Repository repository = getRepository(event); if (repository == null) return null; BasicConfigurationDialog.show(repository); String currentFullBranch = getFullBranch(repository); if (ref != null && ref.getName().equals(currentFullBranch)) ref = null; if (ref == null) { RebaseTargetSelectionDialog rebaseTargetSelectionDialog = new RebaseTargetSelectionDialog( getShell(event), repository); if (rebaseTargetSelectionDialog.open() == IDialogConstants.OK_ID) { String refName = rebaseTargetSelectionDialog.getRefName(); try { ref = repository.getRef(refName); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } } else return null; } jobname = NLS.bind( UIText.RebaseCurrentRefCommand_RebasingCurrentJobName, Repository.shortenRefName(currentFullBranch), ref.getName()); return new RebaseOperation(repository, ref); }
Source:
<code><START> public void failsOverMultipleTimesWithFailingLeader() { <END> for (int i = 0; i < FAILOVERS; i++) { target.continueOrPropagate( i % CLUSTER_SIZE == 0 ? EXCEPTION_WITHOUT_RETRY_AFTER : EXCEPTION_WITH_RETRY_AFTER); } }</code><technical_language>This broken. I expect is @Test public void failsOverMultipleTimesWithFailingLeader() { for (int i = 0; i < FAILOVERS; i++) { target.url(); target.continueOrPropagate( i % (CLUSTER_SIZE * target.failuresBeforeSwitching) != 0 ? EXCEPTION_WITHOUT_RETRY_AFTER : EXCEPTION_WITH_RETRY_AFTER); } } showing throws if do modulus CLUSTER_SIZE * target.failuresBeforeSwitching + 1</technical_language>

Target:
public void failsOverMultipleTimesWithFailingLeader() { String initialUrl = target.url(); for (int i = 0; i < FAILOVERS; i++) { target.continueOrPropagate( target.url().equals(initialUrl) ? EXCEPTION_WITHOUT_RETRY_AFTER : EXCEPTION_WITH_RETRY_AFTER); } }
Source:
<code>public BranchConfigurationDialog(Shell shell, String branchName, Repository repository) { super(shell); myBranchName = branchName; myRepository = repository; myConfig = myRepository.getConfig(); setShellStyle(getShellStyle() | SWT.SHELL_TRIM); <START> myTitle = UIText.BranchConfigurationDialog_BranchConfiguration; <END> setHelpAvailable(false); }</code><technical_language>BranchConfigurationDialog_BranchConfigurationTitle instead</technical_language>

Target:
public BranchConfigurationDialog(Shell shell, String branchName, Repository repository) { super(shell); myBranchName = branchName; myRepository = repository; myConfig = myRepository.getConfig(); setShellStyle(getShellStyle() | SWT.SHELL_TRIM); myTitle = UIText.BranchConfigurationDialog_BranchConfigurationTitle; setHelpAvailable(false); }
Source:
<code>private boolean visible(final Widget w) { <START> if (w.isDisposed()) <END> return false; return Display.syncExec(new ResultRunnable<Boolean>() { @Override public Boolean run() { return !((w instanceof Control) && !((Control) w).getVisible()); } }); }</code><technical_language>braces if condition is line</technical_language>

Target:
private boolean visible(final Widget w) { if (w.isDisposed()) { return false; } return Display.syncExec(new ResultRunnable<Boolean>() { @Override public Boolean run() { return !((w instanceof Control) && !((Control) w).getVisible()); } }); }
Source:
<code>public void adsFandomBtfBlockDesktop(String article) { AdsFandomObject fandomPage = loadPage(article); fandomPage.verifySlot(AdsFandomContent.TOP_LEADERBOARD); fandomPage.verifySlot(AdsFandomContent.TOP_BOXAD); Assertion.assertNull(fandomPage.getSlot(AdsFandomContent.INCONTENT_BOXAD), assertionMessage); <START> Assertion.assertNull(fandomPage.getSlot(AdsFandomContent.BOTTOM_LEADERBOARD), assertionMessage); <END> }</code><technical_language>Thoughts: is - in ideal world I this: java AdSlot topLeaderboard = page.getSlot(AdsFandomContent.TOP_LEADERBOARD); Assertion.assertNotNull(topLeaderboard); Assertion.assertTrue(topLeaderboard.isVisible()); AdSlot floatingMedrec = page.getSlot(AdsFandomContent.INCONTENT_BOXAD); Assertion.assertNull(floatingMedrec); _(pseudo-code)_</technical_language>

Target:
public void adsFandomBtfBlockDesktop(String article) { AdsFandomObject fandomPage = loadPage(article); fandomPage.verifySlot(AdsFandomContent.TOP_LEADERBOARD); fandomPage.verifySlot(AdsFandomContent.TOP_BOXAD); Assertion.assertNull(fandomPage.getSlot(AdsFandomContent.INCONTENT_BOXAD), ASSERT_MESSAGE); Assertion.assertNull(fandomPage.getSlot(AdsFandomContent.BOTTOM_LEADERBOARD), ASSERT_MESSAGE); }
Source:
<code>public final void beforeRun() throws Exception { cacheService = getService(); try { recordStore = getOrCreateStoreIfAllowed(); <START> CacheConfig<?, ?> cacheConfig = cacheService.getCacheConfig(name); <END> if (cacheConfig != null) { tenantContext = cacheConfig.getTenantControl().setTenant(true); } } catch (CacheNotExistsException e) { dispose(); rethrowOrSwallowIfBackup(e); } catch (Throwable t) { dispose(); throw ExceptionUtil.rethrow(t, Exception.class); } if (recordStore != null && recordStore.isWanReplicationEnabled()) { wanEventPublisher = cacheService.getCacheWanEventPublisher(); } beforeRunInternal(); }</code><technical_language>get this config recordstore? If can, eliminate concurrent hashmap lookup cost</technical_language>

Target:
public final void beforeRun() throws Exception { cacheService = getService(); try { recordStore = getOrCreateStoreIfAllowed(); CacheConfig<?, ?> cacheConfig; if (recordStore != null) { cacheConfig = recordStore.getConfig(); } else { cacheConfig = cacheService.getCacheConfig(name); } if (cacheConfig != null) { tenantContext = getTenantControl(cacheConfig).setTenant(true); } } catch (CacheNotExistsException e) { dispose(); rethrowOrSwallowIfBackup(e); } catch (Throwable t) { dispose(); throw ExceptionUtil.rethrow(t, Exception.class); } if (recordStore != null && recordStore.isWanReplicationEnabled()) { wanEventPublisher = cacheService.getCacheWanEventPublisher(); } beforeRunInternal(); }
Source:
<code>public String toFileHistory(final Branch.NameKey branch, final String file) { ParameterizedString pattern = new ParameterizedString(type.getFileHistory()); final Map<String, String> p = new HashMap<String, String>(); p.put("project", encode(branch.getParentKey().get())); p.put("branch", encode(branch.get())); <START> p.put("file", URL.encodeQueryString(file)); <END> return baseUrl + pattern.replace(p); }</code><technical_language>I file path encoded well, it</technical_language>

Target:
public String toFileHistory(final Branch.NameKey branch, final String file) { ParameterizedString pattern = new ParameterizedString(type.getFileHistory()); final Map<String, String> p = new HashMap<String, String>(); p.put("project", encode(branch.getParentKey().get())); p.put("branch", encode(branch.get())); p.put("file", encode(file)); return baseUrl + pattern.replace(p); }
Source:
<code>public CodecState( MediaTimeProvider mediaTimeProvider, MediaExtractor extractor, int trackIndex, MediaFormat format, MediaCodec codec, boolean limitQueueDepth, boolean tunneled, int audioSessionId) { mMediaTimeProvider = mediaTimeProvider; mExtractor = extractor; mTrackIndex = trackIndex; mFormat = format; mSawInputEOS = mSawOutputEOS = false; mLimitQueueDepth = limitQueueDepth; mTunneled = tunneled; mAudioSessionId = audioSessionId; mSampleBaseTimeUs = -1; mCodec = codec; mAvailableInputBufferIndices = new LinkedList<Integer>(); mAvailableOutputBufferIndices = new LinkedList<Integer>(); mAvailableOutputBufferInfos = new LinkedList<MediaCodec.BufferInfo>(); mPresentationTimeUs = 0; String mime = mFormat.getString(MediaFormat.KEY_MIME); Log.d(TAG, "CodecState::CodecState " + mime); mIsAudio = mime.startsWith("audio/"); if (mTunneled && !mIsAudio) { <START> mCodec.setOnFrameRenderedListener(this, null); <END> } }</code><technical_language>Is this class a test thread currently? I wondering if pass a Handler events delivered thread class is (this avoid needing mark volatile clear Handler in release, avoiding need check for stale events in callback). If possible, I mCodec marked volatile, (preferred) a volatile boolean mReleased in callback (related this: setting mCodec null is a signal for stale events moment, nulling field defensive I if needed avoid leaks. If not, a final field.)</technical_language>

Target:
public CodecState( MediaTimeProvider mediaTimeProvider, MediaExtractor extractor, int trackIndex, MediaFormat format, MediaCodec codec, boolean limitQueueDepth, boolean tunneled, int audioSessionId) { mMediaTimeProvider = mediaTimeProvider; mExtractor = extractor; mTrackIndex = trackIndex; mFormat = format; mSawInputEOS = mSawOutputEOS = false; mLimitQueueDepth = limitQueueDepth; mTunneled = tunneled; mAudioSessionId = audioSessionId; mSampleBaseTimeUs = -1; mCodec = codec; mAvailableInputBufferIndices = new LinkedList<Integer>(); mAvailableOutputBufferIndices = new LinkedList<Integer>(); mAvailableOutputBufferInfos = new LinkedList<MediaCodec.BufferInfo>(); mPresentationTimeUs = 0; String mime = mFormat.getString(MediaFormat.KEY_MIME); Log.d(TAG, "CodecState::CodecState " + mime); mIsAudio = mime.startsWith("audio/"); if (mTunneled && !mIsAudio) { mOnFrameRenderedListener = new OnFrameRenderedListener(mCodec); } }
Source:
<code>public void markRead(List<Notification> notifications) { final String idListStr = joinNotificationIds(notifications); <START> new EditTokenClient().request(wiki, <END> new EditTokenClient.Callback() { @Override public void success(@NonNull Call<EditToken> call, @NonNull String token) { service.markRead(token, idListStr).enqueue(new retrofit2.Callback<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>>() { @Override public void onResponse(Call<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>> call, Response<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>> response) { } @Override public void onFailure(Call<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>> call, Throwable t) { L.e(t); } }); } @Override public void failure(@NonNull Call<EditToken> call, @NonNull Throwable t) { L.e(t); } }); }</code><technical_language>hold this a member variable break out put resonsbility client</technical_language>

Target:
public void markRead(List<Notification> notifications) { final String idListStr = TextUtils.join("|", notifications); editTokenClient.request(wiki, new EditTokenClient.Callback() { @Override public void success(@NonNull Call<EditToken> call, @NonNull String token) { requestMarkRead(service, token, idListStr).enqueue(new retrofit2.Callback<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>>() { @Override public void onResponse(Call<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>> call, Response<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>> response) { } @Override public void onFailure(Call<MwQueryResponse<MarkReadResponse.QueryMarkReadResponse>> call, Throwable t) { L.e(t); } }); } @Override public void failure(@NonNull Call<EditToken> call, @NonNull Throwable t) { L.e(t); } }); }
Source:
<code>public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) { super.entityInteract(player, message); if (message.getHandSlot() == EquipmentSlot.HAND) { <START> if (!InventoryUtil.isEmpty(player.getItemInHand()) && player.getItemInHand().getType() == Material.LEASH) { <END> if (this.isLeashed()) { return false; } if (EventFactory.callEvent(new PlayerLeashEntityEvent(this, player, player)).isCancelled()) { return false; } setLeashHolder(player); } else if (player.equals(this.getLeashHolder())) { if (EventFactory.callEvent(new PlayerUnleashEntityEvent(this, player)).isCancelled()) { return false; } setLeashHolder(null); if (player.getGameMode() != GameMode.CREATIVE) { world.dropItemNaturally(this.location, new ItemStack(Material.LEASH)); } } return true; } return false; }</code><technical_language>Please reduce of empty lines/whitespace in this method</technical_language>

Target:
public boolean entityInteract(GlowPlayer player, InteractEntityMessage message) { super.entityInteract(player, message); if (message.getAction() != Action.INTERACT.ordinal()) { return false; } ItemStack handItem = InventoryUtil.itemOrEmpty(player.getInventory().getItem(message.getHandSlot())); if (isLeashed() && player.equals(this.getLeashHolder()) && message.getHandSlot() == EquipmentSlot.HAND) { if (EventFactory.callEvent(new PlayerUnleashEntityEvent(this, player)).isCancelled()) { return false; } setLeashHolder(null); if (player.getGameMode() != GameMode.CREATIVE) { world.dropItemNaturally(this.location, new ItemStack(Material.LEASH)); } return true; } else if (!InventoryUtil.isEmpty(handItem) && handItem.getType() == Material.LEASH) { if (!GlowLeashHitch.isAllowedLeashHolder(this.getType()) || this.isLeashed() || EventFactory.callEvent(new PlayerLeashEntityEvent(this, player, player)).isCancelled()) { return false; } if (player.getGameMode() != GameMode.CREATIVE) { if (handItem.getAmount() > 1) { handItem.setAmount(handItem.getAmount() - 1); } else { handItem = InventoryUtil.createEmptyStack(); } player.getInventory().setItem(message.getHandSlot(), handItem); } setLeashHolder(player); return true; } return false; }
Source:
<code>public void handlesSocket() throws IOException { final Socket socket = Mockito.mock(Socket.class); Mockito.when(socket.getInputStream()).thenReturn( new ByteArrayInputStream( Joiner.on("\r\n").join( <START> "POST / HTTP/1.1", <END> "Host:localhost", "Content-Length: 4", "", "hi" ).getBytes() ) ); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getPort()).thenReturn(0); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(baos); new BkBasic(new TkText("Hello world!")).accept(socket); MatcherAssert.assertThat( baos.toString(), Matchers.containsString("Hello world") ); }</code><technical_language>@hs3180 change this line</technical_language>

Target:
public void handlesSocket() throws IOException { final Socket socket = Mockito.mock(Socket.class); Mockito.when(socket.getInputStream()).thenReturn( new ByteArrayInputStream( Joiner.on("\r\n").join( "GET / HTTP/1.1", "Host:localhost", "Content-Length: 2", "", "hi" ).getBytes() ) ); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getPort()).thenReturn(0); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(baos); new BkBasic(new TkText("Hello world!")).accept(socket); MatcherAssert.assertThat( baos.toString(), Matchers.containsString("Hello world") ); }
Source:
<code>private Mono<SearchPagedResponse> search(SearchRequest request, RequestOptions requestOptions, String continuationToken, SearchFirstPageResponseWrapper firstPageResponseWrapper, Context context) { if (continuationToken == null && firstPageResponseWrapper.getFirstPageResponse() != null) { return Mono.just(firstPageResponseWrapper.getFirstPageResponse()); } SearchRequest requestToUse = (continuationToken == null) ? request : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); return restClient.documents().searchPostWithRestResponseAsync(requestToUse, RequestOptionsConverter.map(requestOptions), context) .onErrorMap(MappingUtils::exceptionMapper) .map(searchDocumentResponse -> new SearchPagedResponse(searchDocumentResponse, serviceVersion)) <START> .doOnNext(response -> { <END> if (continuationToken == null) { firstPageResponseWrapper.setFirstPageResponse(response); } }); }</code><technical_language>do this in map operation above. doOnNext is meant for side-effect operations logging tracing</technical_language>

Target:
private Mono<SearchPagedResponse> search(SearchRequest request, RequestOptions requestOptions, String continuationToken, SearchFirstPageResponseWrapper firstPageResponseWrapper, Context context) { if (continuationToken == null && firstPageResponseWrapper.getFirstPageResponse() != null) { return Mono.just(firstPageResponseWrapper.getFirstPageResponse()); } SearchRequest requestToUse = (continuationToken == null) ? request : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); return restClient.documents().searchPostWithRestResponseAsync(requestToUse, RequestOptionsConverter.map(requestOptions), context) .onErrorMap(MappingUtils::exceptionMapper) .map(searchDocumentResponse -> { SearchPagedResponse response = new SearchPagedResponse(searchDocumentResponse, serviceVersion); if (continuationToken == null) { firstPageResponseWrapper.setFirstPageResponse(response); } return response; }); }
Source:
<code><START> protected Ord<RelDataType> getNewFieldForOldInput(int oldOrdinal, int existingOffset) { <END> assert currentRel != null; int newOrdinal = 0; RelNode oldInput = null; RelNode newInput = null; for (RelNode oldInput1 : currentRel.getInputs()) { newInput = getNewForOldRel(oldInput1); RelDataType oldInputType = oldInput1.getRowType(); int n = oldInputType.getFieldCount(); if (oldOrdinal < n) { oldInput = oldInput1; break; } newOrdinal += newInput.getRowType().getFieldCount(); oldOrdinal -= n; } assert oldInput != null; assert newInput != null; RelDataType oldInputType = oldInput.getRowType(); final int newOffset = calculateFlattenedOffset(oldInputType, oldOrdinal) + existingOffset; newOrdinal += newOffset; final RelDataTypeField field = newInput.getRowType().getFieldList().get(newOffset); return Ord.of(newOrdinal, field.getType()); }</code><technical_language>protected private? Is meant subclassed</technical_language>

Target:
private Ord<RelDataType> getNewFieldForOldInput(int oldOrdinal, int existingOffset) { assert currentRel != null; int newOrdinal = 0; RelNode oldInput = null; RelNode newInput = null; for (RelNode oldInput1 : currentRel.getInputs()) { newInput = getNewForOldRel(oldInput1); RelDataType oldInputType = oldInput1.getRowType(); int n = oldInputType.getFieldCount(); if (oldOrdinal < n) { oldInput = oldInput1; break; } newOrdinal += newInput.getRowType().getFieldCount(); oldOrdinal -= n; } assert oldInput != null; assert newInput != null; RelDataType oldInputType = oldInput.getRowType(); final int newOffset = calculateFlattenedOffset(oldInputType, oldOrdinal) + existingOffset; newOrdinal += newOffset; final RelDataTypeField field = newInput.getRowType().getFieldList().get(newOffset); return Ord.of(newOrdinal, field.getType()); }
Source:
<code>private void getFlowingFlowNodes(FlowNode node) { Collection<SequenceFlow> sequenceFlow = node.getOutgoing(); <START> FlowNode flowNode = sequenceFlow.iterator().next().getTarget(); <END> if (flowNode instanceof Gateway) { getFlowingFlowNodesWithConditions((Gateway) flowNode); } else if (flowNode instanceof Task) { this.followingFlowNodes.add(flowNode); getFlowingFlowNodes(flowNode); } }</code><technical_language>a NPE happen if collection is empty / null</technical_language>

Target:
private void getFlowingFlowNodes(FlowNode node) { Collection<SequenceFlow> sequenceFlow = node.getOutgoing(); if (sequenceFlow.iterator().hasNext()) { FlowNode flowNode = sequenceFlow.iterator().next().getTarget(); if (flowNode instanceof Gateway) { getFlowingFlowNodesWithConditions((Gateway) flowNode); } else if (flowNode instanceof Task) { this.followingFlowNodes.add(flowNode); getFlowingFlowNodes(flowNode); } } }
Source:
<code>void createWidget (int index) { super.createWidget (index); items = new TableItem [4]; columns = new TableColumn [4]; itemCount = columnCount = 0; <START> if (OS.GTK_VERSION < OS.VERSION(3, 21, 0)) { <END> setFontDescription(defaultFont().handle); } }</code><technical_language>Generally check for GTK dev versions. GTK3.21 is a development version, this call GTK3.22</technical_language>

Target:
void createWidget (int index) { super.createWidget (index); items = new TableItem [4]; columns = new TableColumn [4]; itemCount = columnCount = 0; if (OS.GTK_VERSION < OS.VERSION(3, 22, 0)) { setFontDescription(defaultFont().handle); } }