auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void startCompaction(CorfuRuntime rt, LogUnitServer logUnitServer) { // stop periodical tasks to prevent race condition rt.getGarbageInformer().stop(); // wait until all garbage decisions are sent to logUnit servers. rt.getGarbageInformer().waitUntilAllTasksFinish(); // send garbage decisions to logUnit servers while (rt.getGarbageInformer().getGarbageReceivingQueue().size() > 0) { rt.getGarbageInformer().gcUnsafe(); } // run compaction on LogUnit servers logUnitServer.runCompaction(); rt.getAddressSpaceView().resetCaches(); rt.getAddressSpaceView().invalidateServerCaches(); }

Target:
Put this logic into GarbageInformer together with waitUntilAllTasksFinish as we discussed.
Source:
private void writeToChannelVersionOne(WritableByteChannel channel) throws IOException { try (ReadableByteChannel from = Channels.newChannel(combineStreams().getInput())) { ByteStreams.copy(from, channel); return; } }

Target:
This addition is pointless
Source:
protected void setUp() throws Exception { super.setUp(); Statement stmt = con.createStatement(); /* Drop the test table if it already exists for some reason. It is not an error if it doesn't exist. */ TestUtil.createTable(con, "testtz", "col1 INTEGER, col2 TIMESTAMP"); stmt.close(); /* Generally recommended with batch updates. By default we run all tests in this test case with autoCommit disabled. */ con.setAutoCommit(false); }

Target:
Please remove that
Source:
public List<Currency> getCurrencyForName(final String name) { List<Currency> list = _namesToCurrency.get(name); if (list == null) { return new ArrayList<>(); } return _namesToCurrency.get(name); }

Target:
These null checks will disappear if using a multimap
Source:
private static boolean parseAllowAlias(List<Option> options) { Option option = Option.findByName(options, "allow_alias"); if (option != null) { Object value = option.getValue(); return value instanceof Boolean ? (Boolean) value : "true".equals(value); } return false; }

Target:
What is the actual possible runtime type for the value? This seems overly defensive - I would expect the value will either be a string or a Boolean, not randomly changing from run to run.
Source:
public WebArchive createDeployment() { if (resourceLocal) { archive.addClasses( MemberRegistrationWithResourceLocal.class, ResourceLocalResources.class ); } else { archive.addClasses( MemberRegistrationWithJta.class, JtaResources.class ); } return archive; }

Target:
Interesting approach. I guess I'd have tried to use qualifiers or the CDI alternative mechanism, but this seems the simplest.
Source:
private StorageDomain recoverStorageDomain(String sdUUID) { log.info("about to recover SD {}", sdUUID); StorageDomain storageDomain = new StorageDomain(); storageDomain.setId(sdUUID); updateStorageDomain(storageDomain); return storageDomain; }

Target:
log.debug ?
Source:
public Event complianceCreated(Consumer consumer, Set<Entitlement> entitlements, ComplianceStatus compliance) { return new Event(Event.Type.CREATED, Event.Target.COMPLIANCE, consumer.getName(), principalProvider.get(), consumer.getOwner().getId(), consumer.getUuid(), consumer.getId(), null, buildComplianceDataJson(consumer, entitlements, compliance), null, null); }

Target:
We'll need the second usage of consumer.getId() replaced with consumer.getUuid() as well.
Source:
public static String toHexString(byte[] digest) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < digest.length; i++) { if ((digest[i] & 0xFF) < 0x10) buf.append('0'); buf.append(Integer.toHexString(digest[i] & 0xFF)); } return buf.toString(); }

Target:
Use StringBuilder please.
Source:
private boolean isLastKilledQueryGone() { boolean lastKilledQueryIsGone = (lastKilledQuery == null); if (!lastKilledQueryIsGone) { ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); if (generalPool != null) { lastKilledQueryIsGone = generalPool.getQueryMemoryReservations().containsKey(lastKilledQuery); } } return lastKilledQueryIsGone; }

Target:
Invert this so it returns early
Source:
public Batcher(ScheduledExecutorService workExecutor, int capacity, long delay, BatchProcessor<T> processor) { this.workExecutor = workExecutor; this.capacity = capacity; this.delay = delay; this.processor = processor; this.inbox = new ArrayList<T>(); this.scheduled = false; this.lastProcessedTime = 0; }

