auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Api getSiteApi() { START return getAPIForSite(new Site("authmanager.wmflabs.org")); END //return getAPIForSite(getSite()); } Consider reverting this since it's no longer a WIP patch.

Target:
public Api getSiteApi() { return new Api("authmanager.wmflabs.org", false); //return getAPIForSite(getSite()); }
Source:
START public void writeToParcel(Parcel parcel, int i) { END parcel.writeParcelable(amCreateAccountResult, 0); parcel.writeParcelable(legacyCreateAccountResult, 0); } I think this second parameter is meant to be flags and should be passed to the parcel.writeParcelable calls.

Target:
public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(amCreateAccountResult, i); parcel.writeParcelable(legacyCreateAccountResult, i); }
Source:
public void doCreateAccount() { new AMCreateAccountInfoTask() { @Override public void onCatch(Throwable caught) { START L.e("AMCreateAccountInfoTask failed: " + caught.getMessage()); END } @Override public void onFinish(AMCreateAccountInfoResult result) { if (result.getEnabled()) { L.i("Creating account with AuthManager"); captchaHandler.handleCaptcha(new CaptchaResult(result.getCaptchaId()), true); } else { L.i("Creating account with legacy API"); doLegacyCreateAccount(); } } }.execute(); } Same nit about L.e(caught)

Target:
public void doCreateAccount() { new AMCreateAccountInfoTask() { @Override public void onCatch(Throwable caught) { L.e(caught); } @Override public void onFinish(AMCreateAccountInfoResult result) { if (result.getEnabled()) { L.i("Creating account with AuthManager"); captchaHandler.handleCaptcha(new CaptchaResult(result.getCaptchaId()), true); } else { L.i("Creating account with legacy API"); doLegacyCreateAccount(); } } }.execute(); }
Source:
private void init() { inflate(); bind(); START FeedbackUtil.setToolbarButtonLongPressToast(bookmark); END FeedbackUtil.setToolbarButtonLongPressToast(navigate); FeedbackUtil.setToolbarButtonLongPressToast(share); } This is great! It it worth having a FeedbackUtil.setToolbarButtonLongPressToast() variable arity overload?

Target:
private void init() { inflate(); bind(); FeedbackUtil.setToolbarButtonLongPressToast(bookmark, navigate, share); }
Source:
public void setSaveOffline(boolean saved) { if (pages.isEmpty()) { START emptyListSavePagesState = saved; END return; } for (ReadingListPage page : pages) { page.savedOrSaving(saved); ReadingListPageDao.instance().upsert(page); } } I think this can unconditionally be set to saved. (Conditionals are hazardous.) Note: this information is not preserved in the database and will be lost on app restart.

Target:
public void setSaveOffline(boolean saved) { emptyListSavePagesState = saved; for (ReadingListPage page : pages) { page.savedOrSaving(saved); } }
Source:
public boolean getSaveOffline() { START if (pages.size() == 0) { END return emptyListSavePagesState; } for (ReadingListPage page : pages) { if (!page.savedOrSaving()) { return false; } } return true; } isEmpty()

Target:
public boolean getSaveOffline() { if (pages.isEmpty()) { return emptyListSavePagesState; } for (ReadingListPage page : pages) { if (!page.savedOrSaving()) { return false; } } return true; }
Source:
public ReadingListPageDiskRow(@NonNull ReadingListPage row) { super(row.key(), row); START filename = null; END } It looks filename is derived from page title. Have you considered just calling the new constructor like this(row, filenameAlgorithm(row.title)

Target:
public ReadingListPageDiskRow(@NonNull ReadingListPage row) { super(row.key(), row, null); }
Source:
public <T extends Card> void removeCards(Class<T> type, List<Card> items) { Iterator<Card> iterator = items.iterator(); while (iterator.hasNext()) { Card card = iterator.next(); if (type.isInstance(card)) { START items.remove(card); END } } } Sorry, I wrote this wrong earlier. I think you want iterator.remove() to avoid a ConcurrentModificationException.

Target:
public <T extends Card> void removeCards(Class<T> type, List<Card> items) { Iterator<Card> iterator = items.iterator(); while (iterator.hasNext()) { Card card = iterator.next(); if (type.isInstance(card)) { iterator.remove(); } } }
Source:
public void request(@NonNull Context context, int age, final FeedCoordinator.FeedClientCallback cb) { START cb.success(this, new IntegerListCard()); END } This is a nice test! Now we know it's safe for clients to cache and return results immediately.

Target:
public void request(@NonNull Context context, int age, final FeedCoordinator.FeedClientCallback cb) { cb.success(new IntegerListCard()); }
Source:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ (mobileview) or ./ (parsoid) from the href START return new PageTitle(RbSwitch.INSTANCE.isRestBaseEnabled() END ? internalLink.replaceFirst("./", "") : internalLink.replaceFirst("/wiki/", ""), this); } Can we do both replacements unconditionally? I'm worried about pages cached with one service while the other is actually enabled.

Target:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ (mobileview) or ./ (parsoid) from the href return new PageTitle(internalLink.replaceFirst("./", "").replaceFirst("/wiki/", ""), this); }
Source:
@NonNull public ListCardItemView setSubtitle(@Nullable CharSequence subtitle) { START subtitleView.setText(subtitle); END return this; } Wouldn't this mean that we're calling the base method of TextView.setText() and bypassing the overridden method in GoneIfEmptyTextView? (it appears that way in testing.)

