auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean doSelect(Viewer viewer, Object parent, Object element) { if (element instanceof PackageFragmentRootContainer) { if (isApplicable() && viewer instanceof StructuredViewer) { PackageFragmentRootContainer rootContainer = (PackageFragmentRootContainer) element; if (rootContainer.getChildren().length > 0) { return hasFilteredChildren((StructuredViewer) viewer, rootContainer); } return false; } } return true; }

Target:
convert to conditional expression (? :).
Source:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); List<String> types = new ArrayList<String>(session.getLogManager().getTypes()); Collections.sort(types); return createResponse(types); }

Target:
Definitely remove the sorting. If possible, don't convert to a List either, if JSON serialization prints a Set as a JSON array.
Source:
public boolean addStateTransition(final ActivationState from, final EventType event, final ActivationState to) { Objects.requireNonNull(from, "From state cannot be null!"); Objects.requireNonNull(event, "Event cannot be null!"); Objects.requireNonNull(to, "To state cannot be null!"); Transition transition = new Transition(from, event, to); return addStateTransition(transition); }

Target:
Duplicate non-null check (also done in Transition).
Source:
Type leastUpperBound(List<Type> typeAlternatives) { return types.leastUpperBound(typeAlternatives.toArray(new Type[typeAlternatives.size()])); }

Target:
Why convulotions between list and array ?
Source:
public Response getOpenApiSpec(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type, @Context ServletConfig config, @Context Application app) throws Exception { setOpenApiConfiguration(oasConfig); Response response = super.getOpenApi(headers, config, app, uriInfo, type); response.getHeaders().add("Access-Control-Allow-Origin", "*"); return response; }

Target:
Still not thread safe. Needs to be done at startup / postconstruct.
Source:
public Optional<RestRouterConfiguration> build() { if (this.enabled) { try { validate(); } catch (Exception e) { throw logger.configurationValidationError(e); } return Optional.of(new RestRouterConfiguration(ip, port)); } return Optional.empty(); }

Target:
I'm really used to the builders creating all their children all the time, is it really worth doing it differently here?
Source:
protected void initSelectedType() { final VmInterfaceType defaultNicType = getDeafultNicTypeByProfile(); final Collection<VmInterfaceType> vnicTypes = supportedVnicTypes == null ? new ArrayList<VmInterfaceType>() : supportedVnicTypes; if (getNicType().getItems() != vnicTypes) { getNicType().setItems(vnicTypes, defaultNicType); } else { getNicType().setSelectedItem(defaultNicType); } }

Target:
Why not getNicType().getItems() != null?
Source:
public TestToolUtils() throws IOException { super(); }

Target:
Why does this need a super()?
Source:
private Guid getStorageDomainId(Guid poolId, StorageDomainType type, StorageDomainStatus status) { return getStorageDomains(poolId, type, status).stream().map(StorageDomain::getId).findFirst().orElse(Guid.Empty); }

Target:
Isn't there a way to first of all get the first item and only if present return the idea? Can save the mapping of the complete list just to return the first one (IIUC)
Source:
public static List<PostAggregator> prunePostAggregators(TopNQuery query) { return AggregatorUtil.pruneDependentPostAgg( query.getPostAggregatorSpecs(), query.getTopNMetricSpec().getMetricName(query.getDimensionSpec()) ); }

Target:
This doesn't need to be public, it's only called from within this file.
Source:
private boolean isSuspiciousClassInstantiation(ExpressionTree callee) { if (callee.is(Tree.Kind.NAMESPACE_NAME)) { NamespaceNameTree classNameTree = (NamespaceNameTree) callee; QualifiedName className = getFullyQualifiedName(classNameTree); return SUSPICIOUS_CLASS_INSTANTIATIONS.stream().anyMatch(className::equals); } return false; }

Target:
I would put this method just after `isGlobalGetOptMethod()`, to group methods in logical call order.
Source:
private PageMode getMode() { final PageMode currentMode = PageMode.get(request); return currentMode.showLive ? currentMode : APILocator.getHTMLPageAssetRenderedAPI().getDefaultEditPageMode(user, request, uri, response); }

Target:
why are you removing the response, some of the thing we have figured out is that the request must be always coming together with the response, even if it is not used at this time, could be in the future
Source:
public File getDirectory() { if (tmpdir == null) { tmpdir = getTemporaryDirectory(); if (tmpdir == null) { tmpdir = createDirInsideApplication(); } } return tmpdir.toFile(); }

Target:
I'd put this if outside the other. but :+1: anyway... no need for locks, since the temp dir won't change (or shouldn't, anyway)
Source:
public boolean matches(ILoggingEvent actual) { // Match only the first line to skip the validation of hex-dump format. actualMsg = actual.getMessage().split("(?s)[\\r\\n]+")[0]; if (actualMsg.matches(expected)) { // The presence of a newline implies a hex-dump was logged return actual.getMessage().contains(NEWLINE) == shouldContainNewline; } else { return false; } }

Target:
nit: remove `else` as you return in the `if` block anyway.
Source:
private static void addPropertyVariableToResult(Collection<Pair<Object, String>> result, String element) { if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } }

Target:
I think this method has no need to be `static`
Source:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); List<String> extensionJobNames = new ArrayList<>(); if (null != extensionJobs && !extensionJobs.isEmpty()){ for (ExtensionJobsBean extensionJobsBean: extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } return extensionJobNames; } else { return extensionJobNames; } }

Target:
Unnecessary else. You can just return extensionJobNames outside the if statement.
Source:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; displayPatchSetsInReverseOrder = false; displayPersonNameInReviewCategory = true; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; }

