auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Provides @Singleton ManagedServer providesServer(WebConfiguration START webConfiguration) { END return new WebServer(webConfiguration); } nit: wrap +4

Target:
@Provides @Singleton WebServer providesServer(WebConfiguration webConfiguration) { return new WebServer(webConfiguration); }
Source:
public ContentValuesAssert contains(ContentValuesEntry... entries) { isNotEmptyOrNull(entries); Set<ContentValuesEntry> notFound = new LinkedHashSet<ContentValuesEntry>(); for (ContentValuesEntry entry : entries) { if (!containsEntry(actual, entry)) { notFound.add(entry); } } if (notFound.isEmpty()) { return this; } START throw Failures.instance().failure(new WritableAssertionInfo(), shouldContain(actual, entries, notFound)); END } Logic should be reversed ``` java if (!nf.isEmpty()) { throw; } return this; ```

Target:
public ContentValuesAssert contains(ContentValuesEntry... entries) { isNotEmptyOrNull(entries); Set<ContentValuesEntry> notFound = new LinkedHashSet<ContentValuesEntry>(); for (ContentValuesEntry entry : entries) { if (!containsEntry(actual, entry)) { notFound.add(entry); } } if (!notFound.isEmpty()) { throw Failures.instance().failure(new WritableAssertionInfo(), shouldContain(actual, entries, notFound)); } return this; }
Source:
START public boolean equals(Object obj) { END if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ContentValuesEntry other = (ContentValuesEntry) obj; return areEqual(key, other.key) && areEqual(value, other.value); } Annotations should go on the same line as the method declaration.

Target:
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ContentValuesEntry other = (ContentValuesEntry) obj; return areEqual(key, other.key) && areEqual(value, other.value); }
Source:
public void itemWriterForPojos() throws Exception { START AvroItemWriter avroItemWriter = new AvroItemWriter(output,plainOldUserSchemaResource, PlainOldUser.class); END avroItemWriter.afterPropertiesSet(); avroItemWriter.open(new ExecutionContext()); avroItemWriter.write(this.plainOldUsers()); avroItemWriter.close(); verifyRecordsWithEmbeddedHeader(outputStream.toByteArray(), this.plainOldUsers(), PlainOldUser.class); } Should specify the generic type to avoid warnings: `AvroItemWriter< PlainOldUser >`. We have a couple of them in this test class.

Target:
public void itemWriterForPojos() throws Exception { AvroItemWriter<PlainOldUser> avroItemWriter = new AvroItemWriter(output,plainOldUserSchemaResource, PlainOldUser.class); avroItemWriter.open(new ExecutionContext()); avroItemWriter.write(this.plainOldUsers()); avroItemWriter.close(); verifyRecordsWithEmbeddedHeader(outputStream.toByteArray(), this.plainOldUsers(), PlainOldUser.class); }
Source:
START public void itemWriterWithNoEmbeddedHeaders() throws Exception { END AvroItemWriter avroItemWriter = new AvroItemWriter(output, plainOldUserSchemaResource,PlainOldUser.class); avroItemWriter.setEmbedHeader(false); avroItemWriter.afterPropertiesSet(); avroItemWriter.open(new ExecutionContext()); avroItemWriter.write(this.plainOldUsers()); avroItemWriter.close(); verifyRecords(outputStream.toByteArray(), this.plainOldUsers(), PlainOldUser.class, false); } I'm a bit confused by this test and `shouldFailWitNoSchema` test, especially the following part: ```java AvroItemWriter<PlainOldUser> avroItemWriter = new AvroItemWriter<>(output, plainOldUserSchemaResource,PlainOldUser.class); avroItemWriter.setEmbedHeader(false); ``` Why should I provide a Schema if I can set `embedHeader` to false? For the reader, we can read `PlainOldUser`s from an avro file not containing a schema without providing a schema. In the same way, we should be able to write `PlainOldUser`s to an avro file without embedding any schema. In that case, why is the schema mandatory? To be specific, having a mandatory schema and an option to not embed it is confusing to me.

Target:
public void itemWriterWithNoEmbeddedHeaders() throws Exception { AvroItemWriter<PlainOldUser> avroItemWriter = new AvroItemWriter(output, PlainOldUser.class); avroItemWriter.open(new ExecutionContext()); avroItemWriter.write(this.plainOldUsers()); avroItemWriter.close(); verifyRecords(outputStream.toByteArray(), this.plainOldUsers(), PlainOldUser.class, false); }
Source:
START RemotePartitioningMasterStepBuilder beanFactory(BeanFactory beanFactory) { END this.beanFactory = beanFactory; return this; } Is there a reason this is package private? On a fluent builder this feels odd...

Target:
public RemotePartitioningMasterStepBuilder beanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; return this; }
Source:
public BeanValidatingItemProcessor(LocalValidatorFactoryBean localValidatorFactoryBean) throws Exception { super(); Assert.notNull(localValidatorFactoryBean, "localValidatorFactoryBean must not be null"); START localValidatorFactoryBean.afterPropertiesSet(); END Validator validator = localValidatorFactoryBean.getValidator(); SpringValidatorAdapter springValidatorAdapter = new SpringValidatorAdapter(validator); SpringValidator<T> springValidator = new SpringValidator<>(); springValidator.setValidator(springValidatorAdapter); springValidator.afterPropertiesSet(); setValidator(springValidator); } We shouldn't be calling this here. That is the responsibility of the container since it's being injected.

Target:
public BeanValidatingItemProcessor(LocalValidatorFactoryBean localValidatorFactoryBean) { Assert.notNull(localValidatorFactoryBean, "localValidatorFactoryBean must not be null"); this.validator = localValidatorFactoryBean.getValidator(); }
Source:
START public ItemWriter<Integer> itemWriter() { END MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultChannel(requests()); ChunkMessageChannelItemWriter<Integer> chunkMessageChannelItemWriter = new ChunkMessageChannelItemWriter<>(); chunkMessageChannelItemWriter.setMessagingOperations(messagingTemplate); chunkMessageChannelItemWriter.setReplyChannel(replies()); return chunkMessageChannelItemWriter; } This should, at a minimum, return `ItemStreamWriter` since the `ChunkMessageChannelItemWriter` does implement `ItemStream`. That being said, for components like this, I actually usually recommend returning the concrete type so that Spring can see all interfaces implemented.