Target:
Is this change that makes batcher immediately execute after create new instance of Batcher and then added tasks smaller than capacity size?
Source:
public static void removeMagicResponseContextFields(Map<String, Object> responseContext) { responseContext.remove(DirectDruidClient.QUERY_FAIL_TIME); responseContext.remove(DirectDruidClient.QUERY_TOTAL_BYTES_GATHERED); }

Target:
This line should also be removed.
Source:
private void validateAndClose() throws Exception { try { info("Validating static and Helix cluster maps"); verifyEquivalencyWithStaticClusterMap(staticClusterMap.hardwareLayout, staticClusterMap.partitionLayout); if (validatingHelixClusterManager != null) { ensureOrThrow(validatingHelixClusterManager.getErrorCount() == 0, "Helix cluster manager should not have encountered any errors"); } } finally { if (validatingHelixClusterManager != null) { validatingHelixClusterManager.close(); } for (HelixAdmin admin : adminForDc.values()) { admin.close(); } } }

Target:
no Exception is thrown in this method
Source:
public int size() { if (currentOffset == NO_VALUES) { return 0; } return maxOffset - currentOffset - 1; }

Target:
Consider: `return currentOffset == NO_VALUES ? 0 : maxOffset - currentOffset - 1;`
Source:
public void updateEditorPages(int activatedPage) { removeAllPages(); addPages(); if (backToActivePage > 0 && backToActivePage < this.getPageCount()) { setActivePage(backToActivePage); } else { //Set active page if the backToActivePage is out of the range setActivePage(0); } setPartName(getPartName()); }

Target:
activatedPage is not used anymore
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Object checkCompositeRename= HandlerUtil.getVariable(event, LTK_CHECK_COMPOSITE_RENAME_PARAMETER_KEY); if (checkCompositeRename != null) { return checkForCompositeRename(event, checkCompositeRename); } else { performRename(event); } return null; }

Target:
Looking at other HandlerUtil.getVariable() calls, the usual logic is to look for an instance of what you were looking for (in this case Boolean) and to treat any other situation as if null was provided. This would remove the need to check for Boolean in checkForCompositeRename and having code to issue an error log message which should never occur.
Source:
public Arguments setUntypedNullArgument(Argument untypedNullArgument) { if (untypedNullArgument == null) { throw new IllegalArgumentException("the Argument itself may not be null"); } this.untypedNullArgument = untypedNullArgument; return this; }

Target:
Another non-permissible change
Source:
private DebtRemediationFunction remediationFunction(DebtRemediationFunctions drf) { if (func.startsWith("Constant")) { return drf.constantPerIssue(constantCost.replace("mn", "min")); } if ("Linear".equals(func)) { return drf.linear(linearFactor.replace("mn", "min")); } return drf.linearWithOffset(linearFactor.replace("mn", "min"), linearOffset.replace("mn", "min")); }

Target:
@ivandalbosco I see that you just copied this piece from JS, but it's not perfect there :) We can drop `.replace("mn", "min")` everywhere (3 places). This was done as many RSPECs had legacy `mn` for minutes. It should be fixed now. It there is still some RSPEC using `mn` and plugin fails, then you better update this RSPEC
Source:
public void setAnalysisCache(final AnalysisCache cache) { if (cache == null && isAnalysisCacheFunctional()) { analysisCache = new NoopAnalysisCache(); // Log warning only once, if not explicitly disabled if (!isIgnoreIncrementalAnalysis() && LOG.isLoggable(Level.WARNING)) { final String version = PMDVersion.isUnknown() || PMDVersion.isSnapshot() ? "latest" : "pmd-" + PMDVersion.VERSION; LOG.warning("This analysis could be faster, please consider using Incremental Analysis: " + "https://pmd.github.io/" + version + "/pmd_userdocs_getting_started.html#incremental-analysis"); } } else if (!isIgnoreIncrementalAnalysis()) { // ignore new value if incr. analysis is disabled analysisCache = cache; } }

Target:
I find it very unintuitive to find this here... I'd suggest moving the log to `PMD.doPMD`, which is guaranteed to run once and a little more natural
Source:
private static double sortableLongToDouble(long value) { value = value ^ (value >> 63) & Long.MAX_VALUE; return Double.longBitsToDouble(value); }

Target:
Same here. Add clarifying parenthesis
Source:
public static Exception extractExecutionExceptionCause(Exception e) { if (!(e instanceof ExecutionException)) { return e; } Throwable cause = e.getCause(); return cause == null ? e : (cause instanceof Exception ? (Exception) cause : new Exception(cause)); }

Target:
``` if (!(e instanceof ExecutionException) || e.getCause() == null) { return e; } Throwable cause = e.getCause(); return cause instanceof Exception ? (Exception) cause : new Exception(cause); ``` How about making return statement simpler?
Source:
boolean isEmpty() { return (validIndexSegments.isEmpty()); }

Target:
minor: braces unnecessary
Source:
Set getDefaultIgnoreTypeNames() { Set ignored = new HashSet(); String[] ignore = {"org.eclipse.core.runtime.Plugin", "java.lang.ClassLoader", "org.eclipse.team.internal.ccvs.core.CVSTeamProvider", "org.eclipse.core.internal.events.BuilderPersistentInfo", "org.eclipse.core.internal.resources.Workspace", "org.eclipse.core.internal.events.EventStats", "java.net.URL"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-6$ for (String element : ignore) { ignored.add(element); } return ignored; }

Target:
Please do only whitespace changes in this commit.
Source:
public static boolean delete(File file) { if (!file.exists()) return true; if (file.isDirectory()) { File[] children = file.listFiles(); for (File children1 : children) { delete(children1); } } return file.delete(); }

Target:
child
Source:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { bugzillaClient.authenticate(monitor); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; }

Target:
Why do we call authenticate to log out? If we aren't already authenticated, why do we need to log out?
Source:
private double cleanNumber(double dirtyNumber) { double clean; if (dirtyNumber < 1) clean = 0; else clean = dirtyNumber; return clean; }

Target:
Could be simplified to: ```java return dirtyNumber < 1 ? 0 : dirtyNumber; ```
Source:
public Pagination<Payment> getPayments(final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { return paymentProcessor.getPayments(offset, limit, pluginName, withPluginInfo, properties, tenantContext, internalCallContextFactory.createInternalTenantContext(tenantContext)); }

Target:
Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`
Source:
private static Map<String, String> readMessagesFromBundle() { try { ResourceBundle bundle = ResourceBundle.getBundle(APP_ERRORS_MESSAGES_FILE_NAME); Map<String, String> messages = new HashMap<String, String>(); for (String key : bundle.keySet()) { messages.put(key, bundle.getString(key)); } return messages; } catch (MissingResourceException e) { log.error("Could not load audit log messages from the file " + APP_ERRORS_MESSAGES_FILE_NAME); throw new ApplicationException(e); } }

Target:
why do you need to convert the bundle to a map, instead of using it directly?
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BigFraction otherValue = ((ILScore)obj).getValue(); return this.value.equals(otherValue); }

Target:
Is this really needed? Maybe this should be removed for efficiency reasons (but I don't know how often this method is actually used...)
Source:
private boolean isValidReviewer(Account member, ChangeControl control) { if (member.isActive()) { IdentifiedUser user = identifiedUserFactory.create(member.getId()); // Does not account for draft status as a user might want to let a // reviewer see a draft. if (control.forUser(user).isRefVisible()) { return true; } } return false; }

Target:
[optional] this could be shortened to: return control.forUser(user).isRefVisible();
Source:
private boolean support( ValueGroup[] valueGroups ) { return valueGroups.length == 1 && ValueGroup.NUMBER.equals( valueGroups[0] ); }

Target:
please use == for enum comparisons like its done 2 lines above
Source:
public String getConfigFile() { return configFile; }

Target:
You can make this file `File`
Source:
void close() { writeQueue.add(WriteOperation.SHUTDOWN); writerService.shutdown(); }

Target:
Probably won't be used, but you should implement AutoCloseable, since you implement close() anyway.
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 if (groups.isEmpty() && terminated == TERMINATED_WITH_COMPLETED) { // completionEmitted ensures we only emit onCompleted once if (COMPLETION_EMITTED_UPDATER.compareAndSet(this, 0, 1)) { if (!child.isUnsubscribed()) { child.onCompleted(); } } } }

Target:
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.
Source:
protected boolean startError() { if (errorCount == 0) { logger.error("Found one or more vector errors from " + opName); } errorCount++; if (errorCount >= MAX_ERRORS) { return false; } return true; }

Target:
```suggestion logger.error("Found one or more vector errors from {}", opName); ```
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 { closeQuietly(reader); } return resultLineNumbers; }

Target:
We use Java7, so you should use the try-with-resources feature.
Source:
private static void navigate(final Activity activity, final String destName, final String destCode, final Geopoint coords) { Intent launchIntent = new Intent(INTENT_ACTION); 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); }

Target:
Missing `final` (was indicated on the previous patch as well).
Source:
public TestMediaWikiApiImageFetchingStrategy(Map<String, String> serverContent) { Preconditions.checkNotNull(serverContent, "Please specify some server content for images used during the tests. See: TestMediaWikiApiImageFetchingStrategy#serverContent"); this.serverContent = ImmutableMap.copyOf(serverContent); }

Target:
static import
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); } else { return false; } }

Target:
A redundant else statement
Source:
private 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(); }

Target:
Wouldn't it be safer to make this method synchronized?
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() ); } }; }

Target:
No need to expand the lambda
Source:
public 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; }

Target:
Can be package-private?
Source:
public void all_composed_assertions_should_pass() { SoftAssertions delegate = new SoftAssertions(); delegate.assertThat(1).isEqualTo(1); delegate.assertAll(); softly.assertThat(1).isEqualTo(1); softly.assertThat(Lists.newArrayList(1, 2)).containsOnly(1, 2); softly.assertAlso(delegate); softly.assertAll(); assertThat(softly.wasSuccess()).isTrue(); }

Target:
Minor: use AssertJ `org.assertj.core.util.List.list` and static import for readability.
Source:
public void viewInfoUpdated() { this.reinitialize(); }

Target:
* 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(); }
Source:
public JSONPointer(List<String> refTokens) { this.refTokens = refTokens; }

Target:
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"); } ```
Source:
public VM() { mVmStatic = new VmStatic(); mVmDynamic = new VmDynamic(); mVmStatistics = new VmStatistics(); mVmStatic.setImages(new java.util.ArrayList<DiskImage>()); mVmStatic.setInterfaces(new java.util.ArrayList<VmNetworkInterface>()); mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; }

Target:
coudl be just ArrayList since now it is imported ^^ vv
Source:
long consumerLag() { return consumerLag; }

Target:
Would suggest to make it `private`.
Source:
public RegexGroupFilter(final int groupIdx) { if (groupIdx < 1) throw new IllegalArgumentException(MessageFormat.format(HttpServerText.get().invalidIndex, groupIdx)); this.groupIdx = groupIdx - 1; }

Target:
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.
Source:
public void testChunkFillingBlobSizeMultipleOfChunkSize() throws Exception { blobSize = chunkSize * random.nextInt(10) + 1; fillChunksAndAssertSuccess(); }

Target:
missing braces ? `blobSize` can end up to be 1 if `random.nextInt(10)` returns 0.
Source:
EapAkaAttributeFactory()

Target:
Suggest protected to signal that this is for the subclass
Source:
public byte[] toByteArray() { return ByteBuffer.allocate(8).putLong(valueLong).array(); }

Target:
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.
Source:
public String getModeName() { String header = getHeader(); return header.substring(0, header.indexOf(' ')); }

Target:
there is no other way of getting article name?
Source:
public int hashCode() { int result = bitSet; result = 31 * result + bitSet; return result; }

Target:
@vilchik-elena Why not simply returning `bitSet`?
Source:
void setUnresolvedCompact(boolean unresolvedCompact) { this.unresolvedCompact = unresolvedCompact; if (outer != null) { outer.setUnresolvedCompact(true); } }

Target:
Not required
Source:
public static void afterClass() throws Exception { if (sLocalAlluxioJobCluster != null) { sLocalAlluxioJobCluster.stop(); } sFileSystem.close(); }

Target:
hrmmm, is this required? Will this happen already with the cluster teardown? And, is there redundant closing with the `after()` call?
Source:
public void testTrimLongSuffix() throws Exception { String longValue = "12345"; assertThat(LiteralUtils.trimLongSuffix(longValue)).isEqualTo(longValue); assertThat(LiteralUtils.trimLongSuffix(longValue + "l")).isEqualTo(longValue); assertThat(LiteralUtils.trimLongSuffix(longValue + "L")).isEqualTo(longValue); }

Target:
What If I give the empty string as an input of that method ?
Source:
public Map<TableScanNode, Void> visitTableScan(TableScanNode node, Void context) { Map<TableScanNode, Void> ret = new IdentityHashMap<>(); ret.put(node, null); return ret; }

Target:
spell out ret
Source:
public int getStreamIndex() { return streamIndex; }

Target:
should not be this private?
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(); } catch (Exception ex) { if (ex instanceof IOException) { throw (IOException)ex; } throw new IOException(ex); } }

Target:
simpler: ``` } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } ```
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) { throw e; } }

Target:
please remove the `try { .. } catch ( .. )` block altogether now.
Source:
private StockOperation createOperation(StockOperation operation, InventoryStockTake delegate) { operation.setStatus(StockOperationStatus.NEW); IStockOperationType operationType = WellKnownOperationTypes.getAdjustment(); 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; }

Target:
Remove these extra variables that aren't used except in a setter.
Source:
public MarshallingResponseBuilder messages(List<MarshallingMessage> messages) { this.messages.addAll(messages); return this; }

Target:
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.
Source:
long getTokenCount() { return tokens.get(); }

Target:
nit: I think we generally prefer to explicitly state the access modifiers.
Source:
public V getOrFill(K key, Callable<V> callable) { try { return callable.call() ; } catch (Exception e) { e.printStackTrace(); return null; } }

Target:
`printStackTrace()`? Isn't it better to use a logger?
Source:
void setUpHomeMenuIcon() { drawerIconDot.setVisibility(AccountUtil.isLoggedIn() && Prefs.showActionFeedIndicator() && ReleaseUtil.isPreBetaRelease() && Prefs.getTotalUserDescriptionsEdited() >= ACTION_DESCRIPTION_EDIT_UNLOCK_THRESHOLD ? VISIBLE : GONE); }

Target:
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.
Source:
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() ); }

