auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static GermplasmListNewColumnsInfo createGermplasmListNewColumnsInfo(final String columnHeader, final String columnValue) { final GermplasmListNewColumnsInfo germplasmListNewColumnsInfo = new GermplasmListNewColumnsInfo(1); final LinkedHashMap<String, List<ListDataColumnValues>> columnValuesMap = new LinkedHashMap<>(); final List<ListDataColumnValues> listDataColumnValues = new ArrayList<>(); listDataColumnValues.add(new ListDataColumnValues(columnHeader, 1, columnValue)); columnValuesMap.put(columnHeader, listDataColumnValues); germplasmListNewColumnsInfo.setColumnValuesMap(columnValuesMap); germplasmListNewColumnsInfo.addColumn(columnHeader); return germplasmListNewColumnsInfo; }

Target:
Declare `columnValuesMap` as `Map`
Source:
public Tuple<Table> table(final String tableName, HiveConf conf) throws HiveException { // Column statistics won't be accurate if we are dumping only metadata boolean getColStats = !conf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY); return new Tuple<>(functionForSpec, () -> db.getTable(dbName, tableName, false, false, getColStats)); }

Target:
If it is metadata only dump, then need to reset all the table parameters related to stats to false.
Source:
public List<DeprecatedRuleKeyDto> selectAllDeprecatedRuleKeys(DbSession session) { return mapper(session).selectAllDeprecatedRuleKeys(); }

Target:
What about returning a `Set` to emphasis that there is no specific order in the returned collection?
Source:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); // In order to enable KERBEROS authentication method for HDFS // UserGroupInformation.authenticationMethod static field must be set to KERBEROS // It is further used in many places in DfsClient configuration.set("hadoop.security.authentication", "kerberos"); // Set the static configuration to get the rules. try { HadoopKerberosName.setConfiguration(configuration); } catch (IOException exception) { throw new UncheckedIOException(exception); } UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); }

Target:
It is being calles inside the `UserGroupInformation.setConfiguration`. Please remove that. https://github.com/prestodb/presto/pull/11380#discussion_r214222456
Source:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } // Cleanup directories final Path workDir = PATH.getParent(); if (Files.exists(workDir)) { Files.deleteIfExists(PATH); } }

Target:
Does `TemporaryFolder` not take care of cleanup automagically? Is this not one of the reasons to use it?
Source:
public List<String> firstTen(final String... args) { final List<String> list = new ArrayList<String>(args.length); list.addAll(Arrays.asList(args)); final List<String> result = new LinkedList<>(); result.addAll(list.subList(0, InvalidDiamondsUsage.TEN)); return result; }

Target:
@vkuchyn didn't get, why these 2 lines are still here? I thought they were added to cover "happy path", no? If yes, they should be removed
Source:
List<Object> getColumn(int columnIndex) { ArrayList<Object> result = new ArrayList<Object>(); for (Object[] compoundDatum : compoundData) { result.add(compoundDatum[columnIndex]); } return result; }

Target:
List
Source:
private static CharSequence getScreenSecuritySummary(Context context) { final int screenSecurityResId = R.string.preferences__screen_security_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isScreenSecurityEnabled(context)) return context.getString(screenSecurityResId, onRes); return context.getString(screenSecurityResId, offRes); }

Target:
use if else or the ternary
Source:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < mPreviousTotalItemCount) { mCurrentPage = mStartingPageIndex; mPreviousTotalItemCount = totalItemCount; if (totalItemCount == 0) { mLoading = true; } } // If it's still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (mLoading && (totalItemCount > mPreviousTotalItemCount)) { mLoading = false; mPreviousTotalItemCount = totalItemCount; mCurrentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { mLoading = onLoadMore(mCurrentPage + 1, totalItemCount); } }

Target:
Does this mean that initially we try to load the data using this callback? We are also loading it manually, right? How do we prevent loading twice?
Source:
private String buildJsArray(List<ContentType> types) { String typeStr = String.join(",", types.stream().map(t -> t.id() ).collect(Collectors.toList())); return typeStr ; }

Target:
Return the String.join directly without creating the new String
Source:
public void setWhiteListedAgencies(String s) { if (s != null && !s.equals("")) whiteListedAgencies = new HashSet<String>(Arrays.asList(s.split(","))); }

Target:
This is a tiny micro-optimization but I'll mention it since it might add to readability: `Sets.newHashSet(s.split(",")`
Source:
private Throwable unwrap(Object error) { try { return ((ErrorResponse) error).getCause(); } catch (Exception e) { return (Throwable) error; } }