Target:
public ChunkMessageChannelItemWriter<Integer> itemWriter() { MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultChannel(requests()); ChunkMessageChannelItemWriter<Integer> chunkMessageChannelItemWriter = new ChunkMessageChannelItemWriter<>(); chunkMessageChannelItemWriter.setMessagingOperations(messagingTemplate); chunkMessageChannelItemWriter.setReplyChannel(replies()); return chunkMessageChannelItemWriter; }
Source:
START public ClassifierCompositeItemWriterBuilder classifier(Classifier<T, ItemWriter<? super T>> classifier) { END Assert.notNull(classifier, "A classifier is required."); this.classifier = classifier; return this; } Missing generic on return

Target:
public ClassifierCompositeItemWriterBuilder<T> classifier(Classifier<T, ItemWriter<? super T>> classifier) { this.classifier = classifier; return this; }
Source:
public ClassifierCompositeItemWriterBuilder<T> classifier(Classifier<T, ItemWriter<? super T>> classifier) { START Assert.notNull(classifier, "A classifier is required."); END this.classifier = classifier; return this; } Move this assert into the build. As it sits right now, you can end up with an invalid writer (one with the invalid default) by just doing: ``` new ClassifierCompositeItemWriter().build(); ``` A test case for this condition should also be added.

Target:
public ClassifierCompositeItemWriterBuilder<T> classifier(Classifier<T, ItemWriter<? super T>> classifier) { this.classifier = classifier; return this; }
Source:
public CompositeItemWriterBuilder delegates(List<ItemWriter<? super T>> delegates) { Assert.notNull(delegates, "A list of delegates is required."); START Assert.notEmpty(delegates, "The delegates list must have one or more delegates."); END this.delegates = delegates; return this; } I've been doing all asserts in the build method to prevent the duplication you have here (for the null check). If the user passes in null, that's ok as long as they don't call build until they call it with something else...

Target:
public CompositeItemWriterBuilder delegates(List<ItemWriter<? super T>> delegates) { this.delegates = delegates; return this; }
Source:
START protected Properties initJobParameters() { END Properties jobParameters = new Properties(); if (getBeanDefinitionRegistry().containsBeanDefinition(JOB_PARAMETERS_BEAN_DEFINITION_NAME)) { BeanDefinition beanDefintion = getBeanDefinitionRegistry().getBeanDefinition(JOB_PARAMETERS_BEAN_DEFINITION_NAME); Properties properties = (Properties) beanDefintion.getConstructorArgumentValues() .getGenericArgumentValue(Properties.class) .getValue(); if (properties == null) { return new Properties(); } jobParameters.putAll(properties); } return jobParameters; } Is this really something we want people to be able to override?

Target:
private Properties initJobParameters() { Properties jobParameters = new Properties(); if (getBeanDefinitionRegistry().containsBeanDefinition(JOB_PARAMETERS_BEAN_DEFINITION_NAME)) { BeanDefinition beanDefintion = getBeanDefinitionRegistry().getBeanDefinition(JOB_PARAMETERS_BEAN_DEFINITION_NAME); Properties properties = (Properties) beanDefintion.getConstructorArgumentValues() .getGenericArgumentValue(Properties.class) .getValue(); if (properties == null) { return new Properties(); } jobParameters.putAll(properties); } return jobParameters; }
Source:
public void afterPropertiesSet() throws Exception { START Assert.isTrue(!(jsrDecider == null), "A decider implementation is required"); END Assert.notNull(name, "A name is required for a decision state"); } jsrDecider != null or Assert.notNull may be clearer here

Target:
public void afterPropertiesSet() throws Exception { Assert.isTrue(jsrDecider != null, "A decider implementation is required"); Assert.notNull(name, "A name is required for a decision state"); }
Source:
void performComplete(BitmapHunter hunter) { START if (shouldWriteToMemoryCache(hunter.getData().memoryPolicy)) { END Result result = hunter.getResult(); if (result != null) { if (result instanceof Result.Bitmap) { Bitmap bitmap = ((Result.Bitmap) result).getBitmap(); cache.set(hunter.getKey(), bitmap); } } } hunterMap.remove(hunter.getKey()); deliver(hunter); } revert (@JvmField at declaration)

Target:
void performComplete(BitmapHunter hunter) { if (shouldWriteToMemoryCache(hunter.data.memoryPolicy)) { Result result = hunter.getResult(); if (result != null) { if (result instanceof Result.Bitmap) { Bitmap bitmap = ((Result.Bitmap) result).getBitmap(); cache.set(hunter.getKey(), bitmap); } } } hunterMap.remove(hunter.getKey()); deliver(hunter); }
Source:
public Builder executor(@NonNull ExecutorService executorService) { checkNotNull(executorService, "executorService == null"); if (!isChild && this.service != null) { START throw new IllegalStateException("Executor service already set."); END } this.service = executorService; return this; } remove these checks and the isChild flag. the checks don't add any value.

Target:
public Builder executor(@NonNull ExecutorService executorService) { checkNotNull(executorService, "executorService == null"); this.service = executorService; return this; }
Source:
START public MatrixTransformation(Request data) { END this.data = data; } not public

Target:
MatrixTransformation(Request data) { this.data = data; }
Source:
START static int getExifRotation(int orientation) { END int rotation; switch (orientation) { case ORIENTATION_ROTATE_90: case ORIENTATION_TRANSPOSE: rotation = 90; break; case ORIENTATION_ROTATE_180: case ORIENTATION_FLIP_VERTICAL: rotation = 180; break; case ORIENTATION_ROTATE_270: case ORIENTATION_TRANSVERSE: rotation = 270; break; default: rotation = 0; } return rotation; } Private

