auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private BootstrapConfigurationImpl() { this.defaultProviderClassName = null; this.constraintValidatorFactoryClassName = null; this.messageInterpolatorClassName = null; this.traversableResolverClassName = null; this.parameterNameProviderClassName = null; this.clockProviderClassName = null; this.valueExtractorClassNames = new HashSet<>( 0 ); this.validatedExecutableTypes = DEFAULT_VALIDATED_EXECUTABLE_TYPES; this.isExecutableValidationEnabled = true; this.constraintMappingResourcePaths = newHashSet(); this.properties = newHashMap(); }

Target:
Very minor but maybe let's make it consistent and initialize the set and map below in the same way? I had to check if there was a specific reason to initialize it this way compared to the others.
Source:
public static FileUtils.FileCopyResult copyToFileAndClose(InputStream is, File file) throws IOException { file.getParentFile().mkdirs(); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { ByteStreams.copy(is, os); } finally { CloseQuietly.close(is); } return FileUtils.FileCopyResult.buildResult(file.toPath()); }

Target:
I am concerned about the addition of buildResult here, since this will cause every single copy to read the data twice for the copy and for the checksum, instead of once as before, which could be expensive when dealing with large files and cause performance regressions.
Source:
@Override public synchronized boolean cancel( final boolean mayInterruptIfRunning ) { return canceled.compareAndSet( false, true ); }

Target:
If you are using an AtomicBoolean (and dont do anything else), you no longer need the synchronized keyword here.
Source:
protected AbstractToolbarItem<S> getItem(final ToolbarCommand<?> command) { return items .entrySet() .stream() .filter(e -> e.getKey().equals(command)) .findFirst() .orElse(null) .getValue(); }

Target:
hey @manstis , quick looking at this seems that a potential NPE can be produced here? I mean for `orElse(null).getValue()`?
Source:
public CellIdentityCdma() { super(CellIdentityCdma.class.getSimpleName(), TYPE_CDMA, null, null); mNetworkId = Integer.MAX_VALUE; mSystemId = Integer.MAX_VALUE; mBasestationId = Integer.MAX_VALUE; mLongitude = Integer.MAX_VALUE; mLatitude = Integer.MAX_VALUE; mAlphaLong = null; mAlphaShort = null; }

Target:
TAG
Source:
private void header(@NonNull final BecauseYouReadCard card) { CardLargeHeaderView header = new CardLargeHeaderView(getContext()) .setTitle(card.title()) .setSubtitle(card.subtitle()) .setPageTitle(card.pageTitle().getDisplayText()) .setImage(card.image()); header(header); }

Target:
Would encapsulating the underlying implementation of BecauseYouReadCard be better or do we need the PageTitle elsewhere? I'm thinking of my recent PageTitle.getText() bug where I meant to call getDisplayText(). At least the bug could only live in one place. If we expose a large object like PageTitle, we have lots of flexibility to do things beyond what a Card is really meant for. There's some notes on some of the tradeoffs here: https://en.wikipedia.org/wiki/Law_of_Demeter.
Source:
private int getCheckTimeoutInSeconds(ConfigurationGenerator cg) { int checkTimeout = DEFAULT_CHECK_TIMEOUT_IN_SECONDS; try { checkTimeout = Integer.parseInt(cg.getUserConfig().getProperty(PARAM_MONGODB_CHECK_TIMEOUT, DEFAULT_CHECK_TIMEOUT_IN_SECONDS.toString())); } catch (NumberFormatException e) { log.warn(String.format("Invalid format for %s parameter, using default value instead", PARAM_MONGODB_CHECK_TIMEOUT), e); } return checkTimeout; }

Target:
`DEFAULT_CHECK_TIMEOUT_IN_SECONDS.toString()` -> `String.valueOf(DEFAULT_CHECK_TIMEOUT_IN_SECONDS)` now that it's an `int`
Source:
private void closeConnection(String deviceId) { DeviceConfig device = deviceConfigCache.get(deviceId); if (device == null) { logger.error("Could not find device '{}'", deviceId); return; } EpsonProjectorDevice remoteController = device.getConnection(); if (remoteController != null) { try { logger.debug("Closing connection to device '{}' ", deviceId); remoteController.disconnect(); } catch (EpsonProjectorException e) { logger.debug("Error occurred when closing connection to device '{}'", deviceId); } } }

Target:
This should be a WARN instead of an ERROR.
Source:
public void testSimpleAnnotation() { assertGeneratedMatches( Lists.newArrayList("import javax.annotation.Nullable;"), Lists.newArrayList("@Nullable"), Lists.newArrayList("@javax.annotation.Nullable")); }

Target:
I'd prefer ImmutableList.of throughout.
Source:
public void testUnionPointWithEmptyLineString() { assertUnion("POINT (1 2)", "LINESTRING EMPTY", "GEOMETRYCOLLECTION (POINT (1 2))"); }

Target:
I'd expect the union of `POINT (1, 2)` and `LINESTRING EMPTY` to be `POINT (1, 2)`, but this test asserts the result to be `GEOMETRYCOLLECTION (POINT (1 2))`.
Source:
public Layers(EntityLivingBase entity, RenderLivingBase<T> entityRenderer, LayerRenderer<T> layerRenderer, double x, double y, double z) { super(entity, entityRenderer, x, y, z); this.layerRenderer = layerRenderer; }

Target:
protected?
Source:
public void deleteOldDeployments(final IServer server) throws CoreException { File deploymentsRootFolder = getDeploymentsRootFolder(); Arrays.stream(server.getModules()) .forEach(module -> deleteOldDeployment(module, deploymentsRootFolder)); }

Target:
Seems the output name cache should be reset here, not below.
Source:
public CronTab(String format, int line, Hash hash) throws ANTLRException { set(format, line, hash); }