Target:
I'm a bit confused about the exception catching here. The getCause can't fail.. So either error is null, or it isn't an ErrorResponse; both cases can be handled with a check.
Source:
public void run() { try { this.thread.dispatch(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); Logger.warn(this, "%s", ex); // @checkstyle IllegalCatch (1 line) } catch (final Throwable ex) { Logger.error(this, "%s", ExceptionUtils.getStackTrace(ex)); } }

Target:
swallowing the exception? is it intentionally or by mistake?
Source:
public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) { return proxiedHandler.isRedirectRequested(httpResponse, httpContext); }

Target:
`proxiedHandler` can be `null` here and in the next method, right?
Source:
public Post() { this.postContent = randomAlphanumeric(100); }

Target:
Should be set in field declaration.
Source:
private boolean acceptGroup(NuxeoPrincipal originatingPrincipal, String groupName) { return originatingPrincipal.isAdministrator() || originatingPrincipal.getAllGroups().contains(groupName); }

Target:
`private` -> `protected`
Source:
public void start() throws Exception { load(); VIEW_INJECTED_VARS.setEnabled(getConfiguration().isEnablePermissions()); }

Target:
what for you call load?
Source:
public static SchemaPath getCompoundPath(String... strings) { NameSegment s = null; final int length = strings.length; // loop through strings in reverse order for (int i = 0; i < length; i++) { s = new NameSegment(strings[length - 1 - i], s); } return new SchemaPath(s); }

Target:
Could you change this to (i=length-1; i >= 0; i--) such that you don't have to the extra subtraction below.
Source:
private void initListeners() { this.restoreToSavePointListener = new RestoreToLastSavePointListener(session); this.restoreToSavePointListener.register(); this.saveSessionListener = new SaveSessionWhenNoDialectEditorsListener(session); this.saveSessionListener.register(); }

Target:
Code in register() could be done directly in constructor of SaveSessionWhenNoDialectEditorsListener
Source:
private void prepare(ControlWidget screen) { InjectionHelper.inject(screen); translator.updateWidget(screen); screen.onOpened(); }

Target:
Suggest retaining untranslated strings and translating during rendering.
Source:
public void setWriteBuffer(ByteBuffer buffer) { writeBuffer = null; writeBuffer = buffer; }

Target:
This is unnecessary
Source:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { try { lock.lock(); return map.put("key" + key, "value" + key); } finally { lock.unlock(); } }); }

Target:
We don't want to lock inside the try (see the [JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html)). The reason is that if lock.lock() did in fact throw a RuntimeException, then the unlock could cause some unexpected results (since it's re-entrant, it could unlock one more level than intended, for example).
Source:
public void init() { service = new TransformationEngineService(); EKBModelGraph graph = EKBModelGraph.getInstance(); ModelRegistryService registry = ModelRegistryService.getInstance(null); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); service.setModelRegistry(registry); service.setGraphDb(graph); graph.addModel(getModelADescription()); graph.addModel(getModelBDescription()); graph.addModel(getModelCDescription()); }

Target:
same for thos changes
Source:
public void makeOmeTiff(final String name, final CoreMetadata info) throws FormatException, IOException { final String id = getId(name); final OMETiffWriter out = createWriter(name, info, id); writeData(name, info, id, out); out.close(); }

Target:
Can we move to https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html yet?
Source:
private String removeUnprintableChars(String text) { StringBuilder stringbuilder = new StringBuilder(); for(char c0 : text.toCharArray()) { if (c0 != 167 && c0 != 127) { stringbuilder.append(c0); } } return stringbuilder.toString(); }

Target:
Again, variable name
Source:
public void startLog() { (new RangerLoadBegin(sourceDbName, targetDbName, estimatedNumPolicies)).log(LogTag.RANGER_LOAD_START); }

Target:
nit: Remove extra brackets
Source:
public QueryContext(final UserSession session, final DrillbitContext drillbitContext, QueryId queryId) { this(session, drillbitContext, queryId, null); }

Target:
please remove redundant ```final``` modifiers for parameters.
Source:
public Stream<Output> bloomFulltextNodes( @Name( "terms" ) List<String> terms ) throws Exception { Stream<Output> stream; try ( ReadOnlyFulltext indexReader = provider.getReader( BLOOM_NODES, FulltextProvider.FulltextIndexType.NODES ) ) { stream = queryAsStream( terms, indexReader ); } return stream; }

Target:
i would just simply do this (here and method below): ``` try ( ReadOnlyFulltext indexReader = provider.getReader( BLOOM_NODES, FulltextProvider.FulltextIndexType.NODES ) ) { return queryAsStream( terms, indexReader ); } ```
Source:
public LgoProductCurrency( @JsonProperty("id") String id, @JsonProperty("increment") BigDecimal increment, @JsonProperty("limits") LgoLimit limits) { this.id = id; this.increment = increment != null ? increment.stripTrailingZeros() : null; this.limits = limits; }

Target:
DTOs should represent what came from the exchange, this is premature adaptation and should not be here
Source:
private Menu createSortMenu() { Menu submenu = new Menu(shell, SWT.DROP_DOWN); MenuItem subitem; for(int i = 0; i < columnNames.length; i++) { subitem = new MenuItem (submenu, SWT.NONE); subitem.setText(columnNames [i]); final int column = i; subitem.addSelectionListener(widgetSelectedAdapter( e -> { sort(column); })); } return submenu; }

Target:
Put in one line
Source:
public static Properties loadPropertyFile(Resource f) throws IOException { InputStream in = f.in(); try { return loadUniversal(in); } finally { in.close(); } }

Target:
Could be a try-with-resources.
Source:
public static ETwitterCardType getTwitterCardType(@Nullable String identifier) { return ID_MAP.get(identifier).get(); }

Target:
keep Optional return parameter in all enums
Source:
public byte[] get(NamedKey key) { byte[] res = level1.get(key); if (res == null) { res = level2.get(key); } if (res == null) { missCount.incrementAndGet(); } else { put(key, res); hitCount.incrementAndGet(); } return res; }

Target:
wondering if we should also warm up level1 cache when there is a miss in l1 cache and hit in l2 cache ?
Source:
public Statistic createHugePagesFree(HugePage page) { return setDatum( create("hugepages." + page.getSizeKB() + ".free", "Amount of free huge pages of the given size", GAUGE, NONE, INTEGER), page.getAmount()); }