Target:
@NonNull public ListCardItemView setSubtitle(@Nullable CharSequence subtitle) { subtitleView.setText((String) subtitle); return this; }
Source:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); START if (getMainActivity().pageLoadCallbacks() != null) { END getMainActivity().pageLoadCallbacks().onLoadComplete(); } } It might be good to check that getMainActivity() itself doesn't return null as well since this method appears to complete asynchronously?

Target:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getMainActivity() != null && getMainActivity().pageLoadCallbacks() != null) { getMainActivity().pageLoadCallbacks().onLoadComplete(); } }
Source:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if START (getActivity() END != null && getPageLoadCallbacks() != null) { getPageLoadCallbacks().onLoadComplete(); } } Should this just be getPageLoadCallbacks() != null?

Target:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getPageLoadCallbacks() != null) { getPageLoadCallbacks().onLoadComplete(); } }
Source:
START public static boolean isTabListEmpty() { END List<Tab> tabs = getTabs(); return !tabs.isEmpty() && !tabs.get(0).getBackStack().isEmpty(); } The code does the right thing but the name of this method is misleading. It's the opposite of what it name implies.

Target:
public static boolean isTabListEmpty() { List<Tab> tabs = getTabs(); return tabs.isEmpty() || (tabs.size() == 1 && tabs.get(0).getBackStack().isEmpty()); }
Source:
public void START onCreateOptionsMenu(Menu END menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); viewPager.post(new Runnable() { @Override public void run() { setUpOverflowButton(); } }); } Missed this earlier. Should we call the super here and in onOptionsItemSelected?

Target:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_main, menu); viewPager.post(new Runnable() { @Override public void run() { setUpOverflowButton(); } }); }
Source:
public void onSearchOpen() { Callback callback = callback(); if (callback != null) { START callback.getActivityToolbar().setVisibility(View.GONE); END } } Here and elsewhere, the Fragment probably shouldn't force the host to do things by getting its internals and changing them. The dependency on a toolbar is clear because of the callback pattern but exposing the toolbar directly allows any Fragment to change it. It's ok to defer but consider pushing onSearchOpen() into the host and allow it to hide / show the toolbar.

Target:
public void onSearchOpen() { Callback callback = callback(); if (callback != null) { callback.onSearchOpen(); } }
Source:
public void setScrollView(@Nullable ObservableWebView webView) { START webview = END webView; if (webview != null) { webview.addOnScrollChangeListener(this); webview.addOnDownMotionEventListener(this); webview.addOnUpOrCancelMotionEventListener(this); webview.addOnClickListener(this); } } We probably should clear previously set listeners.

Target:
public void setScrollView(@Nullable ObservableWebView webView) { this.webView = webView; if (webView != null) { webView.addOnScrollChangeListener(this); webView.addOnDownMotionEventListener(this); webView.addOnUpOrCancelMotionEventListener(this); webView.addOnClickListener(this); } }
Source:
private static OutputWrapper connectMySql(String param) throws IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql:" + param); return new OutputWrapper(conn); } catch (Exception e) { //e.printStackTrace(); START throw (IOException)new IOException(e.getMessage()).initCause(e); END } } throw new IOException(e)

Target:
private static OutputWrapper connectMySql(String param) throws IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql:" + param); return new OutputWrapper(conn); } catch (Exception e) { throw new IOException(e); } }
Source:
private static OutputWrapper connectPostgres(String param) throws IOException { try { Class.forName("org.postgresql.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:postgresql:" + param); return new OutputWrapper(conn); } catch (Exception e) { START throw new IOException(e.toString()); END } } throw new IOException(e)

Target:
private static OutputWrapper connectPostgres(String param) throws IOException { try { Class.forName("org.postgresql.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:postgresql:" + param); return new OutputWrapper(conn); } catch (Exception e) { throw new IOException(e); } }
Source:
START @OnClick(R.id.reading_list_detail_back_button) protected void onBackPressed(View v) { END if (actionListener != null) { actionListener.onBackPressed(); } } Any reason not to use package protected? protected means subclasses could override this method which doesn't seem otherwise supported by this class.

Target:
@OnClick(R.id.reading_list_detail_back_button) void onBackPressed(View v) { if (actionListener != null) { actionListener.onBackPressed(); } }
Source:
public final <T> TypeAdapter<T> create(@NonNull Gson gson, @NonNull TypeToken<T> typeToken) { Class<?> rawType = typeToken.getRawType(); Set<Field> requiredFields = collectRequiredFields(rawType); if (!requiredFields.isEmpty()) { setFieldsAccessible(requiredFields, true); return new Adapter<>(gson.getAdapter(JsonElement.class), gson.getDelegateAdapter(this, typeToken), requiredFields); } START return null; END } Feel free to ignore: I would handle the null case first because it feels special whereas the nonempty case is generic: if (requiredFields.isEmpty()) { return null } setFieldsAccessible(requiredFields, true); return new Adapter<>(gson.getAdapter(JsonElement.class), gson.getDelegateAdapter(this, typeToken), requiredFields);

Target:
public final <T> TypeAdapter<T> create(@NonNull Gson gson, @NonNull TypeToken<T> typeToken) { Class<?> rawType = typeToken.getRawType(); Set<Field> requiredFields = collectRequiredFields(rawType); if (requiredFields.isEmpty()) { return null; } setFieldsAccessible(requiredFields, true); return new Adapter<>(gson.getDelegateAdapter(this, typeToken), requiredFields); }
Source:
@Override @Nullable public T read(JsonReader in) throws IOException { START JsonElement tree = adapter.read(in); T deserialized = delegate.fromJsonTree(tree); END return allRequiredFieldsPresent(deserialized, requiredFields) ? deserialized : null; } Should this be delegate.read(in)? I'm not sure what it means to get an adapter for JsonElement.class. If we keep the current implementation, does write need to be updated to use adapter.write?