Target:
I would recommend to use <code>this()</code> in this constructor
Source:
public boolean isKeyFrame(byte[] buff, int off, int len) { if (buff == null || len < 1 || buff.length < len) { return false; } int nalType = buff[off] & kTypeMask; // Single NAL Unit Packet if (nalType == kFuA) { // Fragmented NAL units (FU-A). if (parseFuaNaluForKeyFrame(buff, off, len)) { return true; } } else { if (parseSingleNaluForKeyFrame(buff, off, len)) { return true; } } return false; }

Target:
@mdaneshi, do you think it would make sense to have something like this in every static methods that you wrote? ``` if (buf == null || Math.min(buf.length, len) < off + 1 /* required array length for this method to work correctly */) { return false; } ``` I know this is not a common practice currently in libjitsi and we sometimes are a little sloppy when we access arrays, but I believe we should change this and write more defensive code whenever possible.
Source:
public ResponseEntity<?> delete(@RequestBody List<Long> printerIds) throws IOException { for (long id : printerIds) { Printer printer = printerService.get(id); if (printer != null) { printerService.remove(printer); } } return new ResponseEntity<>(HttpStatus.OK); }

Target:
`@ResponseStatus(HttpStatus.NO_RESPONSE)` Then you can change return type to void and remove the return statement
Source:
public DiskWriteModel getDisk(int deviceId) { return fDisks.computeIfAbsent(deviceId, k -> new DiskWriteModel(deviceId, checkNotNull(getStateSystemBuilder()))); }

Target:
Use k, like you did in the other files
Source:
public void testIsConditionValidWhenHeaderIsValid() throws Exception { final ConditionCol52 conditionCol1 = fakeConditionCol52("header1"); final ConditionCol52 conditionCol2 = fakeConditionCol52("header2"); final Validator validator = new Validator(fakeCompositeColumn(conditionCol1, conditionCol2)); assertFalse(validator.isConditionValid(conditionCol2)); }

Target:
In the context of GUVNOR-2821 I would expect `assertTrue` here, can you please update the `fakeConditionCol52` method to achieve this? Let me know if you don't see my point.
Source:
public StatsManagerMetrics(MetricRegistry registry) { this.registry = registry; statsPublishFailureCount = registry.counter(MetricRegistry.name(StatsManager.class, "StatsPublishFailureCount")); totalFetchAndAggregateTime = registry.histogram(MetricRegistry.name(StatsManager.class, "TotalFetchAndAggregateTime")); fetchAndAggregateTimePerStore = registry.histogram(MetricRegistry.name(StatsManager.class, "FetchAndAggregateTimePerStore")); }

Target:
does this need to be a class member?
Source:
BlobStatus(List<String> replicaList) { if (replicaList != null && replicaList.size() > 0) { unavailable.addAll(replicaList); } }

Target:
minor: the `replicaList.size() > 0` check isn't really needed
Source:
protected MemcachedClientCallback createMemcachedClientCallback() { return new MemcachedClientCallback() { @Override public byte[] get(final String key) throws IOException { return _memcached.get(_memcachedNodesManager.getStorageKeyFormat().format( key )); } }; }

Target:
MemcachedClientCallback should be renamed to StorageClientCallback
Source:
public void clientId() throws IOException { Stripe.clientId = "ca_test"; chargeBody = resource("charge.json"); }

Target:
Your tests don't rely on `Stripe.clientId` at all, so you should remove this line, rename the method, and get rid of `tearDownMockAndClientId()` entirely.
Source:
private XADataSource createXaDataSourceInstance(String className) { try { Class<?> dataSourceClass = ClassUtils.forName(className, this.getClass().getClassLoader()); Object instance = BeanUtils.instantiate(dataSourceClass); Assert.isInstanceOf(XADataSource.class, instance); return (XADataSource) instance; } catch (Exception ex) { throw new IllegalStateException( "Unable to create XADataSource instance from '" + className + "'"); } }

Target:
Maybe it would be good to include the causing exception so user knows why it couldn't be created.
Source:
protected Optional<ExampleProjectError> getError(Path projectPath) { POM pom = this.getPom(pomService, projectPath); if (pom.getModules().isEmpty() || pom.getModules() == null) { return Optional.empty(); } else { return Optional.of(new ExampleProjectError(CheckModulesValidator.class.getCanonicalName(), "")); } }

Target:
You need to swap the order of nullcheck / isEmpty, otherwise it will lead to NPE (if getModules returns null, not sure that's possible) and this validator will fail.
Source:
public boolean isOpen() { return mBaseTransport.isOpen() && mTransport != null && mTransport.isOpen(); }

Target:
When is `mTransport == null`? Isn't it always set to something in `open()`? Also, why do you need to check `mBaseTransport`?
Source:
public static void restoreSystemProperties() { System.clearProperty("org.uberfire.nio.git.daemon.enabled"); System.clearProperty("org.uberfire.nio.git.ssh.enabled"); System.clearProperty("org.uberfire.sys.repo.monitor.disabled"); }

Target:
why enabled? why restore those?
Source:
protected void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID id, Patch patch) throws AuthorizeException, SQLException { final Group group = dsoService.find(context, id); if (group != null && isPatchUnprocessable(context, group)) { throw new UnprocessableEntityException("This group cannot be patched."); } patchDSpaceObject(apiCategory, model, id, patch); }

Target:
I'd rather see more specific error messages here, as there's a few different scenarios here we should be aware of: * A permanent group's name can *never* be patched. But, its description can be updated. * Same with a Community/Collection group's name (not editable) & description (editable), unless it's detached. In which case it can be patched. So, at a minimum, it seems like we need different errors & checks here. Permanent groups can *never* have name updates, but can have description updates. Community/Collection groups can be updated if the Community/Collection is deleted, but are otherwise considered "permanent".
Source:
protected String computeMetricName(Message<?> message) { String counterName = nameExpression.getValue(evaluationContext, message, CharSequence.class).toString(); return counterName; }

Target:
no need to assign to counterName just to return on next line. However, we probably should add a null check for the evaluationContext.
Source:
public boolean supportsBitmapIndex(final BitmapIndexSelector selector) { // We can operate on bitmap indexes if this is a constant expression, or if it reads one column that has // an index and does not have multiple values. The lack of multiple values is important because expression // filters treat multi-value arrays as nulls, which doesn't permit index based filtering. return requiredBindings.isEmpty() || (requiredBindings.size() == 1 && selector.getBitmapIndex(Iterables.getOnlyElement(requiredBindings)) != null && !selector.hasMultipleValues(Iterables.getOnlyElement(requiredBindings))); }

Target:
Could you break this statement into multiple for readability?
Source:
public void setM(Market currentMarket) { this.currentMarket = currentMarket; }

Target:
this method should be changed to private
Source:
private long countMapWithAtleastOneQueryCache(Node node) { return maps.stream().filter(distributedObject -> { MapConfig config = node.getConfig().getMapConfig(distributedObject.getName()); if (config != null) { return config.getQueryCacheConfigs().size() >= 1; } return false; }).count(); }

Target:
Please write it as `!config.getQueryCacheConfigs().isEmpty()` instead of checking the size.
Source:
public void addModifiedColumns( GlobalConfiguration globalCfg, Value value, Element parent, PropertyAuditingData propertyAuditingData) { String columnName = propertyAuditingData.getModifiedFlagName(); if ( propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } MetadataTools.addModifiedFlagProperty( parent, propertyAuditingData.getName(), globalCfg.getModifiedFlagSuffix(), columnName ); }

Target:
probably it is better to change it to ``` String columnName; if ( propertyAuditingData.isModifiedFlagNameExplicitlySpecified() ) { columnName = propertyAuditingData.getExplicitModifiedFlagName(); } else { columnName = propertyAuditingData.getModifiedFlagName(); } ```
Source:
private boolean isFailedEqualityComparison(Throwable exception) { if (!(exception instanceof ConditionNotSatisfiedError)) return false; final ConditionNotSatisfiedError conditionNotSatisfiedError = (ConditionNotSatisfiedError) exception; Condition condition = conditionNotSatisfiedError.getCondition(); ExpressionInfo expr = condition.getExpression(); return expr != null && expr.isEqualityComparison() && // it is equality conditionNotSatisfiedError.getCause() == null; // and it is not failed because of exception }

Target:
Why is this final and condition not? Same issue on line 130. Since final is normally not used for local variables in spock, I'd remove it.
Source:
public final RedirectAction getLogoutRedirectAction(final WebContext context) { // it's an AJAX request -> unauthorized (instead of a redirection) if (ajaxRequestResolver.isAjax(context)) { logger.info("AJAX request detected -> returning 401"); cleanRequestedUrl(context); return null; } // authentication has already been tried -> unauthorized final String attemptedAuth = (String) context.getSessionAttribute(getName() + ATTEMPTED_AUTHENTICATION_SUFFIX); if (CommonHelper.isNotBlank(attemptedAuth)) { return null; } init(context); return retrieveLogoutRedirectAction(context); }

Target:
These checks are not necessary for logout.
Source:
public void setMainTabSelectedItem(Erratum selectedItem) { logger.info("setMainTabSelectedItem"); //$NON-NLS-1$ updateErrataDetailFormPanel(selectedItem); }

Target:
debug/trace/remove?
Source:
public EurekaArchaius2InstanceConfig(Config config, String namespace, DataCenterInfo dcInfo) { this.defaultAppGroup = config.getString(FALLBACK_APP_GROUP_KEY, Values.UNKNOWN_APPLICATION); this.namespace = namespace; this.config = config.getPrefixedView(namespace); this.dcInfo = dcInfo; // TODO: Remove this when DiscoveryManager is finally no longer used DiscoveryManager.getInstance().setEurekaInstanceConfig(this); }

Target:
If we need to do this, I feel like we can at least do this somewhere else. A binding for something like DiscoveryManagerInitializer with dependencies on these Config classes might work.
Source:
public AdhocQueryResponse respondingGatewayCrossGatewayQuery(AdhocQueryRequest body, WebServiceContext context) { AssertionType assertion = getAssertion(context, null); if (assertion != null) { assertion.setImplementsSpecVersion(UDDI_SPEC_VERSION.SPEC_2_0.toString()); } return inboundDocQuery.respondingGatewayCrossGatewayQuery(body, assertion, this.getWebContextProperties(context)); }

Target:
Right here (and in the equivalent 3.0 class) is the only place you're using "this" where a field isn't shadowed, is this intentional?
Source:
public void allBindingsChanged(BindingProvider provider) { logger.trace("allBindingsChanged() called."); if (provider instanceof VeluxBindingProvider) { } super.allBindingsChanged(provider); }

Target:
Drop this empty block.
Source:
private Map<String, String> makeParserFields() { final Map<String, String> fieldMapping = Maps.newHashMap(); for (final SchemaPath sp : getColumns()) { final String drillField = sp.getRootSegment().getPath(); try { final String parserField = HttpdParser.parserFormattedFieldName(drillField); fieldMapping.put(drillField, parserField); } catch (Exception e) { LOG.info("Putting field: " + drillField + " into map", e); } } return fieldMapping; }

Target:
Please, remove `final` modifiers as they seem to be redundant.
Source:
public Builder client(@NonNull OkHttpClient client) { if (client == null) { throw new NullPointerException("client == null"); } if (downloader != null) { throw new IllegalArgumentException("Downloader already set."); } downloader = new OkHttp3Downloader(client, client.cache(), true); return this; }

Target:
Message needs changed. What does Retrofit do? Do we care if people overwrite this? I don't, and it breaks your `newBuilder()` desire.
Source:
protected Optional<CoverageReportView> getCoverageReportView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); if (activity != null) { final AbstractWorkbenchActivity coverageActivity = (AbstractWorkbenchActivity) activity; return Optional.of((CoverageReportView) coverageActivity.getWidget()); } else { return Optional.empty(); } }

Target:
Just a small remark feel free to skip it. It would have a nicer look if you keep if else logic direct like if (activity == null) { return Optional.empty(); } else { final AbstractWorkbenchActivity coverageActivity = (AbstractWorkbenchActivity) activity; return Optional.of((CoverageReportView) coverageActivity.getWidget()); }
Source:
private void edit() { if (getWindow() != null) { return; } AffinityGroup affinityGroup = getSelectedItem(); if (affinityGroup == null) { return; } sortVms(affinityGroup); AffinityGroupModel model = new EditAffinityGroupModel(affinityGroup, this, getClusterResolver()); model.init(); setWindow(model); }

Target:
Generally you don't sort the VMs, and in the one case where you do - you don't really sort them either, but just move one to the top of the list. So firstly, consider dropping this method, making edit() protected and add the logic only in VmAffinityGroupListModel. Secondly, you could drop the comparator there and just iterate over the items to find the specific ID and move it to the top of the list, the comparator thing isn't necessary.
Source:
public void testIteratorCloses() throws Exception { Kabob bob = db.getJdbi().onDemand(Kabob.class); Iterator<Something> itty = bob.iterateAll(); assertThat(itty.hasNext()).isFalse(); }

Target:
Considering the expected exception for this test, it seems like the `assertThat` is superfluous, and all we really want is `itty.hasNext();`
Source:
public static void assertSwappedIngredientsMatch(ObjectInstance ing, State s, List<String> ings) { Set<String> swappedIngredients = IngredientFactory.getRecursiveContentsAndSwapped(s, ing); Boolean match = true; assertEquals(swappedIngredients.size(), ings.size()); for (String i : ings) { if (!swappedIngredients.contains(i)) { match = false; break; } } assertTrue(match); }

Target:
Cant the class name be included here so we know where this method is being called from.
Source:
public List<Document> getClientDocuments(String clientId) throws MambuApiException { if (clientId == null || clientId.trim().isEmpty()) { throw new IllegalArgumentException("ClientId ID must not be null or empty"); } return DocumentsService.getDocuments(mambuAPIService, CLIENTS, clientId); }

Target:
Edge case of duplicate code ;) It could be extracted to a common private method with two params for id and type. Up to you if you want to change it or not ;)
Source:
public void testFailForCheckDisksNotInBackupStorage() { final VM vm = new VM(); command.setVm(vm); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); command.setCluster(new Cluster()); Guid storageDomainId = initDiskImage(vm); when(storageDomainStaticDao.get(storageDomainId)).thenReturn(backupStorageDomain(true)); assertFalse("checkDisksNotInBackupStorage() fails to run because one or more disk is in backup domain", command.checkDisksInBackupStorage()); }

Target:
Now this should return true, since there are disks on the storage domain (Remember that you don't check the validate only the method checkDisksInBackupStorage) Change to assertTrue
Source:
public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; if (skip > n) skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; pos = (int) skip; return skip; } }

