auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private FactorComparator(String factorName, int weight, Comparator<T> comparator){ this.factorName = factorName; this.weight = weight; this.comparator = comparator; logger.info("comparator created for " + this.factorName); }

Target:
is this necessary?
Source:
public PatternMatcher(TermContext context) { this.termContext = context; multiSubstitutions = new ArrayList<java.util.Collection<Map<Variable, Term>>>(); }

Target:
why was this done?
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getArtUuid() == null) ? 0 : getArtUuid().hashCode()); result = prime * result + ((getBranchId().isInvalid()) ? 0 : getBranchId().hashCode()); return result; }

Target:
result = prime * result + getBranchId().hashCode(); can use BranchId's hashCode method directly since branchId is not allowed to be null and it will work whether the id is valid or not
Source:
protected void setUpGetUnregisteredVmTemplateExpectations(boolean notFound) { setUpEntityQueryExpectations( QueryType.GetUnregisteredVmTemplate, GetUnregisteredEntityQueryParameters.class, new String[] { "StorageDomainId", "EntityId" }, new Object[] { STORAGE_DOMAIN_ID, TEMPLATE_ID }, notFound ? null : getEntity(1)); }

Target:
Can be private
Source:
public boolean isDomainXmlEnabledForVds(Guid vdsId) { return FeatureSupported.isDomainXMLSupported(getVdsManager(vdsId).getCompatibilityVersion()); }

Target:
The whole purpose of FullListAdapter is to abstract the implementation details of querying the device list from the caller - so how about moving the changes that are done in VmDevicesMonitoring to FullListVDSCommand ?
Source:
public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) doPop(e); }

Target:
Please add also for `if` blocks with only one statement.
Source:
public boolean isSuggestionListDisplayed() { try { waitForElementByElement(searchSuggestions.get(0)); return searchSuggestions.get(0).isDisplayed(); } catch (NoSuchElementException|IndexOutOfBoundsException e) return false; }

Target:
Use .getSize to see if element is on page
Source:
public ConnectionId(final String host, final int port, final String connectionId) { Objects.requireNonNull(host); if (port <= 0) { throw new IllegalArgumentException(String.format("Port must be greater than 0")); } this.host = host; this.port = port; this.connectionId = connectionId; }

Target:
no need to use String.format as there is no parameter. Either provide directly throw new IllegalArgumentException("Port must be greater than 0"); or maybe improve message with somethign like: throw new IllegalArgumentException(String.format("Port must be greater than 0 (provided {0})", port));
Source:
public RecursiveLoggerContextInstantiationException(String message) { super(I18nMessageFactory.createStaticMessage(message)); }