Target:
Please remove unnecessary brackets: 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; updateTagFilter(); updatePlace(place); } }); }

Target:
this is incorrect place for command
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)); context.put("offsets.topic.replication.factor", "1"); context.put(TOPIC_CONFIG, topic); return context; }

Target:
What does this change bring? Did we need this to get the test working?
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"; return "NA"; }

Target:
Should probably 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: break; } return null; }

Target:
Constant simpleSum could even removed as this constant is never used outside this class.
Source:
public void setDefaultProperties(Map<String, Object> defaultProperties) { this.defaultProperties = new HashMap<>(); for (Object key : Collections.list(defaultProperties.propertyNames())) { this.defaultProperties.put((String) key, defaultProperties.get(key)); } }

Target:
I think this could be a one liner: ```java this.defaultProperties = new HashMap<>(defaultProperties); ```
Source:
protected MapSqlParameterSource createVnodeToPnodeParametersMapper( Integer pinnedIndex, Guid vNodeId) { return getCustomMapSqlParameterSource() .addValue("id", Guid.newGuid()) .addValue("vm_numa_node_id", vNodeId) .addValue("vds_numa_node_index", pinnedIndex); }

Target:
Can this be private?
Source:
public String read(String key) { String data = dataManager.read(key); return (data != null) ? encode(cryptoBox.decrypt(iv, decode(data))) : data; }