Target:
shouldn't be the ```max()``` between ```offset``` and ```skip``` to avoid the ```pos``` to be previous than ```offset```?
Source:
public void actionPerformed(AnActionEvent e) { BaseAction.State s = setupAction(e); List<String> lastTask = Collections.singletonList(s.getLastRanTask()); s.performTasks(lastTask); s.cleanup(); }

Target:
You may want to put this into a try/finally block.
Source:
public void addAll(SerializableStatus status) { Assert.isLegal(status != null); SerializableStatus[] statuses = (SerializableStatus[]) status.getChildren(); for (SerializableStatus statuse : statuses) { add(statuse); } }

Target:
rename to s
Source:
protected boolean canDoAction() { return super.canDoAction() && VdsGroupExists() && logicalNetworkExists() && changesAreClusterCompatible(); }

Target:
how about moving logicalNetworkExists() after changesAreClusterCompatible() ? in case changesAreClusterCompatible() returns false, it will save one DB call :)
Source:
protected void reloadCache() { schemaMappingCache.invalidateAll(); // this preloads the list of schema names Set<String> schemas = getSchemaNames(); // invalidate and remove from the schema table mapping all records, start from scratch for (String key : schemaTableMapping.keySet()) { schemaTableMapping.get(key).invalidateAll(); schemaTableMapping.remove(key); } for (final String schema : schemas) { // this preloads the list of table names for each schema getTableNames(schema); } }

Target:
any reason you can't just iterate through the values? schemaTableMapping.values().foreach(v -> v.invalidateAll()); schemaTableMapping.clear();
Source:
public void testSetUser() { Configuration configuration = generateConfiguration(); configuration.setUser("24601", "m@rp.fr", "MM"); assertEquals(User.class, configuration.getUser().getClass()); assertEquals("24601", configuration.getUser().getId()); assertEquals("m@rp.fr", configuration.getUser().getEmail()); assertEquals("MM", configuration.getUser().getName()); }

Target:
This assertion could be removed as it seems to test the Java type system rather than our code
Source:
private void writeStringToFile(File file, String str) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.toString()))) { bw.write(str); } }

