auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START void close() { END writeQueue.add(WriteOperation.SHUTDOWN); writerService.shutdown(); } Probably won't be used, but you should implement AutoCloseable, since you implement close() anyway.

Target:
public void close() { writeQueue.add(WriteOperation.SHUTDOWN); writerService.shutdown(); }
Source:
private void completeInner() { // A group is removed, so check if we need to call `unsubscribe` if (WIP_FOR_UNSUBSCRIBE_UPDATER.decrementAndGet(this) == 0) { // It means `groups.isEmpty() && child.isUnsubscribed()` is true unsubscribe(); } // if we have no outstanding groups (all completed or unsubscribe) and terminated on outer START if (groups.isEmpty() && terminated == TERMINATED_WITH_COMPLETED) { END // completionEmitted ensures we only emit onCompleted once if (COMPLETION_EMITTED_UPDATER.compareAndSet(this, 0, 1)) { if (!child.isUnsubscribed()) { child.onCompleted(); } } } } Wouldn't this be an `if/else`? If we just `unsubscribed` in the previous lines I don't think we should ever go through this flow.

Target:
private void completeInner() { // A group is removed, so check if we need to call `unsubscribe` if (WIP_FOR_UNSUBSCRIBE_UPDATER.decrementAndGet(this) == 0) { // It means `groups.isEmpty() && child.isUnsubscribed()` is true unsubscribe(); } else if (groups.isEmpty() && terminated == TERMINATED_WITH_COMPLETED) { // if we have no outstanding groups (all completed or unsubscribe) and terminated on outer // completionEmitted ensures we only emit onCompleted once if (COMPLETION_EMITTED_UPDATER.compareAndSet(this, 0, 1)) { child.onCompleted(); } } }
Source:
protected boolean startError() { if (errorCount == 0) { START logger.error("Found one or more vector errors from " + opName); END } errorCount++; if (errorCount >= MAX_ERRORS) { return false; } return true; } ```suggestion logger.error("Found one or more vector errors from {}", opName); ```

Target:
protected boolean startError() { if (errorCount == 0) { warn("Found one or more vector errors from " + opName); } errorCount++; if (errorCount >= MAX_ERRORS) { return false; } return true; }
Source:
protected static List<Integer> grep(File fileName, String regexp, List<String> resultLines) { List<Integer> resultLineNumbers = new ArrayList<>(); Reader reader = null; try { reader = new FileReader(fileName); resultLineNumbers = grep(reader, regexp, resultLines); }catch (IOException e) { e.printStackTrace(); } finally { START closeQuietly(reader); END } return resultLineNumbers; } We use Java7, so you should use the try-with-resources feature.

Target:
protected static List<Integer> grep(File fileName, String regexp, List<String> resultLines) { List<Integer> resultLineNumbers = new ArrayList<>(); try(Reader reader = new FileReader(fileName)) { resultLineNumbers = grep(reader, regexp, resultLines); } catch (IOException e) { e.printStackTrace(); } return resultLineNumbers; }
Source:
private static void navigate(final Activity activity, final String destName, final String destCode, final Geopoint coords) { START Intent launchIntent = new Intent(INTENT_ACTION); END launchIntent.putExtra(Intents.EXTRA_NAME, destName); launchIntent.putExtra(Intents.EXTRA_GEOCODE, destCode); launchIntent.putExtra(Intents.EXTRA_LATITUDE, coords.getLatitude()); launchIntent.putExtra(Intents.EXTRA_LONGITUDE, coords.getLongitude()); activity.startService(launchIntent); } Missing `final` (was indicated on the previous patch as well).

Target:
private static void navigate(final Activity activity, final String destName, final String destCode, final Geopoint coords) { final Intent launchIntent = new Intent(INTENT_ACTION); launchIntent.putExtra(Intents.EXTRA_NAME, destName) .putExtra(Intents.EXTRA_GEOCODE, destCode) .putExtra(Intents.EXTRA_LATITUDE, coords.getLatitude()) .putExtra(Intents.EXTRA_LONGITUDE, coords.getLongitude()); activity.startService(launchIntent); }
Source:
public TestMediaWikiApiImageFetchingStrategy(Map<String, String> serverContent) { START Preconditions.checkNotNull(serverContent, END "Please specify some server content for images used during the tests. See: TestMediaWikiApiImageFetchingStrategy#serverContent"); this.serverContent = ImmutableMap.copyOf(serverContent); } static import

Target:
public TestMediaWikiApiImageFetchingStrategy(Map<String, String> serverContent) { checkNotNull(serverContent, "Please specify some server content for images used during the tests. See: TestMediaWikiApiImageFetchingStrategy#serverContent"); this.serverContent = ImmutableMap.copyOf(serverContent); }
Source:
private static boolean shouldCreateMyHandler(PsiElement element) { if (element instanceof LeafPsiElement) { LeafPsiElement leaf = (LeafPsiElement)element; return leaf.getElementType() == GoTypes.RETURN || leaf.getElementType() == GoTypes.FUNC || isPanicCall(leaf); } START else { END return false; } } A redundant else statement

Target:
private static boolean shouldCreateMyHandler(PsiElement element) { if (element instanceof LeafPsiElement) { LeafPsiElement leaf = (LeafPsiElement)element; return leaf.getElementType() == GoTypes.RETURN || leaf.getElementType() == GoTypes.FUNC || isPanicCall(leaf); } return false; }
Source:
START private void cancelRxCommands() { END for (CommandHandle commandHandle : fRxCommands.values()) { if (commandHandle.getRequestMonitor() == null) continue; commandHandle.getRequestMonitor().setStatus(genStatus( "Connection is shut down")); //$NON-NLS-1$ commandHandle.getRequestMonitor().done(); } fRxCommands.clear(); } Wouldn't it be safer to make this method synchronized?

Target:
private synchronized void cancelRxCommands() { for (CommandHandle commandHandle : fRxCommands.values()) { if (commandHandle.getRequestMonitor() == null) continue; commandHandle.getRequestMonitor().setStatus(genStatus( "Connection is shut down")); //$NON-NLS-1$ commandHandle.getRequestMonitor().done(); } fRxCommands.clear(); }
Source:
private Supplier<StorageStatement> storeStatementSupplier( NeoStores neoStores ) { Supplier<IndexReaderFactory> indexReaderFactory = () -> new IndexReaderFactory.Caching( indexingService ); LockService lockService = takePropertyReadLocks ? this.lockService : NO_LOCK_SERVICE; return new Supplier<StorageStatement>() { @Override public StorageStatement get() { return new StoreStatement( neoStores, indexReaderFactory, labelScanStore::newReader, lockService, allocateCommandCreationContext() ); } START }; END } No need to expand the lambda

Target:
private Supplier<StorageStatement> storeStatementSupplier( NeoStores neoStores ) { Supplier<IndexReaderFactory> indexReaderFactory = () -> new IndexReaderFactory.Caching( indexingService ); LockService lockService = takePropertyReadLocks ? this.lockService : NO_LOCK_SERVICE; return () -> new StoreStatement( neoStores, indexReaderFactory, labelScanStore::newReader, lockService, allocateCommandCreationContext() ); }
Source:
START public static byte[] convertBoolArrayToByteArray(boolean[] boolArr) { END byte[] byteArr = new byte[(boolArr.length + 7) / 8]; for (int i = 0; i < byteArr.length; i++) { byteArr[i] = readByte(boolArr, 8 * i); } return byteArr; } Can be package-private?

Target:
static byte[] convertBoolArrayToByteArray(boolean[] boolArr) { byte[] byteArr = new byte[(boolArr.length + 7) / 8]; for (int i = 0; i < byteArr.length; i++) { byteArr[i] = readByte(boolArr, 8 * i); } return byteArr; }
Source:
public void all_composed_assertions_should_pass() { SoftAssertions delegate = new SoftAssertions(); delegate.assertThat(1).isEqualTo(1); delegate.assertAll(); softly.assertThat(1).isEqualTo(1); START softly.assertThat(Lists.newArrayList(1, 2)).containsOnly(1, 2); END softly.assertAlso(delegate); softly.assertAll(); assertThat(softly.wasSuccess()).isTrue(); } Minor: use AssertJ `org.assertj.core.util.List.list` and static import for readability.

Target:
public void all_composed_assertions_should_pass() { // GIVEN SoftAssertions delegate = new SoftAssertions(); delegate.assertThat(1).isEqualTo(1); delegate.assertAll(); softly.assertThat(1).isEqualTo(1); softly.assertThat(list(1, 2)).containsOnly(1, 2); // WHEN softly.assertAlso(delegate); softly.assertAll(); // THEN assertThat(softly.wasSuccess()).isTrue(); }
Source:
public void viewInfoUpdated() { START this.reinitialize(); END } * Why is super.reinitialize() not public? * If you want super.reinitialize() protected, this class could "open it up" instead of defining a new method: @Override public void reinitialize() { super.reinitialize(); }

Target:
public void viewInfoUpdated() { reinitialize(); }
Source:
START public JSONPointer(List<String> refTokens) { END this.refTokens = refTokens; } This should either be a **protected/private/or default** constructor, and the **List** should be copied so the Pointer can't be modified outside of the class. ``` java this.refTokens = refTokens.clone(); ``` as it is now, I could do this: ``` java Builder b = JSONPointer.builder().append("key1"); JSONPointer jp1 = b.build(); b.append("key2"); JSONPointer jp2 = b.build(); if(jp1.toString().equals(jp2.toString()){ throw new Exception("Oops, my pointers are sharing a backing array"); } ```

Target:
public JSONPointer(List<String> refTokens) { this.refTokens = new ArrayList<String>(refTokens); }
Source:
public VM() { mVmStatic = new VmStatic(); mVmDynamic = new VmDynamic(); mVmStatistics = new VmStatistics(); START mVmStatic.setImages(new java.util.ArrayList<DiskImage>()); END mVmStatic.setInterfaces(new java.util.ArrayList<VmNetworkInterface>()); mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; } coudl be just ArrayList since now it is imported ^^ vv

Target:
public VM() { mVmStatic = new VmStatic(); mVmDynamic = new VmDynamic(); mVmStatistics = new VmStatistics(); mVmStatic.setImages(new ArrayList<DiskImage>()); mVmStatic.setInterfaces(new ArrayList<VmNetworkInterface>()); mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; }
Source:
START long consumerLag() { END return consumerLag; } Would suggest to make it `private`.

Target:
private long consumerLag() { return consumerLag; }
Source:
public RegexGroupFilter(final int groupIdx) { if (groupIdx < 1) START throw new IllegalArgumentException(MessageFormat.format(HttpServerText.get().invalidIndex, groupIdx)); END this.groupIdx = groupIdx - 1; } In most other places we suppress boxing warnings by manually boxing in the code with Integer.valueOf() around the expression. This is especially true in MessageFormat.format invocations, which are very common in our error paths. I think that is the general approach preferred within JGit.

Target:
public RegexGroupFilter(final int groupIdx) { if (groupIdx < 1) throw new IllegalArgumentException(MessageFormat.format( HttpServerText.get().invalidIndex, valueOf(groupIdx))); this.groupIdx = groupIdx - 1; }
Source:
public void testChunkFillingBlobSizeMultipleOfChunkSize() throws Exception { START blobSize = chunkSize * random.nextInt(10) + 1; END fillChunksAndAssertSuccess(); } missing braces ? `blobSize` can end up to be 1 if `random.nextInt(10)` returns 0.

Target:
public void testChunkFillingBlobSizeMultipleOfChunkSize() throws Exception { blobSize = chunkSize * (random.nextInt(10) + 1); fillChunksAndAssertSuccess(); }
Source:
START EapAkaAttributeFactory() END Suggest protected to signal that this is for the subclass

Target:
protected EapAkaAttributeFactory()
Source:
public byte[] toByteArray() { START return ByteBuffer.allocate(8).putLong(valueLong).array(); END } I wouldn't implement this (just return null). A long has a fixed size, and we can use putLong() in HTInterval to write them to the file. This method was more for string, structs, etc. that we want to serialize.

Target:
public byte[] toByteArray() { return null; }
Source:
public String getModeName() { String header = getHeader(); START return header.substring(0, header.indexOf(' ')); END } there is no other way of getting article name?

Target:
private String getModeName() { String header = getHeader(); return header.substring(0, header.indexOf(' ')); }
Source:
public int hashCode() { int result = bitSet; result = 31 * result + bitSet; START return result; END } @vilchik-elena Why not simply returning `bitSet`?

Target:
public int hashCode() { return bitSet; }
Source:
void setUnresolvedCompact(boolean unresolvedCompact) { this.unresolvedCompact = unresolvedCompact; if (outer != null) { START outer.setUnresolvedCompact(true); END } } Not required

Target:
void setUnresolvedCompact(boolean unresolvedCompact) { this.unresolvedCompact = unresolvedCompact; }
Source:
public static void afterClass() throws Exception { if (sLocalAlluxioJobCluster != null) { sLocalAlluxioJobCluster.stop(); } START sFileSystem.close(); END } hrmmm, is this required? Will this happen already with the cluster teardown? And, is there redundant closing with the `after()` call?

Target:
public static void afterClass() throws Exception { if (sLocalAlluxioJobCluster != null) { sLocalAlluxioJobCluster.stop(); } }
Source:
public void testTrimLongSuffix() throws Exception { START String longValue = "12345"; END assertThat(LiteralUtils.trimLongSuffix(longValue)).isEqualTo(longValue); assertThat(LiteralUtils.trimLongSuffix(longValue + "l")).isEqualTo(longValue); assertThat(LiteralUtils.trimLongSuffix(longValue + "L")).isEqualTo(longValue); } What If I give the empty string as an input of that method ?

Target:
public void testTrimLongSuffix() throws Exception { assertThat(LiteralUtils.trimLongSuffix(null)).isEqualTo(null); assertThat(LiteralUtils.trimLongSuffix("")).isEqualTo(""); String longValue = "12345"; assertThat(LiteralUtils.trimLongSuffix(longValue)).isEqualTo(longValue); assertThat(LiteralUtils.trimLongSuffix(longValue + "l")).isEqualTo(longValue); assertThat(LiteralUtils.trimLongSuffix(longValue + "L")).isEqualTo(longValue); }
Source:
public Map<TableScanNode, Void> visitTableScan(TableScanNode node, Void context) { START Map<TableScanNode, Void> ret = new IdentityHashMap<>(); END ret.put(node, null); return ret; } spell out ret

Target:
public Map<TableScanNode, Void> visitTableScan(TableScanNode node, Void context) { Map<TableScanNode, Void> result = new IdentityHashMap<>(); result.put(node, null); return result; }
Source:
public int getStreamIndex() { START return streamIndex; END } should not be this private?

Target:
private int getStreamIndex() { return streamIndex; }
Source:
public Void call() throws IOException { if (task == null) { throw new IOException("The callable " + this + " has been serialized somehow, but it is actually not serializable"); } try { return task.call(); START } catch (Exception ex) { END if (ex instanceof IOException) { throw (IOException)ex; } throw new IOException(ex); } } simpler: ``` } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } ```

Target:
public Void call() throws IOException { if (task == null) { throw new IOException("The callable " + this + " has been serialized somehow, but it is actually not serializable"); } try { return task.call(); } catch (IOException ex) { throw ex; } catch (Exception ex) { throw new IOException(ex); } }
Source:
public static File task(File projectDir, String dstName) throws IOException { File dstDir = new File(projectDir.getParent(), FileMetaDataExtractor.encodeSpecialCharsForFileSystem(dstName)); try { if (projectDir.renameTo(dstDir) && XstreamSerializer.renameProject(new File(dstDir, CODE_XML_FILE_NAME), dstName)) { return dstDir; } else { throw new IOException("Cannot rename project directory " + projectDir.getAbsolutePath() + " to " + dstName); } } catch (IOException e) { START throw e; END } } please remove the `try { .. } catch ( .. )` block altogether now.

Target:
public static File task(File projectDir, String dstName) throws IOException { File dstDir = new File(projectDir.getParent(), FileMetaDataExtractor.encodeSpecialCharsForFileSystem(dstName)); if (projectDir.renameTo(dstDir) && XstreamSerializer.renameProject(new File(dstDir, CODE_XML_FILE_NAME), dstName)) { return dstDir; } else { throw new IOException("Cannot rename project directory " + projectDir.getAbsolutePath() + " to " + dstName); } }
Source:
private StockOperation createOperation(StockOperation operation, InventoryStockTake delegate) { operation.setStatus(StockOperationStatus.NEW); START IStockOperationType operationType = WellKnownOperationTypes.getAdjustment(); END operation.setInstanceType(operationType); Stockroom stockroom; stockroom = delegate.getStockroom(); operation.setSource(stockroom); operation.setOperationNumber(delegate.getOperationNumber()); Date dNow = new Date(); operation.setOperationDate(dNow); operation.setItems(createOperationsItemSet(operation, delegate.getItemStockSummaryList())); return operation; } Remove these extra variables that aren't used except in a setter.

Target:
private StockOperation createOperation(StockOperation operation, InventoryStockTake delegate) { operation.setStatus(StockOperationStatus.NEW); IStockOperationType operationType = WellKnownOperationTypes.getAdjustment(); operation.setInstanceType(operationType); Stockroom stockroom = delegate.getStockroom(); operation.setSource(stockroom); operation.setOperationNumber(delegate.getOperationNumber()); operation.setOperationDate(new Date()); operation.setItems(createOperationsItemSet(operation, delegate.getItemStockSummaryList())); return operation; }
Source:
START public MarshallingResponseBuilder messages(List<MarshallingMessage> messages) { END this.messages.addAll(messages); return this; } not sure if there's a reason for removing the parametrized type MarshallingResponseBuilder<T>, see that when setting the messages you loose the type. The other methods state, addMessage, and resout has the type.

Target:
public MarshallingResponseBuilder<T> messages(List<MarshallingMessage> messages) { this.messages.addAll(messages); return this; }
Source:
START long getTokenCount() { END return tokens.get(); } nit: I think we generally prefer to explicitly state the access modifiers.

Target:
protected long getTokenCount() { return tokens.get(); }
Source:
public V getOrFill(K key, Callable<V> callable) { try { return callable.call() ; } catch (Exception e) { START e.printStackTrace(); END return null; } } `printStackTrace()`? Isn't it better to use a logger?

Target:
public V getOrFill(K key, Callable<V> callable) { try { return callable.call() ; } catch (Exception e) { return null; } }
Source:
void setUpHomeMenuIcon() { drawerIconDot.setVisibility(AccountUtil.isLoggedIn() && Prefs.showActionFeedIndicator() && ReleaseUtil.isPreBetaRelease() START && Prefs.getTotalUserDescriptionsEdited() >= ACTION_DESCRIPTION_EDIT_UNLOCK_THRESHOLD ? END VISIBLE : GONE); } This is too much specific logic that is spilling over into a very general function. The only thing on which this needs to depend is Prefs.showActionFeedIndicator(), which it already does.

Target:
void setUpHomeMenuIcon() { drawerIconDot.setVisibility(AccountUtil.isLoggedIn() && Prefs.showActionFeedIndicator() && ReleaseUtil.isPreBetaRelease() ? VISIBLE : GONE); }
Source:
public static int maxMemorySizeWithHotplugInMb(int osId, Version compatibilityVersion) { final ConfigValues configValue = getMaxMemConfigValueByOsId(osId); return Config.<Integer>getValue( configValue, START (compatibilityVersion != null) ? compatibilityVersion.getValue() : Version.getLast().getValue() END ); } Please remove unnecessary brackets: return Config.<Integer>getValue( configValue, compatibilityVersion != null ? compatibilityVersion.getValue() : Version.getLast().getValue()

Target:
public static int maxMemorySizeWithHotplugInMb(int osId, Version compatibilityVersion) { final ConfigValues configValue = getMaxMemConfigValueByOsId(osId); return Config.<Integer>getValue( configValue, compatibilityVersion != null ? compatibilityVersion.getValue() : Version.getLast().getValue() ); }
Source:
public void getPropertiesUpdatePlace(final TrendsPlace place){ CommonDataService.Async.getInstance().getWebClientProperties(new AsyncCallback<WebClientProperties>() { @Override public void onFailure(Throwable caught) { new ExceptionPanel("Default properties will be used. Exception while properties retrieving: " + caught.getMessage()); updatePlace(place); } @Override public void onSuccess(WebClientProperties result) { webClientProperties = result; START updateTagFilter(); END updatePlace(place); } }); } this is incorrect place for command

Target:
public void getPropertiesUpdatePlace(final TrendsPlace place){ CommonDataService.Async.getInstance().getWebClientProperties(new AsyncCallback<WebClientProperties>() { @Override public void onFailure(Throwable caught) { new ExceptionPanel("Default properties will be used. Exception while properties retrieving: " + caught.getMessage()); updatePlace(place); } @Override public void onSuccess(WebClientProperties result) { webClientProperties = result; updatePlace(place); } }); }
Source:
Context prepareDefaultContext(boolean parseAsFlume) { // Prepares a default context with Kafka Server Properties Context context = new Context(); context.put(BOOTSTRAP_SERVERS_CONFIG, testUtil.getKafkaServerUrl()); context.put(PARSE_AS_FLUME_EVENT, String.valueOf(parseAsFlume)); START context.put("offsets.topic.replication.factor", "1"); END context.put(TOPIC_CONFIG, topic); return context; } What does this change bring? Did we need this to get the test working?

Target:
Context prepareDefaultContext(boolean parseAsFlume) { // Prepares a default context with Kafka Server Properties Context context = new Context(); context.put(BOOTSTRAP_SERVERS_CONFIG, testUtil.getKafkaServerUrl()); context.put(PARSE_AS_FLUME_EVENT, String.valueOf(parseAsFlume)); context.put(TOPIC_CONFIG, topic); return context; }
Source:
private String getDatacenter(InetAddressAndPort endpoint) { if (peersA.contains(endpoint)) return "datacenterA"; if (peersB.contains(endpoint)) return "datacenterB"; else if (peersC.contains(endpoint)) return "datacenterC"; START return "NA"; END } Should probably return null

Target:
private String getDatacenter(InetAddressAndPort endpoint) { if (peersA.contains(endpoint)) return "datacenterA"; if (peersB.contains(endpoint)) return "datacenterB"; else if (peersC.contains(endpoint)) return "datacenterC"; return null; }
Source:
private DateTimeFormatter getFormatter(){ switch (this){ case days: return DateTimeFormat.forPattern("yyyy-MM-dd"); case months: return DateTimeFormat.forPattern("yyyy/MM"); case weeks: return DateTimeFormat.forPattern("yyyy/ww"); case years: return DateTimeFormat.forPattern("yyyy"); case quarters: // has to be extended by the calling function return DateTimeFormat.forPattern("yyyy"); case simpleSum: START break; END } return null; } Constant simpleSum could even removed as this constant is never used outside this class.

Target:
private DateTimeFormatter getFormatter(){ switch (this){ case days: return DateTimeFormat.forPattern("yyyy-MM-dd"); case months: return DateTimeFormat.forPattern("yyyy/MM"); case weeks: return DateTimeFormat.forPattern("yyyy/ww"); case years: return DateTimeFormat.forPattern("yyyy"); case quarters: // has to be extended by the calling function return DateTimeFormat.forPattern("yyyy"); } return null; }
Source:
public void setDefaultProperties(Map<String, Object> defaultProperties) { START this.defaultProperties = new HashMap<>(); END for (Object key : Collections.list(defaultProperties.propertyNames())) { this.defaultProperties.put((String) key, defaultProperties.get(key)); } } I think this could be a one liner: ```java this.defaultProperties = new HashMap<>(defaultProperties); ```

Target:
public void setDefaultProperties(Map<String, Object> defaultProperties) { this.defaultProperties = new HashMap<>(defaultProperties); }
Source:
START protected END MapSqlParameterSource createVnodeToPnodeParametersMapper( Integer pinnedIndex, Guid vNodeId) { return getCustomMapSqlParameterSource() .addValue("id", Guid.newGuid()) .addValue("vm_numa_node_id", vNodeId) .addValue("vds_numa_node_index", pinnedIndex); } Can this be private?

Target:
private MapSqlParameterSource createVnodeToPnodeParametersMapper( Integer pinnedIndex, Guid vNodeId) { return getCustomMapSqlParameterSource() .addValue("id", Guid.newGuid()) .addValue("vm_numa_node_id", vNodeId) .addValue("vds_numa_node_index", pinnedIndex); }
Source:
public String read(String key) { String data = dataManager.read(key); START return (data != null) ? encode(cryptoBox.decrypt(iv, decode(data))) : data; END } I would flip this for clarity: `return data == null ? null : encode(cryptoBox.decrypt(iv, decode(data));`

Target:
public String read(String key) { String data = dataManager.read(key); return (data == null) ? null : encode(cryptoBox.decrypt(iv, decode(data))); }
Source:
START public void setUp() throws Exception { END super.init(); } `super.init()` method never throw an exception.

Target:
public void setUp() { super.init(); }
Source:
public S indexNullAs(F indexNullAs) { START indexNullAsValue = Optional.of( indexNullAs ); END return thisAsS(); } `null` is not an acceptable value for `indexNullAs`. You can use `null` to represent "no value was selected", no need for an Optional.

Target:
public S indexNullAs(F indexNullAs) { indexNullAsValue = indexNullAs; return thisAsS(); }
Source:
public void testGenericImageExtraction() { org.atlasapi.media.entity.Series extractedGenericImage = extractor.extract(seriesWithGenericImage()); Image genericImage = Iterables.getOnlyElement(extractedGenericImage.getImages()); START Assert.assertEquals("http://ichef.bbci.co.uk/images/ic/1024x576/p028s846.png", extractedGenericImage.getImage()); END Assert.assertEquals(ImageType.GENERIC_IMAGE_CONTENT_ORIGINATOR, genericImage.getType()); } import static Assert.assertEquals()

Target:
public void testGenericImageExtraction() { org.atlasapi.media.entity.Series extractedGenericImage = extractor.extract(seriesWithGenericImage()); Image genericImage = Iterables.getOnlyElement(extractedGenericImage.getImages()); assertEquals("http://ichef.bbci.co.uk/images/ic/1024x576/p028s846.png", extractedGenericImage.getImage()); assertEquals(ImageType.GENERIC_IMAGE_CONTENT_ORIGINATOR, genericImage.getType()); }
Source:
void testDescribeInstances() { for (String region : ec2Api.getConfiguredRegions()) { Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region); assertNotNull(allResults); START assertTrue(allResults.size() >= 0); END } } How can a set be of a negative size?

Target:
void testDescribeInstances() { for (String region : ec2Api.getConfiguredRegions()) { Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region); assertNotNull(allResults); } }
Source:
START public static String quoteString(String s) { END if (s == null) { return null; } if (!s.matches("^\".*\"$")) { return "\"" + s + "\""; } else { return s; } } Package private should always be enough for testing. Use the same package for tests.

Target:
static String quoteString(String s) { if (s == null) { return null; } if (!s.matches("^\".*\"$")) { return "\"" + s + "\""; } else { return s; } }
Source:
public Object getMin() { if (primitiveType == PrimitiveTypeName.BINARY) { START if (originalType == OriginalType.UTF8) { END return ((Binary) min).toStringUsingUTF8(); } else { return new String(((Binary) min).getBytes()); } } return min; } Had an offline discussion with Aman, we can remove this check and serialize everything using getBytes()

Target:
public Object getMin() { if (primitiveType == PrimitiveTypeName.BINARY && min != null) { return new String(((Binary) min).getBytes()); } return min; }
Source:
public int hashCode() { START int result = name.hashCode(); END result = 31 * result + fullName.hashCode(); return result; } fullName should be enough here too.

Target:
public int hashCode() { return fullName.hashCode(); }
Source:
private SocketConfig createSocketConfig(int socketTimeout) { return SocketConfig.custom() .setSoReuseAddress(true) START .setSoTimeout(socketTimeout > 0 ? socketTimeout : TIMEOUT_THREE_HOURS) END .build(); } I think rather than checking `> 0`, it would make things clearer if you had a static value like `DEFAULT_TIMEOUT = -1` and then use that in `createHttpClient` and change these checks to be `socketTimeout != DEFAULT_TIMEOUT`. Or something along those lines.

Target:
private SocketConfig createSocketConfig(int socketTimeout) { return SocketConfig.custom() .setSoReuseAddress(true) .setSoTimeout(socketTimeout) .build(); }
Source:
CommentBox(CodeMirror cm, CommentInfo info) { this.cm = cm; CommentRange range = info.range(); if (range != null) { fromTo = FromTo.fromCommentRange(range); rangeMarker = cm.markText( fromTo.getFrom(), fromTo.getTo(), START Configuration.create().set("className", END DiffTable.style.range())); } } nit: line break after ( or before ".set" here.

Target:
CommentBox(CodeMirror cm, CommentInfo info) { this.cm = cm; CommentRange range = info.range(); if (range != null) { fromTo = FromTo.create(range); rangeMarker = cm.markText( fromTo.getFrom(), fromTo.getTo(), Configuration.create() .set("className", DiffTable.style.range())); } }
Source:
public void removeTagFromImage(String imageName, String tagToBeRemoved) { selectImage(imageName); new ContextMenu("Remove Tag").select(); String fullTag = ""; Combo combo = new DefaultCombo(); List<String> comboItems = combo.getItems(); for (String item : comboItems) { if (item.contains(tagToBeRemoved)) { fullTag = item; break; } } combo.setSelection(fullTag); START ; END new FinishButton().click(); } This is pretty lonely semicolon :wink:

Target:
public void removeTagFromImage(String imageName, String tagToBeRemoved) { selectImage(imageName); new ContextMenu("Remove Tag").select(); String fullTag = ""; Combo combo = new DefaultCombo(); List<String> comboItems = combo.getItems(); for (String item : comboItems) { if (item.contains(tagToBeRemoved)) { fullTag = item; break; } } combo.setSelection(fullTag); new FinishButton().click(); }
Source:
public void processOnVmStop(Collection<Guid> vmIds) { for (final Guid vmId : vmIds) { START log.infoFormat("process VM {0} that went down", vmId); END ThreadPoolUtil.execute(new Runnable() { @Override public void run() { Backend.getInstance().runInternalAction(VdcActionType.ProcessDownVm, new IdParameters(vmId), ExecutionHandler.createInternalJobContext()); } }); } } do we really need this log? now that it is a command we should have a log for running a command, no?

Target:
public void processOnVmStop(Collection<Guid> vmIds) { for (final Guid vmId : vmIds) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { Backend.getInstance().runInternalAction(VdcActionType.ProcessDownVm, new IdParameters(vmId)); } }); } }
Source:
public BatchServerInventoryView( final ZkPathsConfig zkPaths, final CuratorFramework curator, final ObjectMapper jsonMapper, final Predicate<Pair<DruidServerMetadata, DataSegment>> defaultFilter ) { super( log, zkPaths.getAnnouncementsPath(), zkPaths.getLiveSegmentsPath(), curator, jsonMapper, new TypeReference<Set<DataSegment>>() { } ); Preconditions.checkNotNull(defaultFilter); START this.defaultFilter = defaultFilter; END } nit: can just do this.defaultFilter = Preconditions.checkNotNull(defaultFilter)

Target:
public BatchServerInventoryView( final ZkPathsConfig zkPaths, final CuratorFramework curator, final ObjectMapper jsonMapper, final Predicate<Pair<DruidServerMetadata, DataSegment>> defaultFilter ) { super( log, zkPaths.getAnnouncementsPath(), zkPaths.getLiveSegmentsPath(), curator, jsonMapper, new TypeReference<Set<DataSegment>>() { } ); this.defaultFilter = Preconditions.checkNotNull(defaultFilter); }
Source:
protected void configureEnvironment(final ClusterEnvironment.Builder builder) { START Jackson2ObjectMapperBuilder jacksonBuilder = new Jackson2ObjectMapperBuilder(); END jacksonBuilder.serializationInclusion(JsonInclude.Include.NON_NULL); jacksonBuilder.modules(new CouchbaseJacksonModule(), new JsonValueModule()); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new CouchbaseJacksonModule()); objectMapper.registerModule(new JsonValueModule()); builder.jsonSerializer(JacksonJsonSerializer.create(objectMapper)); } Actually I don't think this is how it should work? We do not expose jackson directly to the user, and all the encoding and decoding happens on the spring side and not with the SDK itself.. shouldn't this go into the mapper/converter logic instead?

Target:
protected void configureEnvironment(final ClusterEnvironment.Builder builder) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new CouchbaseJacksonModule()); objectMapper.registerModule(new JsonValueModule()); builder.jsonSerializer(JacksonJsonSerializer.create(objectMapper)); }
Source:
public void processLockAcquire() { log.debug("Process lock acquire event"); isLeader = true; // Regardless of the role of this node, on leadership acquisition // we shall query the topology provider to get the most up to date // topologyConfigId, which might have changed during our time as non-leaders // and for which we might have missed the change notification and update it on // the sink manager so the value is cached to filter messages upon receive. fetchTopologyFromClusterManager(); START updateTopologyConfigId(topologyDescriptor.getTopologyConfigId()); END onLeadershipAcquire(); } Just doing updateTopologyConfigID is not enough. While process a topology change event, the discovery service does more work refer to processTopologyChangeNotification. While combining two events topology change and leadership change together, it is a bit complex. Would suggest to not call the fetchTopologyFromClusterManager. First, the topology change is a notification API from clusterManager. Even with this call, it will fetch the cached value from clusterManagerAdapter. Second, it just add more complexity and doesn't completely solve the problem.

Target:
public void processLockAcquire() { log.debug("Process lock acquire event"); isLeader.set(true); onLeadershipAcquire(); }
Source:
public DhcpInfo getDhcpInfo() { enforceAccessPermission(); if (mVerboseLoggingEnabled) { mLog.info("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush(); } START DhcpInfo dhcpInfo = mClientModeImpl.syncGetDhcpInfo(); return dhcpInfo; END } Normally you just return mClientModeImpl.getSyncDhcpInfo. If you really want to introduce a local make it final.

Target:
public DhcpInfo getDhcpInfo() { enforceAccessPermission(); if (mVerboseLoggingEnabled) { mLog.info("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush(); } return mClientModeImpl.syncGetDhcpInfo(); }
Source:
public void setUp() throws Exception { START MetadataStorageConnectorConfig config = jsonReadWriteRead( END "{" + "\"type\" : \"db\",\n" + "\"segmentTable\" : \"segments\"\n" + "}", MetadataStorageConnectorConfig.class ); connector = new TestDerbyConnector( Suppliers.ofInstance(config), Suppliers.ofInstance(tablesConfig) ); } why do we use strings here?

Target:
public void setUp() throws Exception { connector = new TestDerbyConnector( Suppliers.ofInstance(new MetadataStorageConnectorConfig()), Suppliers.ofInstance(tablesConfig) ); }
Source:
protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException { if (result.healthy) { resp.setStatus(HttpServletResponse.SC_OK); } else { START resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); END } sendResponse(resp, result.toJson()); } You should use `HttpServletResponse.SC_...` everywhere, no need for `HttpStatus` here.

Target:
protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException { if (result.healthy) { resp.setStatus(HttpServletResponse.SC_OK); } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } sendResponse(resp, result.toJson()); }
Source:
public DeviceInfoReturn attachManagedBlockStorageVolume(Guid volumeId, Map<String, Object> connectionInfo) { JsonRpcRequest request = new RequestBuilder("ManagedVolume.attach_volume") .withParameter("vol_id", START volumeId) END .withParameter("connection_info", connectionInfo) .build(); Map<String, Object> response = new FutureMap(this.client, request); Map<String, Object> info = (Map<String, Object>) response.get("info"); return new DeviceInfoReturn(info); } Same for detach

Target:
public DeviceInfoReturn attachManagedBlockStorageVolume(Guid volumeId, Map<String, Object> connectionInfo) { JsonRpcRequest request = new RequestBuilder("ManagedVolume.attach_volume") .withParameter("vol_id", volumeId.toString()) .withParameter("connection_info", connectionInfo) .build(); Map<String, Object> response = new FutureMap(this.client, request); Map<String, Object> info = (Map<String, Object>) response.get("info"); return new DeviceInfoReturn(info); }
Source:
public static void addHeaders(final HttpMessage httpMessage, final Header... headers) { Validate.notNull(httpMessage, "HttpMessage must not be null"); for (final Header header : headers) { START if (header.getName().equals(MantaHttpHeaders.REQUEST_ID)) { END continue; } httpMessage.addHeader(header); } } As a paranoia sufferer, I would invert the equals to avoid the remote possibility of a NPE: ```java if (MantaHttpHeaders.REQUEST_ID.equals(header.getName())) { ```

Target:
public static void addHeaders(final HttpMessage httpMessage, final Header... headers) { Validate.notNull(httpMessage, "HttpMessage must not be null"); for (final Header header : headers) { if (MantaHttpHeaders.REQUEST_ID.equals(header.getName())) { continue; } httpMessage.addHeader(header); } }
Source:
public String getServletMapping() { START if ("".equals(this.path) || "/".equals(this.path)) { END return "/"; } if (this.path.endsWith("/")) { return this.path + "*"; } return this.path + "/*"; } `this.path` is initialized to a value so this is not necessary.

Target:
public String getServletMapping() { if (this.path.equals("") || this.path.equals("/")) { return "/"; } if (this.path.endsWith("/")) { return this.path + "*"; } return this.path + "/*"; }
Source:
private static InetAddress toInetAddress(Slice ipAddress) { InetAddress address; try { START address = InetAddress.getByAddress(ipAddress.getBytes()); END } catch (UnknownHostException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid IP address binary: " + ipAddress.toStringUtf8(), e); } return address; } Now that this is a standalone function. You can just do `return InetAdress.get...` here, and remove the temporary variable.

Target:
private static InetAddress toInetAddress(Slice ipAddress) { try { return InetAddress.getByAddress(ipAddress.getBytes()); } catch (UnknownHostException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid IP address binary: " + ipAddress.toStringUtf8(), e); } }
Source:
public int hashCode() { return Objects.hash(sqls, sqlFirehoseDatabaseConnector, objectMapper, foldCase); START } END EqualsVerifier test please for equals and hashcode

Target:
public int hashCode() { return Objects.hash(sqls, sqlFirehoseDatabaseConnector, foldCase); }
Source:
protected final List<ResultDocument> getSearchResults(ExecutionContext ctx) { START return null; END } Can we return an empty list here instead?

Target:
protected final List<ResultDocument> getSearchResults(ExecutionContext ctx) { // This should be called at all throw new IllegalStateException(); }
Source:
protected boolean isAppConfiguredInSourceServerXml(String fileName) { START boolean bConfigured = false; END Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.contains(fileName)) { log.debug("Application configuration is found in server.xml : " + fileName); bConfigured = true; } return bConfigured; } Seems like there's a spacing issue here, two spaces instead of 4.

Target:
protected boolean isAppConfiguredInSourceServerXml(String fileName) { Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.contains(fileName)) { log.debug("Application configuration is found in server.xml : " + fileName); return true; } else { return false; } }
Source:
private DataCenter reInitializeDataCenter(String dcId) throws RuntimeException { START log.info("about to reinitialize dc"); END DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; } log.debug ?

Target:
private DataCenter reInitializeDataCenter(String dcId) throws RuntimeException { log.warn("about to reinitialize dc"); DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; }
Source:
public void send(Send request) throws IOException { if (!connected) { throw new ClosedChannelException(); } while (!request.isSendComplete()) { request.writeTo(writeChannel); } START request.release(); END } who releases the request if an IOException is thrown?

Target:
public void send(Send request) throws IOException { try { if (!connected) { throw new ClosedChannelException(); } while (!request.isSendComplete()) { request.writeTo(writeChannel); } } finally { request.release(); } }
Source:
public void canParseNamedCaptureGroupsFromPattern() { assertThat(RegexUtils.getNamedCaptureGroupsFromPattern(""), hasSize(0)); assertThat(RegexUtils.getNamedCaptureGroupsFromPattern("(?<user>.*)"), contains("user")); assertThat(RegexUtils.getNamedCaptureGroupsFromPattern("Node /(?<poolName>.*?)/(?<poolMember>\\S+) address (?<poolAddr>\\S+) monitor status down. .*\\(slot(?<slotNum>[0-9]+)\\)"), START containsInAnyOrder("poolName", "poolMember", "poolAddr", "slotNum")); END } Can we revert this and keep the order deterministic?

Target:
public void canParseNamedCaptureGroupsFromPattern() { assertThat(RegexUtils.getNamedCaptureGroupsFromPattern(""), hasSize(0)); assertThat(RegexUtils.getNamedCaptureGroupsFromPattern("(?<user>.*)"), contains("user")); assertThat(RegexUtils.getNamedCaptureGroupsFromPattern("Node /(?<poolName>.*?)/(?<poolMember>\\S+) address (?<poolAddr>\\S+) monitor status down. .*\\(slot(?<slotNum>[0-9]+)\\)"), contains("poolName", "poolMember", "poolAddr", "slotNum")); }
Source:
public void testActivateAppUnknownApp() throws Exception { App app = when(mock(App.class).isActive()).thenReturn(false).getMock(); MvcResult result = mockMvc.perform(post(AppsController.URI + "/id/activate")).andReturn(); START assertEquals(result.getResolvedException().getMessage(), "Unknown app 'id'"); END } I'd then check the exception class plus parameters, not the message that isn't even sent to the user.

Target:
public void testActivateAppUnknownApp() throws Exception { App app = when(mock(App.class).isActive()).thenReturn(false).getMock(); MvcResult result = mockMvc.perform(post(AppsController.URI + "/id/activate")).andReturn(); throw result.getResolvedException(); }
Source:
public void onReceive(Context ctx, Intent intent) { String action = intent.getAction(); switch (action) { case INSTALL_ACTION: // for play store devices only: // * invoke the receiver and open the page: // `adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n org.wikipedia.dev/org.wikipedia.analytics.InstallReceiver --es "referrer" "referrer_url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FWombat&campaign_id=foo&install_id=bar"` // * invoke the receiver but don't open the app (bad url): // `adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n org.wikipedia.dev/org.wikipedia.analytics.InstallReceiver --es "referrer" "referrer_url=gibberish&campaign_id=foo&install_id=bar"` installReferrer(ctx, intent); break; case Intent.ACTION_BOOT_COMPLETED: // `adb shell am broadcast -a android.intent.action.BOOT_COMPLETED` recordChannelId(ctx); NotificationPollService.start(ctx.getApplicationContext()); break; START default: END L.d("action=" + action); break; } } Doesn't the InstallReceiver depend on a WikipediaApp instance being created by the system? Since NotificationPollService.start() is already called there, I think this would call it a second time

Target:
public void onReceive(Context ctx, Intent intent) { String action = intent.getAction(); switch (action) { case INSTALL_ACTION: // for play store devices only: // * invoke the receiver and open the page: // `adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n org.wikipedia.dev/org.wikipedia.analytics.InstallReceiver --es "referrer" "referrer_url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FWombat&campaign_id=foo&install_id=bar"` // * invoke the receiver but don't open the app (bad url): // `adb shell am broadcast -a com.android.vending.INSTALL_REFERRER -n org.wikipedia.dev/org.wikipedia.analytics.InstallReceiver --es "referrer" "referrer_url=gibberish&campaign_id=foo&install_id=bar"` installReferrer(ctx, intent); break; case Intent.ACTION_BOOT_COMPLETED: // `adb shell am broadcast -a android.intent.action.BOOT_COMPLETED` recordChannelId(ctx); break; default: L.d("action=" + action); break; } }
Source:
private String getTokenToUse(String authTokenCredentialId, String token) { if (!StringUtils.isEmpty(authTokenCredentialId)) { START StringCredentials credentials = CredentialsObtainer.lookupCredentials(authTokenCredentialId, null); END if (credentials != null) { logger.fine("Using Integration Token Credential ID."); return credentials.getSecret().getPlainText(); } } logger.fine("Using Integration Token."); return token; } can this have an overloaded method please so we don't have to pass null around? ```suggestion StringCredentials credentials = CredentialsObtainer.lookupCredentials(authTokenCredentialId); ```

Target:
private String getTokenToUse(String authTokenCredentialId, String token) { if (!StringUtils.isEmpty(authTokenCredentialId)) { StringCredentials credentials = CredentialsObtainer.lookupCredentials(authTokenCredentialId); if (credentials != null) { logger.fine("Using Integration Token Credential ID."); return credentials.getSecret().getPlainText(); } } logger.fine("Using Integration Token."); return token; }
Source:
void onGetBlobError(Exception e, GetBlobOptions options) { START if (options != null && options.getOperationType() == GetBlobOptions.OperationType.BlobInfo) { END onGetBlobInfoError(e); } else { onGetBlobDataError(e, options); } } and then you may be able to drop the `options != null` check.

Target:
void onGetBlobError(Exception e, GetBlobOptions options) { if (options.getOperationType() == GetBlobOptions.OperationType.BlobInfo) { onGetBlobInfoError(e); } else { onGetBlobDataError(e, options); } }
Source:
START public void setSelectedChapter(@NonNull Chapter chapter) { END if (mSelectedChapter != null) { trackView(); } this.mSelectedChapter = chapter; } If you add `@NonNull` here than it's not worth checking the `null` again inside. You should safely assume that the client of the method is fulfilling the non null pre-condition. The IDE will tell the client of the method that a null argument should not be passed. So, either you remove `@NonNull` or remove the check for `!= null` inside.

Target:
public void setSelectedChapter(@NonNull Chapter chapter) { if (mSelectedChapter != null) { trackView(); } mSelectedChapter = chapter; }
Source:
public void open(GenericInputSplit split) throws IOException { super.open(split); START if (serializableIter != null) END it = serializableIter; else it = this.dataSet.iterator(); } we always use parentheses, also for one-line statements.

Target:
public void open(GenericInputSplit split) throws IOException { super.open(split); if (serializableIter != null) { it = serializableIter; } else { it = this.dataSet.iterator(); } }
Source:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Check logcat!"); setContentView(tv); printArgs("The", "Quick", "Brown", "Fox"); Log.i("Fibonacci", "fibonacci's 4th number is " + fibonacci(4)); Greeter greeter = new Greeter("Jake"); Log.d("Greeting", greeter.sayHello()); startSleepyThread(); START synchronized (Boolean.TRUE){} END } Can we remove this? I realize what it was for but I don't think it should be kept around in the example.

Target:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Check logcat!"); setContentView(tv); printArgs("The", "Quick", "Brown", "Fox"); Log.i("Fibonacci", "fibonacci's 4th number is " + fibonacci(4)); Greeter greeter = new Greeter("Jake"); Log.d("Greeting", greeter.sayHello()); startSleepyThread(); }