Target:
I would flip this for clarity: `return data == null ? null : encode(cryptoBox.decrypt(iv, decode(data));`
Source:
public void setUp() throws Exception { super.init(); }

Target:
`super.init()` method never throw an exception.
Source:
public S indexNullAs(F indexNullAs) { indexNullAsValue = Optional.of( indexNullAs ); return thisAsS(); }

Target:
`null` is not an acceptable value for `indexNullAs`. You can use `null` to represent "no value was selected", no need for an Optional.
Source:
public void testGenericImageExtraction() { org.atlasapi.media.entity.Series extractedGenericImage = extractor.extract(seriesWithGenericImage()); Image genericImage = Iterables.getOnlyElement(extractedGenericImage.getImages()); Assert.assertEquals("http://ichef.bbci.co.uk/images/ic/1024x576/p028s846.png", extractedGenericImage.getImage()); Assert.assertEquals(ImageType.GENERIC_IMAGE_CONTENT_ORIGINATOR, genericImage.getType()); }

Target:
import static Assert.assertEquals()
Source:
void testDescribeInstances() { for (String region : ec2Api.getConfiguredRegions()) { Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region); assertNotNull(allResults); assertTrue(allResults.size() >= 0); } }

Target:
How can a set be of a negative size?
Source:
public static String quoteString(String s) { if (s == null) { return null; } if (!s.matches("^\".*\"$")) { return "\"" + s + "\""; } else { return s; } }