Target:
use static import.
Source:
public Map<String, MetricPlotDTOs> createTaskPlots() { sessionId = getSessionIdProvider().getSessionId(); // check new model List<MetricPointEntity> metricDetails = getHibernateTemplate().find( "select m from MetricPointEntity m where m.metricDescription.taskData.sessionId=?", sessionId); if (metricDetails == null || metricDetails.isEmpty()) { return oldWay(); } else { return newWay(metricDetails); } }

Target:
why is it public?
Source:
public void testDeadlock() throws Exception { doTest(1000 * 30); // 30 secs almost always locks boolean interrupted = Thread.interrupted(); if (interrupted) { fail("Thread was interrupted at end of test"); } }

Target:
Why not inline this variable?
Source:
public static QueryGranularity fromString(String str) { String name = str.toUpperCase(); if(name.equals("ALL")) { return QueryGranularity.ALL; } else if(name.equals("NONE")) { return QueryGranularity.NONE; } else if(CALENDRIC_GRANULARITIES.containsKey(name)) { return new PeriodGranularity(CALENDRIC_GRANULARITIES.get(name), null, null); } return new DurationGranularity(convertValue(str), 0); }

Target:
instead of creating a new object every time, it might make more sense to store constants for each predefined granularity string
Source:
public Object[] getElements(Object element) { if (element instanceof Object[]) { return (Object[]) element; } if (element instanceof Collection) { return ((Collection) element).toArray(); } return new Object[0]; }

Target:
style nit: we don't use braces around single line blocks
Source:
public void setUp() throws Exception { super.setUp(); if (SystemUtils.IS_OS_LINUX) { try { eventLoopGroup = new EpollEventLoopGroup(); } catch (Throwable t) { LOG.warn("Could not use Netty Epoll event loop {}", t.getMessage()); eventLoopGroup = new NioEventLoopGroup(); } } else { eventLoopGroup = new NioEventLoopGroup(); } executor = OrderedSafeExecutor.newBuilder() .name("BKClientOrderedSafeExecutor") .numThreads(2) .build(); }

Target:
maybe we should create a common utility function to build EventLoopGroups and do not duplicate this kind of code
Source:
private void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength) { try { long readStart = System.nanoTime(); inputStream.readFully(position, buffer, bufferOffset, bufferLength); stats.readDataBytesPerSecond(bufferLength, System.nanoTime() - readStart); } catch (PrestoException e) { // just in case there is a Presto wrapper or hook throw e; } catch (Exception e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error reading from %s at position %s", id.toString(), position), e); } }

Target:
Don't need the `toString` call.
Source:
public void invalidPropertiesFormat() { VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.DISK); device.setCustomProperties("bootable"); DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateDeviceProperties(Version.v3_3, device); assertFalse(errors.isEmpty()); assertTrue(errors.get(0).getReason() == ValidationFailureReason.SYNTAX_ERROR); }

Target:
Don't you prefer to use assertEquals?
Source:
private boolean isMandatory(MethodExpression expression) { return expression.getMethod().getWords().get(0).equals(MANDATORY) ? true : false; }

Target:
If this is the use of the "MANDATORY" constant then you may want to define it as a "Name" instead of "String": privates static final Name MANDATORY = NameParser.parseUsingCase("Mandatory"); Then you can compare it easily: return expression.getMethod().equals(MANDATORY);
Source:
private DeltaVisit next() { // If our parent has no more children, discard it. if (parent != null && parent.nextChild == null) { parent.data = null; parent = parent.parent; } if (nextChild != null) return new DeltaVisit(this); // If we have no child ourselves, our parent must (if it exists), // due to the discard rule above. With no parent, we are done. if (parent != null) return new DeltaVisit(parent); return null; }

Target:
Good change making this an instance member, thanks.
Source:
boolean delayNextTimeToRun(Date timeToRunTheVm) { this.timeToRunTheVm = timeToRunTheVm; return ++numOfSkips < MAXIMUM_NUM_OF_SKIPS_BEFORE_AUTO_START_VM; }

Target:
we can do something like: numOfSkips = ++numOfSkips % MAXIMUM_NUM_OF_SKIPS_BEFORE_AUTO_START_VM; return numOfSkips == 0; and remove clearSkipCounter, no? if this was already properly verified, we can merge this and think about the change above on master-only
Source:
protected boolean isTransientException(Throwable e) { if(e instanceof SQLException) { final String sqlState = ((SQLException) e).getSQLState(); // retry on connection errors and insufficient resources // (see http://www.postgresql.org/docs/current/static/errcodes-appendix.html) return sqlState.startsWith("08") || sqlState.startsWith("53"); } return false; }

Target:
Of the "53" class of errors, I think only "53300" might be transient, no?
Source:
public JupiterActivity generateJupiterActivity(Operation op, User source, SPath editor) { // send(op, myMsgs, otherMsgs); JupiterActivity jupiterActivity = new JupiterActivity(this.vectorTime, op, source, editor); // add(op, myMsgs) to outgoing; if (!(op instanceof TimestampOperation)) { this.ackJupiterActivityList.add( new OperationWrapper(op, this.vectorTime.getLocalOperationCount())); } // myMsgs = myMsgs + 1; this.vectorTime = this.vectorTime.incrementLocalOperationCount(); return jupiterActivity; }

Target:
So you pointed me to this line and what is the problem here ? The problem is that discardAcknowledgedOperations is never called. This was never done in this method anyway.
Source:
public void testAssignExecutorInvalidExecutor() throws Exception { final ExecutableFlow flow = TestUtils.createExecutableFlow("exectest1", "exec1"); this.executionFlowDao.uploadExecutableFlow(flow); assertThatThrownBy( () -> this.assignExecutor.assignExecutor(flow.getExecutionId(), 1)) .isInstanceOf(ExecutorManagerException.class) .hasMessageContaining("non-existent executor"); }

Target:
Should it be assignExecutor(1, flow.getExecutionId())? Also how do you know 1 is a non-existent executor?
Source:
private static BackgroundHiveSplitLoader backgroundHiveSplitLoaderOfflinePartitions() throws Exception { ConnectorSession connectorSession = new TestingConnectorSession( new HiveSessionProperties(new HiveClientConfig().setMaxSplitSize(new DataSize(1.0, GIGABYTE))).getSessionProperties()); return new BackgroundHiveSplitLoader( SIMPLE_TABLE, createPartitionMetadataWithOfflinePartitions(), TupleDomain.all(), createBucketSplitInfo(Optional.empty(), ImmutableList.of()), connectorSession, new TestingHdfsEnvironment(), new NamenodeStats(), new TestingDirectoryLister(TEST_FILES), directExecutor(), 2, false); }

Target:
no `Exception` is thrown here
Source:
public String toString() { return methodPrefix.toString(); }

Target:
'methodPrefix.toString()' is redundant
Source:
private void setPlatformTextClassifier(@Nullable TextClassifier textClassifier) { android.view.textclassifier.TextClassificationManager textClassificationManager = (android.view.textclassifier.TextClassificationManager) mContext.getSystemService(Context.TEXT_CLASSIFICATION_SERVICE); android.view.textclassifier.TextClassifier platformTextClassifier = textClassifier == null ? null : new PlatformTextClassifier(mContext, textClassifier); textClassificationManager.setTextClassifier(platformTextClassifier); }

Target:
TCM is an optional Android system service. Check for null.
Source:
Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); if ("text/plain".equals(contentType.getMimeType())) { return getContent(httpEntity); } return parseJsonMetadata(httpEntity); }

Target:
mime type is mandatory
Source:
protected void doStop() { log.info("Stopping Netty server"); boss.shutdownGracefully(); if(!datagram) { wrkr.shutdownGracefully(); } try { sock.channel().closeFuture().sync(); } catch (InterruptedException e) { log.warn("Netty server stop interrupted"); Thread.currentThread().interrupt(); } log.info("Netty server stopped"); notifyStopped(); }

Target:
I think it is the boss who should be shut down if (!datagram)
Source:
public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); return new ChannelViewHolder((ChannelView) inflater.inflate(R.layout.channel_item_layout, parent, false)); }

Target:
Maybe pass the layout inflater as a param to the adapter.
Source:
public void onSelectionChanged(int selectedItemCnt) { int numberMergeSelections = adapter.numberMergeSelections; if (adapter.isMergeSelection && selectedItemCnt >= numberMergeSelections) { ToastUtil.showError(getContext(), "We can only merge " + numberMergeSelections + " projects"); } updateSelectionToggle(actionMode.getMenu().findItem(R.id.toggle_selection)); actionMode.setTitle(getResources() .getQuantityString(getActionModeTitleId(actionModeType), selectedItemCnt, selectedItemCnt)); }

Target:
is there a reason that this is displayed everytime? since this is shown when the second project is selected, it will always be there.
Source:
private boolean shouldBeDistributed(PlanNode planNode) { return planNode instanceof AggregationNode || planNode instanceof JoinNode || (planNode instanceof TopNNode && ((TopNNode) planNode).getStep().equals(TopNNode.Step.PARTIAL)); }

Target:
The method will grow (i once already wanted to add something here), so what about putting this in a more lengthy but more readable way? (Note, I also changed TopNNode's condition) ``` if (planNode instanceof JoinNode) { return true; } if (planNode instanceof AggregationNode) { return true; // here you could differentiate between partial/... } if (planNode instanceof TopNNode) { return ((TopNNode) planNode).getStep() != TopNNode.Step.FINAL; } return false; ```
Source:
public void testConcurrency() { final ServerTemplate serverTemplate = templateStorage.load(serverTemplateId); marshal("application/xml", serverTemplate); Thread disconnect = new Thread(() -> disconnect()); disconnect.start(); String response = marshal("application/xml", serverTemplate); LOGGER.info(response); }

Target:
```suggestion assertNotNull(response); ```
Source:
protected Void visitIntegerLiteral(IntegerLiteral node, Integer indent) { builder.append(String.format(Locale.ENGLISH, "%d", node.getValue())); return null; }

Target:
```suggestion builder.append(Integer.toString(node.getValue())); ``` Cheaper than going through `String.format`
Source:
private List<GerritQueryResult> executeQueryRest(String query) throws GerritException { List<GerritQueryResult> results = null; results = client.executeQueryRest(new NullProgressMonitor(), query); return results; }

Target:
This is essentially one line of code, I'd prefer to inline this.
Source:
public QueryWrapper(@JsonProperty("query") String query, @JsonProperty("queryType") String queryType) { this(query, queryType, ""); }

Target:
to avoid redundant pattern check : ```suggestion this(query, queryType, null); ```
Source:
private List<CoordinatorDuty> makeCompactSegmentsDuty() { List<CoordinatorDuty> duties = new ArrayList<>(); duties.add(compactSegments); return ImmutableList.copyOf(duties); }

Target:
Why not `return ImmutableList.of(compactSegments);` instead?
Source:
public CreateServerOptions networks(String... networks) { return networks(ImmutableSet.copyOf(checkNotNull(networks, "network should not be empty"))); }

Target:
The "standard" jclouds pattern would be `checkNotNull(networks, "networks")`, but in this case it's not doing the expected thing since a varargs argument cannot be `null`, it will be an empty array instead. If we want to enforce this check, it probably should be: ``` checkArgument(networks.length > 0, "networks should not be empty"); return networks(ImmutableSet.copyOf(networks)); ``` but since `networks(Iterable<String> networks)` already checks I don't think we need the check here.
Source:
private static AbbreviatedObjectId id(DiffEntry de) { return (de.changeType == ChangeType.DELETE ? de.oldId : de.newId); }

Target:
Style-nit: We don't put () around ?: in a return.
Source:
protected VariableReferenceExpression getVariableReference(RowExpression expression) { if (expression instanceof VariableReferenceExpression) { return ((VariableReferenceExpression) expression); } else { throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Expected a variable reference but got " + expression); } }

Target:
private
Source:
public boolean isLocalOnly() { switch (this) { case LOCAL: return true; default: return false; } }

Target:
it could be simpler `return this == LOCAL`
Source:
protected void findUsers(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, new DirectorySearchParameters("ADUSER@" + ((ProfileEntry) getProfile().getSelectedItem()).getAuthz() + ": " + searchString, SearchType.DirectoryUser, (String) getNamespace().getSelectedItem()), query); //$NON-NLS-1$ //$NON-NLS-2$ }

Target:
Done
Source:
public String getImageUrl(String id) { return getProvider().getUrl() + API_VERSION + "/images/" + id + "/file"; }

Target:
if it's v2 older hosts won't work since they use HEAD, no?
Source:
public User(@NonNull String username, @NonNull String password) { this(username, password, new HashMap<String, Integer>(), null); }

Target:
I recommend using Collections.emptyMap() instead
Source:
public final String consoleClientResourcesUrl() { String url = getString(DynamicMessageKey.CONSOLE_CLIENT_RESOURCES_URL); boolean isAbsolute = url.contains("://"); return isAbsolute ? url : Window.Location.getProtocol() + "//" + Window.Location.getHost() + //$NON-NLS-1$ "/" + BaseContextPathData.getInstance().getRelativePath() + url; //$NON-NLS-1$ }

Target:
no... this can be relative as well... see: frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/ReportInit.java
Source:
private boolean isFileEntryPackageable(ZipEntry entry) { String entryName = entry.getName(); return ApkBuilder.checkFileForPackaging(entry.getName()) && isValidMetaInfEntry(entryName); }

Target:
don't need this. Just refer to entry.getName() in both places
Source:
public void testList() { List<VirtualMachine> list = api().list(); for (VirtualMachine machine : list) { assertTrue(!machine.name().isEmpty()); } }

Target:
I'd just assert that it contains the created VM.
Source:
void addLayer(String id, StyleLayer layer) { layersById.put(id, layer); }

Target:
package-private?
Source:
public void setSelection(ITimeGraphEntry trace) { /* if there is a pending selection, ignore this one */ synchronized (fListenerNotifierLock) { if (fListenerNotifier != null && fListenerNotifier.hasSelectionChanged()) { return; } } fSelectedEntry = trace; fTimeGraphCtrl.selectItem(trace, false); adjustVerticalScrollBar(); }

Target:
idem
Source:
private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) { try { return SecurityActions.getConstructor(ClassFile.class, String.class, int.class, String.class, ClassLoader.class, Arrays2.EMPTY_STRING_ARRAY.getClass()) .newInstance(name, accessFlags, superclass, classLoader, interfaces); } catch (Exception e) { throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause()); } }

Target:
Why not use the constructor right away, i.e. without reflection?
Source:
public boolean addListener(String type, long id, ClassLoaderListener classLoaderListener) { final VirtualClassLoader localClassLoader = ((VirtualClassLoader) getLocalClassLoader(type, id)); return localClassLoader.addListener(classLoaderListener); }

Target:
We can change the return type of getLocalClassLoader only in the implementation to avoid the cast.
Source:
public static final void setPreferenceNodeId (String id) { if (fgPreferenceNodeId == null) { fgPreferenceNodeId = id; } }

Target:
JDT uses compact assignement, e.g. i= 3;
Source:
private void init() { // get the localhost. try { hostname = InetAddress.getLocalHost().getHostName(); hostname = "localhost"; } catch (UnknownHostException e) { logger.warn("Error getting the value of localhost. " + "Proceeding with 'localhost'.", e); } }

Target:
Please remove this. This is probably due to an incorrect /etc/hosts file in your test environment
Source:
protected OSImageToImage(JustProvider provider) { this.provider = provider; }

Target:
Make it package private by removing the `protected` modifier.
Source:
private Optional<Cookie> findCookieWithName(String cookieName, HttpClient httpClient) { Optional<Cookie> cookie = Arrays.stream(httpClient.getState().getCookies()) .filter(c -> cookieName.equals(c.getName())) .findFirst(); return cookie; }

Target:
return immediately, no need to store it in a local var
Source:
public void destroy() { // clients must be destroyed before the pools or // you will create a several second busy wait loop for (JettyHttpClient client : clients) { client.close(); } if (pool != null) { pool.close(); pool = null; if(injector.getExistingBinding(Key.get(MBeanExporter.class)) != null) { injector.getInstance(MBeanExporter.class) .unexport(generatedNameOf(QueuedThreadPoolMBean.class) + "_" + name); } } destroyed.set(true); }

Target:
This class is effectively a provider. Instead of doing the export directly, we should bind the JMX export when we bind IO pool and let the export happen the normal way.
Source:
private Set<String> expandRegionalChannelUris(String channelUri) { Set<String> expandedUris = null; if (BBC1_TXLOG_CHANNEL_URIS.contains(channelUri)) { expandedUris = BBC1_TXLOG_CHANNEL_URIS; } if (BBC2_TXLOG_CHANNEL_URIS.contains(channelUri)) { expandedUris = BBC2_TXLOG_CHANNEL_URIS; } return expandedUris == null ? null : Sets.difference(expandedUris, ImmutableSet.of(channelUri)); }

Target:
you could do the difference and return in inside the if, and save 2 checks.
Source:
public void testMultipleBatchesLateral_WithStreamingAgg() throws Exception { String sql = "SELECT t2.maxprice FROM (SELECT customer.c_orders AS c_orders FROM " + "dfs.`lateraljoin/multipleFiles/` customer) t1, LATERAL (SELECT CAST(MAX(t.ord.o_totalprice)" + " AS int) AS maxprice FROM UNNEST(t1.c_orders) t(ord) GROUP BY t.ord.o_orderstatus) t2"; testBuilder() .optionSettingQueriesForTestQuery("alter session set `%s` = true", PlannerSettings.STREAMAGG.getOptionName()) .sqlQuery(sql) .unOrdered() .baselineColumns("maxprice") .baselineValues(367190) .baselineValues(316347) .baselineValues(146610) .baselineValues(306996) .baselineValues(235695) .baselineValues(177819) .build().run(); }

Target:
Should "planner.enable_hashagg" be set to **false** ? "planner.enable_streamagg" defaults to **true** anyway.
Source:
public boolean isType(String value) { GlusterStatus volStatus = GlusterStatus.valueOf(value); for (GlusterStatus status : values) { if (status.equals(volStatus)) { return true; } } return false; }

Target:
This might throw IllegalArgumentException in case `value` doesn't match any enum constant. It's much easier to compare `value` to name() of enum constants: for (GlusterStatus status : values) { if (status.name().equals(value)) { return true; } } return false;
Source:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.channel().close(); }

Target:
`ctx.close()`
Source:
public CloseNoOpServerProtocolHandler(String websocketPath) { super(websocketPath, null, false); }

Target:
remove public
Source:
public MessageView(Context context, AttributeSet attrs) { super(context, attrs); setOrientation(VERTICAL); }

Target:
Since you are forcing the orientation, it might be a good idea to use the `super.setOrientation()` instead, override the `setOrientation()` method and only print a log or throw an exception if someone tries to mess with it
Source:
public Canvas addShapeIntoView(final Shape shape) { if (shape.getUUID() == null) { shape.setUUID(UUID.uuid()); } shape.getShapeView().setUUID(shape.getUUID()); getView().add(shape.getShapeView()); return this; }

Target:
Shouldn't it be a part of `shape#setUUID` method?
Source:
public boolean getRequiredParamBoolean(final String key) throws ActionParamsException { final String errMsg = "Required parameter '" + key + "' missing!"; final String val = getRequiredParam(key, errMsg); try { return Boolean.parseBoolean(val); } catch (Exception e) { throw new ActionParamsException(errMsg); } }

Target:
You don't need to give this string (even as other similar do) since it's the default message for getRequiredParam(key).
Source:
public void onPingFromClient(PingFromClientEvent event, EntityRef entity){ if (networkSystem.getMode().isServer()) { Instant end = Instant.now(); endMap.put(entity, end); updatePing(entity); } }

Target:
In the `@ReceiveEvent` annotation and in the `@RegisterSystem` annotation you can specify if a event handler / all event handlers of that class are for a server or client. So you don't need to check the mode of networkSystem.
Source:
public boolean areEqual(MapObject o1, MapObject o2) { if (o1 == null ^ o2 == null) { return false; } else if (o1 == o2) { return true; } else { return o1.id.equals(o2.id); } }

Target:
This block is useless.
Source:
public RedisMetadataStore(RedisConnectionFactory connectionFactory) { Assert.notNull(connectionFactory, "'connectionFactory' must not be null."); this.redisTemplate = new StringRedisTemplate(connectionFactory); this.redisTemplate.afterPropertiesSet(); }

Target:
`StringRedisTemplate` constructor takes care of it.
Source:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); m_toLeader = false; m_ackRequestedFromSender = true; }

Target:
Can you use the inherited "m_isLeaderToReplica" instead of adding a new "m_toLeader"? The message is either from leader to replica or from MPI to leader?
Source:
private CuEinvoiceDao getCuEinvoiceDao() { if (ObjectUtils.isNull(null)) { cuEinvoiceDao = SpringContext.getBean(CuEinvoiceDaoOjb.class); } return cuEinvoiceDao; }

Target:
This will always return true, did you want cuEinvoiceDao instead of null here
Source:
public static EchoTagStatementTree newEchoTagStatement(ExpressionTree expression, InternalSyntaxToken eosToken) { SeparatedList<ExpressionTree> expressionList = new SeparatedListImpl(Collections.singletonList(expression), Collections.emptyList()); return newEchoTagStatement(expressionList, eosToken); }

Target:
Can we make this method private?
Source:
private static TextSummarizer getLocalSummarizer() throws IOException { Collection<? extends TextSummarizer> summarizers = Lookup.getDefault().lookupAll(TextSummarizer.class ); if (!summarizers.isEmpty()) { summarizerToUse = summarizers.iterator().next(); return summarizerToUse; } throw new IOException("No summarizers found"); }

Target:
Perhaps it would be better to return null instead of throwing an exception? Nothing has really gone wrong. And then you wouldn't need that empty catch block.
Source:
public void verifyNoVideo() { if(checkIfElementOnPage(mediaNode)) throw new AssertionError("Media Node is still on the page"); else PageObjectLogging.log("verifyNoVideo", "Verified no video is on page", true, driver); }

Target:
could you please put it in brackets to make it easier to read?
Source:
private void startOrStopGeoDataListener() { if (requireGeodata) { geoDataSubscription = locationUpdater.start(GeoDirHandler.UPDATE_GEODATA); } else { geoDataSubscription.unsubscribe(); } }

Target:
Is it save to assign a new subscription here without unsubscribing a potentially existing previous subscription? Or to ask different: Can you guarantee this is not called two times in a row in the activity lifecycle with requireGeodata==true?
Source:
ZipFormatter( Formatters formatters, FormatterUtil formatterUtil, HtmlBuilder html) { this.formatters = formatters; this.util = formatterUtil; this.html = html; }

Target:
not needed.
Source:
private boolean clusterHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); return cluster != null && cluster.getArchitecture() != null && ArchitectureType.ppc.getFamily() == cluster.getArchitecture().getFamily(); }

Target:
I think I saw multiple ppc types in the enum: ppc, ppc64, ppcle, ppc64le
Source:
protected void createIndex(Connection conn, String indexExt, String columnName) throws PersistenceException { if (metaData.isIndexingDisabled()) return; boolean indexExists = indexExists(getIndexName(false, indexExt), conn); if (!indexExists) { String ddl = String.format("CREATE INDEX %s ON %s (%s)", getIndexName(true, indexExt), getTableName(), columnName); if (log.isTraceEnabled()) { log.tracef("Adding index with following DDL: '%s'.", ddl); } executeUpdateSql(conn, ddl); } }

Target:
We can make this private
Source:
public Object getValue() { if (value == null) { return null; } else { return value; } }

Target:
This should be simplified to just: >return value;
Source:
private boolean needProjectionNode (AbstractPlanNode root) { if ( false == root.planNodeClassNeedsProjectionNode()) { return false; } // If there is a complexGroupby at his point, it means that // display columns contain all the order by columns and // does not require another projection node on top of sort node. // If there is a complex aggregation case, the projection plan node is already added // right above the group by plan node. In future, we may inline that projection node. if (m_parsedSelect.hasComplexGroupby() || m_parsedSelect.hasComplexAgg()) { return false; } if (root instanceof AbstractReceivePlanNode && m_parsedSelect.hasPartitionColumnInGroupby()) { // Top aggregate has been removed, its schema is exactly the same to // its local aggregate node. return false; } return true; }

Target:
`false ==` is a peculiar way to express `!`. BTW, `peculiar` is a polite way to say `wrong`.
Source:
public void isExecutable_HeaderCellSelected() { when(scenarioGridModelMock.getSelectedCells()).thenReturn(Collections.emptyList()); when(scenarioGridModelMock.getSelectedHeaderCells()).thenReturn(Lists.create(selectedCell, selectedCell2)); assertTrue(handler.isExecutable(scenarioGridMock)); }

Target:
just one cell please
Source:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof XarSecurityRule)) { return false; } XarSecurityRule rhs = (XarSecurityRule) object; return new EqualsBuilder() .append(this.right, rhs.right) .append(this.simple, rhs.simple) .append(this.securityTool, rhs.securityTool) .isEquals(); }