Target:
@Override @Nullable public T read(JsonReader in) throws IOException { T deserialized = delegate.read(in); return allRequiredFieldsPresent(deserialized, requiredFields) ? deserialized : null; }
Source:
public void cancel(@Nullable Call<?> call) { if (call == null) { return; } call.cancel(); START call = null; END } Why set a reference copy to null?

Target:
public void cancel(@Nullable Call<?> call) { if (call == null) { return; } call.cancel(); }
Source:
private void saveState(Bundle outState) { outState.putBoolean("pausedZeroEnabledState", isZeroEnabled); START outState.putString("pausedZeroConfig", GsonMarshaller.marshal(currentZeroConfig)); END outState.putBoolean("isSearching", isSearching()); outState.putString(LANGUAGE_CODE_BUNDLE_KEY, app.getAppOrSystemLanguageCode()); } Does this mean your type adapter needs to support write?

Target:
private void saveState(Bundle outState) { outState.putBoolean("isSearching", isSearching()); outState.putString(LANGUAGE_CODE_BUNDLE_KEY, app.getAppOrSystemLanguageCode()); }
Source:
private NearbyPage constructNearbyPage(@NonNull String title, double lat, double lon) { Location location = new START Location(title); END location.setLatitude(lat); location.setLongitude(lon); return new NearbyPage(location); } Although the typing is permissive, I think this is supposed to be a location provider like GPS or network

Target:
private NearbyPage constructNearbyPage(@NonNull String title, double lat, double lon) { Location location = new Location(""); location.setLatitude(lat); location.setLongitude(lon); return new NearbyPage(title, location); }
Source:
private void assertCallbackSuccess(@NonNull Call<DescriptionEdit> call, @NonNull Callback cb) { verify(cb).success(eq(call)); //noinspection unchecked verify(cb, START never()).failure(eq(call), END any(Throwable.class)); } This should probably be any() since we really never want this invoked under any argument.

Target:
private void assertCallbackSuccess(@NonNull Call<DescriptionEdit> call, @NonNull Callback cb) { verify(cb).success(eq(call)); //noinspection unchecked verify(cb, never()).failure(any(Call.class), any(Throwable.class)); }
Source:
public void onResponse(@NonNull Call<ZeroConfig> call, @NonNull Response<ZeroConfig> response) { if (response.isSuccessful()) { if (response.body() == null) { START cb.failure(call, new JsonParseException("Response missing required field(s)")); END } cb.success(call, response.body()); } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } I think you should return or else case the success.

Target:
public void onResponse(@NonNull Call<ZeroConfig> call, @NonNull Response<ZeroConfig> response) { if (response.isSuccessful()) { if (response.body() == null) { cb.failure(call, new JsonParseException("Response missing required field(s)")); return; } cb.success(call, response.body()); } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } }
Source:
public View newView(Context context, Cursor cursor, ViewGroup parent) { START return ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) END .inflate(android.R.layout.simple_list_item_1, parent, false); } There's a billion of these LayoutInflater methods but I think LayoutInflater.from(context) is the best for this circumstance.

Target:
public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context) .inflate(android.R.layout.simple_list_item_1, parent, false); }
Source:
@Override protected DescriptionEditSuccessFragment createFragment() { DescriptionEditSuccessFragment fragment = DescriptionEditSuccessFragment.newInstance(); START fragment.setCallback(this); END return fragment; } The Fragment should obtain the host by calling FragmentUtil.getCallback(). I think if the Activity is ratained in a Fragment instance, it'll cause a memory leak.

Target:
@Override protected DescriptionEditSuccessFragment createFragment() { return DescriptionEditSuccessFragment.newInstance(); }
Source:
@Theory public void testWidth(@TestedOn(ints = {WIDTH_DP_XL, WIDTH_DP_L}) int widthDp, @NonNull FontScale fontScale) { setUp(widthDp, LayoutDirection.LOCALE, fontScale, Theme.LIGHT); subject = new DescriptionEditSuccessView(ctx()); START snap(subject); END } You're calling snap but I think you forgot to add the screenshots to this patch.

Target:
@Theory public void testWidth(@TestedOn(ints = {WIDTH_DP_XL, WIDTH_DP_L}) int widthDp, @NonNull FontScale fontScale) { setUp(widthDp, LayoutDirection.LOCALE, fontScale, Theme.LIGHT); snap(subject); }
Source:
@NonNull START @Override public END CardType type() { return CardType.ANNOUNCEMENT; } I guess we're not consistent across the codebase on whether method annotations should be on the same line as the method signature or on their own line(s). Let's pick one or the other and stick to it on at least a per-class basis, though.

Target:
public CardType type() { return CardType.ANNOUNCEMENT; }
Source:
public AnnouncementCardView(Context context) { super(context); START inflate(getContext(), R.layout.view_card_announcement, END this); ButterKnife.bind(this); } How about just context since we have it?

Target:
public AnnouncementCardView(Context context) { super(context); inflate(context, R.layout.view_card_announcement, this); ButterKnife.bind(this); }
Source:
private String getShareSubject() { if (getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE)) { return ShareUtil.getFeaturedImageShareSubject(getContext(), new UtcDate(age).baseCalendar()); } START else END if (pageTitle != null) { return pageTitle.getDisplayText(); } return null; } Unnecessary else :]