Target:
Package private should always be enough for testing. Use the same package for tests.
Source:
public Object getMin() { if (primitiveType == PrimitiveTypeName.BINARY) { if (originalType == OriginalType.UTF8) { return ((Binary) min).toStringUsingUTF8(); } else { return new String(((Binary) min).getBytes()); } } return min; }

Target:
Had an offline discussion with Aman, we can remove this check and serialize everything using getBytes()
Source:
public int hashCode() { int result = name.hashCode(); result = 31 * result + fullName.hashCode(); return result; }

Target:
fullName should be enough here too.
Source:
private SocketConfig createSocketConfig(int socketTimeout) { return SocketConfig.custom() .setSoReuseAddress(true) .setSoTimeout(socketTimeout > 0 ? socketTimeout : TIMEOUT_THREE_HOURS) .build(); }

Target:
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.
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(), Configuration.create().set("className", DiffTable.style.range())); } }

Target:
nit: line break after ( or before ".set" here.
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); ; new FinishButton().click(); }

Target:
This is pretty lonely semicolon :wink:
Source:
public void processOnVmStop(Collection<Guid> vmIds) { for (final Guid vmId : vmIds) { log.infoFormat("process VM {0} that went down", vmId); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { Backend.getInstance().runInternalAction(VdcActionType.ProcessDownVm, new IdParameters(vmId), ExecutionHandler.createInternalJobContext()); } }); } }