Target:
No need to call `file.toString()` -> `FileWriter` can take `File` in the constructor as well.
Source:
private RelNode possiblyWrapRootWithOuterLimitFromContext( RelRoot root ) { Object outerLimitObj = plannerContext.getQueryContext().get(PlannerContext.CTX_SQL_OUTER_LIMIT); if (outerLimitObj == null) { return root.rel; } Long outerLimit = DimensionHandlerUtils.convertObjectToLong(outerLimitObj, true); if (outerLimit == null) { return root.rel; } return LogicalSort.create( root.rel, root.collation, makeBigIntLiteral(0), makeBigIntLiteral(outerLimit) ); }

Target:
Minor: the two calls could be collapsed, since `DimensionHandlerUtils.convertObjectToLong` handles nulls just fine.
Source:
public void testSamePortConfiguredForClientAndElection() throws IOException, ConfigException { QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig(); try { Properties zkProp = getDefaultZKProperties(); zkProp.setProperty("server.1", "localhost:2888:2888"); quorumPeerConfig.parseProperties(zkProp); fail("ConfigException is expected"); } catch (ConfigException ce) { String expectedMessage = "Client and election port must be different! Please update the configuration file on server.1"; assertEquals(expectedMessage, ce.getMessage()); } }

Target:
nit - ConfigException is unused
Source:
public static URLConnection openURLConnection(URL url) throws IOException, ConnectException { return openURLConnection(url,DEFAULT_CONNECTION_TIMEOUT); }