Target:
private static int getExifRotation(int orientation) { int rotation; switch (orientation) { case ORIENTATION_ROTATE_90: case ORIENTATION_TRANSPOSE: rotation = 90; break; case ORIENTATION_ROTATE_180: case ORIENTATION_FLIP_VERTICAL: rotation = 180; break; case ORIENTATION_ROTATE_270: case ORIENTATION_TRANSVERSE: rotation = 270; break; default: rotation = 0; } return rotation; }
Source:
START static int getExifTranslation(int orientation) { END int translation; switch (orientation) { case ORIENTATION_FLIP_HORIZONTAL: case ORIENTATION_FLIP_VERTICAL: case ORIENTATION_TRANSPOSE: case ORIENTATION_TRANSVERSE: translation = -1; break; default: translation = 1; } return translation; } private

Target:
private static int getExifTranslation(int orientation) { int translation; switch (orientation) { case ORIENTATION_FLIP_HORIZONTAL: case ORIENTATION_FLIP_VERTICAL: case ORIENTATION_TRANSPOSE: case ORIENTATION_TRANSVERSE: translation = -1; break; default: translation = 1; } return translation; }
Source:
public void cancelRequest(ImageView view) { // checkMain() is called from cancelExistingRequest() if (view == null) { START throw new AssertionError("view cannot be null."); END } cancelExistingRequest(view); } I'm pretty sure we use IllegalArgumentException for these everywhere else.

Target:
public void cancelRequest(ImageView view) { // checkMain() is called from cancelExistingRequest() if (view == null) { throw new IllegalArgumentException("view cannot be null."); } cancelExistingRequest(view); }
Source:
static int getFileExifRotation(Uri uri) throws IOException { ExifInterface exifInterface = new ExifInterface(uri.getPath()); int orientation = exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); START return orientation; END } nit: inline return with the line above.

Target:
static int getFileExifRotation(Uri uri) throws IOException { ExifInterface exifInterface = new ExifInterface(uri.getPath()); return exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); }
Source:
START public Builder transform(List<? extends Transformation> transformations) { END if (transformations == null) { throw new IllegalArgumentException("Transformation list must not be null."); } for (Object transformation : transformations) { transform((Transformation) transformation); } return this; } You want `List<? super Transformation>` here. Then you get `Transformation` objects without casting.

Target:
public Builder transform(List<? extends Transformation> transformations) { if (transformations == null) { throw new IllegalArgumentException("Transformation list must not be null."); } for (Transformation transformation : transformations) { transform(transformation); } return this; }
Source:
START static boolean isOfflineOnly(int networkPolicy) { END return (networkPolicy & NetworkPolicy.OFFLINE.index) == NetworkPolicy.OFFLINE.index; } These methods will need to be public, otherwise how do I know what the integer value passed to the `Downloader` means?

Target:
public static boolean isOfflineOnly(int networkPolicy) { return (networkPolicy & NetworkPolicy.OFFLINE.index) != 0; }
Source:
START @SuppressWarnings("UnusedDeclaration") public void setLoggingEnabled(boolean enabled) { END loggingEnabled = enabled; } Also really ugly. Suppressing warning should always come with a comment ``` java @SuppressWarnings("UnusedDeclaration") // Public API. ```

Target:
public void setLoggingEnabled(boolean enabled) { loggingEnabled = enabled; }
Source:
public RequestCreator memoryPolicy(MemoryPolicy policy, MemoryPolicy... additional) { if (policy == null) { throw new IllegalArgumentException("Memory policy cannot be null."); } this.memoryPolicy |= policy.index; START if (additional != null && additional.length > 0) { END for (MemoryPolicy memoryPolicy : additional) { if (memoryPolicy == null) { throw new IllegalArgumentException("Memory policy cannot be null."); } this.memoryPolicy |= memoryPolicy.index; } } return this; } If this was `null` it would be an explicit choice by the user. Reject it with an exception.

Target:
public RequestCreator memoryPolicy(MemoryPolicy policy, MemoryPolicy... additional) { if (policy == null) { throw new IllegalArgumentException("Memory policy cannot be null."); } this.memoryPolicy |= policy.index; if (additional == null) { throw new IllegalArgumentException("Memory policy cannot be null."); } if (additional.length > 0) { for (MemoryPolicy memoryPolicy : additional) { if (memoryPolicy == null) { throw new IllegalArgumentException("Memory policy cannot be null."); } this.memoryPolicy |= memoryPolicy.index; } } return this; }
Source:
START public void error() { END if (callback != null) { callback.onError(); } } This should be package scoped, not public.

Target:
@Override void error() { if (callback != null) { callback.onError(); } }
Source:
public Future<?> submit(Runnable task) { if (task == null) { START throw new NullPointerException(); END } PicassoFutureTask ftask = new PicassoFutureTask((BitmapHunter) task); execute(ftask); return ftask; } `AssertionError` instead? Would this ever really happen?