Target:
do we really need this log? now that it is a command we should have a log for running a command, no?
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); this.defaultFilter = defaultFilter; }

Target:
nit: can just do this.defaultFilter = Preconditions.checkNotNull(defaultFilter)
Source:
protected void configureEnvironment(final ClusterEnvironment.Builder builder) { Jackson2ObjectMapperBuilder jacksonBuilder = new Jackson2ObjectMapperBuilder(); 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)); }

Target:
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?
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(); updateTopologyConfigId(topologyDescriptor.getTopologyConfigId()); onLeadershipAcquire(); }

Target:
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.
Source:
public DhcpInfo getDhcpInfo() { enforceAccessPermission(); if (mVerboseLoggingEnabled) { mLog.info("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush(); } DhcpInfo dhcpInfo = mClientModeImpl.syncGetDhcpInfo(); return dhcpInfo; }

Target:
Normally you just return mClientModeImpl.getSyncDhcpInfo. If you really want to introduce a local make it final.
Source:
public void setUp() throws Exception { MetadataStorageConnectorConfig config = jsonReadWriteRead( "{" + "\"type\" : \"db\",\n" + "\"segmentTable\" : \"segments\"\n" + "}", MetadataStorageConnectorConfig.class ); connector = new TestDerbyConnector( Suppliers.ofInstance(config), Suppliers.ofInstance(tablesConfig) ); }

Target:
why do we use strings here?
Source:
protected void sendHealthCheckResponse(HttpServletResponse resp, HealthCheckResult result) throws IOException { if (result.healthy) { resp.setStatus(HttpServletResponse.SC_OK); } else { resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } sendResponse(resp, result.toJson()); }

Target:
You should use `HttpServletResponse.SC_...` everywhere, no need for `HttpStatus` here.
Source:
public DeviceInfoReturn attachManagedBlockStorageVolume(Guid volumeId, Map<String, Object> connectionInfo) { JsonRpcRequest request = new RequestBuilder("ManagedVolume.attach_volume") .withParameter("vol_id", volumeId) .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); }

Target:
Same for detach
Source:
public static void addHeaders(final HttpMessage httpMessage, final Header... headers) { Validate.notNull(httpMessage, "HttpMessage must not be null"); for (final Header header : headers) { if (header.getName().equals(MantaHttpHeaders.REQUEST_ID)) { continue; } httpMessage.addHeader(header); } }

Target:
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())) { ```
Source:
public String getServletMapping() { if ("".equals(this.path) || "/".equals(this.path)) { return "/"; } if (this.path.endsWith("/")) { return this.path + "*"; } return this.path + "/*"; }

Target:
`this.path` is initialized to a value so this is not necessary.
Source:
private static InetAddress toInetAddress(Slice ipAddress) { InetAddress address; try { address = InetAddress.getByAddress(ipAddress.getBytes()); } catch (UnknownHostException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid IP address binary: " + ipAddress.toStringUtf8(), e); } return address; }

Target:
Now that this is a standalone function. You can just do `return InetAdress.get...` here, and remove the temporary variable.
Source:
public int hashCode() { return Objects.hash(sqls, sqlFirehoseDatabaseConnector, objectMapper, foldCase); }

Target:
EqualsVerifier test please for equals and hashcode
Source:
protected final List<ResultDocument> getSearchResults(ExecutionContext ctx) { return null; }

Target:
Can we return an empty list here instead?
Source:
protected boolean isAppConfiguredInSourceServerXml(String fileName) { boolean bConfigured = false; Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.contains(fileName)) { log.debug("Application configuration is found in server.xml : " + fileName); bConfigured = true; } return bConfigured; }

Target:
Seems like there's a spacing issue here, two spaces instead of 4.
Source:
private DataCenter reInitializeDataCenter(String dcId) throws RuntimeException { log.info("about to reinitialize dc"); DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; }

Target:
log.debug ?
Source:
public void send(Send request) throws IOException { if (!connected) { throw new ClosedChannelException(); } while (!request.isSendComplete()) { request.writeTo(writeChannel); } request.release(); }

Target:
who releases the request if an IOException is thrown?
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]+)\\)"), containsInAnyOrder("poolName", "poolMember", "poolAddr", "slotNum")); }

Target:
Can we revert this and keep the order deterministic?
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(); assertEquals(result.getResolvedException().getMessage(), "Unknown app 'id'"); }

Target:
I'd then check the exception class plus parameters, not the message that isn't even sent to the user.
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; default: L.d("action=" + action); break; } }

Target:
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
Source:
private String getTokenToUse(String authTokenCredentialId, String token) { if (!StringUtils.isEmpty(authTokenCredentialId)) { StringCredentials credentials = CredentialsObtainer.lookupCredentials(authTokenCredentialId, null); if (credentials != null) { logger.fine("Using Integration Token Credential ID."); return credentials.getSecret().getPlainText(); } } logger.fine("Using Integration Token."); return token; }

Target:
can this have an overloaded method please so we don't have to pass null around? ```suggestion StringCredentials credentials = CredentialsObtainer.lookupCredentials(authTokenCredentialId); ```
Source:
void onGetBlobError(Exception e, GetBlobOptions options) { if (options != null && options.getOperationType() == GetBlobOptions.OperationType.BlobInfo) { onGetBlobInfoError(e); } else { onGetBlobDataError(e, options); } }

Target:
and then you may be able to drop the `options != null` check.
Source:
public void setSelectedChapter(@NonNull Chapter chapter) { if (mSelectedChapter != null) { trackView(); } this.mSelectedChapter = chapter; }

Target:
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.
Source:
public void open(GenericInputSplit split) throws IOException { super.open(split); if (serializableIter != null) it = serializableIter; else it = this.dataSet.iterator(); }

Target:
we always use parentheses, also for one-line statements.
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(); synchronized (Boolean.TRUE){} }

Target:
Can we remove this? I realize what it was for but I don't think it should be kept around in the example.
Source:
private ContentValues ensureAfter() { ContentValues values = mAfterContentValues; if (values == null) { values = new ContentValues(); mAfterContentValues = values; // also create mAfterKeys mAfterKeys = new HashSet<>(); } return values; }

Target:
Please remove `mAfterKeys` while you're at it. It was only a workaround for the absence of `ContentValues.keySet()` on Android 2.x. Since we don't support Android 2 any more you can remove it in most places and replace by `mAfterContentValues.keySet()` where it's being read.
Source:
private Task<? extends Serializable> createDbTask(Database dbObj) { // note that we do not set location - for repl load, we want that auto-created. CreateDatabaseDesc createDbDesc = new CreateDatabaseDesc(dbObj.getName(), dbObj.getDescription(), null, false, updateDbProps(dbObj, context.dumpDirectory, true)); // If it exists, we want this to be an error condition. Repl Load is not intended to replace a // db. // TODO: we might revisit this in create-drop-recreate cases, needs some thinking on. DDLWork2 work = new DDLWork2(new HashSet<>(), new HashSet<>(), createDbDesc); return TaskFactory.get(work, context.hiveConf); }

Target:
The parameter can bee removed
Source:
public long writeTo(Write writeChannel) throws IOException { long sizeWritten = 0; ReadableByteChannel readableByteChannel = Channels.newChannel(streamToWrite); sizeWritten = writeChannel.appendFrom(readableByteChannel, sizeToWrite); if(sizeWritten != sizeToWrite) { throw new IOException("Not able to write fully. Expected : " + sizeToWrite + " Actual : " + sizeWritten ); } return sizeWritten; }

Target:
what is the purpose of maxWriteTimeInMs now? how is it being used?
Source:
static void addSnapshotJarToClassPath( File jarFile, Path intermediateClassPath, FileSystem fs, Job job ) throws IOException { // Snapshot jars are uploaded to non shared intermediate directory. final Path hdfsPath = new Path(intermediateClassPath, jarFile.getName()); // existing is used to prevent uploading file multiple times in same run. if (!existing.contains(hdfsPath) || !fs.exists(hdfsPath)) { uploadJar(jarFile, hdfsPath, fs); existing.add(hdfsPath); } job.addFileToClassPath(hdfsPath); }

Target:
exists check is not done for SNAPSHOT jars intentionally so that they get updated everytime. SNAPSHOT jars are to be used for testing only and are designed to get updated on each run. Or else there would be no reason for method 'addSnapshotJarToClassPath' to exist. i guess your failure is a result of running concurrent jobs with SNAPSHOT jars.
Source:
public void start(ComponentContext context) { super.start(context); configs.forEach(this::createStreamIfNotExists); processorDescriptors.forEach(this::initProcessor); if (! componentListenerAdded) { // this must be done only once while start method can be called multiple time on hot reload Framework.getRuntime().getComponentManager().addListener(new ComponentsLifeCycleListener()); componentListenerAdded = true; } }

Target:
It's better to make the listener unregister itself at stop time instead of storing a boolean. See for instance `WorkManagerImpl.init` and the implementation of `afterStop`.
Source:
public void reportTaskStatus(int id, Task.TaskStatus status, long miliseconds) throws JMSException { TextMessage message = session.createTextMessage("task:" + propertiesBean.getProperty("engine.unique.id") + ":" + id + ":" + status + ":" + miliseconds); producer.send(message, DeliveryMode.PERSISTENT, 6, 0); log.debug("[{}] Task state sent to dispatcher.", id, status); }

Target:
Please keep it in info level.
Source:
public final BeanMetaData<T> getCurrentBeanMetaData() { if ( currentBeanType != null && currentBeanMetaData == null ) { currentBeanMetaData = beanMetaDataManager.getBeanMetaData( currentBeanType ); } return currentBeanMetaData; }

Target:
Why is it done lazily? Seems we'll need it in any case?
Source:
protected Object handleObjectGet() throws Exception { String workspace = getAttribute("workspace"); ServiceInfo service; if (workspace != null) { WorkspaceInfo ws = geoServer.getCatalog().getWorkspaceByName(workspace); service = geoServer.getService(ws, clazz); } else { service = geoServer.getService(clazz); } if (service == null) { throw new RestletException("Service for workspace " + workspace + " does not exist", Status.CLIENT_ERROR_NOT_FOUND); } return service.clone(true); }

Target:
Given this is configuration, wouldn't it make more sense to show the parameters in the output, accept them in input, and then fix validation like it's done in the UI?
Source:
private String buildHashedPayload(HttpRequest request) { String hashedPayload = ""; try { byte[] unhashedBytes = request.getPayload() == null ? "".getBytes() : ByteStreams.toByteArray(request .getPayload().getInput()); hashedPayload = sha256(unhashedBytes); } catch (IOException e) { throw new HttpException("Error signing request", e); } return hashedPayload; }

Target:
Return the result of `sha256` instead of using the local variable.
Source:
public Map<Long, EventDefinition> getEventDefs(StreamInput id) { return null; }

Target:
It's a little harsh to return null because the deprecated method should work as the original implementation, right? Can't this method read the StreamInputReader and get the information from there?
Source:
public void testSetTitleIconStartMargin() throws Throwable { int startMargin = 100; int navIconWidth = 100; mActivityRule.runOnUiThread(() -> { mToolbar.setNavigationIconContainerWidth(navIconWidth); mToolbar.setTitleIcon(android.R.drawable.sym_def_app_icon); mToolbar.setTitleIconStartMargin(startMargin); }); InstrumentationRegistry.getInstrumentation().waitForIdleSync(); onView(withId(R.id.title_icon)).check(matches(withLeft(navIconWidth + startMargin))); }

Target:
You don't need this. onView() will wait
Source:
Publisher<CoreEvent> getDownstreamPublisher() { return downstreamFlux .compose(downstreamPublisher -> Mono.subscriberContext() .flatMapMany(downstreamContext -> downstreamPublisher.doOnSubscribe(s -> { innerFlux.subscriberContext(downstreamContext).subscribe(); upstreamFlux.subscriberContext(downstreamContext).subscribe(); }))); }

Target:
static import