Target:
I thought the default was false.
Source:
public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) { if (!isValidIp(ipAddress)) { return false; } if (!isValidCIDR(cidr)) { return false; } // check if the gatewayip is the part of the ip range being added. // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links // GW Netmask Stat IP End IP // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1 // https://tools.ietf.org/html/rfc3021 // Added by Wilder Rodrigues final SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress); return !isInRange; }

Target:
why did you reverse this return value @kansal ? I missed it in the first itteration
Source:
public void edit(final UnitVmModel object) { super.edit(object); if (object.getIsNew()) { object.getNumOfDesktops().setEntity(1); } prestartedVmsEditor.setEnabled(true); }

Target:
isn't it true by default?
Source:
public String[] getProtocolsMask(long noOpt) { ctx.setOptions(noOpt); return WolfSSL.getProtocolsMask(noOpt); }

Target:
We should handle the case where "ctx" is null here. Consider either returning null or throwing a IllegalStateException similar to how other methods in WolfSSLContext.java do.
Source:
public synchronized boolean installSingleNodeLayoutIfAbsent() { if ((Boolean) getServerConfig().get("--single") && getCurrentLayout() == null) { setCurrentLayout(getNewSingleNodeLayout()); log.error("HERE ====="); return true; } return false; }

Target:
remove
Source:
public DrillFileSystem(Configuration fsConf, OperatorStats operatorStats) throws IOException { // Configuration objects are mutable, and the underlying FileSystem object may directly use a passed in Configuration. // In order to avoid scenarios where a Configuration can change after a DrillFileSystem is created, we make a copy // of the Configuration. this.fsConf = new Configuration(fsConf); this.underlyingFs = FileSystem.get(this.fsConf); this.codecFactory = new CompressionCodecFactory(this.fsConf); this.operatorStats = operatorStats; this.initialized = true; }

Target:
We can convert `this.fsConf` to be a local variable and in `getConf()` do `return new Configuration(underlyingFs.getConf());`
Source:
@Test public void testParse() throws NoSuchAuthorityCodeException { final URN_Parser parser = URN_Parser.buildParser("urn:ogc:def:CRS:EPSG:6.11.2:4326"); assertEquals("crs", parser.type.name); assertEquals("EPSG", parser.authority); assertEquals("6.11.2", parser.version.toString()); assertEquals("4326", parser.code); assertEquals("EPSG:4326", parser.getAuthorityCode()); }

Target:
this is just white space changes right?
Source:
public void afterPropertiesSet() throws Exception { this.sslContext = this.sslContextSupport.getSSLContext(); Assert.notNull(this.sslContext, "SSLContext must not be null"); }

Target:
Not related to this fix, but can't we get rid of this extra `InitializingBean` operation and just `getSSLContext()` directly in the ctor ?
Source:
public int hashCode() { return Objects.hash( snapshotId, clusterId, volumeId, snapshotName, status, description, status ); }

Target:
status repeated twice. I guess it was there in the original code too.
Source:
public Model getUPDATEModel(Representation representation) { return new ModelImpl() .property("condition", new StringProperty()) .property("patient", new StringProperty()) .property("clinicalStatus", new StringProperty()) .property("verificationStatus", new StringProperty()) .property("previousVersion", new StringProperty()) .property("onsetDate", new StringProperty()) .property("voided", new StringProperty()) .required("condition").required("onsetDate"); }

Target:
What does the above line mean?
Source:
public String getHostFingerprint() throws IOException { if (_client == null) { throw new java.net.ConnectException("SSH is not connected"); } return ((EngineSSHClient)_client).getHostFingerprint(); }

Target:
please import this.
Source:
public void invite(final String friend) throws IOException { try { new JdbcSession(this.sql.source()) // @checkstyle LineLength (1 line) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(1) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } }

Target:
@ekondrashev what `1` means here?
Source:
public AddVdsVDSCommand(P parameters) { super(parameters, false); }

Target:
false=>true (after changing to isNewHost)
Source:
void run() { if (fused) { return; } Observer<? super Long> actual = this.actual; long e = end; for (long i = index; i != e && get() == 0; i++) { actual.onNext((long)i); } if (get() == 0) { lazySet(1); actual.onComplete(); } }

Target:
unnecessary cast to long
Source:
private void fireEventsFor(OLogSequenceNumber lsn) { // may be executed by only one thread at every instant of time final ConcurrentNavigableMap<OLogSequenceNumber, Runnable> eventsToFire = events.headMap(lsn, true); for (Runnable runnable : eventsToFire.values()) runnable.run(); eventsToFire.clear(); }

Target:
Unfortunately here we can have a situation when some events can be lost. I meant that ```eventsToFire``` map can have at the moment of call of method more elements than were processed in the loop because ```eventsToFire``` is backed by ```events``` map.
Source:
public void testPurgeDeletedVault() { api().purgeVault(LOCATION, vaultName); Object[] args = { resourceGroupName, vaultName, false }; checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not purged before timeout"); }

Target:
Unused args?
Source:
public long estimateMemorySize() { return SIZE_OF_OGC_POINT + (point != null ? point.estimateMemorySize() : 0) + (esriSR != null ? esriSR.estimateMemorySize() : 0); }

Target:
In a good implementation, the spatial reference instance should be shared between all instances of geometry coming the same dataset, so usually the esriSR size would not contribute to OGC types, but we don't enforce that on geometry side right now.
Source:
public void auditResponseMessage(T request, K response, AssertionType assertion, NhinTargetSystemType target, String direction, String _interface, Boolean isRequesting, Properties webContextProperties, String serviceName) { LOG.trace("--- Before auditing of response message ---"); if (getAuditLogger() != null && isAuditLoggingOn(serviceName)) { getAuditLogger().auditResponseMessage(request, response, assertion, target, direction, _interface, isRequesting, webContextProperties, serviceName, getAuditTransforms()); } LOG.trace("--- After auditing of response message ---"); }

Target:
Should these cases be reverse? (i.e., don't instantiate the logger unless audit logging is on)
Source:
public GeoJsonLayer(GoogleMap map, JSONObject geoJsonFile) { if (geoJsonFile == null) { throw new IllegalArgumentException("GeoJSON file cannot be null"); } mBoundingBox = null; GeoJsonParser parser = new GeoJsonParser(geoJsonFile); // Assign GeoJSON bounding box for FeatureCollection mBoundingBox = parser.getBoundingBox(); HashMap<GeoJsonFeature, Object> geoJsonFeatures = new HashMap<>(); for (GeoJsonFeature feature : parser.getFeatures()) { geoJsonFeatures.put(feature, null); } mRenderer = new GeoJsonRenderer(map, geoJsonFeatures); storeRenderer(mRenderer); }

Target:
I believe `mRenderer` should be converted to a local variable (instead of member variable) here? `GeoJsonLayer` extends `Layer`, and there is a reference to the `GeoJsonRenderer` superclass `Renderer` within `Layers.storeRenderer()`.
Source:
protected int computeNewLength(int[] dimValSelector, int numProcessed, int numToProcess) { int valid = 0; int length = 0; for (int i = numProcessed; i < dimValSelector.length; i++) { length++; if (SKIP_POSITION_VALUE != dimValSelector[i]) { valid++; } if (valid == numToProcess) { break; } } return length; }

Target:
this condition can be incorporated into the for loop
Source:
protected IMemoryBlockRetrieval createMemoryBlockRetrieval(String model, ILaunchConfiguration config, DsfSession session) { DsfMemoryBlockRetrieval memRetrieval = null; try { memRetrieval = new DsfMemoryBlockRetrieval(model, config, session); } catch (DebugException e) { DsfPlugin.getDefault().getLog().log(e.getStatus()); } return memRetrieval; }

Target:
I think this should throw the DebugException and let the caller deal with it. Someone else may want to do something else than log the error.
Source:
private int getLength(Object o, int index) { if (o instanceof InstructionList) { // we do not store the last point of an instruction Instruction instruction = ((InstructionList) o).get(index); int size; if(instruction instanceof ViaInstruction) size = 0; else size = instruction.getPoints().size(); // the last point of instruction (i.e. first point of next instruction) is not included return size; } if (o instanceof List) { return ((List<PathDetail>) o).get(index).getLength(); } throw new IllegalStateException("We can only handle PathDetails or InstructionList in PathSimplification"); }

Target:
Here I would expect 'getPoints.size-1' for both cases
Source:
private DataPointAssignment marshallToDomain(DataPointAssignmentDto dto) { final DataPointAssignment dpa = new DataPointAssignment(); BeanUtils.copyProperties(dto, dpa); if (dto.getKeyId() != null) { dpa.setKey(KeyFactory.createKey("DataPointAssignment", dto.getKeyId())); } //Lists must be copied separately dpa.setDataPointIds(dto.getDataPointIds()); return dpa; }

Target:
The `BeanUtils.copyProperties()` cant handle this?
Source:
protected boolean equivalent(Constraint constraint) { if (constraint == this || constraint instanceof IsTreeTableConstraint) { return true; } return false; }

Target:
only one return is possible here.
Source:
private Collection<CHGraphImpl> getAllCHGraphs() { // todo: this method is only used to have a 'view' on the two collections. we could also create this only once // as long as the graph collections are only modified in the constructor (otherwise we would have to make sure // the lists are in sync). another option would be something like guava concat. List<CHGraphImpl> result = new ArrayList<>(); result.addAll(nodeBasedCHGraphs); result.addAll(edgeBasedCHGraphs); return result; }

Target:
A minor optimization here is to create the new ArrayList with the nodeBasedCHGraphs already or at least init the size with node+edge
Source:
@Override public boolean equals(Object other) { return other != null && (other instanceof Module) && Objects.equals(name, ((Module)other).name); }

Target:
`other != null` is redundant with `other instanceof Module`, which already returns `false` when `other` is `null`.
Source:
public static boolean textContains(String actual, String text, boolean ignoreCase) { return ignoreCase ? StringUtils.containsIgnoreCase(actual, text) : StringUtils.contains(actual, text); }

Target:
Yes, I agree that there is no "a lot of sense" and this topic is... debatable. From my point of view, "private static" is still make sense because 1) it emphasizes the fact that this method doesn't depend on other class members (doesn't use internal state) 2) JVM doesn't pass `this` as the first parameter to such the methods Here are my points. The last call, of course, in on @Hi-Fi and you :)
Source:
public List<String> getRepositoryDirectories() { return new ArrayList<>(repositoryDirectories); }

Target:
File
Source:
protected void configureDispatch() { bindAnnotated(RpcDispatchHooks.class).to(builder.getDispatchHooks()).in(Singleton.class); bind(RpcDispatchCallFactory.class).to(DefaultRpcDispatchCallFactory.class).in(Singleton.class); bind(DispatchAsync.class).to(RpcDispatchAsync.class).in(Singleton.class); }

Target:
You do not need bindAnnotated, since there's only one implementation of RpcDispatchHooks. bindAnnotated was used to bind an interface for the RPC and REST dispatchers to different implementations
Source:
protected void onExportToCsv() { GWT.log(this.toString() + "onExportToCsv"); scenarioSimulationEditorWrapper.onExportToCsv(getExportCallBack(), new ScenarioSimulationHasBusyIndicatorDefaultErrorCallback(view), context.getStatus().getSimulation()); }

Target:
Is this log necessary?
Source:
public QuotaProgressBar() { super(); tooltip = new WidgetTooltip(this); }

Target:
super is implied
Source:
public TestApplicationContext() { super(); }

Target:
As I said: `TestUtils.createTestApplicationContext()` so, no changes here, please.
Source:
public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException { final long docId = Long.parseLong(documentId); updateCurrentStorageManagerIfNeeded(docId); final FileCursor result = new FileCursor(projection); result.addFile(mCurrentStorageManager.getFileById(docId)); return result; }

Target:
Here it is been generated sometimes a NullPointer exception, because `mCurrentStorageManager` is found in the StorageManager Map with a different id of the current storage managers.
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { if (this.isSAS){ request = filterSAS(request, this.credential); } else { request = filterKey(request); } utils.logRequest(signatureLog, request, "<<"); return request; }

Target:
[bit] prefer inline conditionals for this kind of stuff: ```java request = this.isSAS ? filterSAS(request, this.credential) : filterKey(request); ```
Source:
public void setTTL(K key, long ttl, TimeUnit timeunit) { if (getNodeEngine().getClusterService().getClusterVersion().isLessThan(Versions.V3_11)) { throw new UnsupportedOperationException("setTTL method is available when cluster version is 3.11 or higher"); } checkNotNull(key); setTTLInternal(key, ttl, timeunit); }

Target:
If we add this version check inside `default-record-store`, client initiated operations can also be caught.
Source:
public MessageChannel bindDynamicPubSubProducer(String name) { MessageChannel channel = this.directChannelProvider.lookupSharedChannel(name); if (channel == null) { channel = this.directChannelProvider.createAndRegisterChannel(name); bindPubSubProducer(name, channel); } return channel; }

Target:
Why is `bindDynamicProducer` `synchronized`, but this one not? I need to know more about this `MessageBus` stuff and where it is used from, to determine which behaviour is correct for this methods, but I hope you can provide correct answer anyway
Source:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { // todo: extract common interface super.visitFunctionOrMethodDeclaration(o); check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { super.visitFunctionLit(o); check(o.getSignature(), o.getBlock(), holder); } }; }

Target:
`check` does checkCanceled
Source:
public JwtAuthenticationToken(Jwt jwt) { super(jwt); this.name = this.getToken().getSubject(); }

Target:
This make sense, since `getToken()` is `final`, but what would you think of just doing: ```suggestion this.name = jwt.getSubject(); ``` So that readers of this code have fewer methods to jump through to understand the code.
Source:
public void start() { cacheName = ByteString.fromString(cache.getName()); this.transactional = configuration.transaction().transactionMode().isTransactional(); this.totalOrderProtocol = configuration.transaction().transactionProtocol().isTotalOrder(); this.distributedOrReplicated = configuration.clustering().cacheMode().isDistributed() || configuration.clustering().cacheMode().isReplicated(); }

Target:
no longer used as well.
Source:
private URL getUrl() { String urlString = null; URL url = null; try { urlString = oProxyHelper .getAdapterEndPointFromConnectionManager(DIRECT_CONFIG_SERVICE_NAME); } catch (ConnectionManagerException ex) { LOG.error("Error reading directConfig Url cannot be found: {}", ex.getLocalizedMessage(), ex); } try { url = new URL(urlString); } catch (MalformedURLException ex) { LOG.error("Error while converting urlString into Url format {}", ex.getMessage(), ex); } return url; }

Target:
I am OK with just using ex.getErrorMessage() than getLocalizedMessage(), but I do agree that we should try to stick with one method in our code for loggers.
Source:
public List<SpoonFolder> getSubFolders() { List<SpoonFolder> result = new ArrayList<>(); Set<SpoonFolder> distinctSet = new HashSet<>(); for (SpoonFile f : getAllFiles()) { SpoonFolder folder = f.getParent(); if (distinctSet.add(folder)) { result.add(folder); } } return Collections.unmodifiableList(result); }

Target:
are your sure hashCode/equals of SpoonFolder are correct? I'm not sure they are well tested.
Source:
public MockHttpServletRequest newPutRequest(String requestURI, Object content) { MockHttpServletRequest request = request(RequestMethod.PUT, requestURI); try { String json = new ObjectMapper().writeValueAsString(content); request.setContent(json.getBytes("UTF-8")); } catch (Exception e) { throw new RuntimeException(e); } return request; }

Target:
Instead of the line above, why don't you just call newPutRequest(requestURI, json)?
Source:
private int[] propertyIds() { int props[] = new int[numberOfProps]; for ( int i = 0; i < numberOfProps; i++ ) { props[i] = i; } return props; }

Target:
`int[] props` would make everyone including the style checker much happier
Source:
public void shouldPurgeAnAutoGenerationOption() throws Exception { MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService .getAutoGenerationOption(Context.getPatientService().getPatientIdentifierTypeByUuid(getUuid()))); }

Target:
How sure are you that it was not null before the purging?
Source:
public Page appendColumn(Block block) { requireNonNull(block, "block is null"); if (positionCount != block.getPositionCount()) { throw new IllegalArgumentException("Block does not have same position count"); } Block[] newBlocks = Arrays.copyOf(blocks, blocks.length + 1); System.arraycopy(blocks, 0, newBlocks, 0, blocks.length); newBlocks[blocks.length] = block; return new Page(newBlocks); }

Target:
Why both Arrays.copyOf and System.arrayCopy?
Source:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } finally { // ignored } }

Target:
empty finally block
Source:
private void completeAllExceptionally(Throwable t) { List<Data> completed; synchronized (futures) { completed = new ArrayList<>(futures.size()); completed.addAll(futures.values()); } for (Data data : completed) { data.cancelFuture.cancel(false); data.completeExceptionally(t); } }

Target:
why not use `new ArrayList<>(futures.values());`
Source:
public final int hashCode() { return (int) (w2 >>> 32); }

Target:
Why use only w2? Why the right shift? Likely it doesn't really matter.
Source:
private void close() { try { closeExecutors(); m_loader.close(); if (m_client != null) { m_client.close(); m_client = null; } } catch (Exception ex) { // Ignore } }

Target:
should loader also be checked if it's non-null so that if follows similar paradigm as client. This way can call close() from main()'s exception block -> case where initialize fails in initializing loader for some reason and the logic can thereby make sure the initialized client connection gets closed and is not leaked.
Source:
private static void writeContents( FileSystemAbstraction fileSystemAbstraction, File file, String contents ) { byte[] bytes = contents.getBytes(); try ( StoreChannel storeChannel = fileSystemAbstraction.create( file ) ) { storeChannel.write( ByteBuffer.wrap( bytes ) ); storeChannel.close(); } catch ( IOException e ) { throw new RuntimeException( e ); } }

Target:
The try-with-resources takes care of the closing, right?
Source:
public boolean getAllowUntrustedCertificate() { return vsConnectionConfig != null && vsConnectionConfig.getAllowUntrustedCertificate(); }

Target:
This change seems unnecessary. Best keep this PR limited to _just_ what's necessary to achieve this PR's aims.
Source:
public StopVmCommandBase(T parameters) { super(parameters); setStoragePoolId(getVm().getstorage_pool_id()); }

Target:
A DB call inside the constuctor - not a good practice.
Source:
public String getSQL() { String left = getContextSQL(nodes[LEFT]); String right = getContextSQL(nodes[RIGHT]); StringBuffer sb = new StringBuffer(); sb.append(left).append(' ').append(Tokens.T_STARTS).append(Tokens.T_WITH).append(' '); sb.append(right); return sb.toString(); }

Target:
No space between STARTS and WITH??
Source:
public boolean isApplicable(UpgradeCheckRequest request) throws AmbariException { UpgradeType upgradeType = request.getUpgradeType(); UpgradeCheckInfo annotation = m_checkClass.getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return true; } // empty upgrade type or matching should return true UpgradeType[] upgradeTypes = annotation.required(); if (ArrayUtils.isEmpty(upgradeTypes) || ArrayUtils.contains(upgradeTypes, upgradeType)) { return true; } return false; }

Target:
simplify: `return ...`
Source:
private boolean validateHostPort(String string) { // https://stackoverflow.com/questions/2345063/java-common-way-to-validate-and-convert-hostport-to-inetsocketaddress try { // WORKAROUND: add any scheme to make the resulting URI valid. URI uri = new URI("my://" + string); // may throw URISyntaxException if (uri.getHost() == null || uri.getPort() == -1) { throw new URISyntaxException(uri.toString(), "URI must have host and port parts"); } } catch (URISyntaxException ex) { // validation failed return false; } // validation succeeded return true; }

Target:
maybe `return false` here at once would be better?
Source:
private int nextCorrelationId() { if (!isReserved(correlationId)) correlationId = MIN_RESERVED_CORRELATION_ID; return correlationId++; }

Target:
as before, this could be if-then-else without the increment below for the `if` case.
Source:
public BoltConnectionQueueMonitorAggregate( BoltConnectionQueueMonitor... monitors ) { this.monitors = new ArrayList<>( Arrays.asList( monitors ) ); }

Target:
Can this be just `this.monitors = Arrays.asList( monitors );`?
Source:
public void testElementAt() { int i = fullList.get(0); assertTrue(i == 1); try { fullList.get(fullList.size()); } catch (IndexOutOfBoundsException e) { return; } fail("Should raise an ArrayIndexOutOfBoundsException"); }

Target:
Do you think we should use `assertEquals()` (with as useful message) instead of `assertTrue()` so you'll get a useful stack trace if this fails? Future users might look at this file as an example of how to write a good JUnit test.
Source:
public String shell(PyObject[] args, String[] kws) { ArgParser ap = JythonUtils.createArgParser(args, kws); Preconditions.checkNotNull(ap); String cmd = ap.getString(0); if(args.length == 2) return impl.shell(cmd, ap.getInt(1)); else return impl.shell(cmd); }

Target:
needs a space after the if and needs both here and with the else.
Source:
public synchronized static Set<Class<? extends PhysicalOperator>> getSubTypes(ScanResult classpathScan) { final Set<Class<? extends PhysicalOperator>> ops = classpathScan.getImplementations(PhysicalOperator.class); logger.debug("Found physical operator classes: {}.", ops.size(), ops); return ops; }

Target:
Remove synchronized.
Source:
protected Map<String, Object> subsetMap(String prefix) { Map<String, Object> subset = new TreeMap<String, Object>(); for (Map.Entry<String, Object> e : configMap.entrySet()) { if (e.getKey() != null && e.getKey().startsWith(prefix)) { subset.put(e.getKey(), e.getValue()); } } return subset; }

Target:
Good catch on the null check. I forgot Maps can have `null` as a key.
Source:
public DesiredCapabilities getCapability(String testName) { DesiredCapabilities capabilities = new DesiredCapabilities(); // add capabilities based on dynamic _config.properties variables capabilities = initCapabilities(capabilities); if (R.CONFIG.getBoolean(SpecialKeywords.FULL_RESET_BEFORE_SUITE) && !R.CONFIG.get(SpecialKeywords.FULL_RESET_BEFORE_SUITE).isEmpty()) { LOGGER.info("Will be execute 'fullResetBeforeSuite'!"); executeFullResetBeforeSuite(capabilities); } return capabilities; }

Target:
Let's use debug level instead of info.
Source:
public synchronized IConnection connect(String storm_id, String host, int port, AtomicBoolean[] remoteBpStatus) { return new Client(topoConf, remoteBpStatus, clientChannelFactory, clientScheduleService, host, port, this); }

Target:
This no longer needs to be synchronized. That was used to protect connections, and is no longer needed if all we do is create a new Client.
Source:
public static ContentFilter get() { return ExtensionList.lookupSingleton(ContentFilters.class).isEnabled() ? ALL : DISABLED; }

Target:
It seems cleaner to me to get rid of the DISABLED filter and rewrite the code so that if `isEnabled` is false you never access the filters or create a `FilteredOutputStream` at all. I would also move the ALL filter to `ContentFilter.java` so that this file is just the anonymization config settings.
Source:
public AvailabilityType getAvailability() { ReadAttribute op = new ReadAttribute(getAddress(), "cache-status"); Result res = getASConnection().execute(op); if (res != null && res.isSuccess()) { if (res.getResult().equals("RUNNING")) { return AvailabilityType.UP; } } return AvailabilityType.DOWN; }

Target:
Likewise (re string comparison)
Source:
public boolean isEdgeWithRectilinearRoutingStyle() { boolean isEdgeRectilinearRoutingStyle = false; if (Routing.RECTILINEAR_LITERAL.getLiteral().equals(getRoutingStyle())) { isEdgeRectilinearRoutingStyle = true; } return isEdgeRectilinearRoutingStyle; }

Target:
to remove with the remark below
Source:
private void encodeEventData(ObjectOutput out, Object data) throws IOException { if(data != null) { out.writeObject(data); }else{ logger.warn("encodeEventData data is null"); } }

Target:
would it be better to implement it like this? ```java @Deprecated protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException { return Response.HEARTBEAT_EVENT; } ```
Source:
public void engineIsRunningNotification() { try { log.debug("DWH Heart Beat - Start"); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, () -> { heartBeatVar.setDateTime(new Date()); dwhHistoryTimekeepingDao.save(heartBeatVar); log.debug("DWH Heart Beat - End"); return null; }); } catch (Exception ex) { log.error("Error updating DWH Heart Beat: {}", ex.getMessage()); log.debug("Exception", ex); } }

Target:
Is there a need to have log.debug within transaction scope?
Source:
public BaseCassandraBolt withOutputFields(Fields fields) { Preconditions.checkNotNull("fields should not be null."); this.outputsFields.put(Utils.DEFAULT_STREAM_ID, fields); return this; }

Target:
Missing args, to -> `Preconditions.checkNotNull(fields, "fields should not be null.");`
Source:
private boolean isRelevant(EntityRef entity, Vector3f position) { return entity.isAlwaysRelevant() || worldProvider.isBlockRelevant(position); }

Target:
Have you considered what is the most likely case if any? Is it more likely that an entity is always relevant or is it more likely that the block at the given position is relevant? If the latter is more likely you'd gain a smidgen of performance by inverting the two expressions.
Source:
public String getClassificationValue(ClassificationScheme classification, ExtrinsicObjectType extrinsicObject) { RegistryObjectType registryObjectType = getClassification(classification, extrinsicObject); ClassificationType classType = null; if ((registryObjectType != null) && (registryObjectType instanceof ClassificationType)) { return ((ClassificationType) registryObjectType).getNodeRepresentation(); } return null; }

Target:
Declared but unused.
Source:
@Override public String toString() { return "MetaData{metadata=" + metadata + '}'; }

Target:
Not following XWiki codestyle.
Source:
public static FlowTrigger createTestFlowTrigger(final List<FlowTriggerDependency> deps, final Duration maxWaitDuration) { final FlowTrigger flowTrigger = new FlowTrigger( new CronSchedule("* * * * ? *"), deps, maxWaitDuration); return flowTrigger; }

Target:
The two lines can be merged into one.
Source:
public synchronized void recover(TaskId taskId) throws TooManyTasksFailedException { checkState(groupedLifespanScheduler.isPresent(), "groupedLifespanScheduler is not present for recoverable grouped execution"); if (anySourceSchedulingFinished) { throw new IllegalStateException("Recover after any source scheduling finished is not supported"); } groupedLifespanScheduler.get().onTaskFailed(taskId.getId(), sourceSchedulers); }

Target:
`new PrestoException(GENERIC_RECOVERY_ERROR)` ? Make sure that you rethrow it as is here: https://github.com/prestodb/presto/pull/12529/commits/1690f79d028246209297d0f9743bc0893773ec97#diff-e97f65103d2e8ce8ea2916e4ab25f522R539 (catch PrestoException specifically as a special case)
Source:
public Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = UNKNOWN.createBlockBuilder(new BlockBuilderStatus(), length); for (int i = start; i < start + length; i++) { blockBuilder.appendNull(); } return new Block[] {blockBuilder.build()}; }

Target:
why not `[0..length)`
Source:
public List<ExchangeDownloadStatus> refreshExchangeManager() { LOG.info("force the exchangeManager to refresh: {}"); ExchangeManagerUtil exUtil = new ExchangeManagerUtil(); return exUtil.forceRefreshExchanges(); }

Target:
I don't think we need to LOG.info any-more; we can used LOG.debug or removed.
Source:
protected void postShutdown() { logger().debug("Shutting down the elasticsearch index provider '{0}' in repository '{1}'", getName(), getRepositoryName()); try { client.close(); esNode.stop(); } catch (Exception e) { } }

Target:
shouldn't the exception be logged ?
Source:
private void layoutWikiDataDescription(String description) { // set the text of the description... pageDescriptionText.setText(description); // and wait for it to lay out, so that we know the height of the description text. pageDescriptionText.post(new Runnable() { @Override public void run() { if (!parentFragment.isAdded()) { return; } // only show the description if it's two lines or less if (pageDescriptionText.getLineCount() > 2) { pageDescriptionText.setVisibility(View.GONE); } else { pageDescriptionText.setVisibility(View.VISIBLE); } } }); }

Target:
Also consider pageDescriptionText.setVisibility(pageDescriptionText.getLineCount() > 2 > View.VISIBLE : View.GONE); to emphasize that conditional effects function input and no other logic.
Source:
AsyncSession getSession() { return AsyncSession.this; }

Target:
Is there a reason to not make it `protected` ?
Source:
public static String get() { return props.getOrDefault(VERSION_RELEASE_KEY, "unset"); }

Target:
`getOrDefault` is not available in Java 7.
Source:
protected Composite createWidgets(Composite parent, CDKServer cdkServer, FormToolkit toolkit) { Composite composite = initializeSectionWidget(parent, toolkit); createChooseCredentialsWidgets(composite, toolkit); createEnvironmentWidgets(composite, toolkit, cdkServer); addRegistrationWidgets(parent, cdkServer, toolkit); return composite; }

Target:
![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Add the "@Override" annotation above this method signature [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1161)
Source:
private void drawTiles( Canvas canvas ) { if( mPreviouslyDrawnTiles.size() > 0 ) { drawTilesConsideringPreviouslyDrawnLevel( canvas ); } else { drawTilesWithoutConsideringPreviouslyDrawnLevel( canvas ); } Log.d( getClass().getSimpleName(), "prevous tile count: " + mPreviouslyDrawnTiles.size() ); }

Target:
TODO : remove that log before release.
Source:
private static void cleanUpOldFiles(File dir) { long cutoffTimestamp = System.currentTimeMillis() - (MAX_FILE_AGE_HOURS * Constants.HOUR_MS); File[] files = dir.listFiles(); for (File file : files) { if (!FileUtils.isFileNewer(file, cutoffTimestamp)) { delete(file); } } }

Target:
When do we decide to use `stream`?
Source:
boolean getAsBoolean() throws Exception; } /** Wait until {@code predicate} is satisfied, or fail, with a given timeout. */ public static void waitUntil( String message, int timeoutSeconds, BooleanSupplierWithThrow predicate) throws Exception { int sleep = 125; final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000; while (System.currentTimeMillis() < timeout) { if (predicate.getAsBoolean()) { return; } RunUtil.getDefault().sleep(sleep); } fail(message); }

Target:
nit: long ?
Source:
protected void endVmCommand() { setCommandShouldBeLogged(false); if (getVm() == null) { log.warn("VM is null, not performing full endAction"); setSucceeded(true); } getVm().setStatus(VMStatus.Down); getSnapshotDao().removeMemoryFromActiveSnapshot(getVmId()); getVmDynamicDao().update(getVm().getDynamicData()); setSucceeded(true); }

Target:
missing return here
Source:
protected LevelsClass getListClass() { LevelsClass element = new LevelsClass(); element.fromString(Joiner.on(getSeparator()).join(FluentIterable.from(Arrays.asList( enumType.getEnumConstants())).transform(GET_ACCESS_LEVEL_ENUM_IDENTIFIERS))); return element; }

Target:
element.fromString only returns a BaseProperty, it doesn't change the LevelsClass. i guess the method should only returns a new LevelsClass?
Source:
public void onRefresh() { super.onRefresh(); if (mFile != null) { // Refresh mFile mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); listDirectory(mFile); ((FileDisplayActivity)mContainerActivity).startSyncFolderOperation(mFile); Log_OC.d(TAG, "Parent etag= |" + mFile.getEtag() + "|"); } }

Target:
Remove this Log, please.
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlanNodeStatsEstimate that = (PlanNodeStatsEstimate) o; return Double.compare(that.outputRowCount, outputRowCount) == 0 && Double.compare(that.outputSizeInBytes, outputSizeInBytes) == 0 && Objects.equals(symbolStatistics, that.symbolStatistics); }

Target:
Change from `Object.equals` to `Double.compare` should be part of previous commit.
Source:
public BasicAuthDBConfig( final PasswordProvider initialAdminPassword, final PasswordProvider initialInternalClientPassword, final String initialAdminUser, final String initialAdminRole, final String initialAdminGroupMapping, final boolean enableCacheNotifications, final long cacheNotificationTimeout, final int credentialIterations ) { this.initialAdminPassword = initialAdminPassword; this.initialInternalClientPassword = initialInternalClientPassword; this.initialAdminUser = initialAdminUser; this.initialAdminRole = initialAdminRole; this.initialAdminGroupMapping = initialAdminGroupMapping; this.enableCacheNotifications = enableCacheNotifications; this.cacheNotificationTimeout = cacheNotificationTimeout; this.iterations = credentialIterations; }

Target:
nit: Suggest renaming `iterations` and its getter as well here
Source:
public void setWidth(String width, boolean isFixedLayout) { table.setWidth("100%", true); //$NON-NLS-1$ tableHeader.setWidth("100%", true); //$NON-NLS-1$ }

Target:
Please pass 'isFixedLayout' to the 'setWidth' methods
Source:
private void setCustomServer(String s) { SharedPreferences userPreferences = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance()); SharedPreferences.Editor e = userPreferences.edit(); e.putBoolean("useCustomSyncServer", true); e.putString("syncBaseUrl", s); e.commit(); }

Target:
same commit vs apply question here, one answer answers both
Source:
default List<Pattern> getExcludedResponseHeaderPatterns() { return emptyList(); }

Target:
Generally better to qualify than making static import; this makes me go look at where it's coming from (ie. did you implement your own for some reason?) I tend to use static imports for constants or in Unit tests where its very obvious what is not provided by custom code (ie. assertXXX(..), mock(..), etc.) ```suggestion return Collections.emptyList(); ```
Source:
public HelixAccountServiceFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry) { storeConfig = new HelixPropertyStoreConfig(verifiableProperties); accountServiceConfig = new HelixAccountServiceConfig(verifiableProperties); accountServiceMetrics = new AccountServiceMetrics(metricRegistry); notifier = accountServiceConfig.zkClientConnectString.equals(HelixAccountServiceConfig.INVALID_ZK_CLIENT_CONNECT_STRING) ? null : new HelixNotifier(accountServiceConfig.zkClientConnectString, storeConfig); }

Target:
I don't think the `if` case is required here since it is assumed that `accountServiceConfig.zkClientConnectString` is not invalid (it is used in `getAccountService()`). What do you think?
Source:
private void logExceptionBeforeFailOver(Exception ex, MessageHandler handler, Message<?> message) { if (this.logger.isInfoEnabled()) { this.logger.info("An exception was thrown by '" + handler + "' while handling '" + message + "': " + ex.getMessage() + ". Failing over to the next subscriber."); } else if (this.logger.isDebugEnabled()) { this.logger.debug("An exception was thrown by '" + handler + "' while handling '" + message + "'. Failing over to the next subscriber.", ex); } }

Target:
Debug has to be detected first otherwise we'll always take the INFO branch.
Source:
public void started() { IdgenTask.setEnabled(true); createLocationPrefixAttributeType(); log.info("Idgen Module Started..."); }

Target:
You should not be creating Location Attributes on idgen module startup. This is not a core function of the idgen module and might have other implications. If an implementer wants to use the LocationBasedPrefixProvider, then can take responsibility over ensuring that the correct LocationAttributeType and LocationAttributes exist.
Source:
private static List<RunOrderWithArguments> withEmptyArguments( RunOrder[] runOrders ) { List<RunOrderWithArguments> orderWithArguments = new ArrayList<RunOrderWithArguments>(); for ( RunOrder runOrder : runOrders ) { RunOrderArguments args = new RunOrderArguments( new ArrayList<String>() ); orderWithArguments.add( new RunOrderWithArguments( runOrder, args ) ); } return orderWithArguments; }

Target:
pls use diamond `new ArrayList<>();`
Source:
public String getResourceContent(String name) throws IOException { String output = ""; if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding output = FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); } else output = IOUtils.toString(is, DEFAULT_ENCODING); } } return output; }

Target:
This does not follow XWiki codestyle (missing { and }).
Source:
public void assertStartsWithCount(int eventsCount, String startsWith) { List<LogEntry> logs = auditBackend.queryLogs(new AuditQueryBuilder().predicates( Predicates.eq(LOG_EVENT_ID, ID_FOR_AUDIT_STORAGE_TESTS), new Predicate(new Reference(LOG_DOC_PATH), Operator.STARTSWITH, Literals.toLiteral(startsWith)))); assertEquals(eventsCount, logs.size()); }

Target:
Why not adding this to `Predicates` ?
Source:
public static boolean isInChain(Certificate cert, List<Certificate> chain) { String lookSKI = getCertKeyIdSubject(cert); if (null == lookSKI) { return false; } String foundSKI = null; for (Certificate link : chain) { foundSKI = getCertKeyIdSubject(link); if (lookSKI.equals(foundSKI)) { return true; } } return false; }

Target:
Inverse this, and combine with following lines. Can get rid of an entire branch
Source:
public static Function<HttpPollValue, Double> latency() { return new Function<HttpPollValue, Double>() { @Override @Nullable public Double apply(HttpPollValue input) { if (input.getLatencyFullContent()==null) return null; return input.getLatencyFullContent().doubleValue(); } }; }

Target:
Why convert this to a double, rather than leave it as the exact long value?
Source:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { // The first 8 bytes is size of the request. TCP implementation uses this size to allocate buffer. See {@link BoundedReceive} // Here we just need to consume it. stream.readLong(); } catch (IOException e) { throw new InterruptedException("stream read error." + e); } requestQueue.put(request); }

Target:
nit: this isn't exactly a result of an interrupt, so I think throwing a RuntimeException like `IllegalStateException` would be a better fit here.
Source:
public static final KeyValueStoreListener create() { return new ClientKeyValueStoreListener(); }

Target:
no need the final in static methods
Source:
public void rollback() { for (Path file : tempFiles) { try { if (fileSystem.exists(file) && !fileSystem.delete(file, false)) { throw new IOException("Delete failed"); } } catch (IOException e) { log.warn(e, "Failed to delete temporary file: " + file); } } outputWriter.rollback(); }

Target:
If you did this in the reverse order, you would prevent races... so blindly delete and then check if it still exists.
Source:
private void writePackedRefs(String content) throws IOException { File pr = new File(diskRepo.getDirectory(), "packed-refs"); write(pr, content); final long now = SystemReader.getInstance().getCurrentTime(); final int oneHourAgo = 3600 * 1000; pr.setLastModified(now - oneHourAgo); }

Target:
shouldn't you use a simple System.currrentTimeMillis() instead of the SystemReader?
Source:
protected NuxeoPrincipal createAdministrator() { return new UserPrincipal("Administrator", new ArrayList<>(), false, true); }

Target:
can be replaced by an unmodifiable version like `List.of()`
Source:
private void migrateDirectory(String path, String source, String destination) throws Exception { String newDir = computeTargetPath(path, source, destination); mFileSystem.createDirectory(new AlluxioURI(newDir), FileSystemOptions.createDirectoryDefaults(ServerConfiguration.global())); }

Target:
Doesn't mFileSystem do the merging already?