auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testListDList() { DList<Integer> d = listDList(List.range(0, 1000)); START assertThat(d.toJavaList(), is(d.run().toJavaList())); END } instead of testing `assertThat(d.toJavaList(), is(d.run().toJavaList()));` (that only check that `toJavaList()` is an alias of `run().toJavaList()`) I think we better test something like `assertThat(d.toJavaList(), is(List.range(0, 1000).toJavaList()));` (same for below methods)

Target:
public void testListDList() { DList<Integer> d = listDList(List.range(0, 1000)); assertThat(d.toJavaList(), is(List.range(0, 1000).toJavaList())); }
Source:
START private Always(F0<A> supplier) { END this.supplier = supplier; } package private

Target:
Always(F0<A> supplier) { this.supplier = supplier; }
Source:
START private PureTrampolineEval(Eval<A> start) { END this.start = start; } package private

Target:
PureTrampolineEval(Eval<A> start) { this.start = start; }
Source:
START private BindTrampolineEval(F<A, Eval<B>> f, TrampolineEval<A> next) { END this.next = next; this.f = f; } package private

Target:
BindTrampolineEval(F<A, Eval<B>> f, TrampolineEval<A> next) { this.next = next; this.f = f; }
Source:
START public <B> Eval<B> flatMap(final F<A, Eval<B>> f) { END return bind(f); } could be `final`.

Target:
public final <B> Eval<B> flatMap(final F<A, Eval<B>> f) { return bind(f); }
Source:
START TrampolineEval<A> asTrampoline() { END return this; } `final`.

Target:
final TrampolineEval<A> asTrampoline() { return this; }
Source:
public static <K, A> PriorityQueue<K, A> priorityQueue(Equal<K> e, FingerTree<K, P2<K, A>> ft) { START return new PriorityQueue<K, A>(e, ft); END } nitpicking: could be `new PriorityQueue<>(`

Target:
public static <K, A> PriorityQueue<K, A> priorityQueue(Equal<K> e, FingerTree<K, P2<K, A>> ft) { return new PriorityQueue<>(e, ft); }
Source:
public static <A> PriorityQueue<Integer, A> emptyInt() { START return priorityQueue(Equal.intEqual, FingerTree.empty(Monoid.intMaxMonoid, (P2<Integer, A> p) -> p._1())); END } could be `return empty(Monoid.intMaxMonoid, Equal.intEqual);`

Target:
public static <A> PriorityQueue<Integer, A> emptyInt() { return empty(Monoid.intMaxMonoid, Equal.intEqual); }
Source:
START public IO<Unit> println(final String s) { END return () -> { result = s; return Unit.unit(); }; } Would it make sense to make this return the string, rather than assign it to the instance variable `result`. Longer term, perhaps we need a bind method like: `IO<A> bindLeft(IO<A> io, F<A, IO<B>> f)` which binds, but returns the a from the left argument. But this would be another issue. I would have to check the Haskell doc to see if this exists.

Target:
public IO<String> println(final String s) { return () -> { return s; }; }
Source:
public <C> List<Validation<E, C>> traverseList(F<T, List<C>> f){ return isSuccess() ? f.f(success()).map(c -> Validation.<E, C>success(c)) : list(Validation.<E, C>fail(e.left().value())); START } END Method reference for success here, e.g. `map(Validation::success)` I tried this and did not need the types. ``` return isSuccess() ? f.f(success()).map(Validation::success) : List.list(Validation.fail(e.left().value())); ```

Target:
public <C> List<Validation<E, C>> traverseList(F<T, List<C>> f){ return isSuccess() ? f.f(success()).map(Validation::success) : list(fail(e.left().value())); }
Source:
public final <A, B> Effect1<B> comap(Effect1<A> e1, final F<B, A> f) { return b -> { START e1.f(f.f(b)); END }; } Is the use of curly brackets here necessary when we are returning a void value?

Target:
public final <A, B> Effect1<B> comap(Effect1<A> e1, final F<B, A> f) { return b -> e1.f(f.f(b)); }
Source:
public String toString() { //Don't call getCommand and getData since it causes //AuSetDeferredAttribute to evaluate the deferred value START final StringBuffer sb = new StringBuffer(60).append("[cmd=").append(_cmd); END if (_data != null && _data.length > 0) { sb.append(", {"); for (AuSetAttribute d : (AuSetAttribute[]) _data) { sb.append(d); } sb.append('}'); } return sb.append(']').toString(); } StringBuilder

Target:
public String toString() { final StringBuilder sb = new StringBuilder(60).append("[cmd=").append(_cmd); if (_data != null && _data.length > 0) { sb.append(", {"); for (AuSetAttribute d : (AuSetAttribute[]) _data) { sb.append(d); } sb.append('}'); } return sb.append(']').toString(); }
Source:
public void setConstraint(String constr) { START if (!isValidConstraint(constr)) END throw new WrongValueException("Invalid constraint: " + constr + " (the constraint should be formatted in yyyyMMdd)"); setConstraint(constr != null ? new SimpleDateConstraint(constr) : null); // Bug 2564298 } should put in SimpleDateConstraint

Target:
public void setConstraint(String constr) { setConstraint(constr != null ? new SimpleDateConstraint(constr) : null); // Bug 2564298 }
Source:
public String getUpload() { Desktop desktop = getDesktop(); String upload = _auxinf != null ? _auxinf.upload : null; if (desktop != null && !Strings.isEmpty(upload) && !upload.contains("maxsize=")) upload = upload.concat(",maxsize=" + desktop.getWebApp().getConfiguration().getMaxUploadSize()); START return upload; END } not good to add sth when calling getter

Target:
public String getUpload() { return _auxinf != null ? _auxinf.upload : null; }
Source:
public void testDesktopDestroy() { F85_ZK_1148FileDealer.writeMsg("", false); DesktopAgent da = connect(); da.destroy(); START Assert.assertEquals("DestroyD is called!DestroyC is called!IncludeVM is called!", F85_ZK_1148FileDealer.readMsg()); END F85_ZK_1148FileDealer.close(); } https://github.com/zkoss/zk/pull/1185/files#diff-c52ff1da920c31e56cabddf44f726869R34 You forgot the potential issue

Target:
public void testDesktopDestroy() { F85_ZK_1148FileDealer.writeMsg("", false); DesktopAgent da = connect(); da.destroy(); try { Assert.assertEquals("DestroyD is called!DestroyC is called!IncludeVM is called!", F85_ZK_1148FileDealer.readMsg()); } finally { F85_ZK_1148FileDealer.close(); } }
Source:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); List<String> old = _props.get(key); if (old == null) old = new LinkedList<String>(); START old.addAll(values); END return _props.put(key, old); } the `old`(LinkedList) is not thread-safe, multi-thread addAll might be wrong. You should protect it.

Target:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); synchronized (_props) { List<String> old = _props.get(key); if (old == null) old = new LinkedList<String>(); old.addAll(values); return _props.put(key, old); } }
Source:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); List<String> old = _props.get(key); synchronized (_props) { if (old == null) old = new LinkedList<String>(); old.addAll(values); } START return _props.put(key, old); END } It is better to remain the original code. The fetch-create-put action should be atomic. Or every thread will replace others.

