auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void persist(LocalDocument doc) throws IOException, JsonException { logger.debug("Saving document to RemotePipeline.."); if(!remotePipeline.save(doc)) { // TODO: Why are we cloning here? START LocalDocument ld = new LocalDocument(doc); END IOException e = new IOException("Unable to save changes to core"); if(!onException(ld, e)) { logger.error("Unable to persist an error to the database for doc '" + doc.getID() + "'", e); } } } Wondering the same thing about this line. It was introduced in 5dc4438fbdcc7ad6015a9d7574e00072b0534794. I can only think of some kind of concurrency issue. With `RemotePipeline` now being immutable, I can't see what cloning would achieve.

Target:
private void persist(LocalDocument doc) throws IOException, JsonException { logger.debug("Saving document to RemotePipeline.."); if(!remotePipeline.save(doc)) { IOException e = new IOException("Unable to save changes to core"); if(!onException(doc, e)) { logger.error("Unable to persist an error to the database for doc '" + doc.getID() + "'", e); } } }
Source:
public String getPdxDiskStoreName() { START Assert.state(!StringUtils.isEmpty(pdxDiskStoreName), "The PDX Disk Store name was not properly initialized!"); END return pdxDiskStoreName; } Assert not required if field is final

Target:
public String getPdxDiskStoreName() { return pdxDiskStoreName; }
Source:
public void onEditFailure(@NonNull Throwable caught) { showProgressBar(false); if (caught instanceof MwException) { handleEditingException((MwException) caught); START L.e(caught); } else { showRetryDialog(caught); L.e(caught); END } } Looks like the common `L.e(caught)` can be extracted to the bottom.

Target:
public void onEditFailure(@NonNull Throwable caught) { showProgressBar(false); if (caught instanceof MwException) { handleEditingException((MwException) caught); } else { showRetryDialog(caught); } L.e(caught); }
Source:
void scrollToSection(@NonNull String sectionAnchor) { bridge.execute(JavaScriptActionHandler.prepareToScrollTo(sectionAnchor, "{ highlight: false }")); for (Section section : adapter.sections) { if (section.getAnchor().equals(sectionAnchor)) { START scrollToSection(section); END break; } } } Do we still need this other `scrollToSection()` call, then? It sounds like we're making it scroll twice.

Target:
void scrollToSection(@NonNull String sectionAnchor) { bridge.execute(JavaScriptActionHandler.prepareToScrollTo(sectionAnchor, "{ highlight: false }")); }
Source:
public Set<String> getEditRoles() { START Set<String> roleSet = new HashSet<>(); roleSet.add(edit); return edit != null ? Collections.unmodifiableSet(roleSet) : Collections.emptySet(); END } The logic does not make sense to me. The `edit != null` logic should happen before creating any object, otherwise, it will be a redundant object.

Target:
public Set<String> getEditRoles() { Set<String> roleSet = new HashSet<>(); if (edit != null) { roleSet.add(edit); } return Collections.unmodifiableSet(roleSet); }
Source:
ErrorType getErrorType(@Nullable Throwable caught) { if (caught != null && is404(caught)) { return ErrorType.PAGE_MISSING; } else if (caught != null && isTimeout(caught)) { return ErrorType.TIMEOUT; START } else if (caught != null && isOffline(caught)) { END return ErrorType.OFFLINE; } return ErrorType.GENERIC; } Do these `caught != null` null check conditions necessary?

Target:
ErrorType getErrorType(@Nullable Throwable caught) { if (caught != null && is404(caught)) { return ErrorType.PAGE_MISSING; } else if (isTimeout(caught)) { return ErrorType.TIMEOUT; } else if (isOffline(caught)) { return ErrorType.OFFLINE; } return ErrorType.GENERIC; }
Source:
public void setDescription(@Nullable String text) { START if (invokeSource != SUGGESTED_EDITS_ADD_CAPTION && invokeSource != SUGGESTED_EDITS_TRANSLATE_CAPTION) { END pageDescriptionText.setText(text); } } This will break the current logic of showing "added" contribution

Target:
public void setDescription(@Nullable String text) { pageDescriptionText.setText(text); }
Source:
public void setPageTitle(@NonNull PageTitle pageTitle) { this.pageTitle = pageTitle; originalDescription = pageTitle.getDescription(); setHintText(); START if (invokeSource != SUGGESTED_EDITS_ADD_CAPTION && invokeSource != SUGGESTED_EDITS_TRANSLATE_CAPTION) { END setDescription(originalDescription); } setReviewHeaderText(false); } If a user added caption from the Suggested edits flow, this will break the current logic of showing the "added" caption.

Target:
public void setPageTitle(@NonNull PageTitle pageTitle) { this.pageTitle = pageTitle; originalDescription = pageTitle.getDescription(); setHintText(); setDescription(originalDescription); setReviewHeaderText(false); }
Source:
public void dispose() { START if (disposables != null && !disposables.isDisposed()) { END disposables.clear(); } } These checks do not need to be performed.

Target:
public void dispose() { disposables.clear(); }
Source:
public String getLeadingImageEditLang() { return isTranslation ? targetSummary.getPageTitle().getWikiSite().languageCode() : sourceSummary.getPageTitle().getWikiSite().languageCode(); START } END This will produce a NPE and crash the app if `sourceSummary` or `targetSummary` is null. This can happen if the activity is destroyed (e.g. "don't keep activities) and then recreated when coming back from editing.

Target:
public String getLeadingImageEditLang() { if (isTranslation ? (targetSummary == null || sourceSummary == null) : sourceSummary == null) { return null; } return isTranslation ? targetSummary.getPageTitle().getWikiSite().languageCode() : sourceSummary.getPageTitle().getWikiSite().languageCode(); }
Source:
void setFadeEnabled(boolean enabled) { fadeEnabled = enabled; // to avoid the toolbar applies the opacity before image loaded START pageFragment.getWebView().postDelayed(this::update, DELAY_UPDATE_MS); END } When I see code that uses `postDelayed` to work around a problem, it usually means that there's an incomplete understanding of the underlying issue. (see below)

Target:
void setFadeEnabled(boolean enabled) { fadeEnabled = enabled; update(); }
Source:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().setStatusBarColor(Color.TRANSPARENT); // TODO: translucent status will affect the navigation bar color? START getWindow().setNavigationBarColor(0); END } Fixed and done.

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().setStatusBarColor(Color.TRANSPARENT); }
Source:
private void updateUI() { username.setText(AccountUtil.getUserName()); START contributionsText.setText(getResources().getQuantityString(R.plurals.edit_action_contribution_count, Prefs.getTotalUserDescriptionsEdited())); END requireActivity().invalidateOptionsMenu(); } Needs to update the `contributionsText.setText()` since the `R.plurals.edit_action_contribution_count` contains a `%d`

Target:
private void updateUI() { username.setText(AccountUtil.getUserName()); contributionsText.setText(getResources().getQuantityString(R.plurals.edit_action_contribution_count, Prefs.getTotalUserDescriptionsEdited(), Prefs.getTotalUserDescriptionsEdited())); requireActivity().invalidateOptionsMenu(); }
Source:
public static String getThemePageLibClass(Theme theme) { switch (theme.getFunnelName()) { START case "light": END return "pagelib_theme_light"; case "dark": return "pagelib_theme_dark"; case "black": return "pagelib_theme_black"; case "sepia": return "pagelib_theme_sepia"; default: return "pagelib_theme_light"; } } Maybe it is okay to remove the `case "light"` since it is a default case?

Target:
public static String getThemePageLibClass(Theme theme) { switch (theme.getFunnelName()) { case "dark": return "pagelib_theme_dark"; case "black": return "pagelib_theme_black"; case "sepia": return "pagelib_theme_sepia"; default: return "pagelib_theme_light"; } }
Source:
private String requestPath(Uri requestUri) { if (!requestUri.getPath().isEmpty()) return requestUri.getPath(); else START return "/"; END } Please use ternary operator `?`.

Target:
private String requestPath(Uri requestUri) { return requestUri.getPath().isEmpty() ? "/" : requestUri.getPath(); }
Source:
private static String convertHost(final String host) { if (host == null) { return null; START } END return stripDotSuffix(host).toUpperCase(); } Please use ? ternary operator

Target:
private static String convertHost(final String host) { return host != null ? stripDotSuffix(host).toUpperCase() : null; }
Source:
private static String convertDomain(final String domain) { START if (domain == null) { END return null; } return stripDotSuffix(domain).toUpperCase(); } Please use ? ternary operator

Target:
private static String convertDomain(final String domain) { return domain != null ? stripDotSuffix(domain).toUpperCase() : null; }
Source:
private ExecutionList executionList() { START for (;;) { END ExecutionList executionListLocal = this.executionList; if (executionListLocal != null) { return executionListLocal; } ExecutionList r = new ExecutionList(); if (executionListField.compareAndSet(this, null, r)) { return r; } } } Are you sure we need this?

Target:
private ExecutionList executionList() { ExecutionList executionListLocal = this.executionList; if (executionListLocal != null) { return executionListLocal; } ExecutionList r = new ExecutionList(); if (executionListField.compareAndSet(this, null, r)) { return r; } else { return this.executionList; } }
Source:
START public ClientStats getClientStats() { END final ChannelManager channelManager = requestSender.getChannelManager(); final long activeConnectionCount = channelManager.getOpenChannels().stream().filter(channel -> !channel.isOpen()).count(); final long idleConnectionCount = channelManager.getOpenChannels().stream().filter(Channel::isOpen).count(); return new ClientStats(activeConnectionCount, idleConnectionCount); } Should be declared in `AsyncHttpClient` interface. Implementation here should be flagged with @Override

Target:
public ClientStats getClientStats() { return channelManager.getClientStats(); }
Source:
private static String getPartitionId(InetAddress overrideAddress, Request request, ProxyServer proxyServer) { START return overrideAddress != null ? overrideAddress.toString() + "_" : "" + END request.getConnectionPoolPartitioning() .getPartitionKey(request.getUri(), proxyServer).toString(); } is it supposed to be (overrideAddress != null ? overrideAddress.toString() + "_" : "") + request.getConnectionPoolPartitioning() .getPartitionKey(request.getUri(), proxyServer).toString(); ?

Target:
private static String getPartitionId(InetAddress overrideAddress, Request request, ProxyServer proxyServer) { return (overrideAddress != null ? overrideAddress.toString() + "_" : "") + request.getConnectionPoolPartitioning() .getPartitionKey(request.getUri(), proxyServer).toString(); }
Source:
private static boolean attemptInstantiation() { START if (instantiated == false) { END lock.lock(); try { if (instantiated == false) { asyncHttpClientImplClass = AsyncImplHelper .getAsyncImplClass(AsyncImplHelper.ASYNC_HTTP_CLIENT_IMPL_SYSTEM_PROPERTY); instantiated = true; } } finally { lock.unlock(); } } return (asyncHttpClientImplClass != null); } !instantiated

Target:
private static boolean attemptInstantiation() { if (!instantiated) { lock.lock(); try { if (!instantiated) { asyncHttpClientImplClass = AsyncImplHelper .getAsyncImplClass(AsyncImplHelper.ASYNC_HTTP_CLIENT_IMPL_SYSTEM_PROPERTY); instantiated = true; } } finally { lock.unlock(); } } return asyncHttpClientImplClass != null; }
Source:
public boolean unRegister(String name) { if (asyncHttpClientMap.remove(name) == null) return false; else return true; START } END `return asyncHttpClientMap.remove(name) != null`

Target:
public boolean unRegister(String name) { return asyncHttpClientMap.remove(name) != null; }
Source:
START @Test public void smokes() throws Exception { END assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("test/foo"); assertRoundTrip("test%bar"); assertRoundTrip("test #1"); } ```suggestion @Test public void smokes() throws Exception { ```

Target:
public void smokes() throws Exception { assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("test/foo"); assertRoundTrip("test%bar"); assertRoundTrip("test #1"); }
Source:
public List<BranchProperty> getPropertiesFor(SCMHead head) { List<BranchProperty> properties = new ArrayList<>(); for (Named named : namedExceptions) { if (named.isMatch(head)) { START properties.addAll(named.getProps()); END } } if (properties.isEmpty()) { // if no one defined adds default properties.addAll(defaultProperties); } return properties; } This looks unrelated to the main purpose of the PR, and it seems like it could be a breaking change because branch jobs for existing projects could end up with different properties after the update. Why are the changes to this method needed?

Target:
public List<BranchProperty> getPropertiesFor(SCMHead head) { for (Named named : namedExceptions) { if (named.isMatch(head)) { return new ArrayList<>(named.getProps()); } } return new ArrayList<>(defaultProperties); }
Source:
private @NonNull Action[] getRevisionActions(@NonNull SCMRevision revision, String rawName) { Action[] revisionActions = new Action[0]; try { List<Action> actions = source.fetchActions(revision, event, listener); START revisionActions = actions.toArray(new Action[0]); END } catch (IOException | InterruptedException e) { printStackTrace(e, listener.error("Could not fetch metadata for revision %s of branch %s", revision, rawName)); } return revisionActions; } Slight performance enhancement... ```suggestion revisionActions = actions.toArray(new Action[actions.size()]); ```

Target:
private Action[] getRevisionActions(@NonNull SCMRevision revision, String rawName) { Action[] revisionActions = new Action[0]; try { List<Action> actions = source.fetchActions(revision, event, listener); revisionActions = actions.toArray(new Action[actions.size()]); } catch (IOException | InterruptedException e) { printStackTrace(e, listener.error("Could not fetch metadata for revision %s of branch %s", revision, rawName)); } return revisionActions; }
Source:
public final boolean automaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision, @CheckForNull SCMRevision prevRevision, @NonNull TaskListener listener) { START return automaticBuild(source, head, currRevision, prevRevision, listener, null); END } last seen should be defaulted to lastBuilt

Target:
public final boolean automaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision, @CheckForNull SCMRevision prevRevision, @NonNull TaskListener listener) { return automaticBuild(source, head, currRevision, prevRevision, prevRevision, listener); }
Source:
START private static @NonNull InputStream readFilePath(@NonNull FilePath index) throws IOException, InterruptedException { END InputStream stream = index.read(); assert stream != null; return stream; } We do not use Glick-style annotations. If the method returns `@NonNull` then the `@NonNull` shall be on the line preceding the access modifiers not between the access modifiers and the return type

Target:
private static InputStream readFilePath(@NonNull FilePath index) throws IOException, InterruptedException { InputStream stream = index.read(); assert stream != null; return stream; }
Source:
public synchronized void save() throws IOException { if (BulkChange.contains(this)) { return; } getStateFile().write(this); START SaveableListener.fireOnChange(this, getStateFile()); END } Fire the event outside of the monitor.

Target:
public void save() throws IOException { synchronized (this) { if (BulkChange.contains(this)) { return; } getStateFile().write(this); } SaveableListener.fireOnChange(this, getStateFile()); }
Source:
public void onUpdated(Item item) { if (item instanceof SCMSourceOwner) { try { ((SCMSourceOwner) item).getSCMSources(); } catch (NullPointerException e) { check = false; START throw e; END } } } :ant: not a good test style, since this will make no sense after the bug is fixed, and will not catch unrelated problems. Better to set `check` to `false` initially, then set it to `true` after calling `getSCMSources` (with no `catch` block).

Target:
public void onUpdated(Item item) { if (item instanceof SCMSourceOwner) { try { ((SCMSourceOwner) item).getSCMSources(); } catch (NullPointerException e) { check = new Exception(e); } } }
Source:
public FreeStyleProject newInstance(Branch branch) { FreeStyleProject job = new FreeStyleProject(getOwner(), branch.getName()); job.onCreatedFromScratch(); FreeStyleProject spied = spy(job); // Do nothing.. Running the actual build is not desired/required (and not possible) in this tests. START when(spied.scheduleBuild()).thenReturn(false); END setBranch(spied, branch); return spied; } Could do this without mocks by using a custom `Project` subclass that overrides `scheduleBuild`.

Target:
public FreeStyleProject newInstance(Branch branch) { FreeStyleProject job = new FreeStyleProject(getOwner(), branch.getName()); FreeStyleProject spied = spy(job); // Do nothing.. Running the actual build is not desired/required (and not possible) in this tests. when(spied.scheduleBuild()).thenReturn(false); setBranch(spied, branch); return spied; }
Source:
START public abstract @CheckForNull MultiBranchProject<?,?> createProject(@Nonnull ItemGroup<?> parent, @Nonnull String name, @Nonnull List<? extends SCMSource> scmSources, @Nonnull Map<String,Object> attributes, @Nonnull TaskListener listener) throws IOException, InterruptedException; END @Override public MultiBranchProjectFactoryDescriptor getDescriptor() { return (MultiBranchProjectFactoryDescriptor) super.getDescriptor(); } style guide

Target:
public abstract MultiBranchProject<?,?> createProject(@Nonnull ItemGroup<?> parent, @Nonnull String name, @Nonnull List<? extends SCMSource> scmSources, @Nonnull Map<String,Object> attributes, @Nonnull TaskListener listener) throws IOException, InterruptedException; @Override public MultiBranchProjectFactoryDescriptor getDescriptor() { return (MultiBranchProjectFactoryDescriptor) super.getDescriptor(); }
Source:
START @DataBoundSetter public final void setParameterDefinitions(List<ParameterDefinition> parameterDefinitions) { END this.parameterDefinitions = parameterDefinitions; } code style

Target:
public final void setParameterDefinitions(List<ParameterDefinition> parameterDefinitions) { this.parameterDefinitions = parameterDefinitions; }
Source:
START @Override public boolean filter(Object context, Descriptor descriptor) { END if (context instanceof MultiBranchProject && descriptor instanceof BranchPropertyDescriptor) { return ((BranchPropertyDescriptor) descriptor).isApplicable((MultiBranchProject) context); } else { return true; } } code style

Target:
public boolean filter(Object context, Descriptor descriptor) { if (context instanceof MultiBranchProject && descriptor instanceof BranchPropertyDescriptor) { return ((BranchPropertyDescriptor) descriptor).isApplicable((MultiBranchProject) context); } else { return true; } }
Source:
START public @NonNull PersistedList<BranchSource> getSourcesList() { END return sources; } No way not in the middle :bug: code style

Target:
public PersistedList<BranchSource> getSourcesList() { return sources; }
Source:
START public @CheckForNull Node getBuiltOn() { END Jenkins j = Jenkins.getInstance(); if (builtOn == null || builtOn.isEmpty() || j == null) { return j; } else { return j.getNode(builtOn); } } :bug: code style

Target:
public Node getBuiltOn() { Jenkins j = Jenkins.getInstance(); if (builtOn == null || builtOn.isEmpty() || j == null) { return j; } else { return j.getNode(builtOn); } }
Source:
START @Override protected boolean isApplicable(MultiBranchProjectDescriptor projectDescriptor) { END for (BranchProjectFactoryDescriptor d : projectDescriptor.getProjectFactoryDescriptors()) { Type factoryType = Types.getBaseClass(d.clazz, BranchProjectFactory.class); Type jobType = Types.getTypeArgument(factoryType, 0, /* if using rawtypes, err on the conservative side */ Project.class); if (Project.class.isAssignableFrom(Types.erasure(jobType))) { return true; } } return false; } code style

Target:
protected boolean isApplicable(MultiBranchProjectDescriptor projectDescriptor) { for (BranchProjectFactoryDescriptor d : projectDescriptor.getProjectFactoryDescriptors()) { Type factoryType = Types.getBaseClass(d.clazz, BranchProjectFactory.class); Type jobType = Types.getTypeArgument(factoryType, 0, /* if using rawtypes, err on the conservative side */ Project.class); if (Project.class.isAssignableFrom(Types.erasure(jobType))) { return true; } } return false; }
Source:
<T> void uninstallSubscriber(Class<T> type, Subscriber<T> subscriber) { Map<Subscriber, Subscriber> subscribers = subscribersByType.get(type); if (subscribers != null) { Subscriber original = subscribers.remove(subscriber); if (original != null) { original.invalidate(); START return; END } } throw new IllegalArgumentException( "Missing subscriber for an annotated method. Is " + type + " registered?"); } `return` should be one line below. The sample app crashes (wrong missing subscriber exception) as soon as you pause the app.

Target:
<T> void uninstallSubscriber(Class<T> type, Subscriber<T> subscriber) { Map<Subscriber, Subscriber> subscribers = subscribersByType.get(type); if (subscribers != null) { Subscriber original = subscribers.remove(subscriber); if (original != null) { original.invalidate(); } return; } throw new IllegalArgumentException( "Missing subscriber for an annotated method. Is " + type + " registered?"); }
Source:
private ExecutionType getRandomExecutionType(Bundle bundle) throws Exception { ExecutionType current = bundle.getProcessObject().getOrder(); Random r = new Random(); ExecutionType[] values = ExecutionType.values(); int i; do { i = r.nextInt(values.length); START } while (current.equals(values[i])); END return values[i]; } it is generally recommended to use == for enums comparison

Target:
private ExecutionType getRandomExecutionType(Bundle bundle) throws Exception { ExecutionType current = bundle.getProcessObject().getOrder(); Random r = new Random(); ExecutionType[] values = ExecutionType.values(); int i; do { i = r.nextInt(values.length); } while (current == values[i]); return values[i]; }
Source:
public void setup(Method method) throws Exception { Util.print("test name: " + method.getName()); START bundles[0] = new Bundle(); END bundles[0] = Util.readELBundles()[0][0]; bundles[0] = new Bundle(bundles[0], cluster.getEnvFileName(), cluster.getPrefix()); bundles[0].setInputFeedDataPath(feedInputPath); bundles[0].setProcessWorkflow(aggregateWorkflowDir); } No need for bundles[0] = new Bundle();

Target:
public void setup(Method method) throws Exception { Util.print("test name: " + method.getName()); bundles[0] = Util.readELBundles()[0][0]; bundles[0] = new Bundle(bundles[0], cluster.getEnvFileName(), cluster.getPrefix()); bundles[0].setInputFeedDataPath(feedInputPath); bundles[0].setProcessWorkflow(aggregateWorkflowDir); }
Source:
public static void deleteDirIfExists(String hdfsPath, FileSystem fs) throws IOException { Path path = new Path(hdfsPath); if (fs.exists(path)) { START System.out.println("Deleting HDFS path: "+ path + " on "+fs.getConf().get("fs.default.name")); END fs.delete(path, true); } } Use Logger.

Target:
public static void deleteDirIfExists(String hdfsPath, FileSystem fs) throws IOException { Path path = new Path(hdfsPath); if (fs.exists(path)) { logger.info("Deleting HDFS path: "+ path + " on "+fs.getConf().get("fs.default.name")); fs.delete(path, true); } }
Source:
public static boolean isIdentical(String expected, String actual) throws IOException, SAXException { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); Diff diff = XMLUnit.compareXML(expected, actual); START System.out.println(diff); END return diff.identical(); } Use a logger object.

Target:
public static boolean isIdentical(String expected, String actual) throws IOException, SAXException { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); Diff diff = XMLUnit.compareXML(expected, actual); logger.info(diff); return diff.identical(); }
Source:
StreamSession deriveSession(StreamMessage message) { // StreamInitMessage starts a new channel, and IncomingStreamMessage potentially, as well. // IncomingStreamMessage needs a session to be established a priori, though StreamSession streamSession = message.getOrCreateSession(channel); START if (streamSession == null) throw new IllegalStateException(createLogTag(null, channel) + " no session found for message " + message); END // Attach this channel to the session: this only happens upon receiving the first init message as a follower; // in all other cases, no new control channel will be added, as the proper control channel will be already attached. streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; } Based on my understanding, calling `getOrCreateSession` on `StreamInitMessage` or `IncomingStreamMessage` is guaranty to return a `StreamSession` and calling `getOrCreateSession` on another type of message would throw an `UnsupportedOperationException`. By consequence, it seems that this null check is useless. Am I missing something?

Target:
StreamSession deriveSession(StreamMessage message) { // StreamInitMessage starts a new channel here, but IncomingStreamMessage needs a session // to be established a priori StreamSession streamSession = message.getOrCreateSession(channel); // Attach this channel to the session: this only happens upon receiving the first init message as a follower; // in all other cases, no new control channel will be added, as the proper control channel will be already attached. streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; }
Source:
START private void onChannelClose(Channel channel) END { if (channels.remove(channel.id()) != null && channels.isEmpty()) messageSender.close(); } This is called from different channels, so possibly from different event loop threads, so shouldn't it be synchronized?

Target:
private synchronized void onChannelClose(Channel channel) { if (channels.remove(channel.id()) != null && channels.isEmpty()) messageSender.close(); }
Source:
public static void applyPartitioner() { /* Hashing strategy */ if (conf.partitioner == null) { throw new ConfigurationException("Missing directive: partitioner", false); } String partitionerName = conf.partitioner; try { partitionerName = System.getProperty(Config.PROPERTY_PREFIX + "partitioner", conf.partitioner); partitioner = FBUtilities.newPartitioner(partitionerName); } catch (Exception e) { START throw new ConfigurationException("Invalid partitioner class " + partitionerName, e); END } paritionerName = partitioner.getClass().getCanonicalName(); } The change allows to 1. Set the correct `partitionerName` in the exception message. Previously, the message just include the partitioner set in the conf and it could be wrong when system property is present. 2. Add the stack trace to the exception and enable logging.

Target:
public static void applyPartitioner() { applyPartitioner(conf); }
Source:
public static void before() { // This only works because the way CI works // In CI a new JVM is spun up for each test file, so this doesn't have to worry about another test file // getting this set first System.setProperty("cassandra.nodetool.jmx_notification_poll_interval_seconds", "1"); START DatabaseDescriptor.clientInitialization(); END } I'm curious why we need to initialize client here. Usually we need to do this in Cassandra instance itself, but not on the test class. Do we need it for JMX to work?

Target:
public static void before() { // This only works because the way CI works // In CI a new JVM is spun up for each test file, so this doesn't have to worry about another test file // getting this set first System.setProperty("cassandra.nodetool.jmx_notification_poll_interval_seconds", "1"); }
Source:
public InternalNodeProbe(boolean withNotifications) throws IOException { super("", 0); this.withNotifications = withNotifications; START connect(); // need to double "connect" since constructor calls connect; withNotifications isn't visable the first time END } how about adding a new `NodeProble` constructor with param `boolean connect`, so we don't have to connect twice...

Target:
public InternalNodeProbe(boolean withNotifications) { this.withNotifications = withNotifications; connect(); }
Source:
public boolean permit(int from, int to, IMessage msg) { for (Filter filter : filters) { if (filter.matches(from, to, msg)) START return filter.permitIfMatched; END } return true; } this feels weird to me; if I have the following ``` filter(verb).pass(); filter(verb).drop(); ``` what happens? It looks like the drop will be skipped in favor of pass. Don't see a test for this since each test calls `filters.reset();` before adding the second filter. The pass/drop stuff already exists so nothing for this PR, but I feel that `pass()` should be removed (should file jira for this)

Target:
public boolean permit(int from, int to, IMessage msg) { for (Filter filter : filters) { if (filter.matches(from, to, msg)) return false; } return true; }
Source:
START public NodeProbe create(String host, int port, String username, String password) throws IOException { END return new InternalNodeProbe(host, port, username, password); } personal preference (aka your call) ``` return new InternalNodeProbe(); ``` Rather than have the dumby constructors in `InternalNodeProbe`

Target:
public NodeProbe create(String host, int port, String username, String password) throws IOException { return new InternalNodeProbe(); }
Source:
private static int roundKey(int point, int roundSeconds) { int d = point % roundSeconds; if (d > 0) { point += roundSeconds - d; if (point == Cell.MAX_DELETION_TIME) // the rounding should not be a reason to mark point as unexpirable START point = Cell.MAX_DELETION_TIME; END else if (point < 0) // math overflow happen because of point was close to max possible value return Cell.MAX_DELETION_TIME; return point; } else return point; } why assign `point =` here, but `return` below?

Target:
private static int roundKey(int point, int roundSeconds) { int d = point % roundSeconds; if (d == 0) return point; point += roundSeconds - d; if (point > Cell.MAX_DELETION_TIME) // the rounding should not be a reason to mark point as unexpirable return Cell.MAX_DELETION_TIME; else if (point < 0) // math overflow happen because of point was close to max possible value return Cell.MAX_DELETION_TIME; return point; }
Source:
public void add(Replica replica) { // can only add to full array - if we have sliced it, we must be a snapshot START assert begin == 0; END if (size == contents.length) { int newSize; if (size < 3) newSize = 3; else if (size < 9) newSize = 9; else newSize = size * 2; contents = Arrays.copyOf(contents, newSize); } contents[size++] = replica; } Shouldn't be possible to disable this check.

Target:
public void add(Replica replica) { // can only add to full array - if we have sliced it, we must be a snapshot if (begin != 0) throw new IllegalStateException(); if (size == contents.length) { int newSize; if (size < 3) newSize = 3; else if (size < 9) newSize = 9; else newSize = size * 2; contents = Arrays.copyOf(contents, newSize); } contents[size++] = replica; }
Source:
START static final ReplicaMap<InetAddressAndPort> endpointMap(ReplicaList list) { return new ReplicaMap<>(list, Replica::endpoint); } END This is a method, we can skip `final` here

Target:
static ReplicaMap<InetAddressAndPort> endpointMap(ReplicaList list) { return new ReplicaMap<>(list, Replica::endpoint); }
Source:
public Iterator<Replica> iterator() { return new Iterator<Replica>() { final int end = begin + size; int i = begin; START @Override END public boolean hasNext() { return i < end; } @Override public Replica next() { return contents[i++]; } }; } You can also use `Iterators#fromArray`.

Target:
public Iterator<Replica> iterator() { return new Iterator<Replica>() { final int end = begin + size; int i = begin; @Override public boolean hasNext() { return i < end; } @Override public Replica next() { if (!hasNext()) throw new IllegalStateException(); return contents[i++]; } }; }
Source:
START public static boolean isDummyList(RangesAtEndpoint ranges) END { return all(ranges, Replica::isLocal) || all(ranges, range -> range.endpoint().getHostAddress(true).equals("0.0.0.0:0")); } How does all replicas being local mean it's a dummy list? Only the 2nd half of this predicate is dummy list related.

Target:
public static boolean isDummyList(RangesAtEndpoint ranges) { return all(ranges, range -> range.endpoint().getHostAddress(true).equals("0.0.0.0:0")); }
Source:
START public static <E extends Endpoints<E>> E resolveWriteConflictsInPending(E natural, E pending) END { return pending.without(natural.endpoints()); } Not anymore

Target:
private static <E extends Endpoints<E>> E resolveWriteConflictsInPending(E natural, E pending) { return pending.without(natural.endpoints()); }
Source:
public Iterator<ResultHandler.ComparableRow> iterator() { if (wasFailed()) return Collections.emptyListIterator(); return new AbstractIterator<ResultHandler.ComparableRow>() { Iterator<Row> iter = resultSet.iterator(); protected ResultHandler.ComparableRow computeNext() { if (iter.hasNext()) START { END return new DriverRow(iter.next()); } return endOfData(); } }; } Unnecessary braces for single statement block (there are bunch of these in this file).

Target:
public Iterator<ResultHandler.ComparableRow> iterator() { if (wasFailed()) return Collections.emptyListIterator(); return new AbstractIterator<ResultHandler.ComparableRow>() { Iterator<Row> iter = resultSet.iterator(); protected ResultHandler.ComparableRow computeNext() { if (iter.hasNext()) return new DriverRow(iter.next()); return endOfData(); } }; }
Source:
public String toString() { StringBuilder sb = new StringBuilder("batch: ").append(batchType).append('\n'); for (Single q : queries) START { END sb.append(q.toString()).append('\n'); } sb.append("end batch"); return sb.toString(); } Redundant braces for a single statement block.

Target:
public String toString() { StringBuilder sb = new StringBuilder("batch: ").append(batchType).append('\n'); for (Single q : queries) sb.append(q.toString()).append('\n'); sb.append("end batch"); return sb.toString(); }
Source:
private String columnDefinitionsString(ResultHandler.ComparableColumnDefinitions cd) { StringBuilder sb = new StringBuilder(); if (cd == null) START { END sb.append("NULL"); } else if (cd.wasFailed()) { sb.append("FAILED"); } else { for (ResultHandler.ComparableDefinition def : cd) { sb.append(def.toString()); } } return sb.toString(); } Redundant braces

Target:
private String columnDefinitionsString(ResultHandler.ComparableColumnDefinitions cd) { StringBuilder sb = new StringBuilder(); if (cd == null) sb.append("NULL"); else if (cd.wasFailed()) sb.append("FAILED"); else { for (ResultHandler.ComparableDefinition def : cd) { sb.append(def.toString()); } } return sb.toString(); }
Source:
private Object getParameter(ParameterType type) { for (int ii = 0; ii < parameters.size(); ii += PARAMETER_TUPLE_SIZE) { START if (((ParameterType)parameters.get(ii + PARAMETER_TUPLE_TYPE_OFFSET)).equals(type)) END { return parameters.get(ii + PARAMETER_TUPLE_PARAMETER_OFFSET); } } return null; } Don't need the typecast to `ParameterType`

Target:
private Object getParameter(ParameterType type) { for (int ii = 0; ii < parameters.size(); ii += PARAMETER_TUPLE_SIZE) { if ((parameters.get(ii + PARAMETER_TUPLE_TYPE_OFFSET)).equals(type)) { return parameters.get(ii + PARAMETER_TUPLE_PARAMETER_OFFSET); } } return null; }
Source:
public int hashCode() { START return Objects.hash(replicaList); END } replicaList is not null so I would have just used replicaList.hashCode(). This might allocate a wrapper array for varargs. Objects.hashCode() is the single arg version that won't allocate.

Target:
public int hashCode() { return replicaList.hashCode(); }
Source:
public void executeAsync() { Replicas.checkFull(targetReplicas); START makeDataRequests(targetReplicas.subList(0, targetReplicas.size() > 1 ? 2 : 1).asEndpoints()); END if (targetReplicas.size() > 2) makeDigestRequests(targetReplicas.subList(2, targetReplicas.size()).asEndpoints()); cfs.metric.speculativeRetries.inc(); } Same thing with these two, can you avoid creating the extra intermediate list.

Target:
public void executeAsync() { Replicas.checkFull(targetReplicas); makeDataRequests(targetReplicas.subList(0, targetReplicas.size() > 1 ? 2 : 1)); if (targetReplicas.size() > 2) makeDigestRequests(targetReplicas.subList(2, targetReplicas.size())); cfs.metric.speculativeRetries.inc(); }
Source:
public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs) { if (timeoutSecs < 0) START logger.warn("skipping block-for-peers due to negative timeout. You may encounter errors or timeouts on" + END " the first user query"); if (timeoutSecs > 100) logger.warn("setting the block-for-peers timeout (in seconds) to might be a bit excessive, but using it nonetheless", timeoutSecs); long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs); return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs); } Should this be a warning? They have pretty clearly asked for it?

Target:
public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs) { if (timeoutSecs > 100) logger.warn("setting the block-for-peers timeout (in seconds) to might be a bit excessive, but using it nonetheless", timeoutSecs); long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs); return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs); }
Source:
private static String readFile(File file) throws IOException { Reader in = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); char[] chars = new char[1 << 16]; int length; while ((length = in.read(chars)) > 0) sb.append(chars, 0, length); START in.close(); END return sb.toString(); } We should probably do this in a finally block.

Target:
private static String readFile(File file) throws IOException { Reader in = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); char[] chars = new char[1 << 16]; int length; try { while ((length = in.read(chars)) > 0) sb.append(chars, 0, length); } finally { in.close(); } return sb.toString(); }
Source:
START @NotNull private Cache makeCache() throws IOException { END File cacheDir = File.createTempFile("cache-", ".dir"); cacheDir.delete(); return new Cache(cacheDir, 1024 * 1024); } no `@NotNull` in OkHttp code. https://developer.squareup.com/blog/non-null-is-the-default/

Target:
private Cache makeCache() throws IOException { File cacheDir = File.createTempFile("cache-", ".dir"); cacheDir.delete(); return new Cache(cacheDir, 1024 * 1024); }
Source:
protected void attachCVterms(SqwFile file, String ontID, String commaSepTerms) { START System.err.println("Use of attachCVTerms is deprecated. Please use attachCVlabels"); END attachCVlabels(file, ontID, commaSepTerms); } This should be a call to the logger and not to System.err (throughout this class).

Target:
protected void attachCVterms(SqwFile file, String ontID, String commaSepTerms) { Log.warn("Use of attachCVTerms is deprecated. Please use attachCVlabels"); attachCVlabels(file, ontID, commaSepTerms); }
Source:
public Map<String, ?> getRawCapabilities() { DesiredCapabilities headlessChrome = DesiredCapabilities.chrome(); START headlessChrome.setBrowserName("chromeHeadless"); END return headlessChrome.asMap(); } Do we really want to set the `browserName` property to `chromeHeadless`? chromeHeadless is our internal feature - Selenium or the webdrivers doesn't know anything about it...

Target:
public Map<String, ?> getRawCapabilities() { return DesiredCapabilities.chrome().asMap(); }
Source:
public GitHubSource(String organization, String project, HttpClient httpClient, GitHubLastUpdateCache gitHubLastUpdateCache) { this.httpClient = httpClient; this.projectUrl = String.format("https://api.github.com/repos/%s/%s", organization, project); this.uniqueKey = organization + "@" + project; START this.gson = new Gson(); // TODO think if that should be really a field END this.cache = gitHubLastUpdateCache; } > TODO think if that should be really a field Yeah, I was asking myself the same thing. But technically, there should be nothing wrong with it. But some investigation would be good - if multiple creations of new instances of Gson has some performance impact or not... Another question is if Gson instance itself is anyhow changed when the method `fromJson` is called.

Target:
public GitHubSource(String organization, String project, HttpClient httpClient, GitHubLastUpdateCache gitHubLastUpdateCache) { this.httpClient = httpClient; this.projectUrl = String.format("https://api.github.com/repos/%s/%s", organization, project); this.uniqueKey = organization + "@" + project; this.cache = gitHubLastUpdateCache; }
Source:
private void cleanUpStreams() { START System.setOut(null); END } I think that this is not a clear way to reset values to default - I think, that there should be something like: `System.setOut(System.out);`

Target:
private void cleanUpStreams() { System.setOut(System.out); }
Source:
private void checkCompletedSubgoals(State state) { int len = this.recipeSubgoals.size(); for (int i = 0; i < len; i++) { START if (this.recipeSubgoals.get(i).goalCompleted(state)) { END this.completedSubgoals[i] = true; } } } instead of if, you could just do this.completedSubgoals[i] |= this.recipeSubgoals.get(i).goalCompleted(state);

Target:
private void checkCompletedSubgoals(State state) { int len = this.recipeSubgoals.size(); for (int i = 0; i < len; i++) { this.completedSubgoals[i] |= this.recipeSubgoals.get(i).goalCompleted(state); } }
Source:
public AllowUsingTool(String name, Domain domain, IngredientRecipe ingredient) { super(name, domain, new String[] {AgentFactory.ClassName, ToolFactory.ClassName, ContainerFactory.ClassName} ,ingredient); START this.recipe = null; END } Don't need to set objects explicitly to null.

Target:
public AllowUsingTool(String name, Domain domain, IngredientRecipe ingredient) { super(name, domain, new String[] {AgentFactory.ClassName, ToolFactory.ClassName, ContainerFactory.ClassName} ,ingredient); }
Source:
public void onStart(@NonNull LifecycleOwner owner) { isAppVisible = true; START android.util.Log.i(TAG, "App is now visible."); END executePendingContactSync(); } why util?

Target:
public void onStart(@NonNull LifecycleOwner owner) { isAppVisible = true; Log.i(TAG, "App is now visible."); executePendingContactSync(); }
Source:
public void onStop(@NonNull LifecycleOwner owner) { isAppVisible = false; START android.util.Log.i(TAG, "App is no longer visible."); END } why util?

Target:
public void onStop(@NonNull LifecycleOwner owner) { isAppVisible = false; Log.i(TAG, "App is no longer visible."); }
Source:
protected final void onSend(MasterSecret masterSecret) throws Exception { if (TextSecurePreferences.getSignedPreKeyFailureCount(context) > 5) { ApplicationContext.getInstance(context) .getJobManager() .add(new RotateSignedPreKeyJob(context)); throw new TextSecureExpiredException("Too many signed prekey rotation failures"); } try { onPushSend(); TextSecurePreferences.setNeedsOutageCheck(context, false); START } catch (Exception e) { END TextSecurePreferences.setNeedsOutageCheck(context, true); throw e; } } In general, please try to avoid catching and rethrowing unwrapped exceptions. You can set this value in onCancelled() rather than catching anything here.

Target:
protected final void onSend(MasterSecret masterSecret) throws Exception { if (TextSecurePreferences.getSignedPreKeyFailureCount(context) > 5) { ApplicationContext.getInstance(context) .getJobManager() .add(new RotateSignedPreKeyJob(context)); throw new TextSecureExpiredException("Too many signed prekey rotation failures"); } onPushSend(); }
Source:
private static File getPlaintextExportFile() throws NoExternalStorageException { File backup = PlaintextBackupExporter.getPlaintextExportFile(); File oldBackup = new File(Environment.getExternalStorageDirectory(), "TextSecurePlaintextBackup.xml"); START if (!backup.exists() && oldBackup.exists()) { END return oldBackup; } return backup; } From here to the end of this method, IMO, could be rewritten as: ```java return !backup.exists() && oldBackup.exists() ? oldBackup : backup ; ```

Target:
private static File getPlaintextExportFile() throws NoExternalStorageException { File backup = PlaintextBackupExporter.getPlaintextExportFile(); File oldBackup = new File(Environment.getExternalStorageDirectory(), "TextSecurePlaintextBackup.xml"); return !backup.exists() && oldBackup.exists() ? oldBackup : backup; }
Source:
public static File getSignalStorageDir() throws NoExternalStorageException { final File storage = Environment.getExternalStorageDirectory(); START if (!storage.canWrite()) END throw new NoExternalStorageException(); return storage; } braces please

Target:
private static File getSignalStorageDir() throws NoExternalStorageException { final File storage = Environment.getExternalStorageDirectory(); if (!storage.canWrite()) { throw new NoExternalStorageException(); } return storage; }
Source:
int getWidthAdjustment() { int width = recordButtonFab.getWidth() / 4; return ViewCompat.getLayoutDirection(recordButtonFab) == LAYOUT_DIRECTION_LTR ? -width : width; START } END can these be private?

Target:
private int getWidthAdjustment() { int width = recordButtonFab.getWidth() / 4; return ViewCompat.getLayoutDirection(recordButtonFab) == ViewCompat.LAYOUT_DIRECTION_LTR ? -width : width; }
Source:
public static void setRegistered(Context context, boolean registered) { setBooleanPreference(context, REGISTERED_PREF, registered); if (isGooglePlayServicesAvailable(context)) { setPushRegistered(context, registered); START } END } No side effects please

Target:
public static void setRegistered(Context context, boolean registered) { setBooleanPreference(context, REGISTERED_PREF, registered); }
Source:
START public void setLed() { END String ledColor = TextSecurePreferences.getNotificationLedColor(context); String ledBlinkPattern = TextSecurePreferences.getNotificationLedPattern(context); String ledBlinkPatternCustom = TextSecurePreferences.getNotificationLedPatternCustom(context); if (!ledColor.equals("none")) { String[] blinkPatternArray = parseBlinkPattern(ledBlinkPattern, ledBlinkPatternCustom); setLights(Color.parseColor(ledColor), Integer.parseInt(blinkPatternArray[0]), Integer.parseInt(blinkPatternArray[1])); } } why is this public?

Target:
private void setLed() { String ledColor = TextSecurePreferences.getNotificationLedColor(context); String ledBlinkPattern = TextSecurePreferences.getNotificationLedPattern(context); String ledBlinkPatternCustom = TextSecurePreferences.getNotificationLedPatternCustom(context); if (!ledColor.equals("none")) { String[] blinkPatternArray = parseBlinkPattern(ledBlinkPattern, ledBlinkPatternCustom); setLights(Color.parseColor(ledColor), Integer.parseInt(blinkPatternArray[0]), Integer.parseInt(blinkPatternArray[1])); } }
Source:
protected void onResume() { START dynamicTheme.onCreate(this); END super.onResume(); } I haven't actually tested the code... but: 1. should use `onResume` here? 2. in `RegistrationActivity` there is no call to `dynamicTheme.onResume`

Target:
protected void onResume() { dynamicTheme.onResume(this); super.onResume(); }