Target:
ConnectException is not actually thrown by anything... it shouldn't be declared in the `throws`
Source:
public void updateParentCommandId(ArrayList<VdcActionParametersBase> parameters, CommandBase command) { for (VdcActionParametersBase param : parameters) { param.setParentCommand(command.getActionType()); param.setParentParameters(command.getParameters()); } }

Target:
1. let's replace with params.forEach 2. it makes more sense that this method will reside in HostSetupNetworksParametersBuilder - I don't see how its related to "ReportFailedChildHostOperationsUtil"
Source:
public MetricData getDatapointsForRange(Locator locator, Range range, Granularity gran) { RollupType rollupType = null; String rollupTypeStr = metaCache.safeGet(locator, rollupTypeCacheKey); if ( rollupTypeStr != null ) { rollupType = RollupType.fromString(rollupTypeStr); } if ( rollupType == null ) { rollupType = RollupType.BF_BASIC; } return getNumericMetricDataForRange(locator, range, gran, rollupType); }

Target:
nm. I misread the diff. I thought ```getDatapointsForRange()``` only called ```getNumericMetricDataForRange()```
Source:
public boolean shouldProcessRequestedCashAdvancesFromSaeData() { return (getConcurParameterValue(ConcurParameterConstants.CONCUR_PROCESS_CASH_ADVANCES_FROM_SAE_DATA_IND).equalsIgnoreCase(KFSConstants.ParameterValues.YES)); }

Target:
to be null safe on here, I would suggest using stringutils.equalsignorecase or start the expression with the constant
Source:
static Path resolvePath(Path file, String workingDirectory) { return file == null ? null : (file.isAbsolute() ? file : (file.getFileName().startsWith(File.separator) ? file.toAbsolutePath() : (Paths.get(workingDirectory, file.getFileName().toString())))); }