Target:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); synchronized (_props) { List<String> old = _props.get(key); if (old == null) old = new LinkedList<String>(); old.addAll(values); return _props.put(key, old); } }
Source:
public static List<String> getProperties(String key) { final List<String> v; START v = _props.get(key); END return v; } just `return _props.get(key);` in this method

Target:
public static List<String> getProperties(String key) { return _props.get(key); }
Source:
private boolean isCheckmarkDeselectOther() { if (_ckDeselectOther == null) //ok to race _ckDeselectOther = Boolean .valueOf("true".equals(Library.getProperty("org.zkoss.zul.tree.checkmarkDeselectOthers"))); return Utils.testAttribute(this, "org.zkoss.zul.listbox.checkmarkDeselectOthers", _ckDeselectOther.booleanValue(), true); START } END listbox?

Target:
private boolean isCheckmarkDeselectOther() { if (_ckDeselectOther == null) //ok to race _ckDeselectOther = Boolean .valueOf("true".equals(Library.getProperty("org.zkoss.zul.tree.checkmarkDeselectOthers"))); return Utils.testAttribute(this, "org.zkoss.zul.tree.checkmarkDeselectOthers", _ckDeselectOther.booleanValue(), true); }
Source:
public void test() { connect(); click(jq("$listbox1").toWidget().firstChild()); waitResponse(); Assert.assertTrue(jq("@notification").exists()); waitResponse(); click(jq("body")); waitResponse(); click(jq("$listbox2").toWidget().firstChild()); waitResponse(); Assert.assertTrue(jq("@notification").exists()); START waitResponse(); END } The last `waitResponse` is unnecessary

Target:
public void test() { connect(); click(jq("$listbox1").toWidget().firstChild()); waitResponse(); Assert.assertTrue(jq("@notification").exists()); waitResponse(); click(jq("body")); waitResponse(); click(jq("$listbox2").toWidget().firstChild()); waitResponse(); Assert.assertTrue(jq("@notification").exists()); }
Source:
public void setLocale(Locale locale) { if (!Objects.equals(_locale, locale)) { _locale = locale; if (getFormat() == null) { START if ("en_IN".equals(locale.toString())) { END setFormat("en-IN"); } else { setFormat(getDefaultFormat()); } } invalidate(); } } Hard-coded. What if we add another format in the future?

Target:
public void setLocale(Locale locale) { if (!Objects.equals(_locale, locale)) { _locale = locale; if (getFormat() == null) setFormat(getDefaultFormat()); invalidate(); } }
Source:
private String getName(URL url) { String name = url.getPath(); if (name != null) { START { END final int j = name.lastIndexOf(File.pathSeparatorChar); if (j >= 0) name = name.substring(j + 1); } if (File.pathSeparatorChar != '/') { final int j = name.lastIndexOf('/'); if (j >= 0) name = name.substring(j + 1); } } return name; } extra { ?

Target:
private String getName(URL url) { String name = url.getPath(); if (name != null) { final int i = name.lastIndexOf(File.pathSeparatorChar); if (i >= 0) name = name.substring(i + 1); if (File.pathSeparatorChar != '/') { final int j = name.lastIndexOf('/'); if (j >= 0) name = name.substring(j + 1); } } return name; }
Source:
protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws java.io.IOException { super.renderProperties(renderer); if (_columns > 0) renderer.render("columns", _columns); if (_columns > 0 && _start > 0) renderer.render("start", _start); //F85-ZK-3525: frozen support smooth mode (ee only) START renderer.render("smooth", isSmooth()); END } How about use `render(renderer, "smooth", isSmooth());` instead? It will not send additional data if smooth is false.

Target:
protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws java.io.IOException { super.renderProperties(renderer); if (_columns > 0) renderer.render("columns", _columns); if (_columns > 0 && _start > 0) renderer.render("start", _start); //F85-ZK-3525: frozen support smooth mode (ee only) if (!isSmooth()) renderer.render("smooth", false); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { if (!super.onOptionsItemSelected(item)) { if (item.getItemId() == R.id.clear_history_item) { DBWriter.clearDownloadLog(); START return true; END } return false; } else { return true; } } This will cause a merge conflict with #4244. Please do not change this file.

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (!super.onOptionsItemSelected(item)) { switch (item.getItemId()) { case R.id.clear_history_item: DBWriter.clearDownloadLog(); return true; default: return false; } } else { return true; } }
Source:
public void testFeedListDownloadUrls() { List<Feed> feeds = saveFeedlist(10, 0, false); List<String> urls = DBReader.getFeedListDownloadUrls(); assertNotNull(urls); START assertEquals(urls.size(), feeds.size()); END for (int i = 0; i < urls.size(); i++) { assertEquals(urls.get(i), feeds.get(i).getDownload_url()); } } I'm not 100% sure but I think this should be the other way around. `feeds.size()` seems to be the expected value. This problem is also present in other tests. Before, a failing test just showed something about a failed assertion. Now it shows actual value and expected value, so it is misleading if they are exchanged.

Target:
public void testFeedListDownloadUrls() { List<Feed> feeds = saveFeedlist(10, 0, false); List<String> urls = DBReader.getFeedListDownloadUrls(); assertNotNull(urls); assertEquals(feeds.size(), urls.size()); for (int i = 0; i < urls.size(); i++) { assertEquals(urls.get(i), feeds.get(i).getDownload_url()); } }
Source:
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.w("DBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + "."); DBUpgrader.upgrade(db, oldVersion, newVersion); START if (oldVersion == 1090000) { END db.execSQL("ALTER TABLE " + TABLE_NAME_FEEDS + " ADD COLUMN " + KEY_FEED_SKIP_INTRO + " INTEGER DEFAULT 0;"); db.execSQL("ALTER TABLE " + TABLE_NAME_FEEDS + " ADD COLUMN " + KEY_FEED_SKIP_ENDING + " INTEGER DEFAULT 0;"); } } Please move this to `DBUpgrader`. Also, use `oldVersion < 1090001`. Users might skip AntennaPod versions. When checking for equality, this skips the migration when coming from, say `1080100` instead of exactly `1090000`.

Target:
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.w("DBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + "."); DBUpgrader.upgrade(db, oldVersion, newVersion); }
Source:
public void onStart() { super.onStart(); EventBus.getDefault().register(this); START autoDownload = prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER); END keepUpdated = prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER); autoDelete = prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER); loadSubscriptions(); } I think those can be loaded when actually filtering the items. That way, the Fragment does not need to keep preferences as member variables and watch out that they are always updated.

Target:
public void onStart() { super.onStart(); EventBus.getDefault().register(this); // autoDownload = SubscriptionFilterDialog.AutoDownload.valueOf(prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER)); // keepUpdated = SubscriptionFilterDialog.KeepUpdated.valueOf(prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER)); // autoDelete =SubscriptionFilterDialog.AutoDelete.valueOf(prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER)); loadSubscriptions(); }
Source:
public String getDescription() { START return de.danoeh.antennapod.core.util.TextUtils.getNormalizedText(description); END } Parsing html should be done outside of `Feed.java`. `Feed` is the model that represents the actual feed. How we display the feed afterwards does not belong to the feed itself, in my opinion.

Target:
public String getDescription() { return description; }
Source:
private static boolean isHtml(String str) { final String HTML_TAG_PATTERN = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>"; Pattern htmlValidator = TextUtils.isEmpty(HTML_TAG_PATTERN) ? null : Pattern.compile(HTML_TAG_PATTERN); boolean isHtml = htmlValidator.matcher(str).find(); START return isHtml; END } You don't need a variable here

Target:
private static boolean isHtml(String str) { final String HTML_TAG_PATTERN = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>"; Pattern htmlValidator = TextUtils.isEmpty(HTML_TAG_PATTERN) ? null : Pattern.compile(HTML_TAG_PATTERN); return htmlValidator.matcher(str).find(); }
Source:
public static String getPlainText(String str) { START if (!TextUtils.isEmpty(str) && isHtml(str)) { END HtmlToPlainText formatter = new HtmlToPlainText(); Document feedDescription = Jsoup.parse(str); str = StringUtils.trim(formatter.getPlainText(feedDescription)); } return str; } I think it is safer to explicitly return an empty string if TextUtils.isEmpty to prevent crashes at the caller when the description is null.

Target:
public static String getPlainText(String str) { if (!TextUtils.isEmpty(str) && isHtml(str)) { HtmlToPlainText formatter = new HtmlToPlainText(); Document feedDescription = Jsoup.parse(str); str = StringUtils.trim(formatter.getPlainText(feedDescription)); } else if (TextUtils.isEmpty(str)) { str = ""; } return str; }
Source:
private void setSortOrder(SortOrder sortOrder) { boolean keepSorted = UserPreferences.isQueueKeepSorted(); if (keepSorted) { START UserPreferences.setQueueKeepSortedOrder(sortOrder); END } QueueSorter.sort(sortOrder, true); } This does not need to be conditional anymore. If the queue just saves the order every time, it would support first sorting and then checking "keep sorted".

Target:
private void setSortOrder(SortOrder sortOrder) { UserPreferences.setQueueKeepSortedOrder(sortOrder); QueueSorter.sort(sortOrder, true); }
Source:
void onPlayPause() { if(controller == null) { return; } START controller.init(); END controller.playPause(); } Init should only be called one single time when constructing the controller. That is done in OnStart. Please add a space between if and (

Target:
void onPlayPause() { if (controller == null) { return; } controller.playPause(); }
Source:
public void onResume() { super.onResume(); onPositionObserverUpdate(); START new Thread(() -> controller.init()).start(); END } Do you actually do any heavy lifting here that needs to happen in the background? If so, why do we still do `controller.init()` in `connectToPlaybackService()` which definitely is executed on the UI thread?

Target:
public void onResume() { super.onResume(); onPositionObserverUpdate(); controller.init(); }
Source:
public boolean onStartJob(JobParameters params) { Log.d(TAG, "Job started"); ClientConfig.initialize(getApplicationContext()); START END new Thread(() -> { FeedUpdateUtils.startAutoUpdate(getApplicationContext(), true); UserPreferences.restartUpdateAlarm(false); jobFinished(params, false); // needsReschedule = false }).start(); return true; } The codes here (spawning new thread, using synchronous version of startAutoUpdate(), etc.) are a tad tricky. A way to reduce the complexity could be changing `FeedUpdateUtils.startAutoUpdate()` to accept a `Runnable onCompleteCallback` parameter, so that 1. At `FeedUpdateJobService` level, it simply calls: ```java FeedUpdateUtils.startAutoUpdate(getApplicationContext(), () -> { UserPreferences.restartUpdateAlarm(false); jobFinished(params, false); // needsReschedule = false }); ``` 2. In the underlying DBTasks.refreshAllFeeds(context, feeds), accept the new parameter `Runnable onCompleteCallback`, and invokes the callback upon completion. - `DBTasks` and `FeedUpdateUtils` thus have no need to expose synchronous version of feed updates.

Target:
public boolean onStartJob(JobParameters params) { Log.d(TAG, "Job started"); ClientConfig.initialize(getApplicationContext()); FeedUpdateUtils.startAutoUpdate(getApplicationContext(), () -> { UserPreferences.restartUpdateAlarm(false); jobFinished(params, false); // needsReschedule = false }); return true; }
Source:
public static void refreshAllFeeds(final Context context, final List<Feed> feeds) { START new Thread(() -> refreshAllFeedsSynchronously(context, feeds)).start(); END } that doesn't look right... an executor service is a better abstraction

Target:
public static void refreshAllFeeds(final Context context, final List<Feed> feeds) { refreshAllFeeds(context, feeds, null); }
Source:
START private static String getWebsiteLinkWithFallback(Playable media) { END String link = null; if (media != null) { link = media.getWebsiteLink(); if (link == null) { if (media instanceof FeedMedia) { link = FeedItemUtil.getLinkWithFallback(((FeedMedia)media).getItem()); } // else case not a FeedMedia, return null } } // else no media, return null return link; } In my opinion, this function belongs to `FeedItemUtil`

Target:
private static String getWebsiteLinkWithFallback(Playable media) { if (media == null) { return null; } else if (media.getWebsiteLink() != null) { return media.getWebsiteLink(); } else if (media instanceof FeedMedia) { return FeedItemUtil.getLinkWithFallback(((FeedMedia)media).getItem()); } return null; }
Source:
public static String getLinkWithFallback(FeedItem item) { String link = null; if (item != null) { link = item.getLink(); if (link == null) { Feed feed = item.getFeed(); if (feed != null) { link = feed.getLink(); } } } // else null item, can only return null START return link; END } I think it is easier to read if you don't use nested `if`s. Same for the other method. ``` if (item == null) { return null; } else if (item.getLink() != null) { return item.getLink(); } else if (item.getFeed() != null) { return item.getFeed().getLink(); } return null; ```

Target:
public static String getLinkWithFallback(FeedItem item) { if (item == null) { return null; } else if (item.getLink() != null) { return item.getLink(); } else if (item.getFeed() != null) { return item.getFeed().getLink(); } return null; }
Source:
public String writeToString() { String result = this.podcast + "\t" + this.episode + "\t" + this.deviceId + "\t" + this.action + "\t" + this.timestamp.getTime() + "\t" + String.valueOf(this.started) + "\t" + String.valueOf(this.position) + "\t" + String.valueOf(this.total); START return result; END } You can directly return that instead of creating a String first

Target:
public String writeToString() { return this.podcast + "\t" + this.episode + "\t" + this.deviceId + "\t" + this.action + "\t" + this.timestamp.getTime() + "\t" + String.valueOf(this.started) + "\t" + String.valueOf(this.position) + "\t" + String.valueOf(this.total); }
Source:
private String buildInOperator(int size) { if (size == 1) { return "(?)"; } String builder = "(" + TextUtils.join(",", Collections.nCopies(size, "?")) + ")"; START return builder; END } You can directly return that instead of creating a String first

Target:
private String buildInOperator(int size) { if (size == 1) { return "(?)"; } return "(" + TextUtils.join(",", Collections.nCopies(size, "?")) + ")"; }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent resultData) { START if (requestCode == REQUEST_CODE_RESTORE && resultCode == RESULT_OK && resultData != null) { END Uri uri = resultData.getData(); restoreFrom(uri); } else if (requestCode == REQUEST_CODE_BACKUP_DOCUMENT && resultCode == RESULT_OK && resultData != null) { Uri uri = resultData.getData(); backupToDocument(uri); } } guard clause? ``` if(resultCode != RESULT_OK || resultData == null) return; Uri uri = ... if(requestCode == ... ```

Target:
public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (resultCode != RESULT_OK || resultData == null) { return; } Uri uri = resultData.getData(); if (requestCode == REQUEST_CODE_RESTORE) { restoreFrom(uri); } else if (requestCode == REQUEST_CODE_BACKUP_DOCUMENT) { backupToDocument(uri); } }
Source:
public void testParseDateWithIncorrectWeekday() { START GregorianCalendar exp1 = new GregorianCalendar(2014, 9, 8, 9, 00, 00); END exp1.setTimeZone(TimeZone.getTimeZone("GMT")); Date expected = new Date(exp1.getTimeInMillis()); Date actual = DateUtils.parse("Thu, 8 Oct 2014 09:00:00 GMT"); // actually a Wednesday assertEquals(expected, actual); } Intellij warns that `00` is octal. Shouldn't be a problem but maybe we can avoid the warnings by just writing a single `0`

Target:
public void testParseDateWithIncorrectWeekday() { GregorianCalendar exp1 = new GregorianCalendar(2014, 9, 8, 9, 0, 0); exp1.setTimeZone(TimeZone.getTimeZone("GMT")); Date expected = new Date(exp1.getTimeInMillis()); Date actual = DateUtils.parse("Thu, 8 Oct 2014 09:00:00 GMT"); // actually a Wednesday assertEquals(expected, actual); }
Source:
public static String getMimeTypeFromUrl(String url) { START if (url != null) { END String extension = FilenameUtils.getExtension(url); if (extension != null) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } } return null; } I would change this to `if(url == null) { return null; }` less indentation, code looks a lot cleaner

Target:
public static String getMimeTypeFromUrl(String url) { if (url == null) { return null; } String extension = FilenameUtils.getExtension(url); if (extension == null) { return null; } return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }
Source:
START static protected TextView getTxtvFFFromActivity(MediaplayerActivity activity) { END return activity.txtvFF; } can you change this to `protected static`? This order is really unconventional

Target:
protected static TextView getTxtvFFFromActivity(MediaplayerActivity activity) { return activity.txtvFF; }
Source:
private void updatePlaybackSpeedButton() { if(butPlaybackSpeed == null) { return; } // TODO this possibly needs to change if we introduce an alternative button START if (controller == null || !(this instanceof AudioplayerActivity)) { END butPlaybackSpeed.setVisibility(View.GONE); return; } updatePlaybackSpeedButtonText(); ViewCompat.setAlpha(butPlaybackSpeed, controller.canSetPlaybackSpeed() ? 1.0f : 0.5f); butPlaybackSpeed.setVisibility(View.VISIBLE); } shouldn't AudioplayerActivity override this method to support configuring the button? The default implementation can just return without doing anything. I'd imagine that only the AudioplayerActivity would have a butPlaybackSpeed object and others wouldn't.

Target:
protected void updatePlaybackSpeedButton() { // Only meaningful on AudioplayerActivity, where it is overridden. }
Source:
public static FlattrService getService(AccessToken token) { START if (flattrService == null) { END flattrService = FlattrFactory.getInstance().createFlattrService(token); } return flattrService; } still needs `synchronized`, doesn't it?

Target:
public synchronized static FlattrService getService(AccessToken token) { if (flattrService == null) { flattrService = FlattrFactory.getInstance().createFlattrService(token); } return flattrService; }
Source:
void updateData(List<Podcast> result) { this.searchResults = result; adapter.clear(); if (result != null && result.size() > 0) { gridView.setVisibility(View.VISIBLE); txtvEmpty.setVisibility(View.GONE); START adapter.addAll(result); END adapter.notifyDataSetInvalidated(); } else { gridView.setVisibility(View.GONE); txtvEmpty.setVisibility(View.VISIBLE); } } Call requires API level 11 (we are on 10)

Target:
void updateData(List<Podcast> result) { this.searchResults = result; adapter.clear(); if (result != null && result.size() > 0) { gridView.setVisibility(View.VISIBLE); txtvEmpty.setVisibility(View.GONE); for (Podcast p : result) { adapter.add(p); } adapter.notifyDataSetInvalidated(); } else { gridView.setVisibility(View.GONE); txtvEmpty.setVisibility(View.VISIBLE); } }
Source:
public static boolean setLockscreenBackground() { START return prefs.getBoolean(PREF_LOCKSCREEN_BACKGROUND, false); END } I think 'false' needs to get changed to true. For some reason the 'default' in the preferences doesn't work otherwise. It shows up as being checked but doesn't actually work until you uncheck/check it again. I'm not sure why it works this way. :( (Tested on 5.0.0 and 5.1)

Target:
public static boolean setLockscreenBackground() { return prefs.getBoolean(PREF_LOCKSCREEN_BACKGROUND, true); }
Source:
public GuiceBundle<T> build() { START return new GuiceBundle<T>(Stage.PRODUCTION, autoConfig, modules, configurationClass); END } Why not simply call? ``` return build(Stage.PRODUCTION); ```

Target:
public GuiceBundle<T> build() { return build(Stage.PRODUCTION); }
Source:
public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { TreeNode treeNode = jp.readValueAsTree(); JsonNode oid = ((JsonNode) treeNode).get(MONGO_QUERY_OID); if (oid != null) return oid.asText(); else if(treeNode.isValueNode() && treeNode instanceof TextNode) { return ((JsonNode) treeNode).textValue(); } else START return treeNode.toString(); END } Instead of calling toString() on treeNode what about calling asText() instead. It seems ok and 'else if' condition is no longer needed

Target:
public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { TreeNode treeNode = jp.readValueAsTree(); JsonNode oid = ((JsonNode) treeNode).get(MONGO_QUERY_OID); if (oid != null) return oid.asText(); else return ((JsonNode) treeNode).asText(); }
Source:
public void setCharset(String charset) { START if(charset == null) { throw new UnsupportedCharsetException("provided mediatype does not support setting charset"); } END if(StringUtils.isNotEmpty(charset)) { this.charset = Charset.forName(charset); } } Hier bedoel je dan denk ik if (this.charset == null)

Target:
public void setCharset(String charset) { if(this.charset == null) { throw new UnsupportedCharsetException("provided mediatype does not support setting charset"); } if(StringUtils.isNotEmpty(charset)) { this.charset = Charset.forName(charset); } }
Source:
START public void testAdd() throws ArrayIndexOutOfBoundsException { END SizeLimitedVector slv = new SizeLimitedVector(10); slv.add("testString"); assertEquals(slv.getMaxSize(), 10); assertEquals(slv.get(0), "testString"); } You dont have to declare this RuntimeException here do you? Non of the functions are throwing any exceptions

Target:
public void testAdd() { SizeLimitedVector slv = new SizeLimitedVector(10); slv.add("testString"); assertEquals(slv.getMaxSize(), 10); assertEquals(slv.get(0), "testString"); }
Source:
private String determineDestination(ParameterValueList pvl) { if (StringUtils.isNotEmpty(getDestination())) { return getDestination(); } if (pvl!=null && pvl.containsKey(PARAMETER_DESTINATION)) { START return pvl.getParameterValue(PARAMETER_DESTINATION).asStringValue(""); END } return null; } Wat als deze leeg is? Kan je niet beter NULL teruggeven?

Target:
private String determineDestination(ParameterValueList pvl) { if (StringUtils.isNotEmpty(getDestination())) { return getDestination(); } if (pvl!=null && pvl.containsKey(PARAMETER_DESTINATION)) { return pvl.getParameterValue(PARAMETER_DESTINATION).asStringValue(null); } return null; }
Source:
public void testEmptySessionKeyEmptyInput() throws Exception { exception.expect(NullPointerException.class); START pipe.setSessionKey(null); END session.put("a", "123"); PipeRunResult res = doPipe(pipe, null, session); assertEquals(res.getResult().toString(), "[null]"); } Setters cannot be null (they would not be set). They can however be empty `""`

Target:
public void testEmptySessionKeyEmptyInput() throws Exception { exception.expect(NullPointerException.class); pipe.setSessionKey(""); session.put("a", "123"); PipeRunResult res = doPipe(pipe, null, session); assertEquals(res.getResult().toString(), "[null]"); }
Source:
public Message(Object request) { if (request instanceof Message) { START this.request = ((Message)request).asObject(); END } else { this.request = request; } } Hoe kan hij hier in komen als de input al een Message is?

Target:
private Message(Object request) { if (request instanceof Message) { // this code could be reached when this constructor was public and the actual type of the parameter was not known at compile time. // e.g. new Message(pipeRunResult.getResult()); this.request = ((Message)request).asObject(); } else { this.request = request; } }
Source:
private ArrayList<String> getSuperClasses(Class clazz) { ArrayList<String> superClasses = new ArrayList<String>(); int index = 0; while (clazz.getSuperclass() != null) { // Assign a string with a priority number attached to it and add it to the array of superclasses String str = Integer.toString(index); START superClasses.add(clazz.getSimpleName() + str); END clazz = clazz.getSuperclass(); index++; } return superClasses; } Waarom voeg je de index aan de naam toe? De lijst is toch op dezelfde volgorde als de index?

Target:
private ArrayList<String> getSuperClasses(Class clazz) { ArrayList<String> superClasses = new ArrayList<String>(); while (clazz.getSuperclass() != null) { // Assign a string with a priority number attached to it and add it to the array of superclasses superClasses.add(clazz.getSuperclass().getSimpleName()); clazz = clazz.getSuperclass(); } return superClasses; }
Source:
public void add(String message, Throwable t) { String msgToLog = message; if(t.getMessage() != null) { msgToLog += ": "+t.getMessage(); } add(msgToLog); START log.error(msgToLog, t); END } zou een warning hier niet meer op z'n plaats zijn?

Target:
public void add(String message, Throwable t) { String msgToLog = message; if(t.getMessage() != null) { msgToLog += ": "+t.getMessage(); } add(msgToLog); log.warn(msgToLog, t); }
Source:
protected int getNumberOfPages(File file) { int result = 0; if(file != null) { try (InputStream inStream = new FileInputStream(file)){ Document doc = new Document(inStream); result = doc.getPages().size(); START System.out.println(" get number of pages has ben executed "+result); END } catch (IOException e) { System.out.println(e); } } return result; } Code should not contain System.out.println(). Please remove all occurrences, or replace with appropriate logging.

Target:
protected int getNumberOfPages(File file) throws IOException { int result = 0; if(file != null) { try (InputStream inStream = new FileInputStream(file)){ Document doc = new Document(inStream); result = doc.getPages().size(); } catch (IOException e) { throw e; } } return result; }
Source:
private CisConversionResult createFailureResult(String filename, ConversionOption conversionOption, MediaType mediaType, String message) { CisConversionResult result; StringBuilder msg = new StringBuilder(); if (filename != null) { msg.append(filename); } msg.append(" " + message); START LOGGER.info("Conversion not supported: " + msg.toString()); END result = CisConversionResult.createFailureResult(conversionOption, mediaType, filename, msg.toString()); return result; } This is warning

Target:
private CisConversionResult createFailureResult(String filename, ConversionOption conversionOption, MediaType mediaType, String message) { CisConversionResult result; StringBuilder msg = new StringBuilder(); if (filename != null) { msg.append(filename); } msg.append(" " + message); LOGGER.warn("Conversion not supported: " + msg.toString()); result = CisConversionResult.createFailureResult(conversionOption, mediaType, filename, msg.toString()); return result; }
Source:
public SameSiteCookieHandler(final HttpHandler next, final String mode) { START this(next, mode, null, false); END } do we want to have a disable client checker with a default value set to false, or do we want to have a enable-client-checker with a default value set to true? I wonder how does this work in the long term pov, do we expect to still have a long list of incompatible user agents in the future?

Target:
public SameSiteCookieHandler(final HttpHandler next, final String mode) { this(next, mode, null, true, true, true); }
Source:
public String getLocalName() { String hostName = exchange.getDestinationAddress().getHostName(); START if (hostName == null) { END //return the IP as string return exchange.getDestinationAddress().getHostString(); } return hostName; } Hi @tmiyargi @fl4via and/or @stuartwdouglas will have a final say on this one. I'm just a lurker in this project. Having said that, I think the backward compatiblity of this shouldn't play a role here, because this bug fix is about fixing a wrong value that was being retuned, before this change.

Target:
public String getLocalName() { return exchange.getDestinationAddress().getHostName(); }
Source:
public Long getContentLength() { try { if (Files.isSymbolicLink(file) && Files.notExists(file)) { START return 0L; END } return Files.size(file); } catch (IOException e) { throw new RuntimeException(e); } } I think this should be null as well

Target:
public Long getContentLength() { try { if (Files.isSymbolicLink(file) && Files.notExists(file)) { return null; } return Files.size(file); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
private SerializedValue getSerializedValue(RestAction<?> action, Object object) throws ActionException { String bodyClass = action.getBodyClass(); if (bodyClass != null) { List<ContentType> contentTypes = action.getClientProducedContentTypes(); Serialization serialization = findSerialization(bodyClass, contentTypes); if (serialization != null) { START try { END return serialize(serialization, object, bodyClass, contentTypes); } catch (SerializationException e) { throw new ActionSerializationException(e); } } } throw new ActionSerializationException( "Unable to serialize request body. No serializer found."); } I think it was more readable with `try-catch` was part of `serialize`

Target:
private SerializedValue getSerializedValue(RestAction<?> action, Object object) throws ActionException { String bodyClass = action.getBodyClass(); if (bodyClass != null) { List<ContentType> contentTypes = action.getClientProducedContentTypes(); Serialization serialization = findSerialization(bodyClass, contentTypes); if (serialization != null) { return serialize(serialization, object, bodyClass, contentTypes); } } throw new ActionSerializationException( "Unable to serialize request body. No serializer found."); }
Source:
public void resolve_hasAnnotations_hasNoCookieParams() { // given HasAnnotations hasAnnotations = mock(HasAnnotations.class); // when String value = resolver.resolve(hasAnnotations); // then START assertThat(value).isEqualTo(SOME_VALUE); END } I think the assert should be that `value` is null. It looks like it's your assert that is throwing the NPE

Target:
public void resolve_hasAnnotations_hasNoCookieParams() { // given HasAnnotations hasAnnotations = mock(HasAnnotations.class); // when resolver.resolve(hasAnnotations); }
Source:
public ActionBinding generate() throws UnableToCompleteException { String implName = getSuperTypeName() + SUFFIX; PrintWriter printWriter = getGeneratorUtil().tryCreatePrintWriter(getPackage(), implName); if (printWriter != null) { try { doGenerate(implName, printWriter); registerMetadata(); } finally { printWriter.close(); START } END } else { getLogger().debug("Action already generated. Returning."); } return createActionBinding(implName); } It would save a lot of duplication if you move this try finally up into mergeTemplate. The printwriter is never used after it's called anyways.

Target:
public ActionBinding generate() throws UnableToCompleteException { String implName = getSuperTypeName() + SUFFIX; if (doGenerate(implName)) { registerMetadata(); } return createActionBinding(implName); }
Source:
public DispatchRequest undo(LogInAction action, LogInResult result, AsyncCallback<Void> callback, UndoCommand<LogInAction, LogInResult> undoCommand) { undoCommand.undo(action, result, callback); START return new CompletedDispatchRequest(); END } `return undoCommand.undo(action, result, callback);`

Target:
public DispatchRequest undo(LogInAction action, LogInResult result, AsyncCallback<Void> callback, UndoCommand<LogInAction, LogInResult> undoCommand) { return undoCommand.undo(action, result, callback); }
Source:
START public TypedAction getAction() { END return action; } protected

Target:
protected TypedAction getAction() { return action; }
Source:
public DispatchCall(ExceptionHandler exceptionHandler, SecurityCookieAccessor securityCookieAccessor, A action, AsyncCallback<R> callback) { this.action = action; this.callback = callback; this.exceptionHandler = exceptionHandler; this.securityCookieAccessor = securityCookieAccessor; START prepareCall(); END } This should be done later in the class life cycle (not in the ctor)

Target:
public DispatchCall( ExceptionHandler exceptionHandler, SecurityCookieAccessor securityCookieAccessor, A action, AsyncCallback<R> callback) { this.action = action; this.callback = callback; this.exceptionHandler = exceptionHandler; this.securityCookieAccessor = securityCookieAccessor; }
Source:
START protected <T> GinLinkedBindingBuilder<T> bindAnnotated(Class<T> clazz) { END GinAnnotatedBindingBuilder<T> binding = bind(clazz); if (annotationClass != null) { return binding.annotatedWith(annotationClass); } return binding; } Revert to private

Target:
private <T> GinLinkedBindingBuilder<T> bindAnnotated(Class<T> clazz) { GinAnnotatedBindingBuilder<T> binding = bind(clazz); if (annotationClass != null) { return binding.annotatedWith(annotationClass); } return binding; }
Source:
START protected EventBus getEventBus() { END return eventBus; } The final was there so that the user can't override the method.

Target:
protected final EventBus getEventBus() { return eventBus; }
Source:
public Widget asWidget() { START return getView() == null ? null : getView().asWidget(); END } view should never be null. If anything the contract should be enforced in the ctor and the check here removed.

Target:
public Widget asWidget() { return getView().asWidget(); }
Source:
START public void removeFromParentSlot() { END assert parent != null : "Tried to remove a presenter that has no parent from its parent"; parent.removeFromSlot(slot, this); } Do you think naming it `removeFromParent()` could be enough?

Target:
public void removeFromParentSlot() { if (parent == null) { return; } parent.removeFromSlot(slot, this); }
Source:
START public LogInHandler(Logger logger, Authenticator authenticator, UserSessionDao loginCookieDao) { END super(LogInAction.class); this.logger = logger; this.authenticator = authenticator; this.loginCookieDao = loginCookieDao; } rm public

Target:
LogInHandler(Logger logger, Authenticator authenticator, UserSessionDao loginCookieDao) { super(LogInAction.class); this.logger = logger; this.authenticator = authenticator; this.loginCookieDao = loginCookieDao; }
Source:
protected DispatchRequest doExecute() { super.doExecute(); try { RequestBuilder requestBuilder = buildRequest(); return new GwtHttpDispatchRequest(requestBuilder.send()); START } catch (RequestException | ActionException e) { END onExecuteFailure(e); } return new CompletedDispatchRequest(); } Java 7 rocks for that :D

Target:
protected DispatchRequest doExecute() { try { RequestBuilder requestBuilder = buildRequest(); return new GwtHttpDispatchRequest(requestBuilder.send()); } catch (RequestException | ActionException e) { onExecuteFailure(e); } return new CompletedDispatchRequest(); }
Source:
public void iNavigateTo(String nameToken) { START if (nameToken.equals(NameTokens.LOGIN)) { END applicationPage.navigateToNotLoggedIn(nameToken); } else { applicationPage.navigateToWithMenu(nameToken); } } Do it the other way around, it's safer to do : `NameTokens.LOGIN.equals(nameToken)`

Target:
public void iNavigateTo(String nameToken) { if (NameTokens.LOGIN.equals(nameToken)) { applicationPage.navigateToNotLoggedIn(nameToken); } else { applicationPage.navigateToWithMenu(nameToken); } }
Source:
START public ResourceLoader(AppResources resources, WidgetResources widgetResources) { END resources.styles().ensureInjected(); widgetResources.header().ensureInjected(); } rm public

Target:
ResourceLoader(AppResources resources, WidgetResources widgetResources) { resources.styles().ensureInjected(); widgetResources.header().ensureInjected(); }
Source:
protected void onReveal() { ActionBarVisibilityEvent.fire(this, false); if (!Strings.isNullOrEmpty(getLoggedInCookie())) { tryLoggingInWithCookieFirst(); } if (!currentUser.isLoggedIn() && !isOnLoginPage()) { START PlaceRequest p = new Builder().nameToken(NameTokens.login).with(REDIRECT_PARAMETER_NAME, getHistoryToken()).build(); END placeManager.revealPlace(p); } } For better readability, maybe on multiple lines?

Target:
protected void onReveal() { ActionBarVisibilityEvent.fire(this, false); if (!Strings.isNullOrEmpty(getLoggedInCookie())) { tryLoggingInWithCookieFirst(); } }
Source:
START public CrawlFilter(@ServiceUrl String serviceUrl, END @ServiceKey String key, Logger log) { this.serviceUrl = serviceUrl; this.key = key; this.log = log; } rm public

Target:
CrawlFilter(@ServiceUrl String serviceUrl, @ServiceKey String key, Logger log) { this.serviceUrl = serviceUrl; this.key = key; this.log = log; }
Source:
public void setUp(HttpRequestBuilderFactory httpRequestBuilderFactory, UrlUtils urlUtils) { START requestBuilder = mock(RequestBuilder.class); END given(httpRequestBuilderFactory.create(any(Method.class), anyString())).willReturn(requestBuilder); given(urlUtils.encodeQueryString(DECODED_VALUE_1)).willReturn(ENCODED_VALUE_1); given(urlUtils.encodeQueryString(DECODED_VALUE_2)).willReturn(ENCODED_VALUE_2); given(urlUtils.encodeQueryString(DECODED_VALUE_3)).willReturn(ENCODED_VALUE_3); } you could `forceMock(RequestBuilder.class` and `@Inject` it as a field of `DefaultRestRequestBuilderFactoryTest`

Target:
public void setUp(HttpRequestBuilderFactory httpRequestBuilderFactory, UrlUtils urlUtils) { given(httpRequestBuilderFactory.create(any(Method.class), anyString())).willReturn(requestBuilder); given(urlUtils.encodeQueryString(DECODED_VALUE_1)).willReturn(ENCODED_VALUE_1); given(urlUtils.encodeQueryString(DECODED_VALUE_2)).willReturn(ENCODED_VALUE_2); given(urlUtils.encodeQueryString(DECODED_VALUE_3)).willReturn(ENCODED_VALUE_3); }
Source:
GoogleAnalyticsNavigationTracker( @GaAccount String gaAccount, PlaceManager placeManager, EventBus eventBus, GoogleAnalytics analytics) { this.gaAccount = gaAccount; this.placeManager = placeManager; this.eventBus = eventBus; this.analytics = analytics; START if (GWT.isScript()) { END Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { init(); } }); } } Not needed anymore, they seems to have fixed the bug with "localhost" within ga.js

Target:
GoogleAnalyticsNavigationTracker(@GaAccount String gaAccount, PlaceManager placeManager, EventBus eventBus, GoogleAnalytics analytics) { this.gaAccount = gaAccount; this.placeManager = placeManager; this.eventBus = eventBus; this.analytics = analytics; Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { init(); } }); }
Source:
START public ActionMetadataProviderGenerator( END TypeOracle typeOracle, Logger logger, Provider<VelocityContext> velocityContextProvider, VelocityEngine velocityEngine, GeneratorUtil generatorUtil, EventBus eventBus) { super(typeOracle, logger, velocityContextProvider, velocityEngine, generatorUtil); eventBus.register(this); } rm public

Target:
ActionMetadataProviderGenerator(TypeOracle typeOracle, Logger logger, Provider<VelocityContext> velocityContextProvider, VelocityEngine velocityEngine, GeneratorUtil generatorUtil, EventBus eventBus) { super(typeOracle, logger, velocityContextProvider, velocityEngine, generatorUtil); eventBus.register(this); }
Source:
START public ServiceDefinitions(Logger logger, END TypeOracle typeOracle, GeneratorUtil generatorUtil) throws UnableToCompleteException { this.logger = logger; this.typeOracle = typeOracle; this.generatorUtil = generatorUtil; findAllServices(); } You can rm public

Target:
ServiceDefinitions(Logger logger, TypeOracle typeOracle, GeneratorUtil generatorUtil) throws UnableToCompleteException { this.logger = logger; this.typeOracle = typeOracle; this.generatorUtil = generatorUtil; findAllServices(); }
Source:
public void onFailure(Throwable caught) { if (hasResponse()) { START GWT.log("HTTP " + getResponse().getStatusCode() + ": " + getResponse().getStatusText()); END } Message message = new Message(translateCauses(caught), MessageStyle.ERROR); DisplayMessageEvent.fire(hasHandlers, message); } you should remove this log.

Target:
public void onFailure(Throwable caught) { Message message = new Message(translateCauses(caught), MessageStyle.ERROR); DisplayMessageEvent.fire(hasHandlers, message); }
Source:
public void revealDefaultPlace() { START revealPlace(new PlaceRequest(NameTokens.getHome())); END } should add the false parameter so that when first entering the app, we don't end up blocked in the app.

Target:
public void revealDefaultPlace() { revealPlace(new PlaceRequest(NameTokens.getHome()), false); }
Source:
short getCurrentTimeMillis() { START return (short) System.currentTimeMillis(); END } How about using proper bitmasking to make the usage of the two last timestamp bytes more obvious?

Target:
long getCurrentTimeMillis() { return System.currentTimeMillis(); }
Source:
public void setDynamicMdcFieldType(String fieldPattern, String type) { START final Pattern pattern = Pattern.compile(fieldPattern); END dynamicMdcFieldTypes.put(pattern, type); } Nit: No need for `final`.

Target:
public void setDynamicMdcFieldType(String fieldPattern, String type) { Pattern pattern = Pattern.compile(fieldPattern); setDynamicMdcFieldType(pattern, type); }