Target:
This is not really relevant IMO. It's not data of that rules, just an internal helper. In practice this is always going to be true anyway since it's a singleton component.
Source:
public static boolean containsSearchAnnotations(XClass mappedClass) { List<XClass> hierarchy = ReflectionHelper.createXClassHierarchy( mappedClass ); for ( XClass clazz : hierarchy ) { if ( containsLocalSearchAnnotation( clazz ) ) { return true; } } return false; }

Target:
Any reason why you added `ReflectionHelper.`? Might as well remove it so that we see it's a method of this very class?
Source:
private static int computeNewVectorCapacity(int usedCapacity, int newPayload, int currentCapacity) { int newUsedCapacity = BaseAllocator.nextPowerOfTwo(usedCapacity + newPayload); assert newUsedCapacity >= 0; return newUsedCapacity <= currentCapacity ? currentCapacity : newUsedCapacity; }

Target:
`Math.max(newUsedCapacity, currentCapacity)` would be a little bit clearer here.
Source:
private static void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; try { CorfuServerNode current = activeServer; if (current != null) { activeServer.close(); } } catch (Throwable th) { log.error("cleanShutdown: failed during shutdown", th); } // Flush the async appender before exiting to prevent the loss of logs LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.stop(); }

Target:
This doesn't help at all, I suspect it can even cause loss of the logs. Logback already have solved the problem, and we have it enabled https://github.com/CorfuDB/CorfuDB/blob/30c8d154f59dfe22d4cc16b94ab9e2c51851c2e5/infrastructure/src/main/resources/logback.prod.xml#L5
Source:
public void preInit(FMLPreInitializationEvent event) { Log.setModLog(event.getModLog()); configDir = new File(event.getModConfigurationDirectory(), "antiqueatlas"); configDir.mkdir(); extTileIdMap = ExtTileIdMap.instance(); extTileConfig = new ExtTileConfig(new File(configDir, "tileids.json")); extTileConfig.load(extTileIdMap); // Assign default values AFTER the config file loads, so that the old saved values are kept: registerVanillaCustomTiles(); checkSaveConfig(); }

Target:
As I said in the last PR (https://github.com/AntiqueAtlasTeam/AntiqueAtlas/pull/205) that did something like this, this should use `LogManager.getLogger(...)`. Honestly, `Log#modLog` should just be changed to ```java private static final Logger LOGGER = LogManager.getLogger(AntiqueAtlasMod.ID); ```
Source:
public void close() { try { if (this.readingRaw.get() && !finalizeRaw() && LOGGER.isWarnEnabled()) { LOGGER.warn("Finalize on readRaw() returned false for " + this); } if (this.client.isConnected()) this.client.logout(); this.client.disconnect(); } catch (Exception e) { LOGGER.warn("failed to disconnect FTPClient", e); } }

Target:
Checkstyle violation: ``` [ant:checkstyle] [ERROR] /home/travis/build/spring-projects/spring-integration/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/FtpSession.java:157: 'if' construct must use '{}'s. [NeedBraces] ``` You can verify yourself locally using `gradlew clean :spring-integration-ftp:check`
Source:
protected FileType doGetType() throws Exception { return (this.stat == null) ? FileType.IMAGINARY : FileType.FILE_OR_FOLDER; }

Target:
No extra (clutter) please.
Source:
public EquivalentHashMap( int initialCapacity, float loadFactor, Equivalence<K> keyEq, Equivalence<V> valueEq) { int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; this.loadFactor = loadFactor; threshold = (int)(capacity * DEFAULT_LOAD_FACTOR); table = new Node[capacity]; this.keyEq = keyEq; this.valueEq = valueEq; }

Target:
`capacity * loadFactor` maybe?
Source:
private void mockSSHClient() { try { doNothing().when(sshclient).connect(); doNothing().when(sshclient).authenticate(); } catch(Exception e) }

Target:
just throw the exception upwards..
Source:
public static String sanitizeKey(final Contentlet vanityUrl) throws DotDataException, DotRuntimeException, DotSecurityException { Host host = hostAPI.find(vanityUrl.getStringProperty(VanityUrlContentType.SITE_FIELD_VAR), APILocator.systemUser(), false); return sanitizeKey(host.getIdentifier(), fixURI(vanityUrl.getStringProperty(VanityUrlContentType.URI_FIELD_VAR)), vanityUrl.getLanguageId()); }

Target:
![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove the redundant '!unknownSymbol!' thrown exception declaration(s). [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ARedundantThrowsDeclarationCheck)
Source:
protected void dataTemplateToJsonGenerator(Object data, DataSchema schema, JsonGenerator generator, boolean order) throws IOException { if (order) { JacksonTraverseCallback callback = new SchemaOrderTraverseCallback(schema, generator); Data.traverse(data, callback); } else { objectToJsonGenerator(data, generator, false); } }

Target:
You can revert this change now.
Source:
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { ListResponse<KubernetesSupportedVersionResponse> response = kubernetesVersionService.listKubernetesSupportedVersions(this); response.setResponseName(getCommandName()); setResponseObject(response); }

Target:
these exceptions are unacceptable (intended pun miserably failed) we are listing clusters, no resource-, allocation-, or any change related exception should ever occur. at most a entity not found kind of thing.
Source:
public void loggedInUserPropertyFalseTest() throws Exception { context.turnOffAuthorisationSystem(); configurationService.setProperty("webui.user.assumelogin", false); context.restoreAuthSystemState(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/authn/status") .header("X-On-Behalf-Of", eperson.getID())) .andExpect(status().isBadRequest()); context.turnOffAuthorisationSystem(); configurationService.setProperty("webui.user.assumelogin", true); context.restoreAuthSystemState(); }

Target:
the turnOff is not really needed
Source:
protected void addExtraHeaders(Builder webResource) { if (additionalHeaders != null) { for (String key : additionalHeaders.keySet()) { webResource.header(key, additionalHeaders.get(key)); } } }

Target:
Could use an entrySet.
Source:
private boolean hasNewFragment(EList<InteractionFragment> currentList, List<InteractionFragment> newList) { boolean newFragment = false; if (newList.size() > currentList.size()) { newFragment = true; } return newFragment; }

Target:
I think return (newList.size() > currentList.size()) is sufficient
Source:
void closeResultSets() throws SQLException { closeResultSets(activeResultSets); if (generatedKeysResultSet != null && !generatedKeysResultSet.isClosed()) { generatedKeysResultSet.internalClose(); } generatedKeysResultSet = null; }

Target:
This is unnecessary as generatedKeysResultSet is added to activeResultSets when created
Source:
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.apache.jasper.compiler.JspConfig", classLoader)) { try { String resourceName = getResourceName(view, environment); if (resourceLoader.getResource(resourceName).exists()) { return true; } return new File("src/main/webapp", resourceName).exists(); } catch (AccessControlException ex) { return false; } } return false; }

Target:
The scope of this `try` block is broader than necessary. It only needs to contain this line.
Source:
public Object visit(final AntlrBaseNode node) { return node.accept(this); }

Target:
Why does this return Object instead of T ?
Source:
public static void addDiskToVm(BaseDisk disk, Guid vmId) { DbFacade.getInstance().getBaseDiskDao().save(disk); VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId), VmDeviceType.DISK, VmDeviceType.DISK, null, true, false, ""); }

Target:
please remove alias setting (should be encapsulated in addManagedDevice
Source:
private static Throwable getConfigFailureException(ITestContext context) { Throwable t = null; for (IInvokedMethod method : context.getSuite().getAllInvokedMethods()) { ITestNGMethod m = method.getTestMethod(); if (m.isBeforeSuiteConfiguration() && (!method.getTestResult().isSuccess())) { t = method.getTestResult().getThrowable(); break; } } return t; }

Target:
return here
Source:
protected String toString(Operator operator) { if (Operator.STARTSWITH.equals(operator)) return LIKE; return operator.toString(); }

Target:
I recommend adding `{}` here
Source:
static UberDocument toUberDocument(final Object object) { if (object == null) { return null; } if (object instanceof UberDocument) { return (UberDocument) object; } if (object instanceof Iterable) { } else if (object instanceof Map) { } throw new IllegalArgumentException("Don't know how to handle type : " + object.getClass()); }

Target:
This looks like a leftover and it hasn't any usage. Can we remove it?
Source:
public ArgumentSplitter(String arguments) { this.arguments = arguments; }

Target:
There is no point exposing this constructor if there is not even a single public method. All methods are private (except for the static, which does not require a constructor to be used)
Source:
public LgoProducts getProducts() { LgoProducts products = null; try { products = this.proxy.getProducts( exchange.getNonceFactory().createValue(), exchange.getSignatureService()); } catch (HttpStatusIOException e) { LgoErrorAdapter.adapt(e); } return products; }

Target:
please improve error handling in accordance to: https://github.com/knowm/XChange/wiki/New-Implementation-Best-Practices#step-7 you should introduce and LgoException that implements HttpStatusExceptionSupport try catch adapt should be done in methods that implement generic interfaces, *Raw methods should throw our the LgoException
Source:
protected void addAttachmentToNote(T document, AccountingXmlDocumentBackupLink backupLink, Note note) { try { Attachment attachment = accountingXmlDocumentDownloadAttachmentService.createAttachmentFromBackupLink(document, backupLink); note.setAttachment(attachment); } catch (IOException e) { LOG.error("addAttachmentToNote, unable to create attachment: " + e.getMessage()); String message = MessageFormat.format( configurationService.getPropertyValueAsString(CuFPKeyConstants.ERROR_CREATE_ACCOUNTING_DOCUMENT_ATTACHMENT_DOWNLOAD), KFSConstants.BLANK_SPACE + backupLink.getLinkUrl()); throw new ValidationException(message); } }

Target:
Do you still need to prepend the blank space, now that you're using MessageFormat.format()? If not, then you should be able to simplify this a little further.
Source:
public Void getResult() { throw new UnsupportedOperationException(getClass().getName()); }

Target:
This is effectively final class, so just `throw new UnsupportedOperationException()`
Source:
public PlanWithProperties visitUnnest(UnnestNode node, PreferredProperties preferredProperties) { PreferredProperties translatedPreferred = preferredProperties.translate(variable -> { checkArgument(variable instanceof VariableReferenceExpression, "Expect VariableReferenceExpression"); return node.getReplicateVariables().contains(variable) ? Optional.of(variable) : Optional.empty(); }); return rebaseAndDeriveProperties(node, planChild(node, translatedPreferred)); }

Target:
Please add the actual type, just in case it ever fails
Source:
public ValidationResult isAnyDomainInProcess() { List<StoragePoolIsoMap> poolIsoMaps = getStoragePoolIsoMapDao().getAllForStoragePool(storagePool.getId()); for (StoragePoolIsoMap domainIsoMap : poolIsoMaps) { if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$status %1$s", StorageDomainStatus.Locked)); } } return ValidationResult.VALID; }

Target:
please put the correct status.
Source:
private boolean isFunctionNameMatch(RowExpression rowExpression, String expectedName) { if (castToExpression(rowExpression) instanceof FunctionCall) { return ((FunctionCall) castToExpression(rowExpression)).getName().toString().equalsIgnoreCase(expectedName); } return false; }

Target:
static
Source:
public boolean hasError() { return result != null && result.getType() != null && CommandResult.Type.ERROR.equals(result.getType()); }

Target:
We can slightly simplify: ```java return result != null && Objects.equals(CommandResult.Type.ERROR, result.getType()); ```
Source:
private void setupVdsNetworkInterfaceDao() { when(getDbFacadeMockInstance().getInterfaceDao()).thenReturn(vdsNetworkInterfaceDaoMock); List<VdsNetworkInterface> expectedVdsNetworkInterface = Collections.singletonList(vdsNetworkInterface); when(vdsNetworkInterfaceDaoMock.getVdsInterfacesByNetworkId(networkId)).thenReturn( expectedVdsNetworkInterface); }

Target:
Why did you have to change the order of the lines here?...
Source:
public void setProject(IProject project) { this.project=project; }

Target:
Do we need this method public ? The place where it's used is in the same package so protected/default should work ?
Source:
public List<String> values(String name) { return headers == null ? null : headers.get("Request-Id"); }

Target:
I think this should be `headers.get(name)`.
Source:
@Override protected Pair<Recipients, Boolean> doInBackground(Recipients... recipients) { Capability textCapability = DirectoryHelper.getUserCapabilities(context, recipients[0]).getTextCapability(); return new Pair<>(recipients[0], textCapability == Capability.SUPPORTED); }

Target:
dude
Source:
public void cleanup() { myIdeFrame = null; myNavigationHelper.cleanup(); myNavigationHelper = null; myStateComponent = null; myTaskContext = null; }

Target:
Generally speaking, there's no need to null out the fields of an object if no one is going to hold the reference to the object afterwards. The GC is going to do its job, you don't need to help. :)
Source:
public static DateTime setBeginValidTime(DateTime beginValidTimeArg, DateTime issueInstant) { DateTime beginValidTime = beginValidTimeArg; final DateTime now = new DateTime(); if (beginValidTime == null || beginValidTime.isAfter(now)) { beginValidTime = now; } // If provided time is after the given issue instant, // modify it to include the issue instant if (beginValidTime.isAfter(issueInstant)) { if (issueInstant.isAfter(now)) { beginValidTime = now; } } else { beginValidTime = issueInstant; } return beginValidTime; }

Target:
Why is this public?
Source:
private void setupRestrictedNotification() { final Resources res = getResources(mContext, mActiveDataSubId); final String title = res.getString(R.string.disable_tether_notification_title); final String message = res.getString(R.string.disable_tether_notification_message); showNotification(R.drawable.stat_sys_tether_general, title, message, ""); }

Target:
We do not have synchronized protection inside this function, If you would like to protect mUpdateLock from outside of this function, I think you may need to add a note to remind caller in the future to remember protect it.
Source:
private File getFeatureTypeDir( File featureTypesBaseDir, String namespacePrefix, String typeName) { return new File(featureTypesBaseDir, getDataStoreName(namespacePrefix, typeName)); }

Target:
Any specific reason to make this method no ``static`` anymore ?
Source:
public static void setupSystemProperties() { int freePort = TestUtilGit.findFreePort(); System.setProperty("org.uberfire.nio.git.daemon.port", String.valueOf(freePort)); logger.info("Git port used:{}", freePort); //These are not needed for the tests System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); }

Target:
Just a note about consistency: does it make any sense to find free port and set system property if you're setting `org.uberfire.nio.git.daemon.enabled=false` on the lines below that?
Source:
public void setPreferredAgencies(String s) { if (s != null && !s.equals("")) preferredAgencies = Sets.newHashSet(s.split(",")); }

Target:
"This method is not actually very useful and will likely be deprecated in the future."
Source:
synchronized void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}updating builder with topic(s) with possible matching regex subscription(s)", logPrefix, subscriptionUpdates.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); }

Target:
Thanks for the PR! I just noticed these two log messages are completely redundant; can we remove one of them, or combine into a single log?
Source:
public void releaseCursor(Cursor cursor) { try { cursor.release(); if (cursors.remove(cursor)) { if (provider.isClosed() && cursors.isEmpty()) { releaseResources(); } } } catch (Exception e) { LOGGER.warn("Exception was found trying to release cursor resources. Execution will continue", e); } finally { statistics.decrementOpenCursors(); } }

Target:
why not put this with an `&&` in the previous `if`?
Source:
protected void doStop() { autoEncryptionSupport.close(); super.doStop(); LDAPCache.clear(); }

Target:
Check for null missing?
Source:
private Now(A a) { this.a = a; }

Target:
make the constructor package private instead of private to avoid going through a generated synthetic constructor.
Source:
private String getWorkspaceRelativePath(String sourcePath) { if (org.apache.commons.lang.StringUtils.isBlank(sourcePath) || sourcePath.contains("{")) { return sourcePath; } IPath absolutePath = new Path(sourcePath); IContainer container = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(absolutePath); if (container != null) { return container.getFullPath().toPortableString(); } return null; }

Target:
I am not sure that toPortableString() is preferred here to just toString(). IPath.toString() makes only separator '/' for all platforms and it is what we need. Docs say that if toPortableString() is used it has to be matched with fromPortableString() when converting back to Path. toPortableString() doubles all ':' after the one that belongs to the device part (for Windows). For example "c:\one\two:x" will be transformed into "c://one/two::x". If segments have no ':' symbols, then there is no difference from toString(). However if a segment has ':' symbol, fromPortableString() is necessary to restore the original path, even for Linux.