Target:
private String getShareSubject() { return getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE) ? ShareUtil.getFeaturedImageShareSubject(getContext(), age) : null; }
Source:
protected void checkArgType(ObjectInspector[] arguments, int i, PrimitiveCategory type) throws UDFArgumentTypeException{ PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arguments[i]).getPrimitiveCategory(); if (primitiveCategory != type) { throw new START UDFArgumentTypeException(0, END "A " + type.getClass().getSimpleName() + " argument was expected for " + getFuncName() + " but an argument of type " + arguments[i].getTypeName() + " was given." ); } } i? but 0 was used previously... not sure if it's an existing bug or if it was set like that on purpose.

Target:
protected void checkArgType(ObjectInspector[] arguments, int i, PrimitiveCategory type) throws UDFArgumentTypeException{ checkArgType(arguments[i], i, type); }
Source:
START @VisibleForTesting END public void putIdForLanguage(@NonNull String code, int id) { ids.put(code, id); } This doesn't seem to be @VisibleForTesting since WikipediaApp requires this method to be public and UserTest only requires package privacy

Target:
public void putIdForLanguage(@NonNull String code, int id) { ids.put(code, id); }
Source:
public int getIdForLanguage(@NonNull String code) { Integer id = ids.get(code); return START id != null ? id : 0; END } If you flip this conditional, you can use == instead of negated logic

Target:
public int getIdForLanguage(@NonNull String code) { Integer id = ids.get(code); return id == null ? 0 : id; }
Source:
public static START HashMap<String, END Integer> getLoginUserIds() { TypeToken<HashMap<String, Integer>> type = new TypeToken<HashMap<String, Integer>>(){}; return GsonUnmarshaller.unmarshal(type, getString(R.string.preference_key_login_user_id_map, "{}")); } Can this return a Map instead of a HashMap implementation?

Target:
public static Map<String, Integer> getLoginUserIds() { TypeToken<HashMap<String, Integer>> type = new TypeToken<HashMap<String, Integer>>(){}; return GsonUnmarshaller.unmarshal(type, getString(R.string.preference_key_login_user_id_map, "{}")); }
Source:
public void notifyItemChanged(@NonNull Card card) { START notifyItemChanged(feedAdapter.getItemPosition(card)); END } I'm sorry if I missed this earlier but the null check of feedAdapter in the int overload of this method suggests a similar null check is necessary here. Also consider checking the return value of getItemPosition() in case it's not present in the adapter

Target:
public void notifyItemChanged(@NonNull Card card) { if (feedAdapter != null && feedAdapter.getItemPosition(card) > -1) { notifyItemChanged(feedAdapter.getItemPosition(card)); } }
Source:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int pos) { if (holder instanceof ReadingListPageItemHolder) { ((ReadingListPageItemHolder) START holder).bindItem(readingList.getPages().get(pos)); END } } I believe this will be flagged as a potential NPE by Android Studio. It makes sense that this will never happen so I recommend adding a readingList != null to the conditional, suppressing the warning, or throwing an IllegalStateException if null to show that the author was considering this case and only true warnings are flagged by Android Studio.

Target:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int pos) { if (readingList != null && holder instanceof ReadingListPageItemHolder) { ((ReadingListPageItemHolder) holder).bindItem(readingList.getPages().get(pos)); } }
Source:
private ErrorType getErrorType(@NonNull Context context, @Nullable Throwable caught) { if (caught != null && !is404(context, caught)) { if (context instanceof PageActivity) { return ErrorType.PAGE_OFFLINE; } START else { END return ErrorType.OFFLINE; } } return ErrorType.GENERIC; } Needless else :]

Target:
private ErrorType getErrorType(@NonNull Context context, @Nullable Throwable caught) { if (caught != null && !is404(context, caught)) { if (context instanceof PageActivity) { return ErrorType.PAGE_OFFLINE; } return ErrorType.OFFLINE; } return ErrorType.GENERIC; }
Source:
public RecentChangesPoller(WikibaseRepository wikibase, Date firstStartTime, int batchSize, Map<Long, Boolean> seenIDs, int tailSeconds) { this.wikibase = wikibase; START this.firstStartTime = firstStartTime != null ? new Date(firstStartTime.getTime()) : null; END this.batchSize = batchSize; this.seenIDs = seenIDs; this.tailSeconds = tailSeconds; } same here about dates - maybe better to move to immutable ones?

Target:
public RecentChangesPoller(WikibaseRepository wikibase, Date firstStartTime, int batchSize, Map<Long, Boolean> seenIDs, int tailSeconds) { this.wikibase = wikibase; this.firstStartTime = firstStartTime; this.batchSize = batchSize; this.seenIDs = seenIDs; this.tailSeconds = tailSeconds; }
Source:
@Override protected void buildScript(int age) { if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } // OfflineClient must always come last, since we rely on the last request in the series // being a network request (and not a disk I/O request) to determine online/offline state // for purposes of updating the feed UI. START addPendingClient(new OfflineClient()); END } FWIW, I believe we can observe (be notified and respond to) changes to airplane mode and connectivity state (basically anything you see in your system status bar connectivity icon): https://developer.android.com/reference/android/net/NetworkInfo.DetailedState.html You can also track network successes and failures in the existing Interceptor for RESTBase switching and then rebroadcast those as OFFLINE / ONLINE events on our event bus. Since global network health seems to be what we're after but we still want to avoid mingling responsibilities, intercepting requests might be the way go.