Target:
public Future<?> submit(Runnable task) { PicassoFutureTask ftask = new PicassoFutureTask((BitmapHunter) task); execute(ftask); return ftask; }
Source:
@Test public void forOverrideRequest() { Action action = mockAction(ASSET_KEY_1, ASSET_URI_1); AssetRequestHandler handler = new AssetRequestHandler(context); START List<RequestHandler> handlers = new ArrayList<RequestHandler>(Arrays.asList(handler)); END // must use non-mock constructor because that's where Picasso's list of handlers is created Picasso picasso = new Picasso(context, dispatcher, cache, null, null, handlers, stats, false, false); BitmapHunter hunter = forRequest(picasso, dispatcher, cache, stats, action); assertThat(hunter.requestHandler).isEqualTo(handler); } Don't need to wrap in `ArrayList`

Target:
@Test public void forOverrideRequest() { Action action = mockAction(ASSET_KEY_1, ASSET_URI_1); RequestHandler handler = new AssetRequestHandler(context); List<RequestHandler> handlers = Arrays.asList(handler); // Must use non-mock constructor because that is where Picasso's list of handlers is created. Picasso picasso = new Picasso(context, dispatcher, cache, null, null, handlers, stats, false, false); BitmapHunter hunter = forRequest(picasso, dispatcher, cache, stats, action); assertThat(hunter.requestHandler).isEqualTo(handler); }
Source:
@Override RemoteViewsTarget getTarget() { START return new RemoteViewsTarget(remoteViews, viewId); END } Cache this instance in a field? Or is it only called once?

Target:
@Override RemoteViewsTarget getTarget() { if (target == null) { target = new RemoteViewsTarget(remoteViews, viewId); } return target; }
Source:
public Builder(Context context) { if (context == null) { throw new IllegalArgumentException("Context must not be null."); } START if (!hasPermission(context, Manifest.permission.INTERNET)) { END throw new IllegalArgumentException("INTERNET permission is required."); } this.context = context.getApplicationContext(); } I think this is a bit too early. We support loading from many places other than the internet.

Target:
public Builder(Context context) { if (context == null) { throw new IllegalArgumentException("Context must not be null."); } this.context = context.getApplicationContext(); }
Source:
public NetworkBitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action, Downloader downloader) { super(picasso, dispatcher, cache, stats, action); this.downloader = downloader; this.retryCount = DEFAULT_RETRY_COUNT; if (!hasPermission(picasso.context, Manifest.permission.INTERNET)) { Picasso.HANDLER.post(new Runnable() { @Override public void run() { START throw new SecurityException("INTERNET permission is required."); END } }); } } `IllegalStateException`

Target:
public NetworkBitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action, Downloader downloader) { super(picasso, dispatcher, cache, stats, action); this.downloader = downloader; this.retryCount = DEFAULT_RETRY_COUNT; if (!hasPermission(picasso.context, Manifest.permission.INTERNET)) { Picasso.HANDLER.post(new Runnable() { @Override public void run() { throw new IllegalStateException("INTERNET permission is required."); } }); } }
Source:
public int hashCode() { int result = remoteViews.hashCode(); result = 31 * result + viewId; START return result; END } Inline method body to one line.

Target:
@Override public int hashCode() { return 31 * remoteViews.hashCode() + viewId; }
Source:
void detach(Action action) { START if (actions != null) { END actions.remove(action); } if (this.action == action) { this.action = null; } } And then `else if` this

Target:
void detach(Action action) { if (this.action == action) { this.action = null; } else if (actions != null) { actions.remove(action); } }
Source:
@Test public void attachMultipleRequests() throws Exception { Action action1 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); Action action2 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action1); assertThat(hunter.actions).isNull(); hunter.attach(action2); assertThat(hunter.actions).isNotNull(); START assertThat(hunter.actions).hasSize(1); END } chain with previous line's assertion