Target:
private?
Source:
private void encodeComponent(CharSequence s) { if (CharsetUtil.UTF_8.equals(charset)) { encodeUtf8Component(s); } else { encodeNonUtf8Component(s); } }

Target:
imho we can do the equals check once in the constructor, store the result in an field and so reduce the overhead even more..
Source:
public MatchingApplicabilityTagsRule(IAtsClient atsClient) { this.atsClient = atsClient; featureDefinitionData = null; validFeatureValues = null; }

Target:
not necessary since JVM initializes all object fields to null
Source:
public void test() { connect(); Assert.assertEquals(jq("$innerLabel").text(), "someValue"); }

Target:
``` Assert.assertTrue(jq("$innerLabel").exists()); Assert.assertEquals(jq("$innerLabel").text(), "someValue"); ```
Source:
public void addResolverListener(String expression, ResolverListener listener) throws CloudnameException { DynamicExpression dynamicExpression = new DynamicExpression(expression, listener, this, zkGetter); synchronized (dynamicAddressMonitor) { DynamicExpression previousExpression = dynamicAddressesByListener.put( listener, dynamicExpression); if (previousExpression != null) { throw new IllegalArgumentException("It is not legal to register a listener twice."); } } dynamicExpression.start(); }

Target:
final
Source:
public void clearCache() throws SQLException { ((Session)this.getDBConnection().getSession()).clear(); }