Target:
Looks that works OK, but for me it's hard to read. I would rather see better readable return.
Source:
public void removeServiceEventListener(Object listener) { assert getExecutor().isInExecutorThread(); ListenerEntry entry = new ListenerEntry(listener, null); if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_LISTENERS) { String msg = new Formatter().format( "%s %s removed as a service listener to %s (id=%s)", //$NON-NLS-1$ DsfPlugin.getDebugTime(), LoggingUtils.toString(listener), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fListeners.remove(entry); }

Target:
Let's only use DsfDebugOptions.DEBUG_SESSION_LISTENERS here but have it include the others directly in DsfDebugOptions.
Source:
private static void validateEntityLabel(EntityType entityType) { String label = entityType.getLabel(); if (label.isEmpty()) { throw new MolgenisValidationException( new ConstraintViolation(format("Label of EntityType [%s] is empty", entityType.getId()))); } else if (label.trim().equals("")) { throw new MolgenisValidationException(new ConstraintViolation( format("Label of EntityType [%s] contains only white space", entityType.getId()))); } }

Target:
I smell an incoming NPE here...
Source:
public void deleteIfExists(File path, String user, String logPrefix) throws IOException { LOG.info("Deleting path {}", path); Path p = path.toPath(); if (Files.exists(p)) { try { FileUtils.forceDelete(path); } catch (FileNotFoundException ignored) } }

Target:
We could just call deleteIfExists(path) since it's same.
Source:
protected void releaseTransport(Transport transport) { if (dedicatedTransport == null) { //we aren't using this transport. we can release it super.releaseTransport(transport); } }

Target:
This could be even `if (dedicatedTransport != transport)`
Source:
String prepare(String name, Map<String, Map<String, String>> domain) { StringBuilder builder = new StringBuilder(name); while (domain.containsKey(name)) { builder.append("~"); } domain.put(builder.toString(), new LinkedHashMap<>()); return builder.toString(); }

Target:
You probably made it a couple of thousand times slower :-) Keys rarely overlap in this domain creating a StringBuilder has an initialization cost that is not amortized.
Source:
public synchronized void deleteFile() { closeFile(); File historyTreeFile = fConfig.getStateFile(); try { if (!historyTreeFile.delete()) { /* We didn't succeed in deleting the file */ Activator.getDefault().logError("Failed to delete" + historyTreeFile.getName()); //$NON-NLS-1$ } } catch (SecurityException e) { Activator.getDefault().logError(e.getMessage(), e); } }

Target:
is this a RuntimeException? In which case you probably don't want to catch it.
Source:
public void delete(UserEntityFile userEntityFile) { getEntityManager().remove(userEntityFile); }

Target:
Replace method content with... super.delete(userEntityFile); ...as the underlying code will not only delete the entity but also fire an event about it.
Source:
public void init() { if (dubboConfigBinder == null) { try { dubboConfigBinder = applicationContext.getBean(DubboConfigBinder.class); } catch (BeansException ignored) { if (log.isDebugEnabled()) { log.debug("DubboConfigBinder Bean can't be found in ApplicationContext."); } // Use Default implementation dubboConfigBinder = createDubboConfigBinder(applicationContext.getEnvironment()); } } dubboConfigBinder.setIgnoreUnknownFields(ignoreUnknownFields); dubboConfigBinder.setIgnoreInvalidFields(ignoreInvalidFields); }

Target:
If we allow to create sub class of this **DubboConfigBindingBeanPostProcessor ** and some **init method** get override then it might cause issue. So better to make init final or provide. What do you say?
Source:
public static void removeDuplicateImages(Feed feed) { Set<String> known = new HashSet<String>(); for (FeedItem item : feed.getItems()) { String url = (item.hasItemImage()) ? item.getImage().getDownload_url() : null; if (url != null) { if (known.contains(url)) { item.setImage(null); } else { known.add(url); } } } }

Target:
I find it even easier to read without the `(...)`
Source:
protected void selectedItemsChanged() { super.onSelectedItemChanged(); updateActionAvailability(); }

Target:
Shouldn't this also be changed to super.selectedItemsChanged()?
Source:
public int[] borrowIntArray(int positionCount) { int[] array; while (intArraysTop >= 0 && intArrays[intArraysTop].length < positionCount) { estimatedSizeInBytes -= sizeOfIntArray(intArrays[intArraysTop].length); --intArraysTop; } if (intArraysTop < 0) { array = new int[positionCount]; estimatedSizeInBytes += sizeOfIntArray(positionCount); } else { array = intArrays[intArraysTop]; --intArraysTop; } ++borrowedIntArrays; return array; }

Target:
Shouldn't this loop release memory of "discarded" arrays? E.g. intArrays[intArraysTop] = null?
Source:
public Collection<MergeStrategySection> getAllMergeStrategySections() { List<MergeStrategySection> all = new ArrayList<MergeStrategySection>(); all.addAll(getLocalMergeStrategySections()); all.addAll(getInheritedMergeStrategySections()); return all; }

Target:
I suspect that you want to preserve order here and return a List?
Source:
public String getDeleteDescription() { return getName() + (getAlias() == null ? "" : " (" + getAlias() + ")"); }

Target:
Alias should never be null.
Source:
boolean selectCommonAncestor(ReadOnlyDocument doc1, ReadOnlyDocument doc2) throws CouchbaseLiteException { if (!c4doc.getRawDoc().selectCommonAncestorRevision(doc1.getRevID(), doc2.getRevID())) return false; setC4Doc(c4doc); // self.c4Doc = _c4Doc; // This will update to the selected revision return true; }

Target:
Is CouchbaseLiteException thrown from anything in this method? Or it should return void but throw CouchbaseLiteException instead?
Source:
public void setHazelcastRegisteredEventListenerId(String hazelcastRegisteredEventListenerId) { this.hazelcastRegisteredEventListenerId = hazelcastRegisteredEventListenerId; }

Target:
`protected`. It would be bad to allow end-user to mutate on this local property.
Source:
protected String getFileName(ITask task, Predicate<String> fileExists) { String encodedFileName = CoreUtil.asFileName(task.getTaskId()); // for backwards-compatibility with versions that always encoded file names, // we will use an encoded name if the file with an encoded name already exists if (encodedFileName.length() <= FILENAME_MAX_LEN && fileExists.test(encodedFileName)) { return encodedFileName; } // if file with encoded name does not exist, we will only encode file name if it is required String fileName; if (requiresEncoding(task.getTaskId())) { fileName = encodedFileName; } else { fileName = task.getTaskId(); } // trim the file name if it is too long return trimFilenameIfRequired(fileName); }

Target:
In what case can the file exist but be too long? If we are on a system with a longer filename limit, we should just use the existing file and not worry about the length, I think.
Source:
public boolean createIndex(String indexName) { Assert.notNull(indexName, "No index defined for Query"); try { CreateIndexRequest indexRequest = createIndexRequest(indexName); return client.indices().create(indexRequest, RequestOptions.DEFAULT).isAcknowledged(); } catch (Exception e) { throw new ElasticsearchException("Failed to create index " + indexName, e); } }

Target:
why the extraction to a variable? I would keep it inlined: ``` return client.indices().create(createIndexRequest(indexName), RequestOptions.DEFAULT).isAcknowledged(); ```
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(ShipyardProperties.SHIPYARD_CREDENTIAL, "<remote-service-key-given-by-shipyard-cli>"); return properties; }

Target:
What is this property used for?
Source:
protected boolean writeNeedsRemoteValue(InvocationContext ctx, WriteCommand command, Object key) { if (command.hasFlag(Flag.CACHE_MODE_LOCAL)) { return false; } if (ctx.isOriginLocal()) { // The return value only matters on the originator. // Conditional commands also check the previous value only on the originator. if (!command.readsExistingValues()) { return false; } // TODO Could make DELTA_WRITE/ApplyDeltaCommand override SKIP_REMOTE_LOOKUP by changing next line to // return !command.hasFlag(Flag.SKIP_REMOTE_LOOKUP) || command.alwaysReadsExistingValues(); if (command.hasFlag(Flag.SKIP_REMOTE_LOOKUP)) { return false; } } else { // Ignore SKIP_REMOTE_LOOKUP on remote nodes // TODO Can we ignore the CACHE_MODE_LOCAL flag as well? if (!command.alwaysReadsExistingValues()) { return false; } } return true; }

Target:
It seems this could be changed to `return !command.hasFlag(Flag.SKIP_REMOTE_LOOKUP))`
Source:
public BulkReceiveLibraryBackend(LibraryDto dto, Integer quantity, Project project, SampleClass aliquotClass, String defaultSciName, LibraryTemplateService libraryTemplateService) throws IOException { super("libraryReceipt", LibraryDto.class, "Libraries", dto, quantity); if (isDetailedSampleEnabled() && aliquotClass == null) throw new InvalidParameterException("Aliquot class cannot be null"); this.project = project; this.aliquotClass = aliquotClass; this.defaultSciName = defaultSciName; this.libraryTemplateService = libraryTemplateService; newBox = dto.getBox(); }

Target:
![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove the declaration of thrown exception 'java.io.IOException', as it cannot be thrown from constructor's body. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ARedundantThrowsDeclarationCheck)
Source:
public void evict(AccountExternalId id) { byKey.remove(id.getKey()); byAccountId.remove(id.getAccountId()); byEmail.remove(new EmailWrapper(id.getEmailAddress())); }

Target:
getEmailAddress can return null.
Source:
public void outjectRequestMap() { for (ValuedParameter vparameter : methodInfo.getValuedParameters()) { result.include(vparameter.getParameter().getName(), vparameter.getValue()); } }

Target:
create a `vparameter.getName()` that delegates to `Parameter`
Source:
public AbstractBlockFamily(BlockFamilyDefinition definition, BlockShape shape, BlockBuilderHelper blockBuilder) { }

Target:
seems like these constructors should set `protected` properties on the base class. They're called via `super` below.
Source:
public void onStop() { super.onStop(); mGoogleApiClient.stopAutoManage(getActivity()); if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } }

Target:
Maybe we can move the null check on `mGoogleApiClient` a level above so to protect also the access to `stopAutoManage`. wdyt?
Source:
protected Guid getQuotaId() { if (getNewDisk() != null && (isInternalManagedDisk())) { return ((DiskImage) getNewDisk()).getQuotaId(); } return null; }

Target:
please remove redundant brackets (isInter...)
Source:
public JClogin() { logger.trace("JClogin(constructor) called."); logger.trace("JClogin(this={}) called.",this); }

Target:
One of these two trace lines should be removed.
Source:
public ScriptingJobs(ScriptingAdaptor adaptor, XenonEngine xenonEngine, SchedulerConnectionFactory connectionFactory) { this.adaptor = adaptor; this.xenonEngine = xenonEngine; this.adaptorName = adaptor.getName(); this.connectionFactory = connectionFactory; connections = Utils.emptyMap(1); }

Target:
I think using this util obfuscates the code
Source:
public TMSKeyBuilder(final String prefix, TileLayerDispatcher layers) { this.prefix = Strings.isNullOrEmpty(prefix) ? "" : prefix + "/"; this.layers = layers; }

Target:
I really dislike how this confuses things. Most of the `/`s are in the templates, but then this one special slash is being added here. This is a really good opportunity for future mistakes. Maybe this is a case for changing from using `String.format()` with templates that all do essentially the same thing for varying numbers of parameters to say just using `String.join()`.
Source:
public void testLeftJoinMissingStats() { PlanNodeStatsEstimate leftStats = planNodeStats( 0, new SymbolStatistics(LEFT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(LEFT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); PlanNodeStatsEstimate rightStats = planNodeStats( 0, new SymbolStatistics(RIGHT_JOIN_COLUMN, SymbolStatsEstimate.unknown()), new SymbolStatistics(RIGHT_OTHER_COLUMN, SymbolStatsEstimate.unknown())); assertJoinStats(LEFT, leftStats, rightStats, leftStats); }

Target:
nit: I somehow liked the old, more concise `UNKNOWN_STATS`
Source:
public Collection<ClassDefinition> generate(ExtensionContext input) throws UnableToCompleteException { PrintWriter printWriter = tryCreate(); if (printWriter != null) { mergeTemplate(printWriter); commit(printWriter); registerGinBinding(); } else { getLogger().debug("Jackson Mapper Provider already generated. Returning."); } return Lists.newArrayList(getClassDefinition()); }

Target:
Didn't you remove guava from GWTP?
Source:
@Test public void shouldHandleSchemeInsensitiveCase() { String[] schemes = { "http", "https", "HTTP", "HTTPS", "HTtP", }; for (String scheme : schemes) { final Uri uri = URI_1.buildUpon().scheme(scheme).build(); final Boolean shouldHandle = networkHandler.canHandleRequest( TestUtils.mockRequest(uri) ); assertThat(shouldHandle).isTrue(); } }

Target:
👍 ah. a good reason to make `picasso3` the package name, so long as it has common names like `Request` in the API.
Source:
public void populate(CoreSession session) throws ClientException { UserManager um = Framework.getLocalService(UserManager.class); Framework.doPrivileged(() -> { // Create some users if (um != null) { createUsersAndGroups(um); } }); }

Target:
if (um != null) { Framework.doPrivileged(() -> createUsersAndGroups(um)); }
Source:
public void stop(BundleContext context) throws Exception { try { Job.getJobManager().join(LUCENE_JOB_FAMILY, null); plugin = null; } finally { super.stop(context); } }

Target:
Might be also in finally?
Source:
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { ObjectUtil.checkNotNull(unit, "unit"); if (delay < 0) { delay = 0; } validateScheduled0(delay, unit); return schedule(new ScheduledFutureTask<Void>( this, ObjectUtil.checkNotNull(command, "command"), deadlineNanos(unit.toNanos(delay)))); }

Target:
move null check back as first action to not change behaviour.
Source:
public Integer invoke() { Integer result = 0; try (InputStream in = cache.getViaStream(key)) { int read = 0; while ((read = in.read(buffer)) != -1) result = result + read; return value = result; } catch (IOException e) { throw new RuntimeException(e); } catch (NullPointerException e) { return null; } }

Target:
I think that `if (in == null) return null` is a slightly better way to deal with this...
Source:
public CoreEvent process(CoreEvent event) throws MuleException { try { return processToApply(event, this); } catch (Exception error) { Throwable cause = error.getCause(); if (cause instanceof RetryContextInitializationException && cause.getCause() instanceof ExpressionRuntimeException) { // Runtime exception caused by Retry Ctx initialization, propagating throw ((ExpressionRuntimeException) cause.getCause()); } else { // Not caused by context initialization. Throwing as raised. throw error; } } }

Target:
check for `cause != null`
Source:
private static void addChildren(Map<String, List<PatchLineComment>> parentMap, List<PatchLineComment> children, List<PatchLineComment> outResult) { if (children != null) { for (PatchLineComment c : children) { outResult.add(c); addChildren(parentMap, parentMap.get(c.getKey()), outResult); } } }

Target:
Missing a .get() here after .getKey() as the UUID is the key in the map, not the PatchLineComment.Key object instance.
Source:
public void dispose() { LogManager.logInfo("Disposing", this); //$NON-NLS-1$ fWindow= null; }

Target:
What is this logging buying us ? Do we really need so much of it?
Source:
public boolean equals(byte[] obj, Object otherObj) { if (obj == otherObj) return true; if (obj == null || byte[].class != obj.getClass()) return false; if (otherObj == null || byte[].class != otherObj.getClass()) return false; byte[] byteArray = obj; byte[] otherByteArray = (byte[]) otherObj; return Arrays.equals(byteArray, otherByteArray); }

Target:
the second part of the OR is redundant: byte[].class != obj.getClass()
Source:
public EngineSearcherTotalHitsMatcher(Query query, int totalHits) { this.query = query; this.totalHits = totalHits; }

Target:
can be private
Source:
protected boolean processEntryForContext(final ILogData data) { if (data != null) { try { final Object payload = data.getPayload(runtime); } catch (Throwable e) { log.error("Exception caught at address {}, {}, {}", data.getGlobalAddress(), data.getStreams(), data.getType()); throw e; } } return false; }

Target:
Why don't you push this down to `LogData::getPayload` ? (since that's when deserialize is actually invoked)
Source:
public boolean isQueryCacheable(Query query) { // O(n) impl, but I don't think we'll ever have a million query types here return !query.isDescending() && !unCacheable.contains(query.getType()); }

Target:
any reason for disabling cache for descending order queries ?
Source:
public static boolean isMoeFile(IResource resource) { if(resource instanceof IFile ) { String fileExtension = resource.getFileExtension(); return fileExtension != null && resource.getFileExtension().equals(MODEL_OBJECT_ELEMENTFILE_EXTENSION); } return false; }

Target:
Just replace all this new code with MODEL_OBJECT_ELEMENTFILE_EXTENSION.equals(resource.getFileExtension()).
Source:
public Property[] getProperties() { return m_properties.toArray(new Property[m_properties.size()]); }

Target:
could we change to List<Properties> or is this API fixed?
Source:
public void setup() throws NoSuchFieldException, IllegalAccessException { // Before "onCreate", we need to record the instance count for the test instanceCountField = OpenHelperManager.class.getDeclaredField("instanceCount"); instanceCountField.setAccessible(true); instanceCount = instanceCountField.getInt(null); activity = Robolectric.buildActivity(OrmLiteActivity_.class).create().get(); }

Target:
No need for this. The tests must be independent, hence the instance count here should be zero.
Source:
public static Injector getInjector() { if ( injector == null ) { injector = Guice.createInjector( new GuiceModule( emf ) ); } return injector; }

Target:
Do we need to do this here? This seems like it's creating a circular dependency of the EMF into Guice, but the EMF depends on Guice.
Source:
public void serialize() throws Exception { String xml = serializer.serialize(header); System.out.println(xml); XMLAssert.assertXpathExists("/subscriptionHeader/contentUri", xml); XMLAssert.assertXpathExists("/subscriptionHeader/packageHeader", xml); XMLAssert.assertXpathExists("/subscriptionHeader/packageHeader/name", xml); }

Target:
We don't like System.out :)
Source:
protected IMicroblockContainerTile getMicroblockTile(IBlockAccess world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); return tile instanceof IMicroblockContainerTile ? (IMicroblockContainerTile) tile : null; }

Target:
Instanceof nightmare?
Source:
public void setMethod(final ZonemasterRequest.Method method) { this.method = method.getMethod(); this.id = method.getId(); }

Target:
should be a protected method
Source:
public Dimension getFloatingItemOffset() { if (editPart instanceof FloatingLabelEditPart) { return ((FloatingLabelEditPart) editPart).getFloatingItemOffset(); } return new Dimension(); }

Target:
Multi return is forbidden.
Source:
private static synchronized ITerminalConnector getConnector(IRemoteConnection irc) throws RemoteConnectionException { ITerminalConnector con = cons.get(irc.getAddress()); if(con == null) { con = TerminalConnectorExtension.makeTerminalConnector( "org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector"); //$NON-NLS-1$ cons.put(irc.getAddress(),con); } else if(irc.isOpen()) { return null; } else { irc.open(new NullProgressMonitor()); return null; } return con; }

Target:
irc is not open if con is null initially. The logic here is a bit muddled.
Source:
public long getGlobalClassLoaderId() { return (long) ClassLoaderIdentifier.GLOBAL_ID; }

Target:
Why not declare GLOBAL_ID as a long?
Source:
private int getCmasSeverity() { switch (messageIdentifier) { case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_OBSERVED: case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_LIKELY: return SmsCbCmasInfo.CMAS_SEVERITY_EXTREME; case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_OBSERVED: case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_LIKELY: case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_OBSERVED: case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_LIKELY: case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_OBSERVED: case SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_LIKELY: return SmsCbCmasInfo.CMAS_SEVERITY_SEVERE; default: return SmsCbCmasInfo.CMAS_SEVERITY_UNKNOWN; } }

Target:
Even though these two are "CMAS Severe Alerts", shouldn't getCmasSeverity() still return CMAS_SEVERITY_EXTREME? Spec says "Severity of Extreme, Urgency of Expected..."
Source:
public Collection<String> getAliases(final KeyStore keyStore) throws ScriptSignatureException { try { if (keyStore != null) return Collections.list(keyStore.aliases()); } catch (KeyStoreException e) { throw new ScriptSignatureException("Keystore not initialized properly. Try again.", e); } throw new ScriptSignatureException("Keystore not initialized properly. Try again.", null); }

Target:
instead of thowing we could return an empty list
Source:
public List<Expression> getExpressions() { List<Expression> result = new ArrayList<Expression>(groupByAttributes); result.add(expression); return result; }

Target:
Type argument Expression is not need.