Target:
@Test public void attachMultipleRequests() throws Exception { Action action1 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); Action action2 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action1); assertThat(hunter.actions).isNull(); hunter.attach(action2); assertThat(hunter.actions).isNotNull().hasSize(1); }
Source:
static BitmapFactory.Options createBitmapOptions(Request data) { final boolean justBounds = data.hasSize(); final boolean hasConfig = data.config != null; START final boolean instantiate = hasConfig || justBounds; END // Only instantiate if we need it final BitmapFactory.Options options = instantiate ? new BitmapFactory.Options() : null; if (justBounds) { options.inJustDecodeBounds = true; } if (hasConfig) { options.inPreferredConfig = data.config; } return options; } This is only used once and isn't very descriptive. Can we do: ``` java BitmapFactory.Options options = null; if (hasConfig || justBounds) { options = new.. } ```

Target:
static BitmapFactory.Options createBitmapOptions(Request data) { final boolean justBounds = data.hasSize(); final boolean hasConfig = data.config != null; BitmapFactory.Options options = null; if (justBounds || hasConfig) { options = new BitmapFactory.Options(); options.inJustDecodeBounds = justBounds; if (hasConfig) { options.inPreferredConfig = data.config; } } return options; }
Source:
public int getOpacity() { Bitmap bm = bitmap; START return (bm == null || bm.hasAlpha() || bitmapPaint.getAlpha() < 255) END ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; } `bm` should never be `null`.

Target:
@Override public int getOpacity() { Bitmap bm = bitmap; return (bm.hasAlpha() || bitmapPaint.getAlpha() < 255) ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; }
Source:
@Override public void onReceive(Context context, Intent intent) { // On some versions of Android this may be called with a null Intent START if (null == intent) END return; String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } } Add `{` and `}`.

Target:
@Override public void onReceive(Context context, Intent intent) { // On some versions of Android this may be called with a null Intent if (null == intent) { return; } String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }
Source:
static long calculateDiskCacheSize(File dir) { long size = MIN_DISK_CACHE_SIZE; try { StatFs statFs = new StatFs(dir.getAbsolutePath()); START long available = statFs.getBlockCount() * statFs.getBlockSize(); END // Target 2% of the total space. size = available / 50; } catch (IllegalArgumentException ignored) { } // Bound inside min/max size for disk cache. return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE); } I think this still could overflow since it's coerced to a long at the end. You should cast one of the arguments to a `long` to ensure long multiplication is performed.

Target:
static long calculateDiskCacheSize(File dir) { long size = MIN_DISK_CACHE_SIZE; try { StatFs statFs = new StatFs(dir.getAbsolutePath()); long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize(); // Target 2% of the total space. size = available / 50; } catch (IllegalArgumentException ignored) { } // Bound inside min/max size for disk cache. return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE); }
Source:
Bitmap quickMemoryCacheCheck(String key) { Bitmap cached = cache.get(key); if (cached != null) { stats.dispatchCacheHit(); } else { START stats.dispatchCacheMiss(); END } return cached; } We need to change the method names to be more descriptive.

Target:
Bitmap quickMemoryCacheCheck(String key) { Bitmap cached = cache.get(key); if (cached != null) { stats.dispatchCacheHit(); } return cached; }
Source:
START @SuppressWarnings("UnusedDeclaration") public void shutdown() { END cache.clear(); cleanupThread.shutdown(); stats.shutdown(); dispatcher.shutdown(); if (this == singleton) { singleton = null; } shutdown = true; } What's with the suppression? Also what happens when you call shutdown twice?

Target:
public void shutdown() { if (shutdown) { return; } cache.clear(); cleanupThread.shutdown(); stats.shutdown(); dispatcher.shutdown(); if (this == singleton) { singleton = null; } shutdown = true; }
Source:
DeferredImageViewRequest(Picasso picasso, Uri uri, int resourceId, ImageView imageView, PicassoBitmapOptions options, List<Transformation> transformations, boolean skipCache, boolean noFade, int errorResId, Drawable errorDrawable, String key, Callback callback) { super(picasso, uri, resourceId, imageView, options, transformations, skipCache, noFade, errorResId, errorDrawable, key, callback); ViewTreeObserver observer = imageView.getViewTreeObserver(); START if (observer.isAlive()) { END observer.addOnGlobalLayoutListener(this); } } I don't think it will ever be false directly after you get it. It can however be when you try to remove it.

Target:
DeferredImageViewRequest(Picasso picasso, Uri uri, int resourceId, ImageView imageView, PicassoBitmapOptions options, List<Transformation> transformations, boolean skipCache, boolean noFade, int errorResId, Drawable errorDrawable, String key, Callback callback) { super(picasso, uri, resourceId, imageView, options, transformations, skipCache, noFade, errorResId, errorDrawable, key, callback); ViewTreeObserver observer = imageView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(this); }
Source:
NetworkBroadcastReceiver(Context context) { START this.connectivityManager = END (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); } If you drop the `this.` it should fit on one line!

Target:
NetworkBroadcastReceiver(Context context) { connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); }
Source:
static void closeQuietly(InputStream is) { START try { END if (is != null) { is.close(); } } catch (IOException ignored) { } } Nit: use `if (is == null) return;` instead.

Target:
static void closeQuietly(InputStream is) { if (is == null) { return; } try { is.close(); } catch (IOException ignored) { } }
Source:
Bitmap execute(Request request) throws IOException { BitmapHunter hunter = BitmapHunter.forRequest(context, this, dispatcher, request, downloader); START return hunter.hunt(); END } Inline `hunter`. `return BH.fR(..).hunt()`

Target:
Bitmap execute(Request request) throws IOException { return BitmapHunter.forRequest(context, this, dispatcher, request, downloader).hunt(); }
Source:
void submit(Request request) { Object target = request.getTarget(); if (target == null) return; cancelExistingRequest(target, request.uri); targetsToRequests.put(target, request); START requestSparseArray.put(request.getTargetRef().hashCode(), request); END request.future = service.submit(request); } this is very sketchy. Hash codes aren't unique

Target:
void submit(Request request) { Object target = request.getTarget(); if (target == null) return; cancelExistingRequest(target, request.uri); targetsToRequests.put(target, request); request.future = service.submit(request); }
Source:
Bitmap decodeAsset(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { START String path = uri.getPath().replaceFirst("/", ""); END AssetManager assets = context.getAssets(); if (bitmapOptions != null && bitmapOptions.inJustDecodeBounds) { BitmapFactory.decodeStream(assets.open(path), null, bitmapOptions); calculateInSampleSize(bitmapOptions); } return decodeStream(assets.open(path), bitmapOptions); } Use `.substring(1)` so that we don't have to allocate a new `String` instance.

Target:
Bitmap decodeAsset(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { String path = uri.getPath().substring(1); AssetManager assets = context.getAssets(); if (bitmapOptions != null && bitmapOptions.inJustDecodeBounds) { BitmapFactory.decodeStream(assets.open(path), null, bitmapOptions); calculateInSampleSize(bitmapOptions); } return decodeStream(assets.open(path), bitmapOptions); }
Source:
Bitmap decodeResource(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { START String path = uri.getPath().replaceFirst("/", ""); END try { return decodeResource(Integer.parseInt(path), bitmapOptions); } catch (NumberFormatException ignore) { throw new IOException("\"" + path + "\" isn't a valid resource id"); } } Use `.substring(1)` so that we don't have to allocate a new `String` instance.

Target:
Bitmap decodeResource(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { String path = uri.getPath().substring(1); try { return decodeResource(Integer.parseInt(path), bitmapOptions); } catch (NumberFormatException exception) { throw new IOException("\"" + path + "\" isn't a valid resource id", exception); } }
Source:
private void changeRegion(RateControlRegion region, long nowMs) { if (rateControlRegion == region) { return; } rateControlRegion = region; if (logger.isTraceEnabled()) { logger.trace(Logger.Category.BWE, diagnosticContext .makeTimeSeriesPoint("aimd_region", nowMs) .addKey("aimd", hashCode()) START .addField("value", region).toString()); END } } Are you sure? The trace() methods would have these signatures if we change String to Object: Object Object, Throwable Category, Object Category, Object, Throwable

Target:
private void changeRegion(RateControlRegion region, long nowMs) { if (rateControlRegion == region) { return; } rateControlRegion = region; if (logger.isTraceEnabled()) { logger.trace(Logger.Category.BWE, diagnosticContext .makeTimeSeriesPoint("aimd_region", nowMs) .addKey("aimd", hashCode()) .addField("value", region)); } }
Source:
public PacketTransformer getRTPTransformer() { START return this.retransmissionRequesterDelegate.getRTPTransformer(); END } I think this hooks up the delagate as the transformer, bypassing RetransmissionRequesterImpl#reverseTransform()

Target:
public PacketTransformer getRTPTransformer() { return this; }
Source:
public RawPacket reverseTransform(RawPacket pkt) { if (extensionId != -1) { RawPacket.HeaderExtension he = pkt.getHeaderExtension((byte) extensionId); if (he != null && he.getExtLength() == 2) { int seq = RTPUtils.readUint16AsInt( he.getBuffer(), he.getOffset() + 1); START packetReceived( END seq, pkt.getPayloadType(), pkt.isPacketMarked()); } } return pkt; } I know the pt is only used in logging, but it's implicitly converted from a byte to an int here

Target:
public RawPacket reverseTransform(RawPacket pkt) { if (extensionId != -1) { RawPacket.HeaderExtension he = pkt.getHeaderExtension((byte) extensionId); if (he != null && he.getExtLength() == 2) { int seq = RTPUtils.readUint16AsInt( he.getBuffer(), he.getOffset() + 1); packetReceived( seq, RawPacket.getPayloadType(pkt), pkt.isPacketMarked()); } } return pkt; }
Source:
private static String toHexString(byte b) { char[] hexes START = new char[] END { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; StringBuilder hexStringBuilder = new StringBuilder(2); hexStringBuilder.append(hexes[(b & 0xF0) >> 4]); hexStringBuilder.append(hexes[b & 0x0F]); return hexStringBuilder.toString(); } Can we make these static? Also, missing docs

Target:
private static String toHexString(byte b) { StringBuilder hexStringBuilder = new StringBuilder(2); hexStringBuilder.append(hexes[(b & 0xF0) >> 4]); hexStringBuilder.append(hexes[b & 0x0F]); return hexStringBuilder.toString(); }
Source:
public FrameDesc findFrameDesc(byte[] buf, int off, int len) { RawPacket pkt = new RawPacket(buf, off, len); START return findFrameDesc(pkt.getSSRCAsLong(), pkt.getTimestamp()); END } We could use the static versions of getSSRCAsLong and getTimestamp here

Target:
public FrameDesc findFrameDesc(byte[] buf, int off, int len) { return findFrameDesc( RawPacket.getSSRCAsLong(buf, off, len), RawPacket.getTimestamp(buf, off, len)); }
Source:
public byte getAbsSendTimeExtensionID(){ START return extensionID == -1 ? extensionID_for_debugging : extensionID ; END } Can we please remove extensionID_for_debugging? When testing with jitsi-meet abs-send-time is configured with id=3, so you can already test it.

Target:
public byte getAbsSendTimeExtensionID(){ return extensionID; }
Source:
START public <K,V> List<K> Keys(TreeMap<K,V> _map) END { ArrayList<K> keys = new ArrayList<K>(); for(Map.Entry<K,V> entry : _map.entrySet()) { keys.add(entry.getKey()); } return keys; } private

Target:
private <K,V> List<K> Keys(TreeMap<K,V> _map) { ArrayList<K> keys = new ArrayList<K>(); for(Map.Entry<K,V> entry : _map.entrySet()) { keys.add(entry.getKey()); } return keys; }
Source:
START long ConvertMsTo24Bits(long timeMs) END { long time24Bits = (long)(((timeMs << kAbsSendTimeFraction) + 500) / 1000) & 0x00FFFFFF; return time24Bits; } private

Target:
private long ConvertMsTo24Bits(long timeMs) { long time24Bits = (long)(((timeMs << kAbsSendTimeFraction) + 500) / 1000) & 0x00FFFFFF; return time24Bits; }
Source:
START boolean IsWithinClusterBounds(long sendDeltaMs, Cluster clusterAggregate) END { if(clusterAggregate.count == 0) { return true; } double clusterMean = clusterAggregate.sendMeanMs / (double)clusterAggregate.count; return Math.abs((double)sendDeltaMs - clusterMean) < 2.5f; } private

Target:
private boolean IsWithinClusterBounds(long sendDeltaMs, Cluster clusterAggregate) { if(clusterAggregate.count == 0) { return true; } double clusterMean = clusterAggregate.sendMeanMs / (double)clusterAggregate.count; return Math.abs((double)sendDeltaMs - clusterMean) < 2.5f; }
Source:
START void addCluster(List<Cluster> clusters, Cluster cluster) END { cluster.sendMeanMs /= (double)cluster.count; cluster.recvMeanMs /= (double)cluster.count; cluster.meanSize /= cluster.count; clusters.add(cluster); } private

Target:
private void addCluster(List<Cluster> clusters, Cluster cluster) { cluster.sendMeanMs /= (double)cluster.count; cluster.recvMeanMs /= (double)cluster.count; cluster.meanSize /= cluster.count; clusters.add(cluster); }
Source:
public boolean matches(long ssrc) { START if (primarySSRC != ssrc && rtxSSRC != ssrc) END { return false; } return true; } `return (primarySSRC == ssrc || rtxSSRC == ssrc)`?

Target:
public boolean matches(long ssrc) { return primarySSRC == ssrc || rtxSSRC == ssrc; }
Source:
public static boolean isKeyframe(ByteArrayBuffer baf) { START if (baf.getLength() < 2) END return false; // The data follows the one-byte header. byte b = baf.getBuffer()[baf.getOffset() + 1]; return (b & KF_MASK) != 0; } Are we sure a `null` never reaches this point?

Target:
public static boolean isKeyframe(ByteArrayBuffer baf) { if (baf == null || baf.getLength() < 2) { return false; } // The data follows the one-byte header. byte b = baf.getBuffer()[baf.getOffset() + 1]; return (b & KF_MASK) != 0; }
Source:
public RawPacket reverseTransform(RawPacket pkt) { START if (enabled && !closed && pkt != null && pkt.getVersion() == 2) END { incomingRawPacketCache.cachePacket(pkt); } return pkt; } We could get rid of the checks for pkt if we use the RTPPacketPredicate

Target:
public RawPacket reverseTransform(RawPacket pkt) { if (enabled && !closed) { incomingRawPacketCache.cachePacket(pkt); } return pkt; }
Source:
START public static boolean isPacketMarked(byte[] buffer, int offset, int length) END { return (buffer[offset + 1] & 0x80) != 0; } Can we please move this static method to the top of the file and maybe have it sanity check the length?

Target:
public static boolean isPacketMarked(byte[] buffer, int offset, int length) { if (buffer == null || buffer.length < offset + length || length < 2) { return false; } return (buffer[offset + 1] & 0x80) != 0; }
Source:
public KeyframeRequester(int mediaSenderSSRC) { super(FIR_RETRY_INTERVAL_MS); this.mediaSenderSSRC = mediaSenderSSRC; START this.sequenceNumber = new AtomicInteger(0); END this.remainingRetries = 0; } I'm going to make a very moot point here, I admit. But isn't that easier to read if you initialize sequenceNumber above given that it's final and doesn't get initialized with a constructor argument?

Target:
public KeyframeRequester(int mediaSenderSSRC) { super(FIR_RETRY_INTERVAL_MS); this.mediaSenderSSRC = mediaSenderSSRC; this.remainingRetries = 0; }
Source:
public Node node() { final Node castCache = Node.class.cast(this.cache); final Node answer; START final boolean isDocument = castCache instanceof Document; END if (isDocument) { answer = castCache.cloneNode(true); } else { answer = this.createImportedNode(castCache); } return answer; } @Suseika please inline `isDocument`

Target:
public Node node() { final Node castCache = Node.class.cast(this.cache); final Node answer; if (castCache instanceof Document) { answer = castCache.cloneNode(true); } else { answer = this.createImportedNode(castCache); } return answer; }
Source:
private Node createImportedNode(final Node node) { START assert !(node instanceof Document); END final Document document; try { document = DFACTORY.newDocumentBuilder().newDocument(); } catch (final ParserConfigurationException ex) { throw new IllegalStateException(ex); } final Node imported = document.importNode(node, true); document.appendChild(imported); return imported; } @Suseika please remove `assert`, we don't use them

Target:
private Node createImportedNode(final Node node) { final Document document; try { document = DFACTORY.newDocumentBuilder().newDocument(); } catch (final ParserConfigurationException ex) { throw new IllegalStateException(ex); } final Node imported = document.importNode(node, true); document.appendChild(imported); return imported; }
Source:
public String getStringData() { try { return IOUtils.toString(this.stream); } catch (final IOException exception) { START throw new RuntimeException("Unable to read input", exception); END } } why throw RuntimeException? Throw IllegalArgumentException and remove SuppressWarnings

Target:
public String getStringData() { try { return IOUtils.toString(this.stream); } catch (final IOException exception) { throw new IllegalArgumentException( "Unable to read input", exception ); } }
Source:
public String toString() { START return prependIfDeerInstance("Title-matching Generator"); END } Just pass in the `name` variable to this

Target:
public String toString() { return name; }
Source:
START public String sanitize(String title) { END return removeCommonPrefixes(titleTransform.apply(title) .replaceAll(" & ", " and ") .replaceAll("[^\\d\\w\\s]", "").toLowerCase()); } Does this need to be public?

Target:
private String sanitize(String title) { return removeCommonPrefixes(titleTransform.apply(title) .replaceAll(" & ", " and ") .replaceAll("[^\\d\\w\\s]", "").toLowerCase()); }
Source:
private AliasResolvingEquivalenceGenerator(Builder builder) { this.resolver = checkNotNull(builder.resolver); this.publishers = checkNotNull(builder.publishers); this.lookupEntryStore = checkNotNull(builder.lookupEntryStore); this.namespacesSet = checkNamespacesSet(checkNotNull(builder.namespacesSet)); this.aliasMatchingScore = checkNotNull(builder.aliasMatchingScore); START this.includeUnpublishedContent = builder.includeUnpublishedContent; END this.cls = checkNotNull(builder.cls); } I'd add a checkNotNull here and make the builder field a `Boolean`. This will make sure someone sets the field instead of it defaulting to false.

Target:
private AliasResolvingEquivalenceGenerator(Builder builder) { this.resolver = checkNotNull(builder.resolver); this.publishers = checkNotNull(builder.publishers); this.lookupEntryStore = checkNotNull(builder.lookupEntryStore); this.namespacesSet = checkNamespacesSet(builder.namespacesSet); this.aliasMatchingScore = checkNotNull(builder.aliasMatchingScore); this.includeUnpublishedContent = checkNotNull(builder.includeUnpublishedContent); this.cls = checkNotNull(builder.cls); }
Source:
public void testRealBbcTxlogRegularExamples() { assertTxlogNitroScore("THE HOUSING ENFORCERS", "Episode 2", "The Housing Enforcers", scoreOnMatch); //will likely add equiv rules for this in future START assertTxlogNitroScore("!MPOSSIBLE", "Episode 7", "Impossible", scoreOnMismatch); END } this should equiv

Target:
public void testRealBbcTxlogRegularExamples() { assertTxlogNitroScore("THE HOUSING ENFORCERS", "Episode 2", "The Housing Enforcers", scoreOnMatch); }
Source:
private ContentEquivalenceUpdateTask publisherUpdateTask(final Publisher... publishers) { return new ContentEquivalenceUpdateTask( START (SelectedContentLister) contentLister, END contentResolver, getNewDefaultExecutor(), progressStore(), equivUpdater, ignored ).forPublishers(publishers); } This cast feels a bit out of place but I don't really have a better suggestion - maybe where this is autowired we could add a separate bean that has a return type of SelectedContentLister that returns the same object as the normal ContentLister bean?

Target:
private ContentEquivalenceUpdateTask publisherUpdateTask(final Publisher... publishers) { return new ContentEquivalenceUpdateTask( contentLister, contentResolver, getNewDefaultExecutor(), progressStore(), equivUpdater, ignored ).forPublishers(publishers); }
Source:
START @Override public ScoredCandidates<Item> score(Item subject, Set<? extends Item> candidates, END ResultDescription desc) { DefaultScoredCandidates.Builder<Item> equivalents = DefaultScoredCandidates.fromSource(NAME); for (Item candidate : candidates) { equivalents.addEquivalent(candidate, score(subject, candidate)); } return equivalents.build(); } style: put @override on the line above for method declarations, and if your parameters make the line too long list all parameters line by line e.g. public ScoredCandidates<Item> score( Item subject, Set<? extends Item> candidates, ResultDescription desc ) { ....

Target:
public ScoredCandidates<Item> score( Item subject, Set<? extends Item> candidates, ResultDescription desc) { DefaultScoredCandidates.Builder<Item> equivalents = DefaultScoredCandidates.fromSource(NAME); candidates.forEach(candidate -> equivalents.addEquivalent(candidate, score(subject, candidate))); return equivalents.build(); }
Source:
START @Override public String toString(){ END return NAME; } style: stick this at the bottom of the class for neatness, and as above don't forget to move the @override to the line above

Target:
public String toString(){ return NAME; }
Source:
public boolean contains(@Nullable ServiceId serviceId) { return serviceId != null && serviceId.equals(serviceIdMap.get(serviceId.getId())); START } END There are different ServiceId objects with the same serviceId field? e.g. that contain different aliases?

Target:
public boolean contains(@Nullable ServiceId serviceId) { return serviceId != null && serviceIdMap.get(serviceId.getId()).contains(serviceId); }
Source:
private EquivalenceUpdatingWorker equivUpdatingWorker() { return new EquivalenceUpdatingWorker( contentResolver, lookupStore, equivalenceResultStore, equivUpdater, Predicates.or(ImmutableList.<Predicate<? super Content>>of( sourceIsIn( BBC_REDUX, YOUVIEW, YOUVIEW_STAGE, YOUVIEW_BT, YOUVIEW_BT_STAGE, BETTY, BT_TVE_VOD, BT_VOD ), Predicates.and( Predicates.instanceOf(Container.class), sourceIsIn( BBC, C4_PMLSD, ITV, FIVE, BBC_REDUX, ITUNES, RADIO_TIMES, LOVEFILM, TALK_TALK, YOUVIEW, NETFLIX, START BBC_NITRO END ) ) )) ); } Why have you only added it to the container part of the or?

Target:
private EquivalenceUpdatingWorker equivUpdatingWorker() { return new EquivalenceUpdatingWorker( contentResolver, lookupStore, equivalenceResultStore, equivUpdater, Predicates.or(ImmutableList.<Predicate<? super Content>>of( sourceIsIn( BBC_REDUX, YOUVIEW, YOUVIEW_STAGE, YOUVIEW_BT, YOUVIEW_BT_STAGE, BETTY, BT_TVE_VOD, BT_VOD, BBC_NITRO ), Predicates.and( Predicates.instanceOf(Container.class), sourceIsIn( BBC, C4_PMLSD, ITV, FIVE, BBC_REDUX, ITUNES, RADIO_TIMES, LOVEFILM, TALK_TALK, YOUVIEW, NETFLIX, BBC_NITRO ) ) )) ); }
Source:
public EquivalenceUpdatingWorker(ContentResolver contentResolver, LookupEntryStore entryStore, EquivalenceResultStore resultStore, EquivalenceUpdater<Content> equivUpdater, Predicate<Content> filter) { this.contentResolver = checkNotNull(contentResolver); this.entryStore = checkNotNull(entryStore); this.resultStore = checkNotNull(resultStore); this.equivUpdater = checkNotNull(equivUpdater); this.filter = checkNotNull(filter); this.telescopeProxy = OwlTelescopeReporter.create( START OwlTelescopeReporters.EQUIVALENCE_UPDATING_WORKER, END Event.Type.EQUIVALENCE ); } Doesn't this mean you'll have a single reporter for the whole life of the worker (and a single reporter means a single task I think?) I thought it had been talked about having a new task every hour or similar?

Target:
public EquivalenceUpdatingWorker(ContentResolver contentResolver, LookupEntryStore entryStore, EquivalenceResultStore resultStore, EquivalenceUpdater<Content> equivUpdater, Predicate<Content> filter) { this.contentResolver = checkNotNull(contentResolver); this.entryStore = checkNotNull(entryStore); this.resultStore = checkNotNull(resultStore); this.equivUpdater = checkNotNull(equivUpdater); this.filter = checkNotNull(filter); }
Source:
private void rotateTelescope() { if (telescope == null) { telescope = OwlTelescopeReporter.create( OwlTelescopeReporters.EQUIVALENCE_UPDATING_WORKER, Event.Type.EQUIVALENCE ); telescope.startReporting(); START timeSinceTelescopeRotated = DateTime.now(); END } else if (timeSinceTelescopeRotated.plusHours(1).isBeforeNow()) { telescope.endReporting(); telescope.startReporting(); } } I'd personally do a 'timeToNextRotate' method, then you don't need the +1 each time, but that's just me nitpicking

Target:
private void rotateTelescope() { if (telescope == null) { telescope = OwlTelescopeReporter.create( OwlTelescopeReporters.EQUIVALENCE_UPDATING_WORKER, Event.Type.EQUIVALENCE ); telescope.startReporting(); timeSinceTelescopeRotated = DateTime.now(); } else if (timeSinceTelescopeRotated.plusHours(1).isBeforeNow()) { telescope.endReporting(); telescope = OwlTelescopeReporter.create( OwlTelescopeReporters.EQUIVALENCE_UPDATING_WORKER, Event.Type.EQUIVALENCE ); telescope.startReporting(); timeSinceTelescopeRotated = DateTime.now(); } }