Target:
I think we should extend the DBConnection interface to have a clearCache() & have the hibernate implementation call this clear. Having it in here ties the context object to close to the hibernate implementation (which I want to avoid if we ever want to drop hibernate).
Source:
private Optional<LocalMemoryContext> getSystemMemoryContext() { try { return Optional.of(systemMemoryContextSupplier.get()); } catch (Exception ignored) { // This is possible with races, e.g., a task is created and then immediately aborted, // so that the task context hasn't been created yet (as a result there's no memory context available). } return Optional.empty(); }

Target:
`RuntimeException`?
Source:
private boolean isFilterExpressionValid(InetAddress inetAddress, String filterExpression) { // Consider profiles without filter expression or an empty one as matching. if (Strings.isNullOrEmpty(filterExpression)) { return true; } else { try { return filterDao.isValid(inetAddress.getHostAddress(), filterExpression); } catch (FilterParseException e) { LOG.warn("Filter expression '{}' is invalid. ", e); } } return false; }

Target:
Missing filter expression?
Source:
public void replaceNodeShouldRemoveOldNode() throws Exception { Node oldNode = r.createSlave("foo", "", null); Node newNode = r.createSlave("foo-new", "", null); r.jenkins.addNode(oldNode); r.jenkins.getNodesObject().replaceNode(oldNode, newNode); r.jenkins.getNodesObject().load(); assertNull(r.jenkins.getNode(oldNode.getNodeName())); }

Target:
```suggestion assertNull(r.jenkins.getNode("foo")); ``` since it is not otherwise obvious that the node’s name did not change somewhere in here.
Source:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } }, new Command() { @Override public void execute() { //do nothing. } } ); } else { //just rename. rename( false ); } }

Target:
Don't have it as a parameter then! I guess it was just easier to copy and paste the code used before, but now delegate to the View interface.
Source:
public void removeThreadFilters(IExecutionDMContext[] threads) throws CoreException { synchronized (fFilteredThreadsByTarget) { if (threads != null && threads.length > 0) { IContainerDMContext target = DMContexts.getAncestorOfType(threads[0], IContainerDMContext.class); Set<IExecutionDMContext> set = fFilteredThreadsByTarget.get(target); if (set != null) { set.removeAll(Arrays.asList(threads)); if (set.isEmpty()) { fFilteredThreadsByTarget.remove(target); } } } } }

Target:
I'm not clear on why this one is needed.
Source:
public Collection<IAtsTeamWorkflow> getSiblingTeamWorkflows(IAtsTeamWorkflow teamWf) { List<IAtsTeamWorkflow> teams = new LinkedList<IAtsTeamWorkflow>(); teamWf.getStoreObject(); Object action = getAction(teamWf); for (Object teamArt : atsServices.getRelationResolver().getRelated(action, AtsRelationTypes.ActionToWorkflow_WorkFlow)) { if (!teamArt.equals(teamWf)) { teams.add(atsServices.getWorkItemFactory().getTeamWf(teamArt)); } } return teams; }

Target:
Doesn't look like the above store object is being used. Suggest removing it.
Source:
public ResultIterator iterator(String query, int fetchSize, int readTimeoutOverride) throws DatabaseEngineException { try { getConnection(); Statement stmt = createSelectStatement(readTimeoutOverride); stmt.setFetchSize(fetchSize); logger.trace(query); return createResultIterator(stmt, query); } catch (final DatabaseEngineTimeoutException e) { throw e; } catch (final Exception e) { throw new DatabaseEngineException("Error querying", e); } }

Target:
The first `iterator` method in AbstractDatabaseEngine had this signature: ``` public synchronized ResultIterator iterator(String query) ``` Then people added more iterator methods, some of them `synchronized`, some of them not. I think all methods that use the connection should be `synchronized`; this means this one would need to be `synchronized`, but all other `iterator` methods call this one and don't need to be.
Source:
public void initializeServers(NotificationSystem notificationSystem) { List<MockDataNodeId> dataNodes = clusterMap.getDataNodes(); for (int i = 0; i < dataNodes.size(); i++) { if (sslEnabledDataCenterList != null) { dataNodes.get(i).setSslEnabledDataCenters(sslEnabledDataCenterList); } initializeServer(dataNodes.get(i), sslProps, enableHardDeletes, prefetchDataNodeIndex == i ? true : false, notificationSystem, time); } }

Target:
suggest changing `prefetchDataNodeIndex == i ? true : false` to `prefetchDataNodeIndex == i`.
Source:
public Payload(final Object data, final Visibility visibility, final String visibilityId) { if(null == data){ this.type = Object.class.getName(); }else{ this.type = data.getClass().getName(); } this.data = data; this.visibility = visibility; this.visibilityId = visibilityId; }

Target:
why object class?, maybe set type to null could be a better idea
Source:
public CloseableIterator<CacheEntry<K, V>> iterator() { return new CloseableIteratorMapper<>(new RemovableCloseableIterator<>(Closeables.iterator(stream()), cache, e -> e.getKey()), e -> new EntryWrapper<>(cache, e)); }

Target:
nitpick: `e -> e.getKey()` could be replaced by `CacheEntry::getKey`. the same for the change below. ps. not sure which one is more efficient.
Source:
public void disableAutoLimit() { autoLimitRowCount = null; }

Target:
```suggestion autoLimitRowCount = 0; ```
Source:
public void testScriptCallFromJavascript() throws Exception { cacheManager.getCache().remove("a"); assertNull(cacheManager.getCache().get("a")); String result = (String) scriptingManager.runScript("testInnerScriptCall.js", new TaskContext().cache(cacheManager.getCache("test_cache")).addParameter("a", "ahoj")).get(); assertEquals("script1:additionFromJavascript", result); assertEquals("ahoj", cacheManager.getCache().get("a")); }

Target:
Do we need those 2 lines here?
Source:
public RestartVdsReturnValue getReturnValue() { return (RestartVdsReturnValue)(super.getReturnValue()); }

Target:
Please remove unnecessary brackets: return (RestartVdsReturnValue) super.getReturnValue();
Source:
public void closeThisNode(long endtime) { super.closeThisNode(endtime); fListeners.stream().forEach(l -> l.nodeClosed(this, endtime)); }

Target:
idem
Source:
public Set<Integer> getSegments() { synchronized (segments) { Set<Integer> segmentsCopy = new HashSet<Integer>(segments); segmentsCopy.addAll(segments); return segmentsCopy; } }

Target:
why the `addAll()`?
Source:
public void dispose() { //Remove all message from the queue this.h.removeCallbacksAndMessages(null); this.parent.dispose(); this.h = null; this.owner = null; this.parent = null; }

Target:
> Use this.h.removeCallbacksAndMessages(null) instead. Done in Patch set 2
Source:
private boolean isHost(final Permissionable permissionable) { return permissionable instanceof Host || (permissionable instanceof Contentlet && Host.class.getSimpleName().equals(((Contentlet) permissionable).getContentType().name())) || (null != permissionable && permissionable instanceof PermissionableProxy && Host.class.getName().equals(PermissionableProxy.class.cast(permissionable).getType())); }

Target:
I think we should use the `contentlet.isHost()` method here rather than recreating it
Source:
public boolean isMine() { IRepository repos = getReview() != null ? getReview().getRepository() : null; return getAuthor() != null && repos != null && (repos.getAccount() == getAuthor() || (repos.getAccount() != null && (repos.getAccount().getEmail().equals(getAuthor().getEmail())))); }

Target:
Don't need parens around repos.getAccount().getEmail().equals(getAuthor().getEmail())
Source:
private void runSe(String filename) { JavaScriptVisitorContext context; try { context = createContext(new TestInputFile("src/test/resources/se/", filename)); verifier.scanExpectedIssues(context); SeChecksDispatcher seChecksDispatcher = new SeChecksDispatcher(ImmutableList.of((SeCheck) verifier)); seChecksDispatcher.scanTree(context); } catch (IOException e) { Throwables.propagate(e); } }

Target:
@janos-ss I would rather catch the `IOException` inside `createContext `.
Source:
public void testReturnKey() throws Exception { long[] ids = b.insertNames("a", "b", "c", "d", "e"); assertThat(ids).containsExactly(new long[] { 1, 2, 3, 4, 5 }); }

Target:
Meh: This is a vararg method. I think you can just say `.containsExactly(1, 2, 3, 4, 5)`
Source:
public void testIndexSeekAndScan() throws Exception { updateAndCommit( asList( IndexEntryUpdate.add( 1L, index, "a" ), IndexEntryUpdate.add( 2L, index, "a" ), IndexEntryUpdate.add( 3L, index, "b" ) ) ); assertThat( query( exact( 1, "a" ) ), equalTo( asList( 1L, 2L ) ) ); assertThat( query( IndexQuery.exists( 1 ) ), equalTo( asList( 1L, 2L, 3L ) ) ); }

Target:
exists is statically imported.
Source:
Response forget(URI lraId, URI parentId) { return invokeParticipantMethod(forgetMethod, lraId, parentId, FORGET); }

Target:
Shouldn't you be clearing out the entry in participantStatusMap. Similarly whenever compensate or complete callbacks finish successfully.
Source:
private void resetAuthorities(String username) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); Collection<? extends GrantedAuthority> updatedAuthorities = userDetails.getAuthorities(); Object principal = toPrincipal(username); principalSecurityContextRegistry .getSecurityContexts(principal) .forEach(securityContext -> resetAuthorities(securityContext, updatedAuthorities)); }

Target:
I think that this may overlap with concurrent updates to the authorities by other threads
Source:
private void internalEndWithFailure() { log.error("Ending command '{}' with failure.", getClass().getName()); endWithFailure(); rollbackQuota(); if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { compensate(); } }

Target:
similar approach should be taken here, but the condition is simpler: try { endWithFailure(); } finally { if (getCommandCompensationPhase() == CommandCompensationPhase.END_COMMAND) { compensate(); } }
Source:
public void testCountWithInternalStore() { final StreamsBuilder builder = new StreamsBuilder(); final String input = "count-test-input"; final MockProcessorSupplier<String, Object> supplier = new MockProcessorSupplier<>(); builder .table(input, consumed) .groupBy(MockMapper.selectValueKeyValueMapper(), stringSerialized) .count() .toStream() .process(supplier); testCountHelper(builder, input, supplier); }

Target:
Why we cannot continue to reuse a single `MockProcessorSupplier`?
Source:
private static URL mapToURL(String path) { try { return new URL(path); } catch (MalformedURLException e) { try { return new File(path).toURI().toURL(); } catch (MalformedURLException e1) { throw new IllegalStateException(e1); } } }

Target:
new IllegalArgumentException is more appropriate
Source:
protected void addSearchFilter(final ActiveFilterItem filter, final ColumnFilter columnFilter) { ((CoreFunctionFilter)columnFilter).setLabelValue(filter.getLabelValue()); basicFilterAddEvent.fire(new BasicFilterAddEvent(getDataSetId(), filter, columnFilter)); }

Target:
unchecked cast, in class below there's a checked cast. Isn't it necessary here too?
Source:
void addAdditionalDependencies(Set<String> back) throws Exception { if (additionalDependencies != null) { for (Dependency dependency : additionalDependencies) { addToClasspath(factory.createDependencyArtifact(dependency), back, false); } } }

Target:
protected
Source:
private void runEventLoopUntilEmpty() { Display display = Display.getCurrent(); while (display.readAndDispatch()) { } display.sleep(); return; }

Target:
Possible deadlock: remove this call to sleep(). It's possible that no events will ever arrive.
Source:
private Map<String, List<Entry<T>>> copy(final Map<String, List<Entry<T>>> original) { final Map<String, List<Entry<T>>> copy = new HashMap<>(); original.forEach((key, value) -> copy.put(key, new CopyOnWriteArrayList<>(value))); return copy; }

Target:
OK, thanks for the size improvement. As for the synchronized issue, let's open a jira then and do nothing for now.
Source:
@Override public void track(TrackPayload track) { super.track(track); Double value = track.properties().getDouble("value", Double.MIN_VALUE); if (value.equals(Double.MIN_VALUE)) { Apptimize.track(track.event()); } else { Apptimize.track(track.event(), value); } }

Target:
You can leave it as `double` to avoid auto boxing.
Source:
public ContentTypeManager() { super(null, InstanceScope.INSTANCE); }

Target:
Can the constructor be private?
Source:
public void testStartAndCompleteTaskUseOfAsyncResponseHandler() { ResponseCallback callback = new BlockingResponseCallback(null); testStartAndCompleteTask(new AsyncResponseHandler(callback)); }

Target:
You may also check responses from callback.
Source:
Delete(String keyspace, String table, List<Selector> columns) { super(keyspace); this.table = table; this.columns = columns; this.where = new Where(this); this.usings = new Options(this); this.conditions = new Conditions(this); // This is for JAVA-1089, if the query deletes an element in a list, the statement should be non-idempotent. for (Selector sel : columns) { if (sel instanceof CollectionElementSelector) { if (((CollectionElementSelector) sel).key instanceof Integer) { setNonIdempotentOps(); } } } }

Target:
I believe this is wrong: it would also return true for maps with integer keys. We will need to create separate subclasses or find another way to distinguish list element deletions from other cases.
Source:
File remove(long sizeInBytes) { File reserveFile = null; Queue<File> reserveFilesForSize = internalMap.get(sizeInBytes); if (reserveFilesForSize != null) { if (reserveFilesForSize.size() != 0) { reserveFile = reserveFilesForSize.remove(); } } return reserveFile; }

Target:
minor: can put both conditions together with a "&&"?
Source:
public PersistenceConfiguration create() { List<StoreConfiguration> stores = new LinkedList<StoreConfiguration>(); for (StoreConfigurationBuilder<?, ?> loader : this.stores) stores.add(loader.create()); return new PersistenceConfiguration(passivation, stores); }

Target:
This was like this before, but shouldn't we make this List<StoreConfiguration> stores = new ArrayList<StoreConfiguration>(stores.size()); instead. LinkedList should only really be used when removing or adding not from the tail.
Source:
private void setAmbryHeadersForPut(JSONObject headers, String ttlInSecs, String serviceId, Container container, String contentType, String ownerId) throws JSONException { setAmbryHeadersForPut(headers, ttlInSecs, serviceId, container, contentType, ownerId, true, true); }

Target:
`container` is not specified in @param.
Source:
public void validateArguments(List<Expr> args) { if (!(args.size() > 0)) { throw new IAE("Function[%s] needs at least 1 argument", name()); } }

Target:
Could simplify to: ```java if (args.isEmpty()) { ```
Source:
public boolean setValue(T newValue) { if (!validator.validate(newValue)) return false; PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }

Target:
I'd remove the empty lines before and after this one.
Source:
public void testNestedInvalidateAndApplyCompletes() throws Exception { final AtomicBoolean hasRun = new AtomicBoolean(); final SideEffect innerSideEffect = SideEffect.createPaused(() -> { }).resume(); SideEffect.createPaused(() -> { // Make sure that there are no infinite loops. assertFalse(hasRun.get()); hasRun.set(true); innerSideEffect.markDirty(); innerSideEffect.runIfDirty(); }).resume(); runAsync(); assertTrue(hasRun.get()); }

Target:
Here is the same issue like in line 208 (resume being void)
Source:
SubscribedRepository(String name) { this.name = name; subscribeSpecs = new HashMap<String, SubscribeSpec>(); }

Target:
Use a concurrentHasMap, then you can remove the synchronized on the public methods.
Source:
public void testFixedMeanFixedVariance() { Double[] params = new Double[2]; params[0] = MEAN; params[1] = VARIANCE; UnivarGaussian gaussian = new UnivarGaussian(); gaussian.setParams(params); testGaussian(gaussian); }

Target:
Simpler: `Double[] params = { MEAN, VARIANCE }`
Source:
public void saveSessionBackupFromResult( final BackupResult backupResult ) throws IOException { final byte[] data = backupResult.getData(); if ( data != null ) { final String key = _sessionIdFormat.createBackupKey( _session.getId() ); _memcached.set( key, toMemcachedExpiration(_session.getMemcachedExpirationTimeToSet()), data ); } else { _log.warn( "No data set for backupResultStatus " + backupResult.getStatus() + " for sessionId " + _session.getIdInternal() + ", skipping backup" + " of non-sticky session in secondary memcached." ); } }

Target:
I can't see it here, but probably it's now blocking while it shouldn't (at least not always).
Source:
public void teardown() throws Exception { if (lifeCycleManager != null) { lifeCycleManager.stop(); } }

Target:
Something per-method needs to assign null to lifeCycleManager.
Source:
protected void queueRequest(final ITmfDataRequest request) { if (fExecutor == null || fExecutor.isShutdown()) { request.cancel(); return; } TmfEventThread thread = new TmfEventThread(this, request); if (TmfCoreTracer.isRequestTraced()) { TmfCoreTracer.traceRequest(request, "QUEUED"); //$NON-NLS-1$ } fExecutor.execute(thread); }

Target:
Could be replaced with executorIsShutdown?
Source:
public boolean isDuplicate(@NonNull AvoidRoadInfo item) { for (AvoidRoadInfo existingItem : existingItems) { if (item.latitude == existingItem.latitude && item.longitude == existingItem.longitude && item.name.equals(existingItem.name)) { return true; } } return false; }

Target:
Implement equals in AvoidRoadInfo
Source:
public void onCompleted() { long r = get(); if (r != Long.MIN_VALUE) { actual.onCompleted(); } }

Target:
nit: inline
Source:
public Extensions() { factories = new CopyOnWriteArrayList<>(); }

Target:
Again, now this initializer will have to be repeated in any additional constructors added.
Source:
public void export_credentials_provider_extension_credentials() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); ConfigurationAsCode.get().export(out); System.out.println(out.toString()); assertThat(out.toString(), containsString("username: \"user1\"")); assertThat(out.toString(), containsString("id: \"sudo_password\"")); }

Target:
this still needed?
Source:
private Predicate<String> createPredicate() { if(includeLists != null) { return e -> includeLists.contains(e); } else if (excludeLists != null) { return e -> !excludeLists.contains(e); } else { return e -> true; } }

Target:
Missing a blank after "if" If `propertyToList` returns empty list, check `if (!includeLists.isEmpty())`
Source:
public void testEmailWith64CharacterLocalPartIsValid() { // Local part should allow up to 64 octets: https://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 for (int num = 1; num < 64; num++) { isValidEmail( stringOfLength( num ) + "@foo.com" ); } }

Target:
You're missing 64 here. `<=` would be better.
Source:
public void save(AuditLog event) { Map<String, Object> returnVal = null; if (event.isExternal()) { returnVal = getCallsHandler().executeModification("InsertExternalAuditLog", getExternalEventSqlMapper(event)); } else { returnVal = getCallsHandler().executeModification("InsertAuditLog", getSqlMapper(event)); } event.setAuditLogId((Integer) returnVal.get("audit_log_id")); }

Target:
No need to set null here ...
Source:
public void testCrossSourceMultiFragmentJoin() throws Exception { try { client.alterSession(ExecConstants.SLICE_TARGET, 1); client.queryBuilder() .sql("select x.person_id, y.salary from h2.drill_h2_test.person x " + "join %s y on x.person_id = y.person_id ", TABLE_NAME) .run(); } finally { client.resetSession(ExecConstants.SLICE_TARGET); } }

Target:
Not critical but there is `queryBuilder()` method that implicitly performs `client.queryBuilder()`, also there is `run` method for those queries that does not need to return any result (check `ClusterTest` class).
Source:
private static void setDropdown(Combo comboBox, INamedElement el, List<String> names) { comboBox.removeAll(); for (String name : names) { comboBox.add(name); } // pre-selects the elements that are now in the action: comboBox.select((null == el) ? names.size() - 1 : comboBox.indexOf(el.getName())); }

Target:
names.forEach( name -> comboBox.add(name)); would be more concise
Source:
boolean isHandleWritable() { return !getLedgerMetadata().isClosed(); }

Target:
I am not sure that it is 'closed' for a non recovery reader. Maybe I need a coffee :)
Source:
public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX()

Target:
Don't leave this empty - better to add the call to _super()_ - even though it is implicit, as this enables placing a debug breakpoint in the constructor.
Source:
public void fireModelChanged(TestModelChange change) { for (ITestModelListener listener : fListeners) { listener.testModelChanged(change); } }

Target:
I see a ConcurrentModificationException in all derived tests from StructuredViewerTest#testDeleteInput. java.util.ConcurrentModificationException at java.util.Vector$Itr.checkForComodification(Vector.java:1210) at java.util.Vector$Itr.next(Vector.java:1163) at org.eclipse.jface.tests.viewers.TestModel.fireModelChanged(TestModel.java:40) at org.eclipse.jface.tests.viewers.TestElement.deleteChild(TestElement.java:134) at org.eclipse.jface.tests.viewers.TestElement.deleteChild(TestElement.java:128) at org.eclipse.jface.tests.viewers.StructuredViewerTest.testDeleteInput(StructuredViewerTest.java:164) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at junit.framework.TestCase.runTest(TestCase.java:176) at junit.framework.TestCase.runBare(TestCase.java:141) at junit.framework.TestResult$1.protect(TestResult.java:122) at junit.framework.TestResult.runProtected(TestResult.java:142) at junit.framework.TestResult.run(TestResult.java:125) at junit.framework.TestCase.run(TestCase.java:129) at junit.framework.TestSuite.runTest(TestSuite.java:252) at junit.framework.TestSuite.run(TestSuite.java:247) at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:764) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Source:
public double approximate(int currentNode) { Dijkstra dijkstra = new Dijkstra(graph, weighting, traversalMode); Path path = reverse ? dijkstra.calcPath(to, currentNode) : dijkstra.calcPath(currentNode, to); if (path.isFound()) return path.getWeight(); else return Double.POSITIVE_INFINITY; }

Target:
really only btw :) .... wouldn't `return path.isFound() ? path.getWeight() : Double.POSITIVE_INFINITY;` be slightly better as you used the ternary op in the line above?
Source:
public boolean isValidAuthorizations(String user, List<ByteBuffer> auths) throws AccumuloSecurityException { if (auths.size() == 0) { // avoid deserializing auths from ZK cache return true; } Authorizations userauths = getCachedUserAuthorizations(user); for (ByteBuffer auth : auths) { if (!userauths.contains(ByteBufferUtil.toBytes(auth))) { return false; } } return true; }

Target:
You should call `.isEmpty()`
Source:
public synchronized long getTimestamp(final int offset) { HistogramScaledData scaledData = fScaledData; if (scaledData != null) { return fScaledData.fFirstBucketTime + Math.round(scaledData.fBucketDuration * offset); } return 0; }

Target:
scaledData, thread safety and all
Source:
private String serializeToXmlString(EntityDescriptor entityDescriptor) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(entityDescriptor); if (marshaller == null) { throw new Saml2Exception("Unable to resolve Marshaller"); } Element element = marshaller.marshall(entityDescriptor); return SerializeSupport.prettyPrintXML(element); } catch (Exception e) { throw new Saml2Exception(e); } }

Target:
I think lines 71-74 don't need to be inside the try block. It would be nice to take them out in order to keep the try block as small as possible.
Source:
public boolean isInIdClass() { return isInIdClass != null ? isInIdClass : ( parent != null && parent.isInIdClass() ); }

Target:
just my personal opinion but not sure this helps code readability
Source:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; // grab the original request from Spring to forward security related attributes // such as requests host, ports and headers this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(atts -> atts.getRequest()); }

Target:
Not sure if you notice, a method reference can be used here: ``` this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest); ```
Source:
AbstractBuilder(int initialCapacity) { this.list = new ArrayList<T>(initialCapacity); }

Target:
minor: no need to add explicit type argument here
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (Guid.isNullOrEmpty(getParameters().getHookId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_ID_IS_REQUIRED); return false; } if (getGlusterHook() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_DOES_NOT_EXIST); return false; } if (getMissingServerHooks().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NO_CONFLICT_SERVERS); return false; } return true; }

Target:
The above two checks can be moved to a common parent class, as the same is repeated in GlusterHookStatusChangeCommand as well.
Source:
private void displayDetails(String period, String unit, String dataType) throws Exception { System.out.println("***********************************************"); System.out.println("executing for:"); System.out.println(unit + "(" + period + ")"); System.out.println("dataType=" + dataType); System.out.println("***********************************************"); }

Target:
Can we use logger ?
Source:
static Module module() { return new CacheModule() { @Override protected void configure() { final String cacheName = CACHE_NAME; final TypeLiteral<Cache<ActiveSession.Key, ActiveSession>> type = new TypeLiteral<Cache<ActiveSession.Key, ActiveSession>>() {}; core(type, cacheName) // .memoryLimit(1024) // reasonable default for many sites .maxAge(12, HOURS) // expire sessions if they are inactive .evictionPolicy(EvictionPolicy.LRU) // keep most recently used ; bind(WebSession.class).in(RequestScoped.class); } }; }

Target:
This doesn't exactly work anymore. We need to implement the same behavior in the database code.
Source:
private void setUsernameInRequest() { Http.Session session = Http.Context.current().session(); String email = session.get(ConstantsManager.COOKIE_EMAIL_FIELD_NAME); Controller.request().setUsername(email); }

Target:
`Http.Context.current().request().setUsername(email);` Tu pourras donc aussi enlever le import de Controller
Source:
private boolean useProtocolV2() { return Objects.equals(transferConfig.protocolVersion, ProtocolVersion.V2) && clientRequestedV2; }

Target:
Optional: Can be written as ProtocolVersion.V2.equals(transferConfig.protocolVersion), since we know that ProtocolVersion.V2 is never null.
Source:
private synchronized int purgeExpiredRecallRequests(long expirationTime, int purgeSize) { int n = new TapeRecallCatalog().purgeCatalog(expirationTime, purgeSize); if (n == 0) { log.trace("No entries have been purged from tape_recall table"); } else { log.info("{} entries have been purged from tape_recall table", n); } return n; }

Target:
I would remove the if an always log the number of entries removed, which can be 0
Source:
public A value() { return supplier != null ? supplier.f() : null; }

Target:
should just be `return supplier.f()`. In FJ we do not special on case `null` imput value: protecting each input parameter against null would litter the code with garbage, maybe also impact perf and, in this case, hide root issue by propagating a null value. Only dedicated APIs like `Option.fromNull` explicitly deal with `null`.
Source:
@Override public void onDestroyView() { super.onDestroyView(); if (disposable != null) { disposable.dispose(); } }

Target:
Please move the annotation to its own line
Source:
void generateParameterValueSet(ActivationClassBuilder acb) throws StandardException { Vector parameterList = getCompilerContext().getParameterList(); int numberOfParameters = (parameterList == null) ? 0 : parameterList.size(); if (numberOfParameters < 0) return; ParameterNode.generateParameterValueSet (acb, numberOfParameters, parameterList); }

Target:
Why? It seems that this cannot happen
Source:
public Boolean getXD_JMX_ENABLED() { return (jmxEnabled != null && jmxEnabled) ? jmxEnabled : null; }

Target:
seems odd to return null here even if it had been explicitly set to FALSE
Source:
private void validateTag(String xmlTag) { Conditions.checkNotNullOrEmpty(xmlTag, "xmlTag"); // resources can only have three tags: "resourceDoc", "applicationDocs" or "grammars" boolean valid = false; if (xmlTag.compareTo("resourceDoc") == 0) { valid = true; } else if (xmlTag.compareTo("applicationDocs") == 0) { valid = true; } else if (xmlTag.compareTo("grammars") == 0) { valid = true; } if (!valid) { throw new OseeArgumentException("Invalid resource document tag"); } }

Target:
This looks like a C style equality check. Also, it does not account for case mismatches. Conside using if("resourceDoc".equalsIgnoreCase(xmlTag))... instead.
Source:
public int compareTo(ModuleMetadata other) { return this.getName().compareTo(other.getName()); }

Target:
Should include other properties to break ties here
Source:
private BlockingQueue<Runnable> newQueue(boolean needPrioritySort) { return needPrioritySort ? new PriorityBlockingQueue<>() : new LinkedBlockingQueue<>(); }

Target:
static
Source:
public void run() { if (historyPage.getCurrentRepo() == null) return; dialog = new GitHistoryRefFilterConfigurationDialog( historyPage.getSite().getWorkbenchWindow().getShell(), historyPage.getCurrentRepo(), historyPage.helper); if (dialog.open() == Window.OK) { historyPage.refresh(historyPage.selectedCommit()); } }

Target:
missing braces
Source:
public String getAccumuloClasspath() { return verifyNotNull(ADMIN_ACCUMULO_CLASSPATH_PROP, getString(ADMIN_ACCUMULO_CLASSPATH_PROP, ADMIN_ACCUMULO_CLASSPATH_DEFAULT)); }

Target:
Could this ever be null since `getString()` is passed a default?
Source:
private AuthenticationException onError(JwtException e) { if (logger.isDebugEnabled()) { logger.debug("Authentication error for Jwt Token: " + e.getMessage()); } if (e instanceof BadJwtException) { return new InvalidBearerTokenException(e.getMessage(), e); } else { return new AuthenticationServiceException(e.getMessage(), e); } }

Target:
I'm not seeing the added benefit of this one since `AuthenticationWebFilter` displays the same information. Is it necessary?
Source:
private void validateCallbackUrl(String callbackUrl) { try { new URL(callbackUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException("Callback URL must be valid if provided!"); } }

Target:
Maybe we could also pass the root cause when creating the new exception.
Source:
private boolean canViewInjectedVars(@Nonnull User user, @Nonnull Run<?,?> run) throws UsernameNotFoundException { SecurityContext initialContext = null; try { Authentication auth = user.impersonate(); initialContext = hudson.security.ACL.impersonate(auth); return EnvInjectPlugin.canViewInjectedVars(run); } finally { if (initialContext != null) { SecurityContextHolder.setContext(initialContext); } } }

Target:
BTW can be written more concisely with an effectively final variable: ``` java Authentication auth = user.impersonate(); SecurityContext initialContext = ACL.impersonate(auth); try { return EnvInjectPlugin.canViewInjectedVars(run); } finally { SecurityContextHolder.setContext(initialContext); } ``` (There are also two newer overloads with closures, but neither are suitable for Java 8 lambdas.)
Source:
public void doPrefetch(int index, long relativeOffset, long size) { try { readOptions.get(index).doPrefetch(relativeOffset, size); } catch (Exception e) { logger.error("Data Prefetch failed", e); } }

Target:
so why is this an error and not a warning? Since the system proceeds without giving up, I think it should be a warning
Source:
public void latchAwaitSeconds(int sec) throws InterruptedException { System.out.println("AWAIT " + latch); if (!latch.await(sec, TimeUnit.SECONDS)) { throw new RuntimeException("Await failed"); } }

Target:
This should probably be removed