Target:
protected void buildScript(int age) { if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } }
Source:
@Override public void error(@NonNull Throwable caught) { START if (caught instanceof OfflineClient.OfflineException) { appendCard(new OfflineCard()); } END //noinspection ConstantConditions requestNextCard(wiki); } This looks good and will cover us for all usage of the feed.

Target:
@Override public void error(@NonNull Throwable caught) { //noinspection ConstantConditions requestNextCard(wiki); }
Source:
public Call<MwQueryResponse<QueryResult>> request(@NonNull WikiSite wiki, @NonNull PageTitle title, @NonNull Callback cb) { START List<PageTitle> titles = new ArrayList<>(); titles.add(title); END return request(wiki, cachedService.service(wiki), titles, cb); } It looks like this client is only ever used for a single title, which is being shared as an image. Let's skip converting to a List and just pass the PageTitle straight though. You can just call service.request(title.toString()) below rather than TextUtils.join as well. (The PageTitle class overrides toString() to return the namespace-prefixed title string.)

Target:
public Call<MwQueryResponse<QueryResult>> request(@NonNull WikiSite wiki, @NonNull PageTitle title, @NonNull Callback cb) { return request(wiki, cachedService.service(wiki), title, cb); }
Source:
public Model checkSyntax(InputStream dataset, String baseURI, RDFFormat format) { Model parsed = null; try { parsed = Rio.parse(dataset, baseURI, format); } catch (IOException ioe) { log.error("Couldn't read your dataset: {}", ioe.getMessage()); System.exit(1); } catch (RDFParseException rpe) { log.error("Your dataset is not valid RDF. Please fix it: {}", rpe.getMessage()); System.exit(1); START return null; END } return parsed; } Not much use to return null after exit :)

Target:
public Model checkSyntax(InputStream dataset, String baseURI, RDFFormat format) throws IOException, RDFParseException { return Rio.parse(dataset, baseURI, format); }
Source:
@Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { actionMode = mode; START mode.setTag(getTag()); END mode.getMenuInflater().inflate(R.menu.menu_action_mode_reading_list, menu); return true; } I think this can be a bit cleaner by calling super.onCreateActionMode(), and not exposing getTag(), and then proceed to inflate the menu. (and remove the default inflating of the menu in super()). Or better yet, create an abstract method that asks for the resource-id of the menu to inflate.

Target:
@Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { super.onCreateActionMode(mode, menu); mode.getMenuInflater().inflate(R.menu.menu_action_mode_reading_list, menu); actionMode = mode; return true; }
Source:
public void testBadSyntax() throws Exception { InputStream badRDF = openTestDatasetStream(BAD_RDF_FILE_NAME); validator.checkSyntax(badRDF, BASE_URI, RDF_FORMAT); START badRDF.close(); END } close() should be in a finally block, or use try-with-resource

Target:
public void testBadSyntax() throws Exception { try (InputStream badRDF = openTestDatasetStream(BAD_RDF_FILE_NAME)) { validator.checkSyntax(badRDF, BASE_URI, RDF_FORMAT); } }
Source:
START @Override public END void onDestroyView() { recyclerView.setAdapter(null); unbinder.unbind(); unbinder = null; super.onDestroyView(); } Needs a line break for consistency

Target:
public void onDestroyView() { recyclerView.setAdapter(null); unbinder.unbind(); unbinder = null; super.onDestroyView(); }
Source:
public InterruptibleCharSequence(CharSequence inner) { START super(); END this.inner = inner; } Call to `super()` is implicit and not required.

Target:
public InterruptibleCharSequence(CharSequence inner) { this.inner = inner; }
Source:
static <C extends Condition, CPS extends AbstractConditionParserState<C>> C parseCondition( ObjectParser<CPS, QueryParseContext> condParser, XContentParser parser, QueryParseContext parseContext ) throws IOException { CPS state = condParser.parse(parser, parseContext); String error = START state.checkValid(); END if (error != null) { throw new ParsingException(parser.getTokenLocation(), error); } return state.condition(); } nitpick: I'd throw IllegalArgumentException directly from there. note that IAExc will be catched by the toplevel parse function (fromXContent) and the token location will be added from there.

Target:
static <C extends Condition, CPS extends AbstractConditionParserState<C>> C parseCondition( ObjectParser<CPS, QueryParseContext> condParser, XContentParser parser, QueryParseContext parseContext ) throws IOException { CPS state = condParser.parse(parser, parseContext); state.checkValid(); return state.condition(); }
Source:
double START getMillisAtPercentile(double END percentile) { return current.getValueAtPercentile(percentile) / TimeValue.NSEC_PER_MSEC; } `current` Histogram isn't threadsafe on its own, so synchronization is needed here.

Target:
synchronized double getMillisAtPercentile(double percentile) { return current.getValueAtPercentile(percentile) / TimeValue.NSEC_PER_MSEC; }
Source:
RollingHistogram(int size) { current = new Histogram(LOWEST_DISCERNABLE_VALUE.nanos(), HIGHEST_TRACKABLE_VALUE.nanos(), SIGNIFICANT_DIGITS); list = new ArrayList<>(); recorder = new Recorder(LOWEST_DISCERNABLE_VALUE.nanos(), HIGHEST_TRACKABLE_VALUE.nanos(), SIGNIFICANT_DIGITS); START this.size = size; END } maybe assert size > 0, rotate will fail if size is 0?

Target:
RollingHistogram(int size) { current = new Histogram(LOWEST_DISCERNABLE_VALUE.nanos(), HIGHEST_TRACKABLE_VALUE.nanos(), SIGNIFICANT_DIGITS); list = new ArrayList<>(); recorder = new Recorder(LOWEST_DISCERNABLE_VALUE.nanos(), HIGHEST_TRACKABLE_VALUE.nanos(), SIGNIFICANT_DIGITS); assert size > 0; this.size = size; }
Source:
public WikibaseUris(String host) { root = "http://" + host; START String rootHttps = "https://" + host; END entityData = root + "/wiki/Special:EntityData/"; entityDataHttps = rootHttps + "/wiki/Special:EntityData/"; entity = root + "/entity/"; statement = entity + "statement/"; value = root + "/value/"; reference = root + "/reference/"; prop = root + "/prop/"; } Not a big fan of this. If we have root as property, rootHttps should be similar. Otherwise it looks weird, even if technical use differs.

Target:
public WikibaseUris(String host) { root = "http://" + host; rootHttps = "https://" + host; entityData = root + "/wiki/Special:EntityData/"; entityDataHttps = rootHttps + "/wiki/Special:EntityData/"; entity = root + "/entity/"; statement = entity + "statement/"; value = root + "/value/"; reference = root + "/reference/"; prop = root + "/prop/"; }
Source:
public SimSwitcherQuery(Similarity similarity, Query subQuery) { this.similarity = START Objects.requireNonNull(similarity); END this.subQuery = Objects.requireNonNull(subQuery); } static import ?

Target:
public SimSwitcherQuery(Similarity similarity, Query subQuery) { this.similarity = requireNonNull(similarity); this.subQuery = requireNonNull(subQuery); }
Source:
public void onBackPressed() { if (getFragment().onBackPressed()) { return; } START WikipediaApp.getInstance().getApplicationContext().startService(AnalyticsIntentService.getIntent(EventLoggingConfig.EXIT_PUSH)); END finish(); } A couple notes: - getApplicationContext() returns the same thing as the actual getInstance() call. - Doing this inside onBackPressed() seems counter-intuitive. It's within the realm of possibility for a user to never press the Back button to leave the app (e.g. always pressing the Home button). Why not do this in onDestroy()?

Target:
public void onBackPressed() { if (getFragment().onBackPressed()) { return; } finish(); }
Source:
public void setUserVisibleHint(boolean visible) { super.setUserVisibleHint(visible); if (!isAdded()) { return; } if (visible) { funnel.enter(); START feedAdapter.notifyDataSetChanged(); END } else { funnel.exit(); } } Since we're now using bus events, do we need this anymore? (The whole idea was to send events to individual cards, and avoid having to rebuild the whole view hierarchy of the RecyclerView.)

Target:
public void setUserVisibleHint(boolean visible) { super.setUserVisibleHint(visible); if (!isAdded()) { return; } if (visible) { funnel.enter(); } else { funnel.exit(); } }
Source:
public static START Change.Source<? extends Change.Batch> buildKafkaPoller( END String kafkaServers, Collection<String> clusterNames, Uris uris, int batchSize, Date startTime) { Map<String, Class<? extends ChangeEvent>> topicsToClass = clusterNamesAwareTopics(clusterNames); ImmutableSet<String> topics = ImmutableSet.copyOf(topicsToClass.keySet()); return new KafkaPoller(buildKafkaConsumer(kafkaServers, topicsToClass, batchSize), uris, startTime, batchSize, topics); } `buildKafkaPoller()` should return type `KafkaPoller` and not `Change.Source<? extends Change.Batch>` (minor simplification).

Target:
public static KafkaPoller buildKafkaPoller( String kafkaServers, Collection<String> clusterNames, Uris uris, int batchSize, Date startTime) { Map<String, Class<? extends ChangeEvent>> topicsToClass = clusterNamesAwareTopics(clusterNames); ImmutableSet<String> topics = ImmutableSet.copyOf(topicsToClass.keySet()); return new KafkaPoller(buildKafkaConsumer(kafkaServers, topicsToClass, batchSize), uris, startTime, batchSize, topics); }
Source:
public PreferenceMultiLine(Context ctx, AttributeSet attrs) { START this(ctx, END attrs, 0); } Ideally we should call super() in all cases, and put your setLayoutResource() call inside an init() method which is called from all constructors.

Target:
public PreferenceMultiLine(Context ctx, AttributeSet attrs) { super(ctx, attrs); }
Source:
private PartitionInfo makePartitionInfo(String name, int id) { PartitionInfo pi = START mock(PartitionInfo.class); END when(pi.partition()).thenReturn(id); when(pi.topic()).thenReturn(name); return pi; } Do we really need to mock `PartitionInfo`? It looks like a simple DTO...

Target:
private PartitionInfo makePartitionInfo(String name, int id) { return new PartitionInfo(name, id, null, null, null); }
Source:
public void setUpTopicPartitions() { topicPartitions = topics.stream() // Get partitions .flatMap((String topic) -> consumer.partitionsFor(topic).stream()) // Create TopicPartition objects .map(p -> new TopicPartition(p.topic(), p.partition())) START .collect(ImmutableList.toImmutableList()); END } `ImmutableList.toImmutableList()` seems a bit redundant. Static import?

Target:
private ImmutableList<TopicPartition> setUpTopicPartitions() { return topics.stream() // Get partitions .flatMap((String topic) -> consumer.partitionsFor(topic).stream()) // Create TopicPartition objects .map(p -> new TopicPartition(p.topic(), p.partition())) .collect(ImmutableList.toImmutableList()); }
Source:
private int removePrefixes(char[] s, int len) { if (len > 5 && START StemmerUtil.startsWith(s, END len, "naj")) return StemmerUtil.deleteN(s, 0, len, 3); return len; } might want to use "import static" for these static methods

Target:
private int removePrefixes(char[] s, int len) { if (len > 5 && startsWith(s, len, "naj")) { return deleteN(s, 0, len, 3); } return len; }
Source:
public void onBindViewHolder(@NonNull LanguageViewHolder holder, int position) { String languageName = WikipediaApp.getInstance().getAppLanguageLocalizedName(items.get(position)); START holder.languageName.setText(String.format(getContext().getString(R.string.multilingual_onboarding_laguage_string), String.valueOf(position + 1), languageName == null ? items.get(position) : languageName)); END } This line does not need additional logic for the unsupporting languages. I've updated my patch to fix it. Please try to rebase your patch, thanks!

Target:
public void onBindViewHolder(@NonNull LanguageViewHolder holder, int position) { String languageName = WikipediaApp.getInstance().getAppLanguageLocalizedName(items.get(position)); holder.languageName.setText(String.format(getContext().getString(R.string.multilingual_onboarding_laguage_string), String.valueOf(position + 1), languageName)); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SEARCH_REQUEST_ADD_A_LANGUAGE) { if (resultCode == Activity.RESULT_OK) { int position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); setUpLanguageScroll(position); if (app.language().getAppLanguageCodes().size() == 1) { START searchResultsFragment.startSearch(query, END query != null && query.length() > 1); } } } } Any reason for not using the local `startSearch()` function here?

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SEARCH_REQUEST_ADD_A_LANGUAGE) { if (resultCode == Activity.RESULT_OK) { int position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); setUpLanguageScroll(position); if (app.language().getAppLanguageCodes().size() == 1) { startSearch(query, query != null && query.length() > 1); } } } }
Source:
public void contextInitialized(final ServletContextEvent sce) { // configuring metrics registry before calling super(), in case we have other dependencies using dropwizard // metrics (this would require some additional magic to configure those as well, but the order still make // sense START configure(METRICS_REGISTRY); END super.contextInitialized(sce); initializeServices(); } Why is this here since you do not depend on ServletContextEvent? Could it be moved to the constructor and have shutdownHooks unmodifiable?

Target:
public void contextInitialized(final ServletContextEvent sce) { super.contextInitialized(sce); initializeServices(); }
Source:
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { View view = ((View) object); container.removeView(view); START view.setTag(-1); END } Does the tag relate to any action?

Target:
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { View view = ((View) object); container.removeView(view); }
Source:
public AutomatonHitEnum build(String source, HitWeigher queryWeigher, HitWeigher corpusWeigher) { if (reverse == null) { return new AutomatonHitEnum.Forward(forward, source, queryWeigher, corpusWeigher); } else { START BitSet startPositions = END reverse.runAllReverse(source); return new AutomatonHitEnum.TwoPass(forward, startPositions, source, queryWeigher, corpusWeigher); } } I'd store this BitSet inside this factory instance and have a signature like: startPositions = reverse.runAllReverse(source, startPositions); So that this reused bitset is only stored in one place.

Target:
public AutomatonHitEnum build(String source, HitWeigher queryWeigher, HitWeigher corpusWeigher) { if (reverse == null) { return new AutomatonHitEnum.Forward(forward, source, queryWeigher, corpusWeigher); } else { startPositions = reverse.run(source, startPositions); return new AutomatonHitEnum.TwoPass(forward, startPositions, source, queryWeigher, corpusWeigher); } }
Source:
public final boolean incrementToken() throws IOException { if (input.incrementToken()) { String converted = STEMMER.stemWord(termAtt.toString()); if (converted != null) // if we can't stem it, return unchanged START termAtt.setEmpty().append(converted); END return true; } else { return false; } } are there guarantees that converted is not empty? if it can be empty we should probably skip it (calling while(input.incrementToken()) instead of if (input.incrementToken()).

Target:
public final boolean incrementToken() throws IOException { if (input.incrementToken()) { String converted = STEMMER.stemWord(termAtt.toString()); if (converted != null) { // if we can't stem it, return unchanged termAtt.setEmpty().append(converted); } return true; } else { return false; } }
Source:
public void makeProgress(int progress) { START new Handler().postDelayed(() -> { END circularProgressBar.setCurrentProgress(progress); if (progress == MAX_PROGRESS) { new Handler().postDelayed(() -> { setCircularProgressVisibility(GONE); circularProgressBar.setCurrentProgress(NO_PROGRESS); }, FINAL_LOAD_DELAY); } }, NO_DELAY); } Is there a reason for post()ing this, instead of just executing it?

Target:
public void makeProgress(int progress) { circularProgressBar.setCurrentProgress(progress); }
Source:
public CamusWrapper<String> decode(Message message) { long timestamp = 0; String payloadString; try { START payloadString = new String(message.getPayload(), "UTF-8"); END } catch (UnsupportedEncodingException e) { log.error("Unable to load UTF-8 encoding, falling back to system default", e); payloadString = new String(message.getPayload()); } return new CamusWrapper<String>(payloadString, System.currentTimeMillis()); } I wonder if there is any reason to even decode to a string. Would making this a ByteArrayMessageDecoder be simpler? Then we could use it for anything! :)

Target:
public CamusWrapper<String> decode(Message message) { String payloadString; try { payloadString = new String(message.getPayload(), "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("Unable to load UTF-8 encoding, falling back to system default", e); payloadString = new String(message.getPayload()); } return new CamusWrapper<String>(payloadString, System.currentTimeMillis()); }
Source:
public static void addDeclIfNew(Map<String, String> decls, String prefix, String uri) { if (!decls.containsKey(prefix)) { decls.put(prefix, uri); } else { final String currentUri = decls.get(prefix); if (!currentUri.equals(uri)) { START log.warn("Prefix {}: <{}> is already declared, and will not be overwritten with <{}>", END prefix, currentUri, uri); } } } I don't think this warning should be here for system-defined prefixes, because it's essentially is informing the user about something they can't change. If somebody does override schema: (which I still think is crazy, but ok, let's leave this possibility) then there's no point warning them about us not overwriting it back. We just should ignore our setting then.

Target:
public static void addDeclIfNew(Map<String, String> decls, String prefix, String uri) { if (!decls.containsKey(prefix)) { decls.put(prefix, uri); } }
Source:
public void maybeShowIndicatorDots() { editOptionIndicatorDot.setVisibility((Prefs.showEditMenuOptionIndicator() START && Prefs.getTotalUserDescriptionsEdited() >= ACTION_DESCRIPTION_EDIT_UNLOCK_THRESHOLD) ? END VISIBLE : GONE); } Again, this is too much specific logic that this component does not need to know about. It should only depend on Prefs.showEditMenuOptionIndicator().

Target:
public void maybeShowIndicatorDots() { editOptionIndicatorDot.setVisibility(Prefs.showEditMenuOptionIndicator() ? VISIBLE : GONE); }
Source:
Korean() { NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder(); builder.add("\u00B7", "\u0020"); builder.add("\u318D", "\u0020"); START builder.add("\u00AD", "\""); builder.add("\u200C", "\""); END charMap = builder.build(); } u00AD and u200C should map to "" (empty string) not "\"" (double quote). The original JSON has "\\u00AD=>" ... but the quotes are around the mapping \\u00AD=> (map to nothing) and not part of the mapping!

Target:
Korean() { NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder(); builder.add("\u00B7", "\u0020"); builder.add("\u318D", "\u0020"); builder.add("\u00AD", ""); builder.add("\u200C", ""); charMap = builder.build(); }
Source:
private void writeObject(ObjectOutputStream out) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (OutputStreamDataOutput osdo = new OutputStreamDataOutput(bos)) { automaton.save(osdo); } byte[] bytes = bos.toByteArray(); START out.writeInt(bytes.length); END out.write(bytes); } why do you need to know the size in bytes in the output? It looks like it's just used for logging?

Target:
private void writeObject(ObjectOutputStream out) throws IOException { automaton.save(new OutputStreamDataOutput(out)); }
Source:
static Iterator<SerializableFST> transform(Iterator<String> iterator) throws IOException { BytesRefSorter sorter = new InMemorySorter(Comparator.naturalOrder()); while (iterator.hasNext()) { sorter.add(new BytesRef(iterator.next())); } FST<Object> automaton = buildAutomaton(sorter); return automaton == null ? Iterators.emptyIterator() : START Collections.singletonList(new END SerializableFST(automaton)).iterator(); } static import?

Target:
public static Iterator<SerializableFST> transform(Iterator<String> iterator) throws IOException { // sort/dedupe based on the utf8 byte representation of the dictionary BytesRefSorter sorter = new InMemorySorter(Comparator.naturalOrder()); while (iterator.hasNext()) { sorter.add(new BytesRef(iterator.next())); } FST<Object> automaton = buildAutomaton(sorter); return automaton == null ? Iterators.emptyIterator() : Collections.singletonList(new SerializableFST(automaton)).iterator(); }
Source:
public START static String END randomAsciiOfLength(int count) { return RandomStringUtils.randomAlphabetic(count); } Done

Target:
public String randomAsciiOfLength(int count) { return RandomStringUtils.randomAlphabetic(count); }
Source:
private FileItem START checkFileItem(FileItem END item, FileItem prevValue, String fieldName) { if (prevValue == null) { if (fieldName.equals(item.getFieldName())) { return item; } return null; } else { return prevValue; } } With a few less imbricated if's (minor enough, feel free to ignore): private FileItem checkFileItem(FileItem item, FileItem prevValue, String fieldName) { if (prevValue != null) return prevValue; if (fieldName.equals(item.getFieldName())) { return item; } return null; }

Target:
private FileItem checkFileItem(FileItem item, FileItem prevValue, String fieldName) { if (prevValue != null) { return prevValue; } if (fieldName.equals(item.getFieldName())) { return item; } return null; }
Source:
public JsonNode getEventSchema(String eventString) { // Assume that all eventStrings are in JSON, not in YAML, due to // a slight difference in allowed unicode characters in YAML. // See: https://phabricator.wikimedia.org/T227484 START JsonNode event = this.schemaLoader.parse(eventString, false); END return this.getEventSchema(event); } Well, adding classes for better semantics, but ok let's go with inspecting the event then. some.trim().startsWith("{") should do it right?

Target:
public JsonNode getEventSchema(String eventString) { JsonNode event = this.schemaLoader.parse(eventString); return this.getEventSchema(event); }
Source:
public static Properties processProperties(final String propertyFileName) throws IOException { final File propertyFile = new File(propertyFileName); START if (!propertyFile.exists()) { END throw new FileNotFoundException(propertyFile.toString()); } final Properties properties = new Properties(); final InputStream is = new FileInputStream(propertyFile); try { properties.load(is); } finally { if (is != null) { is.close(); } } return properties; } Wouldn't FileInputStream do it by itself if file does not exists?

Target:
private static Properties processProperties(final String propertyFileName) throws IOException { final File propertyFile = new File(propertyFileName); if (!propertyFile.exists()) { throw new FileNotFoundException(propertyFile.toString()); } final Properties properties = new Properties(); try (InputStream is = new FileInputStream(propertyFile)) { properties.load(is); } return properties; }